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
Fixes #59, public assets and improved restricted access, new AssetModelProvider SPI
Christian Bauerfe0119e6e708
diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AbstractAssetActivity.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AbstractAssetActivity.javaindex 4d6807f77..5f929565c 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AbstractAssetActivity.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AbstractAssetActivity.java@@ -211,6 +211,7 @@ public abstract class AbstractAssetActivity<Vview.setLocation(asset.getCoordinates());view.showDroppedPin(asset.getGeoFeature(20));view.flyTo(asset.getCoordinates());+ view.setAccessPublicRead(asset.isAccessPublicRead());}@Override@@ -360,8 +361,10 @@ public abstract class AbstractAssetActivity<V}protected Optional<MetaItemDescriptor> getMetaItemDescriptor(MetaItem item) {- return AssetMeta- .getAssetMeta(item.getName().orElse(""))+ // TODO Should use meta item descriptors from server+ return Arrays.stream(AssetMeta.values())+ .filter(assetMeta -> assetMeta.getUrn().equals(item.getName().orElse("")))+ .findFirst().map(assetMeta -> (MetaItemDescriptor)assetMeta);}@@ -398,10 +401,11 @@ public abstract class AbstractAssetActivity<V// Meta item value is read only if value is fixedif (valueHolder instanceof MetaItem) {- return ((MetaItem) valueHolder).getName()- .flatMap(AssetMeta::getAssetMeta)+ // TODO Should use meta item descriptors from server+ return Arrays.stream(AssetMeta.values())+ .filter(assetMeta -> assetMeta.getUrn().equals(((MetaItem) valueHolder).getName())).map(AssetMeta::isValueFixed)- .orElse(false);+ .findFirst().orElse(false);}if (valueHolder instanceof AssetAttribute) {diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetBaseView.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetBaseView.javaindex 7403f3685..77bf5a2d3 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetBaseView.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetBaseView.java@@ -75,6 +75,8 @@ public interface AssetBaseView<P extends AssetBaseView.Presenter> extends IsWidgvoid flyTo(double[] coordinates);+ void setAccessPublicRead(boolean enabled);+void setAttributeViews(List<AttributeView> attributeViews);void addAttributeViews(List<AttributeView> attributeViews);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 6be1d3d32..52a05aa75 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@@ -39,6 +39,8 @@ public interface AssetEdit extends FormView, AssetBaseView<AssetEdit.Presenter>void onMapClicked(double lng, double lat);+ void onAccessPublicRead(boolean enabled);+void onAssetTypeSelected(AssetType value);boolean addAttribute(String name, String type);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 1b2fb4d9b..74e3adf39 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@@ -86,7 +86,7 @@ public class AssetEditActivityprotected final AssetAttributeMapper assetAttributeMapper;protected final Consumer<ConstraintViolation[]> validationErrorHandler;protected List<ProtocolDescriptor> protocolDescriptors = new ArrayList<>();- protected List<MetaItemDescriptor> metaItemDescriptors = new ArrayList<>(Arrays.asList(AssetMeta.values()));+ protected List<MetaItemDescriptor> metaItemDescriptors = new ArrayList<>(Arrays.asList(AssetMeta.values())); // TODO Get meta item descriptors from serverdouble[] selectedCoordinates;protected List<AssetAttribute> initialAssetAttributes;@@ -196,6 +196,11 @@ public class AssetEditActivityview.setLocation(selectedCoordinates);}+ @Override+ public void onAccessPublicRead(boolean enabled) {+ asset.setAccessPublicRead(enabled);+ }+@Overridepublic void onAssetTypeSelected(AssetType type) {asset.setType(type);diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditImpl.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditImpl.javaindex 365174f9a..0c0925d07 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditImpl.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetEditImpl.java@@ -116,6 +116,11 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {@UiFieldMapWidget mapWidget;+ @UiField+ FormGroup accessPublicReadGroup;+ @UiField+ FormCheckBox accessPublicReadCheckBox;+/* ############################################################################ */@UiField@@ -216,6 +221,12 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {UI ui = GWT.create(UI.class);initWidget(ui.createAndBindUi(this));+ accessPublicReadCheckBox.addValueChangeHandler(event -> {+ if (presenter != null) {+ presenter.onAccessPublicRead(event.getValue());+ }+ });+splitPanel.setOnResize(() -> mapWidget.resize());}@@ -234,6 +245,8 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {parentAssetSelector.init();locationOutput.setCoordinates(null, null);centerMapButton.setEnabled(false);+ accessPublicReadCheckBox.setValue(false);+ typeGroup.setVisible(false);typeGroup.setError(false);typeListBox.setValue(null);typeListBox.setAcceptableValues(new ArrayList<>());@@ -416,6 +429,11 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {presenter.centerMap();}+ @Override+ public void setAccessPublicRead(boolean enabled) {+ accessPublicReadCheckBox.setValue(enabled);+ }+/* ############################################################################ */@Override@@ -442,6 +460,7 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {@Overridepublic void setTypeEditable(boolean editable) {+ typeGroup.setVisible(editable);typeListBox.setEnabled(editable);typeInput.setReadOnly(!editable);customTypeInfoLabel.setVisible(editable && typeListBox.getValue() == AssetType.CUSTOM);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 a2d9d8839..6d58e5797 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@@ -13,13 +13,13 @@.mapWidget {margin: 0 0 1em 1em;- height: 17em;+ height: 19em;}.stringEditor {- min-width: 5em;- width: 100%;- }+ min-width: 5em;+ width: 100%;+ }.numberEditor {min-width: 5em;@@ -125,6 +125,18 @@</w:FormGroupActions></w:actions></w:FormGroup>++ <w:FormGroup ui:field="accessPublicReadGroup">+ <w:label>+ <w:FormLabel text="{managerMessages.publicAccess}"/>+ </w:label>+ <w:field>+ <w:FormField addStyleNames="larger">+ <w:FormCheckBox ui:field="accessPublicReadCheckBox"/>+ </w:FormField>+ </w:field>+ </w:FormGroup>+</div><w:MapWidget ui:field="mapWidget"@@ -132,7 +144,7 @@</div><div class="layout horizontal center wrap">- <w:FormGroup ui:field="typeGroup" addStyleNames="flex">+ <w:FormGroup ui:field="typeGroup" addStyleNames="flex" visible="false"><w:label><w:FormLabel text="{managerMessages.assetType}"/></w:label>diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetView.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetView.javaindex d053ef82c..d238a1433 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetView.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetView.java@@ -33,4 +33,6 @@ public interface AssetView extends AssetBaseView<AssetView.Presenter> {void setFormBusy(boolean busy);void setIconAndType(String icon, String type);++ void setAccessPublicReadAnchor(String path);}diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.javaindex b72e060a1..db3b16455 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewActivity.java@@ -19,6 +19,7 @@*/package org.openremote.manager.client.assets.asset;+import com.google.gwt.http.client.URL;import com.google.inject.Provider;import org.openremote.manager.client.Environment;import org.openremote.manager.client.app.dialog.JsonEditor;@@ -53,6 +54,7 @@ import org.openremote.model.datapoint.DatapointInterval;import org.openremote.model.datapoint.NumberDatapoint;import org.openremote.model.event.shared.TenantFilter;import org.openremote.model.simulator.SimulatorState;+import org.openremote.model.value.Values;import javax.inject.Inject;import java.util.ArrayList;@@ -275,6 +277,15 @@ public class AssetViewActivitypublic void writeAssetToView() {super.writeAssetToView();view.setIconAndType(asset.getWellKnownType().getIcon(), asset.getType());++ // Build the link manually, shorter result than AssetQueryMapper, and we must hardcode the path anyway+ String query = Values.createObject()+ .put("select", Values.createObject().put("include", Values.create("ALL")))+ .put("id", Values.create(asset.getId()))+ .toJson();+ view.setAccessPublicReadAnchor(+ "/" + asset.getTenantRealm() + "/asset/public/query?q=" + URL.encodeQueryString(query)+ );}protected List<FormButton> createAttributeActions(AssetAttribute attribute, AttributeViewImpl view) {diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.javaindex 10408446d..edd9b95ba 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.java@@ -26,6 +26,7 @@ import com.google.gwt.resources.client.CssResource;import com.google.gwt.uibinder.client.UiBinder;import com.google.gwt.uibinder.client.UiField;import com.google.gwt.uibinder.client.UiHandler;+import com.google.gwt.user.client.Window;import com.google.gwt.user.client.ui.*;import com.google.inject.Provider;import org.openremote.manager.client.Environment;@@ -42,8 +43,6 @@ import org.openremote.manager.client.widget.PushButton;import org.openremote.model.Constants;import org.openremote.model.asset.Asset;import org.openremote.model.asset.AssetType;-import org.openremote.model.attribute.AttributeEvent;-import org.openremote.model.event.bus.EventRegistration;import org.openremote.model.geo.GeoJSON;import org.openremote.model.value.ObjectValue;@@ -128,6 +127,13 @@ public class AssetViewImpl extends Composite implements AssetView {@UiFieldMapWidget mapWidget;+ @UiField+ FormGroup accessPublicReadGroup;+ @UiField+ FormCheckBox accessPublicReadCheckBox;+ @UiField+ FormAnchor accessPublicReadAnchor;+/* ############################################################################ */FlowPanel liveUpdatesNavItem = new FlowPanel();@@ -149,7 +155,6 @@ public class AssetViewImpl extends Composite implements AssetView {final List<AttributeView> attributeViews = new ArrayList<>();protected Presenter presenter;protected Asset asset;- protected EventRegistration<AttributeEvent> eventRegistration;@Injectpublic AssetViewImpl(AssetBrowser assetBrowser,@@ -223,10 +228,9 @@ public class AssetViewImpl extends Composite implements AssetView {mapWidget.setVisible(false);showDroppedPin(GeoJSON.EMPTY_FEATURE_COLLECTION);- if (eventRegistration != null) {- environment.getEventBus().remove(eventRegistration);- eventRegistration = null;- }+ accessPublicReadGroup.setVisible(false);+ accessPublicReadCheckBox.setValue(false);+ accessPublicReadAnchor.setHref("");attributeViews.clear();attributeViewContainer.clear();@@ -329,6 +333,17 @@ public class AssetViewImpl extends Composite implements AssetView {}}+ @Override+ public void setAccessPublicRead(boolean enabled) {+ accessPublicReadGroup.setVisible(enabled);+ accessPublicReadCheckBox.setValue(enabled);+ }++ @Override+ public void setAccessPublicReadAnchor(String path) {+ accessPublicReadAnchor.setHref(Window.Location.getProtocol() + "//" + Window.Location.getHost() + path);+ }+@Overridepublic void setAttributeViews(List<AttributeView> attributeViews) {this.attributeViews.clear();@@ -356,7 +371,6 @@ public class AssetViewImpl extends Composite implements AssetView {@Overridepublic void setIconAndType(String icon, String type) {headline.setIcon(icon);- // TODO: Should unknown/undefined asset type default to customAssetType assetType = AssetType.getByValue(type).orElse(AssetType.CUSTOM);if (assetType == AssetType.CUSTOM) {headline.setSub(type);diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.ui.xml b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.ui.xmlindex 75cfe09b2..418a93aba 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.ui.xml+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetViewImpl.ui.xml@@ -122,6 +122,22 @@</w:actions></w:FormGroup>+ <w:FormGroup ui:field="accessPublicReadGroup">+ <w:label>+ <w:FormLabel text="{managerMessages.publicAccess}"/>+ </w:label>+ <w:field>+ <w:FormField addStyleNames="larger">+ <g:HTMLPanel styleName="layout horizontal center">+ <w:FormCheckBox ui:field="accessPublicReadCheckBox" enabled="false"/>+ <w:FormAnchor ui:field="accessPublicReadAnchor"+ target="_blank"+ text="{managerMessages.shareLink}"/>+ </g:HTMLPanel>+ </w:FormField>+ </w:field>+ </w:FormGroup>+</div><w:MapWidget ui:field="mapWidget"diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/MetaEditor.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/MetaEditor.javaindex 50d0cf248..f5b3386cc 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/MetaEditor.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/MetaEditor.java@@ -299,9 +299,7 @@ public class MetaEditor extends AbstractAttributeViewExtension {}}- metaItemDescriptors.addAll(- Arrays.asList(environment.getSecurityService().isSuperUser() ? AssetMeta.values() : AssetMeta.unRestricted())- );+ metaItemDescriptors.addAll(Arrays.asList(AssetMeta.values())); // TODO Get meta item descriptors from serverthis.metaItemDescriptors = metaItemDescriptors.stream().filter(metaItemDescriptor -> {@@ -349,7 +347,7 @@ public class MetaEditor extends AbstractAttributeViewExtension {protected List<MetaItemEditor> getExistingItemEditors() {return IntStream.range(0, itemListPanel.getWidgetCount())- .mapToObj(i -> (MetaItemEditor)itemListPanel.getWidget(i))+ .mapToObj(i -> (MetaItemEditor) itemListPanel.getWidget(i)).collect(Collectors.toList());}@@ -376,11 +374,15 @@ public class MetaEditor extends AbstractAttributeViewExtension {}protected void onMetaItemTypeChanged(MetaItemEditor itemEditor, boolean updateItem) {- Optional<AssetMeta> assetMeta = AssetMeta.getAssetMeta(itemEditor.nameList.getSelectedValue());-if (updateItem) {itemEditor.item.clearValue();- Value initialValue = assetMeta.map(AssetMeta::getInitialValue).orElse(null);++ // TODO Should use meta item descriptors from server+ Value initialValue = Arrays.stream(AssetMeta.values())+ .filter(assetMeta -> assetMeta.getUrn().equals(itemEditor.nameList.getSelectedValue()))+ .map(MetaItemDescriptor::getInitialValue)+ .findFirst().orElse(null);+ValueType valueType = EnumUtil.enumFromString(ValueType.class, itemEditor.typeList.getSelectedValue()).orElse(null);if (valueType == ValueType.BOOLEAN && initialValue == null) {initialValue = Values.create(false);@@ -484,7 +486,7 @@ public class MetaEditor extends AbstractAttributeViewExtension {List<MetaItemEditor> editors = getExistingItemEditors();IntStream.range(0, editors.size()).forEach(i -> {- MetaItemEditor editor = editors.get(i);+ MetaItemEditor editor = editors.get(i);List<ValidationFailure> failures = !hasMetaFailures ? null : validationResult.getMetaFailures().get(i);updateEditorFailures(editor, failures);}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 d7cdc9808..aa453343f 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@@ -522,4 +522,8 @@ public interface ManagerMessages extends Messages {String refreshDeviceRegistrations();String tenant();++ String publicAccess();++ String shareLink();}diff --git a/manager/client/src/main/java/org/openremote/manager/client/widget/FormAnchor.java b/manager/client/src/main/java/org/openremote/manager/client/widget/FormAnchor.javanew file mode 100644index 000000000..af9919497--- /dev/null+++ b/manager/client/src/main/java/org/openremote/manager/client/widget/FormAnchor.java@@ -0,0 +1,28 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.client.widget;++public class FormAnchor extends com.google.gwt.user.client.ui.Anchor {++ public FormAnchor() {+ setStyleName("or-FormAnchor");+ }++}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 3bf7ffb85..41c150520 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@@ -321,7 +321,9 @@ metaItemDisplayName[FORMAT]=FormatmetaItemDisplayName[DESCRIPTION]=DescriptionmetaItemDisplayName[ABOUT]=AboutmetaItemDisplayName[READ_ONLY]=Read only-metaItemDisplayName[PROTECTED]=Protected+metaItemDisplayName[ACCESS_RESTRICTED_READ]=Restricted read access+metaItemDisplayName[ACCESS_RESTRICTED_WRITE]=Restricted write access+metaItemDisplayName[ACCESS_PUBLIC_READ]=Public read accessmetaItemDisplayName[RANGE_MIN]=Min valuemetaItemDisplayName[RANGE_MAX]=Max valuemetaItemDisplayName[STEP]=Step@@ -410,3 +412,5 @@ refresh=RefreshdeleteNotifications=Delete all notificationsrefreshDeviceRegistrations=Refresh device registrationstenant=Tenant+publicAccess=Public read access+shareLink=Share linkdiff --git a/manager/client/src/main/webapp/css/style.html b/manager/client/src/main/webapp/css/style.htmlindex 0a1172529..7948a70aa 100644--- a/manager/client/src/main/webapp/css/style.html+++ b/manager/client/src/main/webapp/css/style.html@@ -188,7 +188,8 @@margin: 1em 0;}- .or-Hyperlink {+ .or-Hyperlink,+ .or-FormAnchor {display: inline-block;white-space: nowrap;}@@ -198,7 +199,9 @@}.or-Hyperlink a,- .or-Hyperlink a:visited {+ .or-Hyperlink a:visited,+ .or-FormAnchor,+ .or-FormAnchor:visited {cursor: pointer;font-weight: 600;text-decoration: none;@@ -207,8 +210,17 @@border-radius: 0.2em;}+ .or-FormAnchor,+ .or-FormAnchor:visited {+ font-style: italic;+ font-weight: normal;+ text-decoration: underline;+ }+.or-Hyperlink a:hover,- .or-Hyperlink a:focus {+ .or-Hyperlink a:focus,+ .or-FormAnchor:hover,+ .or-FormAnchor:focus {text-decoration: underline;}@@ -330,7 +342,7 @@}.or-FormLabelIcon {- margin: 0.2em 0.4em 0.1em 0.1em;+ margin-right: 0.4em;font-size: 1.2em;opacity: 0.4;align-self: flex-end;diff --git a/manager/client/src/main/webapp/css/theme.html b/manager/client/src/main/webapp/css/theme.htmlindex fd9ee175b..65c21ebe2 100644--- a/manager/client/src/main/webapp/css/theme.html+++ b/manager/client/src/main/webapp/css/theme.html@@ -328,6 +328,11 @@color: var(--theme-mediumgrey);}+ .or-FormAnchor,+ .or-FormAnchor a:visited {+ color: var(--theme-darkgrey);+ }+.or-MainContent {background-color: var(--theme-white);-webkit-box-shadow: 0px 2px 2px 0px rgba(44, 44, 44, 0.4);diff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.javaindex 6f38a0ebc..fdf1fab1d 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@@ -465,7 +465,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(AssetQuery.Include.ALL, false))+ .select(new AssetQuery.Select(AssetQuery.Include.ALL)).attributeMeta(new AssetQuery.AttributeRefPredicate(AssetMeta.AGENT_LINK,@@ -493,7 +493,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(AssetQuery.Include.ALL, false))+ .select(new AssetQuery.Select(AssetQuery.Include.ALL)).attributeMeta(new AssetQuery.AttributeRefPredicate(AssetMeta.AGENT_LINK,@@ -717,7 +717,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Conspublic synchronized Map<String, Asset> getAgents() {if (agentMap == null) {agentMap = assetStorageService.findAll(new AssetQuery()- .select(new AssetQuery.Select(AssetQuery.Include.ALL, false))+ .select(new AssetQuery.Select(AssetQuery.Include.ALL)).type(AssetType.AGENT)).stream().collect(Collectors.toMap(Asset::getId, agent -> agent));diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetAttributeLinkingService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetAttributeLinkingService.javaindex ebc0383ec..1175f71f5 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@@ -218,7 +218,7 @@ public class AssetAttributeLinkingService implements ContainerService, Consumer<ServerAsset asset = assetStorageService.find(new AssetQuery().id(attributeRef.getEntityId())- .select(new AbstractAssetQuery.Select(AbstractAssetQuery.Include.ALL, false, false, attributeRef.getAttributeName()))+ .select(new AbstractAssetQuery.Select(AbstractAssetQuery.Include.ALL, false, attributeRef.getAttributeName())));Optional<AssetAttribute> attribute;diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetModel.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetModel.javanew file mode 100644index 000000000..ebe7ecc2b--- /dev/null+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetModel.java@@ -0,0 +1,89 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.server.asset;++import org.openremote.model.asset.AssetModelProvider;+import org.openremote.model.attribute.MetaItem;+import org.openremote.model.attribute.MetaItemDescriptor;++import java.util.*;+import java.util.logging.Logger;+import java.util.stream.Stream;++import static java.util.stream.Collectors.joining;+import static org.openremote.model.util.TextUtil.isNullOrEmpty;++/**+ * Explore the asset model of this project and access the {@link AssetModelProvider}s through {@link ServiceLoader}.+ */+public class AssetModel {++ private static final Logger LOG = Logger.getLogger(AssetModel.class.getName());++ public final static MetaItemDescriptor[] META_ITEM_DESCRIPTORS;+ public final static String META_ITEM_RESTRICTED_READ_SQL_FRAGMENT;+ public final static String META_ITEM_PUBLIC_READ_SQL_FRAGMENT;++ static {+ List<MetaItemDescriptor> metaItemDescriptorList = new ArrayList<>();+ ServiceLoader.load(AssetModelProvider.class).forEach(assetModelProvider -> {+ LOG.fine("Adding meta item descriptors of: " + assetModelProvider);+ metaItemDescriptorList.addAll(Arrays.asList(assetModelProvider.getMetaItemDescriptors()));+ });+ META_ITEM_DESCRIPTORS = metaItemDescriptorList.toArray(new MetaItemDescriptor[metaItemDescriptorList.size()]);++ META_ITEM_RESTRICTED_READ_SQL_FRAGMENT =+ " ('" + streamMetaItemDescriptors().filter(i -> i.getAccess().restrictedRead).map(MetaItemDescriptor::getUrn).collect(joining("','")) + "')";+ META_ITEM_PUBLIC_READ_SQL_FRAGMENT =+ " ('" + streamMetaItemDescriptors().filter(i -> i.getAccess().publicRead).map(MetaItemDescriptor::getUrn).collect(joining("','")) + "')";+ }++ public static Stream<MetaItemDescriptor> streamMetaItemDescriptors() {+ return Arrays.stream(META_ITEM_DESCRIPTORS);+ }++ public static Optional<MetaItemDescriptor> getMetaItemDescriptor(String urn) {+ if (isNullOrEmpty(urn))+ return Optional.empty();+ for (MetaItemDescriptor metaItemDescriptor : META_ITEM_DESCRIPTORS) {+ if (metaItemDescriptor.getUrn().equals(urn))+ return Optional.of(metaItemDescriptor);+ }+ return Optional.empty();+ }++ public static boolean isMetaItemRestrictedRead(MetaItem metaItem) {+ return getMetaItemDescriptor(metaItem.getName().orElse(null))+ .map(meta -> meta.getAccess().restrictedRead)+ .orElse(false);+ }++ public static boolean isMetaItemRestrictedWrite(MetaItem metaItem) {+ return getMetaItemDescriptor(metaItem.getName().orElse(null))+ .map(meta -> meta.getAccess().restrictedWrite)+ .orElse(false);+ }++ public static boolean isMetaItemPublicRead(MetaItem metaItem) {+ return getMetaItemDescriptor(metaItem.getName().orElse(null))+ .map(meta -> meta.getAccess().publicRead)+ .orElse(false);+ }+}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 2844f9367..f7a346222 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@@ -19,8 +19,6 @@*/package org.openremote.manager.server.asset;-import com.fasterxml.jackson.core.JsonProcessingException;-import org.openremote.container.Container;import org.openremote.container.message.MessageBrokerService;import org.openremote.container.timer.TimerService;import org.openremote.manager.server.security.ManagerIdentityService;@@ -30,10 +28,11 @@ import org.openremote.manager.shared.asset.AssetResource;import org.openremote.manager.shared.http.RequestParams;import org.openremote.manager.shared.security.Tenant;import org.openremote.model.Constants;-import org.openremote.model.ValidationFailure;import org.openremote.model.asset.*;+import org.openremote.model.asset.AbstractAssetQuery.Select;import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.Meta;import org.openremote.model.attribute.MetaItem;import org.openremote.model.util.TextUtil;import org.openremote.model.value.Value;@@ -41,14 +40,15 @@ import org.openremote.model.value.ValueException;import org.openremote.model.value.Values;import javax.ws.rs.WebApplicationException;-import javax.ws.rs.core.Response;+import java.io.IOException;import java.util.*;import java.util.logging.Logger;import static javax.ws.rs.core.Response.Status.*;-import static org.openremote.model.asset.AssetMeta.PROTECTED;+import static org.openremote.container.Container.JSON;+import static org.openremote.model.asset.AbstractAssetQuery.Access.PUBLIC_READ;+import static org.openremote.model.asset.AbstractAssetQuery.Access.RESTRICTED_READ;import static org.openremote.model.attribute.AttributeEvent.Source.CLIENT;-import static org.openremote.model.attribute.MetaItem.mergeMeta;import static org.openremote.model.util.TextUtil.isNullOrEmpty;public class AssetResourceImpl extends ManagerWebResource implements AssetResource {@@ -85,7 +85,9 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour}List<ServerAsset> assets = assetStorageService.findAll(- new AssetQuery().select(new AbstractAssetQuery.Select(AbstractAssetQuery.Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES, true)).userId(getUserId())+ new AssetQuery().select(+ new Select(AbstractAssetQuery.Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES, RESTRICTED_READ)+ ).userId(getUserId()));// Filter assets that might have been moved into a different realm and can no longer be accessed by user@@ -101,7 +103,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour}return assets.toArray(new ServerAsset[assets.size()]);} catch (IllegalStateException ex) {- throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);+ throw new WebApplicationException(ex, BAD_REQUEST);}}@@ -124,7 +126,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourreturn assetStorageService.findUserAssets(realmId, userId, assetId).toArray(new UserAsset[0]);} catch (IllegalStateException ex) {- throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);+ throw new WebApplicationException(ex, BAD_REQUEST);}}@@ -148,6 +150,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourreturn;}+ // Restricted users or regular users in a different realm can not create linksif (isRestrictedUser()|| !getAuthenticatedTenant().getId().equals(realmId))throw new WebApplicationException(FORBIDDEN);@@ -165,6 +168,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourreturn;}+ // Restricted users or regular users in a different realm can not delete linksif (isRestrictedUser()|| !getAuthenticatedTenant().getId().equals(realmId))throw new WebApplicationException(FORBIDDEN);@@ -180,9 +184,9 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour// Check restrictedif (isRestrictedUser()) {if (!assetStorageService.isUserAsset(getUserId(), assetId)) {- throw new WebApplicationException(Response.Status.FORBIDDEN);+ throw new WebApplicationException(FORBIDDEN);}- asset = assetStorageService.find(assetId, true, true);+ asset = assetStorageService.find(assetId, true, RESTRICTED_READ);} else {asset = assetStorageService.find(assetId, true);}@@ -192,136 +196,123 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourif (!isTenantActiveAndAccessible(asset)) {LOG.fine("Forbidden access for user '" + getUsername() + "': " + asset);- throw new WebApplicationException(Response.Status.FORBIDDEN);+ throw new WebApplicationException(FORBIDDEN);}return asset;} catch (IllegalStateException ex) {- throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);+ throw new WebApplicationException(ex, BAD_REQUEST);}}@Overridepublic void update(RequestParams requestParams, String assetId, Asset asset) {try {- ServerAsset serverAsset;- // Check restricted- if (isRestrictedUser()) {- if (!assetStorageService.isUserAsset(getUserId(), assetId)) {- throw new WebApplicationException(Response.Status.FORBIDDEN);- }+ ServerAsset serverAsset = assetStorageService.find(assetId, true);+ if (serverAsset == null)+ throw new WebApplicationException(NOT_FOUND);- serverAsset = assetStorageService.find(assetId, true);+ // Current and new realm of asset must be accessible+ if (!isTenantActiveAndAccessible(serverAsset) || !isTenantActiveAndAccessible(asset)) {+ LOG.fine("Current or new tenant not accessible by user '" + getUsername() + "', can't update: " + serverAsset);+ throw new WebApplicationException(FORBIDDEN);+ }- if (serverAsset == null)- throw new WebApplicationException(NOT_FOUND);+ boolean isRestrictedUser = isRestrictedUser();++ // The asset that will ultimately be stored (override/ignore some values for restricted users)+ ServerAsset resultAsset = ServerAsset.map(+ asset,+ serverAsset,+ isRestrictedUser ? serverAsset.getName() : null, // TODO We could allow restricted users to update names?+ isRestrictedUser ? serverAsset.getRealmId() : null, // Restricted users can not change realm+ isRestrictedUser ? serverAsset.getParentId() : null, // Restricted users can not change realm+ serverAsset.getType(), // The type an never change+ null, // Anybody can set a new location+ isRestrictedUser ? serverAsset.isAccessPublicRead() : null, // Restricted user can not change access public flag+ isRestrictedUser ? serverAsset.getAttributes() : null // Restricted users need manual attribute merging (see below)+ );- //Restricted users don't have permission to update an asset to become a root asset- if (isNullOrEmpty(asset.getRealmId())) {- throw new WebApplicationException("RealmId is missing", BAD_REQUEST);- }+ // For restricted users, merge existing and updated attributes depending on write permissions+ if (isRestrictedUser) {- if (isNullOrEmpty(asset.getParentId())) {- throw new WebApplicationException("ParentId is missing", BAD_REQUEST);+ if (!assetStorageService.isUserAsset(getUserId(), assetId)) {+ throw new WebApplicationException(FORBIDDEN);}- //Add/Update check+ // Merge updated with existing attributesfor (AssetAttribute updatedAttribute : asset.getAttributesList()) {- //Restricted users may only add protected attributes- if (!updatedAttribute.isProtected()) {- updatedAttribute.addMeta(new MetaItem(PROTECTED, Values.create(true)));- }- Optional<Long> timestamp = updatedAttribute.getValueTimestamp();- if (!timestamp.isPresent() || timestamp.get() <= 0) {- updatedAttribute.setValueTimestamp(timerService.getCurrentTimeMillis());- }+ // Proper validation happens on merge(), here we only need the name to continue+ String updatedAttributeName =+ updatedAttribute.getName().orElseThrow(() -> new IllegalStateException("Missing attribute name"));- String updatedAttributeName = updatedAttribute- .getName()- .orElseThrow(() -> new WebApplicationException("No name supplied for attribute(s)", BAD_REQUEST));- Optional<AssetAttribute> serverAttribute = serverAsset.getAttribute(updatedAttributeName);-- //Check if attribute is present on the asset in storage+ // Check if attribute is present on the asset in storage+ Optional<AssetAttribute> serverAttribute = resultAsset.getAttribute(updatedAttributeName);if (serverAttribute.isPresent()) {- AssetAttribute attr = serverAttribute.get();+ AssetAttribute existingAttribute = serverAttribute.get();- if (attr.isProtected()) {- List<ValidationFailure> validationFailures = updatedAttribute.getValidationFailures();- if (!validationFailures.isEmpty()) {- LOG.fine(String.format("MetaItems validation failures: %s", Container.JSON.writeValueAsString(validationFailures)));- throw new WebApplicationException(String.format("MetaItems validation failures: %s", Container.JSON.writeValueAsString(validationFailures)), BAD_REQUEST);- }- //check if non protected write items are modified- updatedAttribute.getMetaStream().filter(metaItem -> !AssetMeta.isMetaItemProtectedWritable(metaItem)).forEach(metaItem -> {- attr.getMetaItem(metaItem.getName().orElse(null)).ifPresent(serverMetaItem -> {- if (!metaItem.getObjectValue().equalsIgnoreKeys(serverMetaItem.getObjectValue())) {- throw new WebApplicationException("MetaItems should be protected write", BAD_REQUEST);- }- });-- });-- mergeMeta(attr.getMeta(), updatedAttribute.getMeta(), false);- updatedAttribute.setMeta(attr.getMeta());- serverAsset.replaceAttribute(updatedAttribute);- } else {- throw new WebApplicationException("Attribute is already present as private", Response.Status.CONFLICT);+ // If the existing attribute is not writable by restricted client, ignore it+ if (!existingAttribute.isAccessRestrictedWrite()) {+ LOG.fine("Existing attribute not writable by restricted client, ignoring update of: " + updatedAttributeName);+ continue;}++ // Merge updated with existing meta items (modifying a copy)+ Meta updatedMetaItems = updatedAttribute.getMeta();+ Meta existingMetaItems = existingAttribute.getMeta().copy();++ // Remove any writable existing meta items+ existingMetaItems.removeIf(AssetModel::isMetaItemRestrictedWrite);++ // Add any writable updated meta items+ updatedMetaItems.stream().filter(AssetModel::isMetaItemRestrictedWrite).forEach(existingMetaItems::add);++ // Replace existing with updated attribute+ updatedAttribute.setMeta(existingMetaItems);+ resultAsset.replaceAttribute(updatedAttribute);+} else {- //If not present, then add the attribute- if (updatedAttribute.getMetaStream().filter(metaItem ->- !metaItem.getName().orElseThrow(() -> new IllegalStateException("No name found on meta item")).equalsIgnoreCase(PROTECTED.getUrn()))- .anyMatch(metaItem -> !AssetMeta.isMetaItemProtectedWritable(metaItem))) {- throw new WebApplicationException("MetaItems should be protected write", BAD_REQUEST);- }- serverAsset.addAttributes(updatedAttribute);- }- }- //Removal check- serverAsset.getAttributesList().removeIf(serverAttribute ->- serverAttribute.getName().isPresent() && !asset.hasAttribute(serverAttribute.getName().get()) && serverAttribute.isProtected()- );- } else {- serverAsset = assetStorageService.find(assetId, true);- if (serverAsset == null)- throw new WebApplicationException(NOT_FOUND);- }+ // An attribute added by a restricted user can only have meta items which are writable+ updatedAttribute.getMetaStream().forEach(metaItem -> {+ if (!AssetModel.isMetaItemRestrictedWrite(metaItem)) {+ LOG.fine("Attribute has " + metaItem + " not writable by restricted client: " + updatedAttributeName);+ throw new WebApplicationException(+ "Attribute has meta item not writable by restricted client: " + updatedAttributeName,+ BAD_REQUEST+ );+ }+ });- //TODO move checks to optimise flow. Check if it could be easier- Tenant tenant = identityService.getIdentityProvider().getTenantForRealmId(asset.getRealmId());- if (tenant == null)- throw new WebApplicationException(BAD_REQUEST);+ // An attribute added by a restricted user must be readable by restricted users+ if (!updatedAttribute.isAccessRestrictedRead()) {+ updatedAttribute.addMeta(new MetaItem(AssetMeta.ACCESS_RESTRICTED_READ, Values.create(true)));+ }- // Check old realm, must be accessible- if (!isTenantActiveAndAccessible(tenant)) {- LOG.fine("Forbidden access for user '" + getUsername() + "', can't update: " + serverAsset);- throw new WebApplicationException(Response.Status.FORBIDDEN);- }+ // An attribute added by a restricted user must be writable by restricted users+ if (!updatedAttribute.isAccessRestrictedWrite()) {+ updatedAttribute.addMeta(new MetaItem(AssetMeta.ACCESS_RESTRICTED_WRITE, Values.create(true)));+ }- ServerAsset updatedAsset;- // When restricted user the asset is mapped manually- if (!isRestrictedUser()) {- // Map into server-side asset, do not allow to change the type- updatedAsset = ServerAsset.map(asset, serverAsset, null, serverAsset.getType(), null);- } else {- updatedAsset = serverAsset;- }+ // Add the new attribute+ resultAsset.addAttributes(updatedAttribute);+ }+ }- // Check new realm- if (!isTenantActiveAndAccessible(updatedAsset)) {- LOG.fine("Forbidden access for user '" + getUsername() + "', can't update: " + serverAsset);- throw new WebApplicationException(Response.Status.FORBIDDEN);+ // Remove missing attributes+ resultAsset.getAttributesList().removeIf(existingAttribute ->+ existingAttribute.getName().isPresent()+ && !asset.hasAttribute(existingAttribute.getName().get()) && existingAttribute.isAccessRestrictedWrite()+ );}- assetStorageService.merge(updatedAsset, isRestrictedUser() ? getUsername() : null);+ // Store the result+ assetStorageService.merge(resultAsset, isRestrictedUser ? getUsername() : null);} catch (IllegalStateException ex) {- throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);- } catch (JsonProcessingException ex) {- throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR);+ throw new WebApplicationException(ex, BAD_REQUEST);}}@@ -351,7 +342,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourcase ILLEGAL_SOURCE:case NO_AUTH_CONTEXT:case INSUFFICIENT_ACCESS:- throw new WebApplicationException(Response.Status.FORBIDDEN);+ throw new WebApplicationException(FORBIDDEN);case ASSET_NOT_FOUND:case ATTRIBUTE_NOT_FOUND:throw new WebApplicationException(NOT_FOUND);@@ -369,7 +360,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour}} catch (IllegalStateException ex) {- throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);+ throw new WebApplicationException(ex, BAD_REQUEST);}}@@ -377,7 +368,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourpublic Asset create(RequestParams requestParams, Asset asset) {try {if (isRestrictedUser()) {- throw new WebApplicationException(Response.Status.FORBIDDEN);+ throw new WebApplicationException(FORBIDDEN);}// If there was no realm provided (create was called by regular user in manager UI), use the auth realm@@ -387,7 +378,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourif (!isTenantActiveAndAccessible(asset)) {LOG.fine("Forbidden access for user '" + getUsername() + "', can't create: " + asset);- throw new WebApplicationException(Response.Status.FORBIDDEN);+ throw new WebApplicationException(FORBIDDEN);}ServerAsset serverAsset = ServerAsset.map(asset, new ServerAsset());@@ -406,7 +397,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourreturn assetStorageService.merge(serverAsset);} catch (IllegalStateException ex) {- throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);+ throw new WebApplicationException(ex, BAD_REQUEST);}}@@ -414,26 +405,26 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourpublic void delete(RequestParams requestParams, String assetId) {try {if (isRestrictedUser()) {- throw new WebApplicationException(Response.Status.FORBIDDEN);+ throw new WebApplicationException(FORBIDDEN);}- ServerAsset asset = assetStorageService.find(assetId, true, false);+ ServerAsset asset = assetStorageService.find(assetId, true);if (asset == null)return;if (!isTenantActiveAndAccessible(asset)) {LOG.fine("Forbidden access for user '" + getUsername() + "', can't delete: " + asset);- throw new WebApplicationException(Response.Status.FORBIDDEN);+ throw new WebApplicationException(FORBIDDEN);}if (!assetStorageService.delete(assetId)) {throw new WebApplicationException(BAD_REQUEST);}} catch (IllegalStateException ex) {- throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);+ throw new WebApplicationException(ex, BAD_REQUEST);}}@Override- public Asset[] queryAssets(RequestParams requestParams, AbstractAssetQuery query) {+ public Asset[] queryAssets(RequestParams requestParams, AssetQuery query) {try {if (query == null) {return EMPTY_ASSETS;@@ -441,7 +432,9 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourif (isRestrictedUser()) {query = query.userId(getUserId());- query.select.filterProtected(true);+ if (query.select == null)+ query.select = new Select();+ query.select.filterAccess(RESTRICTED_READ);}Tenant tenant = query.tenantPredicate != null@@ -469,12 +462,12 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourreturn result.toArray(new Asset[result.size()]);} catch (IllegalStateException ex) {- throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);+ throw new WebApplicationException(ex, BAD_REQUEST);}}@Override- public Asset[] queryPublicAssets(RequestParams requestParams, AbstractAssetQuery query) {+ public Asset[] queryPublicAssets(RequestParams requestParams, AssetQuery query) {String requestRealm = getRequestRealm();@@ -489,21 +482,29 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourquery.tenantPredicate.realm = requestRealm;}- // Set public only flag+ // Force public access filter on queryif (query.select == null) {- query.select(new AssetQuery.Select().publicOnly(true));+ query.select(new Select().filterAccess(PUBLIC_READ));} else {- query.select.publicOnly = true;+ query.select.filterAccess(PUBLIC_READ);}- // Limit to protected attributes and meta items- query.select.filterProtected = true;-try {List<ServerAsset> result = assetStorageService.findAll(query);return result.toArray(new Asset[result.size()]);} catch (IllegalStateException ex) {- throw new WebApplicationException(ex, Response.Status.BAD_REQUEST);+ throw new WebApplicationException(ex, BAD_REQUEST);+ }+ }++ @Override+ public Asset[] queryPublicAssets(RequestParams requestParams, String q) {+ AssetQuery assetQuery;+ try {+ assetQuery = JSON.readValue(q, AssetQuery.class);+ } catch (IOException ex) {+ throw new WebApplicationException("Error parsing query parameter 'q' as JSON object", BAD_REQUEST);}+ return queryPublicAssets(requestParams, assetQuery);}}diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetRoute.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetRoute.javaindex d0f57a745..4939c067a 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetRoute.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetRoute.java@@ -179,8 +179,8 @@ public final class AssetRoute {if (!assetStorageService.isUserAsset(authContext.getUserId(), event.getEntityId())) {throw new AssetProcessingException(Reason.INSUFFICIENT_ACCESS);}- // Must be protected attributes- if (!attribute.isProtected()) {+ // Must be writable by restricted client+ if (!attribute.isAccessRestrictedWrite()) {throw new AssetProcessingException(Reason.INSUFFICIENT_ACCESS);}}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 c7c1b8ea1..40dab9215 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,6 +39,8 @@ import org.openremote.manager.shared.security.User;import org.openremote.model.Constants;import org.openremote.model.ValidationFailure;import org.openremote.model.asset.*;+import org.openremote.model.asset.AbstractAssetQuery.OrderBy;+import org.openremote.model.asset.AbstractAssetQuery.Select;import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.event.shared.TenantFilter;import org.openremote.model.util.TextUtil;@@ -60,6 +62,10 @@ import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_import static org.openremote.manager.server.asset.AssetRoute.isPersistenceEventForEntityType;import static org.openremote.manager.server.event.ClientEventService.CLIENT_EVENT_TOPIC;import static org.openremote.manager.server.event.ClientEventService.getSessionKey;+import static org.openremote.model.asset.AbstractAssetQuery.Access.PRIVATE_READ;+import static org.openremote.model.asset.AbstractAssetQuery.Access.RESTRICTED_READ;+import static org.openremote.model.asset.AbstractAssetQuery.Include.ALL;+import static org.openremote.model.asset.AbstractAssetQuery.Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES;import static org.openremote.model.util.TextUtil.isNullOrEmpty;public class AssetStorageService extends RouteBuilder implements ContainerService, Consumer<AssetState> {@@ -86,22 +92,6 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicprotected PersistenceService persistenceService;protected ManagerIdentityService identityService;protected ClientEventService clientEventService;- protected static final String protectedAssetMetaClause; // Maybe these should be in the DB-- static {- StringBuilder sb = new StringBuilder(" ('");- sb.append(- String.join(- "','",- Arrays.stream(AssetMeta.values())- .filter(am -> am.getAccess().protectedRead)- .map(AssetMeta::getUrn)- .toArray(String[]::new)- )- );- sb.append("')");- protectedAssetMetaClause = sb.toString();- }@Overridepublic void init(Container container) throws Exception {@@ -197,7 +187,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicServerAsset asset = find(event.getAssetId(),true,- identityService.getIdentityProvider().isRestrictedUser(authContext.getUserId()) // Restricted users get filtered state+ identityService.getIdentityProvider().isRestrictedUser(authContext.getUserId()) ? RESTRICTED_READ : PRIVATE_READ);if (asset != null) {replyWithAttributeEvents(sessionKey, asset, event.getAttributeNames());@@ -218,17 +208,17 @@ 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 ? AssetQuery.Include.ALL : AssetQuery.Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES, false)).id(assetId));+ return find(new AssetQuery().select(new Select(loadComplete ? ALL : ALL_EXCEPT_PATH_AND_ATTRIBUTES)).id(assetId));}/**- * @param loadComplete If the whole asset data (including path and attributes) should be loaded.- * @param filterProtected If the asset attributes should be filtered and only protected details included.+ * @param loadComplete If the whole asset data (including path and attributes) should be loaded.+ * @param access The required access permissions of the asset data.*/- public ServerAsset find(String assetId, boolean loadComplete, boolean filterProtected) {+ public ServerAsset find(String assetId, boolean loadComplete, AbstractAssetQuery.Access access) {if (assetId == null)throw new IllegalArgumentException("Can't query null asset identifier");- return find(new AssetQuery().select(new AssetQuery.Select(loadComplete ? AssetQuery.Include.ALL : AssetQuery.Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES, filterProtected)).id(assetId));+ return find(new AssetQuery().select(new Select(loadComplete ? ALL : ALL_EXCEPT_PATH_AND_ATTRIBUTES, access)).id(assetId));}public ServerAsset find(AbstractAssetQuery query) {@@ -309,7 +299,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic// Validate parentif (asset.getParentId() != null) {// If this is a not a root asset...- ServerAsset parent = find(em, asset.getParentId(), true, false);+ ServerAsset parent = find(em, asset.getParentId(), true);// .. the parent must existif (parent == null)throw new IllegalStateException("Parent not found: " + asset.getParentId());@@ -344,7 +334,6 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicthrow new IllegalStateException("Storing asset failed, invalid attributes: " + invalid);}-// If this is real merge and desired, copy the persistent version number over the detached// version, so the detached state always wins and this update will go through and ignore// concurrent updates@@ -421,7 +410,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic"select ua from UserAsset ua where ua.id.realmId = :realmId and ua.id.userId = :userId order by ua.createdOn desc", UserAsset.class).setParameter("realmId", realmId).setParameter("userId", userId).getResultList();- } else if (isNullOrEmpty(userId)){+ } else if (isNullOrEmpty(userId)) {return entityManager.createQuery("select ua from UserAsset ua where ua.id.realmId = :realmId and ua.id.assetId = :assetId order by ua.createdOn desc", UserAsset.class).setParameter("realmId", realmId).setParameter("assetId", assetId).getResultList();@@ -503,10 +492,19 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicvoid acceptStatement(PreparedStatement st) throws SQLException;}- protected ServerAsset find(EntityManager em, String assetId, boolean loadComplete, boolean filterProtected) {+ protected ServerAsset find(EntityManager em, String assetId, boolean loadComplete) {+ return find(em, assetId, loadComplete, PRIVATE_READ);+ }++ protected ServerAsset find(EntityManager em, String assetId, boolean loadComplete, AbstractAssetQuery.Access access) {if (assetId == null)throw new IllegalArgumentException("Can't query null asset identifier");- return find(em, new AssetQuery().select(new AssetQuery.Select(loadComplete ? AssetQuery.Include.ALL : AssetQuery.Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES, filterProtected)).id(assetId));+ return find(+ em,+ new AssetQuery().select(+ new Select(loadComplete ? ALL : ALL_EXCEPT_PATH_AND_ATTRIBUTES, access)+ ).id(assetId)+ );}public ServerAsset find(EntityManager em, AbstractAssetQuery query) {@@ -521,6 +519,19 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic}protected List<ServerAsset> findAll(EntityManager em, AbstractAssetQuery query) {++ // Use a default projection if it's missing+ if (query.select == null)+ query.select = new Select();+ if (query.select.include == null)+ query.select.include = ALL_EXCEPT_PATH_AND_ATTRIBUTES;+ if (query.select.access == null)+ query.select.access = PRIVATE_READ;++ // Default to order by creation date if the query may return multiple results+ if (query.orderBy == null && query.id == null)+ query.orderBy = new OrderBy(OrderBy.Property.CREATED_ON);+PreparedAssetQuery querySql = buildQuery(query);return em.unwrap(Session.class).doReturningWork(new AbstractReturningWork<List<ServerAsset>>() {@@ -542,6 +553,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic}protected PreparedAssetQuery buildQuery(AbstractAssetQuery query) {+ LOG.fine("Building: " + query);StringBuilder sb = new StringBuilder();boolean recursive = query.select.recursive;List<ParameterBinder> binders = new ArrayList<>();@@ -572,11 +584,11 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicStringBuilder sb = new StringBuilder();AssetQuery.Include include = query.select.include;boolean recursive = query.select.recursive;- boolean includeMainProperties = include == AssetQuery.Include.ALL ||+ boolean includeMainProperties = include == ALL ||include == AssetQuery.Include.ALL_EXCEPT_PATH ||- include == AssetQuery.Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES;+ include == ALL_EXCEPT_PATH_AND_ATTRIBUTES;- sb.append("select A.ID as ID, A.NAME as NAME");+ sb.append("select A.ID as ID, A.NAME as NAME, A.ACCESS_PUBLIC_READ as ACCESS_PUBLIC_READ");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");@@ -598,20 +610,20 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic}if (!recursive || level == 3) {- if (include == AssetQuery.Include.ALL) {+ if (include == ALL) {sb.append(", get_asset_tree_path(A.ID) as PATH");} else {sb.append(", NULL as PATH");}}- if (include != AssetQuery.Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES) {+ if (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));+ sb.append(buildAttributeSelect(query.select.attributeNames, query.select.access, namesOnly, binders));}} else {sb.append(", NULL as ATTRIBUTES");@@ -620,9 +632,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicreturn sb.toString();}- protected String buildAttributeSelect(String[] attributeNames, boolean filterProtected, boolean namesOnly, List<ParameterBinder> binders) {-- if (attributeNames == null && !filterProtected && !namesOnly) {+ protected String buildAttributeSelect(String[] attributeNames, AbstractAssetQuery.Access access, boolean namesOnly, List<ParameterBinder> binders) {+ if (attributeNames == null && access == PRIVATE_READ && !namesOnly) {return ", A.ATTRIBUTES as ATTRIBUTES";}@@ -636,21 +647,21 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicsb.append(" where AM.VALUE #>> '{name}' = '");sb.append(AssetMeta.LABEL.getUrn());sb.append("'))) from jsonb_each(A.attributes) as AX");- if (filterProtected) {- // Use implicit inner join on meta array set to only select attributes with a protected=true meta item+ if (access != PRIVATE_READ) {+ // Use implicit inner join on meta array set to only select non-private attributessb.append(", jsonb_array_elements(AX.VALUE #> '{meta}') as AM");}- } else if (filterProtected) {+ } else if (access != PRIVATE_READ) {// Use sub-select for processing the attributes the meta inside each attribute is replaced with filtered meta// (coalesce null to empty array because jsonb_set() with null will clear the whole object)sb.append("select json_object_agg(AX.key, jsonb_set(AX.value, '{meta}', coalesce(AMF.VALUE, jsonb_build_array()), 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+ // Use implicit inner join on meta array set to only select attributes with a non-private access meta itemsb.append(", jsonb_array_elements(AX.VALUE #> '{meta}') as AM");- // Use subquery to filter out meta items not marked as protected+ // Use subquery to filter out meta items not marked as non-private accesssb.append(" INNER JOIN LATERAL (");sb.append("select jsonb_agg(AM.value) AS VALUE from jsonb_array_elements(AX.VALUE #> '{meta}') as AM");sb.append(" where AM.VALUE #>> '{name}' IN");- sb.append(protectedAssetMetaClause);+ sb.append(access == RESTRICTED_READ ? AssetModel.META_ITEM_RESTRICTED_READ_SQL_FRAGMENT : AssetModel.META_ITEM_PUBLIC_READ_SQL_FRAGMENT);sb.append(") as AMF ON true");} else {sb.append("select json_object_agg(AX.key, AX.value) from jsonb_each(A.attributes) as AX");@@ -669,13 +680,13 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicsb.append(") ");}- if (filterProtected) {- // Filter protected Attributes- AssetQuery.AttributeMetaPredicate protectedPredicate =+ if (access != PRIVATE_READ) {+ // Filter non-private access attributes+ AssetQuery.AttributeMetaPredicate accessPredicate =new AssetQuery.AttributeMetaPredicate()- .itemName(AssetMeta.PROTECTED)+ .itemName(access == RESTRICTED_READ ? AssetMeta.ACCESS_RESTRICTED_READ: AssetMeta.ACCESS_PUBLIC_READ).itemValue(new AssetQuery.BooleanPredicate(true));- sb.append(buildAttributeMetaFilter(protectedPredicate, binders));+ sb.append(buildAttributeMetaFilter(accessPredicate, binders));}sb.append(") AS ATTRIBUTES");@@ -820,14 +831,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicbinders.add(st -> st.setString(pos, query.userId));}- if (level == 1 && query.select.publicOnly) {- // TODO: Change this once public asset mechanism is finalised- AbstractAssetQuery.StringPredicate publicPredicate =- new AbstractAssetQuery.StringPredicate(AbstractAssetQuery.Match.BEGIN, false, "urn:openremote:public:");- sb.append(publicPredicate.caseSensitive ? " and A.ASSET_TYPE " : " and upper(A.ASSET_TYPE)");- sb.append(publicPredicate.match == AssetQuery.Match.EXACT ? " = ?" : " like ?");- final int pos = binders.size() + 1;- binders.add(st -> st.setString(pos, publicPredicate.prepareValue()));+ if (level == 1 && query.select.access == AbstractAssetQuery.Access.PUBLIC_READ) {+ sb.append(" and A.ACCESS_PUBLIC_READ is true");}if (query.type != null) {@@ -837,7 +842,6 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicbinders.add(st -> st.setString(pos, query.type.prepareValue()));}-if (query.attributeMetaPredicate != null) {String attributeMetaFilter = buildAttributeMetaFilter(query.attributeMetaPredicate, binders);@@ -1045,6 +1049,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicServerAsset asset = new ServerAsset();asset.setId(rs.getString("ID"));asset.setName(rs.getString("NAME"));+ asset.setAccessPublicRead(rs.getBoolean("ACCESS_PUBLIC_READ"));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));@@ -1055,7 +1060,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServiccase 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("ID"), rs.getLong("OBJ_VERSION"), rs.getTimestamp("CREATED_ON"), rs.getString("NAME"),+ rs.getString("ASSET_TYPE"), rs.getBoolean("ACCESS_PUBLIC_READ"),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"));diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAsset.java b/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAsset.javaindex 7641b4b2a..59cd61b27 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAsset.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAsset.java@@ -53,26 +53,32 @@ public class ServerAsset extends Asset {* Easy conversion between types, we copy all properties (not a deep copy!)*/public static ServerAsset map(Asset asset, ServerAsset serverAsset) {- return map(asset, serverAsset, null, null, null);+ return map(asset, serverAsset, null, null, null, null, null, null, null);}public static ServerAsset map(Asset asset, ServerAsset serverAsset,+ String overrideName,+ String overrideRealmId,String overrideParentId,String overrideType,- Double[] overrideLocation) {+ Double[] overrideLocation,+ Boolean overrideAccessPublicRead,+ ObjectValue overrideAttributes) {serverAsset.setVersion(asset.getVersion());- serverAsset.setName(asset.getName());+ serverAsset.setName(overrideName != null ? overrideName : asset.getName());if (overrideType != null) {serverAsset.setType(overrideType);} else {serverAsset.setType(asset.getType());}+ serverAsset.setAccessPublicRead(overrideAccessPublicRead != null ? overrideAccessPublicRead : asset.isAccessPublicRead());+serverAsset.setParentId(overrideParentId != null ? overrideParentId : asset.getParentId());serverAsset.setParentName(null);serverAsset.setParentType(null);- serverAsset.setRealmId(asset.getRealmId());+ serverAsset.setRealmId(overrideRealmId != null ? overrideRealmId : asset.getRealmId());serverAsset.setTenantRealm(null);serverAsset.setTenantDisplayName(null);@@ -92,7 +98,7 @@ public class ServerAsset extends Asset {serverAsset.setLocation(null);}- serverAsset.setAttributes(asset.getAttributes());+ serverAsset.setAttributes(overrideAttributes != null ? overrideAttributes : asset.getAttributes());return serverAsset;}@@ -106,13 +112,13 @@ public class ServerAsset extends Asset {}@SuppressWarnings("unchecked")- public ServerAsset(String id, long version, Date createdOn, String name, String type,+ public ServerAsset(String id, long version, Date createdOn, String name, String type, boolean accessPublicRead,String parentId, String parentName, String parentType,String realmId, String tenantRealm, String tenantDisplayName,Object location,Array path, String attributes) throws SQLException {super(- id, version, createdOn, name, type,+ id, version, createdOn, name, type, accessPublicRead,parentId, parentName, parentType,realmId, tenantRealm, tenantDisplayName,path != null ? (String[]) path.getArray() : null,@@ -126,7 +132,7 @@ public class ServerAsset extends Asset {if (location != null) {Geometry geomPoint = PGGeometryTypeDescriptor.toGeometry(location);if (geomPoint instanceof org.geolatte.geom.Point) {- position = (Point)JTS.to(geomPoint);+ position = (Point) JTS.to(geomPoint);}}@@ -138,7 +144,7 @@ public class ServerAsset extends Asset {}public ServerAsset(@NotNull String name, @NotNull String type) {- this(name, type, null, null);+ this(name, type, false, null, null);}public ServerAsset(@NotNull String name, @NotNull AssetType type, Asset parent) {@@ -146,15 +152,15 @@ public class ServerAsset extends Asset {}public ServerAsset(@NotNull String name, @NotNull String type, Asset parent) {- this(name, type, parent, null);+ this(name, type, false, parent, null);}public ServerAsset(@NotNull String name, @NotNull AssetType type, Asset parent, String realmId) {super(name, type, parent, realmId);}- public ServerAsset(@NotNull String name, @NotNull String type, Asset parent, String realmId) {- super(name, type, parent, realmId);+ public ServerAsset(@NotNull String name, @NotNull String type, boolean accessPublicRead, Asset parent, String realmId) {+ super(name, type, accessPublicRead, parent, realmId);}public Point getLocation() {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 dd8851820..974e5532a 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@@ -607,6 +607,8 @@ public class RulesEngine<T extends Ruleset> {@Overridepublic List<String> getResults() {+ if (this.select == null)+ this.select = new Select();Include oldValue = this.select.include;this.select.include = Include.ONLY_ID_AND_NAME;try {diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/AbstractManagerSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/AbstractManagerSetup.javaindex 29cfbad9e..b6a4ea9d1 100644--- a/manager/server/src/main/java/org/openremote/manager/server/setup/AbstractManagerSetup.java+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/AbstractManagerSetup.java@@ -78,7 +78,7 @@ public abstract class AbstractManagerSetup implements Setup {.setMeta(new Meta(new MetaItem(LABEL, Values.create("Alarm enabled")),new MetaItem(DESCRIPTION, Values.create("Send notifications when presence is detected")),- new MetaItem(PROTECTED, Values.create(true)),+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),new MetaItem(RULE_STATE, Values.create(true)),new MetaItem(SHOW_ON_DASHBOARD, Values.create(true)))),@@ -86,7 +86,7 @@ public abstract class AbstractManagerSetup implements Setup {.setMeta(new Meta(new MetaItem(LABEL, Values.create("Presence detected")),new MetaItem(DESCRIPTION, Values.create("Presence detected in any room")),- new MetaItem(PROTECTED, Values.create(true)),+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),new MetaItem(RULE_STATE, Values.create(true)),new MetaItem(RULE_EVENT, Values.create(true)),new MetaItem(STORE_DATA_POINTS, Values.create(true)),@@ -96,20 +96,20 @@ public abstract class AbstractManagerSetup implements Setup {.setMeta(new Meta(new MetaItem(LABEL, Values.create("Vacation until")),new MetaItem(DESCRIPTION, Values.create("Vacation mode enabled until")),- new MetaItem(PROTECTED, Values.create(true)),+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),new MetaItem(RULE_STATE, Values.create(true)))),new AssetAttribute("autoSceneSchedule", AttributeType.BOOLEAN, Values.create(true)).setMeta(new MetaItem(LABEL, Values.create("Automatic scene schedule")),new MetaItem(DESCRIPTION, Values.create("Predict presence and automatically adjust scene schedule")),- new MetaItem(PROTECTED, Values.create(true)),+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),new MetaItem(RULE_STATE, Values.create(true))),new AssetAttribute("lastExecutedScene", AttributeType.STRING, Values.create("HOME")).setMeta(new MetaItem(LABEL, Values.create("Last executed scene")),- new MetaItem(PROTECTED, Values.create(true)),+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),new MetaItem(READ_ONLY, Values.create(true)),new MetaItem(RULE_STATE, Values.create(true)),new MetaItem(SHOW_ON_DASHBOARD, Values.create(true))@@ -117,7 +117,7 @@ public abstract class AbstractManagerSetup implements Setup {new AssetAttribute("lastDetectedScene", AttributeType.STRING, Values.create("home")).setMeta(new MetaItem(LABEL, Values.create("Last detecteded scene by rules")),- new MetaItem(PROTECTED, Values.create(true)),+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),new MetaItem(READ_ONLY, Values.create(true)),new MetaItem(RULE_STATE, Values.create(true)),new MetaItem(SHOW_ON_DASHBOARD, Values.create(true))@@ -149,7 +149,7 @@ public abstract class AbstractManagerSetup implements Setup {new MetaItem(DESCRIPTION, Values.create("Someone is moving or resting in the room")),new MetaItem(RULE_STATE, Values.create(true)),new MetaItem(RULE_EVENT, Values.create(true)),- new MetaItem(PROTECTED, Values.create(true)),+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),new MetaItem(STORE_DATA_POINTS, Values.create(true)),new MetaItem(SHOW_ON_DASHBOARD, Values.create(true))),@@ -157,13 +157,13 @@ public abstract class AbstractManagerSetup implements Setup {.setMeta(new MetaItem(LABEL, Values.create("First time someone was present in the room")),new MetaItem(RULE_STATE, Values.create(true)),- new MetaItem(PROTECTED, Values.create(true))+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true))),new AssetAttribute("lastPresenceDetected", TIMESTAMP_MILLIS).setMeta(new MetaItem(LABEL, Values.create("Last time someone was present in the room")),new MetaItem(RULE_STATE, Values.create(true)),- new MetaItem(PROTECTED, Values.create(true))+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true))));}@@ -176,7 +176,7 @@ public abstract class AbstractManagerSetup implements Setup {new MetaItem(RULE_STATE, Values.create(true)),new MetaItem(RULE_EVENT, Values.create(true)),new MetaItem(RULE_EVENT_EXPIRES, Values.create("16m")),- new MetaItem(PROTECTED, Values.create(true)),+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),new MetaItem(READ_ONLY, Values.create(true)),new MetaItem(STORE_DATA_POINTS, Values.create(true)),new MetaItem(SHOW_ON_DASHBOARD, Values.create(true)),@@ -191,7 +191,7 @@ public abstract class AbstractManagerSetup implements Setup {.setMeta(new MetaItem(LABEL, Values.create("Humidity")),new MetaItem(RULE_STATE, Values.create(true)),- new MetaItem(PROTECTED, Values.create(true)),+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),new MetaItem(READ_ONLY, Values.create(true)),new MetaItem(STORE_DATA_POINTS, Values.create(true)),new MetaItem(SHOW_ON_DASHBOARD, Values.create(true)),@@ -208,7 +208,7 @@ public abstract class AbstractManagerSetup implements Setup {.setMeta(new MetaItem(LABEL, Values.create("Current temperature")),new MetaItem(RULE_STATE, Values.create(true)),- new MetaItem(PROTECTED, Values.create(true)),+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),new MetaItem(READ_ONLY, Values.create(true)),new MetaItem(STORE_DATA_POINTS, Values.create(true)),new MetaItem(SHOW_ON_DASHBOARD, Values.create(true)),@@ -225,7 +225,7 @@ public abstract class AbstractManagerSetup implements Setup {.setMeta(new MetaItem(LABEL, Values.create("Target temperature")),new MetaItem(RULE_STATE, Values.create(true)),- new MetaItem(PROTECTED, Values.create(true)),+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),new MetaItem(SHOW_ON_DASHBOARD, Values.create(true)),new MetaItem(FORMAT, Values.create("%0.1f C"))).addMeta(shouldBeLinked ? agentLinker.get() : null)@@ -248,25 +248,25 @@ public abstract class AbstractManagerSetup implements Setup {new AssetAttribute(switchAttributePrefix + "OnOff", BOOLEAN).setMeta(new MetaItem(LABEL, Values.create(switchLabelPrefix + " on/off")),- new MetaItem(PROTECTED, Values.create(true))+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true))).addMeta(shouldBeLinked ? agentLinker.apply(0) : null),// Start timenew AssetAttribute(switchAttributePrefix + "StartTime", TIMESTAMP_SECONDS).setMeta(new MetaItem(LABEL, Values.create(switchLabelPrefix + " earliest start time")),- new MetaItem(PROTECTED, Values.create(true))+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true))).addMeta(shouldBeLinked ? agentLinker.apply(1) : null),// Stop timenew AssetAttribute(switchAttributePrefix + "StopTime", TIMESTAMP_SECONDS).setMeta(new MetaItem(LABEL, Values.create(switchLabelPrefix + " latest stop time")),- new MetaItem(PROTECTED, Values.create(true))+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true))).addMeta(shouldBeLinked ? agentLinker.apply(2) : null),// Smart enablednew AssetAttribute(switchAttributePrefix + "SmartEnabled", BOOLEAN).setMeta(new MetaItem(LABEL, Values.create(switchLabelPrefix + " smart control enabled")),- new MetaItem(PROTECTED, Values.create(true))+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true))).addMeta(shouldBeLinked ? agentLinker.apply(3) : null));}@@ -281,14 +281,14 @@ public abstract class AbstractManagerSetup implements Setup {new MetaItem(RANGE_MIN, Values.create(0)),new MetaItem(RANGE_MAX, Values.create(255)),new MetaItem(RULE_STATE, Values.create(true)),- new MetaItem(PROTECTED, Values.create(true)),+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),new MetaItem(FORMAT, Values.create("%d"))).addMeta(shouldBeLinked ? agentLinker.get() : null),new AssetAttribute("ventilationAuto", BOOLEAN).setMeta(new MetaItem(LABEL, Values.create("Ventilation auto")),new MetaItem(RULE_STATE, Values.create(true)),- new MetaItem(PROTECTED, Values.create(true))+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true))));}@@ -405,21 +405,21 @@ public abstract class AbstractManagerSetup implements Setup {new AssetAttribute(scene.attributeName, AttributeType.STRING, Values.create(AttributeExecuteStatus.READY.name())).setMeta(new MetaItem(LABEL, Values.create(scene.attributeLabel)),- new MetaItem(PROTECTED, Values.create(true)),+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),new MetaItem(EXECUTABLE, Values.create(true)),new MetaItem(AGENT_LINK, new AttributeRef(agent.getId(), scene.attributeName).toArrayValue())),new AssetAttribute(scene.attributeName + "AlarmEnabled", AttributeType.BOOLEAN).setMeta(new MetaItem(LABEL, Values.create(scene.attributeLabel + " alarm enabled")),- new MetaItem(PROTECTED, Values.create(true)),+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),new MetaItem(META_MACRO_ACTION_INDEX, Values.create(0)),new MetaItem(AGENT_LINK, new AttributeRef(agent.getId(), scene.attributeName).toArrayValue())),new AssetAttribute(scene.attributeName + "TargetTemperature", AttributeType.NUMBER).setMeta(new MetaItem(LABEL, Values.create(scene.attributeLabel + " target temperature")),- new MetaItem(PROTECTED, Values.create(true)),+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),new MetaItem(META_MACRO_ACTION_INDEX, Values.create(1)),new MetaItem(AGENT_LINK, new AttributeRef(agent.getId(), scene.attributeName).toArrayValue()))@@ -431,7 +431,7 @@ public abstract class AbstractManagerSetup implements Setup {new AssetAttribute(scene.attributeName + "Time" + dayOfWeek.name(), AttributeType.STRING).setMeta(new MetaItem(LABEL, Values.create(scene.attributeLabel + " time " + dayName)),- new MetaItem(PROTECTED, Values.create(true)),+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),new MetaItem(RULE_STATE, Values.create(true)),new MetaItem(META_TIMER_VALUE_LINK, Values.create(TimerValue.TIME.toString())),new MetaItem(AGENT_LINK, new AttributeRef(agent.getId(), scene.attributeName + dayName).toArrayValue())@@ -439,7 +439,7 @@ public abstract class AbstractManagerSetup implements Setup {new AssetAttribute(scene.attributeName + "Enabled" + dayOfWeek.name(), AttributeType.BOOLEAN).setMeta(new MetaItem(LABEL, Values.create(scene.attributeLabel + " enabled " + dayName)),- new MetaItem(PROTECTED, Values.create(true)),+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),new MetaItem(META_TIMER_VALUE_LINK, Values.create(TimerValue.ENABLED.toString())),new MetaItem(AGENT_LINK, new AttributeRef(agent.getId(), scene.attributeName + dayName).toArrayValue()))@@ -450,21 +450,21 @@ public abstract class AbstractManagerSetup implements Setup {new AssetAttribute("sceneTimerEnabled", AttributeType.BOOLEAN, Values.create(true)).setMeta(new MetaItem(LABEL, Values.create("Scene timer enabled")),- new MetaItem(PROTECTED, Values.create(true)),+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),new MetaItem(SHOW_ON_DASHBOARD, Values.create(true)),new MetaItem(READ_ONLY, Values.create(true))),new AssetAttribute("enableSceneTimer", AttributeType.STRING, Values.create(AttributeExecuteStatus.READY.name())).setMeta(new MetaItem(LABEL, Values.create("Enable scene timer")),- new MetaItem(PROTECTED, Values.create(true)),+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),new MetaItem(EXECUTABLE, Values.create(true)),new MetaItem(AGENT_LINK, new AttributeRef(agent.getId(), "enableSceneTimer").toArrayValue())),new AssetAttribute("disableSceneTimer", AttributeType.STRING, Values.create(AttributeExecuteStatus.READY.name())).setMeta(new MetaItem(LABEL, Values.create("Disable scene timer")),- new MetaItem(PROTECTED, Values.create(true)),+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),new MetaItem(EXECUTABLE, Values.create(true)),new MetaItem(AGENT_LINK, new AttributeRef(agent.getId(), "disableSceneTimer").toArrayValue()))diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.javaindex 192b28980..d9c1b8ff3 100644--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java@@ -455,7 +455,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {),new AssetAttribute("windowOpen", AttributeType.BOOLEAN, Values.create(false)).setMeta(- new MetaItem(PROTECTED, Values.create(true))+ new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true))));apartment2Livingroom = assetStorageService.merge(apartment2Livingroom);diff --git a/manager/server/src/main/resources/org/openremote/manager/server/setup/database/V20171031_01__Schema.sql b/manager/server/src/main/resources/org/openremote/manager/server/setup/database/V20171203_01__Schema.sqlsimilarity index 91%rename from manager/server/src/main/resources/org/openremote/manager/server/setup/database/V20171031_01__Schema.sqlrename to manager/server/src/main/resources/org/openremote/manager/server/setup/database/V20171203_01__Schema.sqlindex e9da5d017..4a238b635 100644--- a/manager/server/src/main/resources/org/openremote/manager/server/setup/database/V20171031_01__Schema.sql+++ b/manager/server/src/main/resources/org/openremote/manager/server/setup/database/V20171203_01__Schema.sql@@ -28,15 +28,16 @@ create table ALERT_NOTIFICATION ();create table ASSET (- ID varchar(43) not null,- ATTRIBUTES jsonb,- CREATED_ON timestamp with time zone not null,- NAME varchar(1023) not null,- PARENT_ID varchar(36),- REALM_ID varchar(255) not null,- ASSET_TYPE varchar(255) not null,- OBJ_VERSION int8 not null,- LOCATION geometry,+ ID varchar(43) not null,+ ATTRIBUTES jsonb,+ CREATED_ON timestamp with time zone not null,+ NAME varchar(1023) not null,+ PARENT_ID varchar(36),+ REALM_ID varchar(255) not null,+ ASSET_TYPE varchar(255) not null,+ ACCESS_PUBLIC_READ boolean not null,+ OBJ_VERSION int8 not null,+ LOCATION geometry,primary key (ID),check (ID != PARENT_ID));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 d4bc75749..ca778808b 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@@ -24,6 +24,7 @@ import org.openremote.manager.shared.http.RequestParams;import org.openremote.manager.shared.http.SuccessStatusCode;import org.openremote.model.asset.AbstractAssetQuery;import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AssetQuery;import org.openremote.model.asset.UserAsset;import javax.annotation.security.RolesAllowed;@@ -145,12 +146,14 @@ public interface AssetResource {Asset get(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId);/**- * TODO Update docs, how restricted user handling is actually implemented- * <p>* 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.+ * different than its authenticated realm, or if the original or target realm is not accessible. A 403 status is+ * returned if the user is restricted and the asset is not linked to the user. A 400 status is returned if the+ * asset's parent doesn't exist. A 400 status is returned if a restricted user attempts to write private meta items+ * of any attributes. If a restricted user tries to write asset properties or dynamic attributes or+ * meta items of dynamic attributes which are not writable by a restricted user, such data is ignored. For more+ * details on limitations of restricted users, see {@link UserAsset}.*/@PUT@Path("{assetId}")@@ -211,12 +214,12 @@ public interface AssetResource {void delete(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId);/**- * Retrieve assets using an {@link AbstractAssetQuery}.+ * Retrieve assets using an {@link AssetQuery}.* <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.+ * is determined by the {@link AssetQuery#select} value.*/@POST@Path("query")@@ -225,10 +228,10 @@ public interface AssetResource {@SuccessStatusCode(200)@RolesAllowed({"read:assets"})@SuppressWarnings("unusable-by-js")- Asset[] queryAssets(@BeanParam RequestParams requestParams, AbstractAssetQuery query);+ Asset[] queryAssets(@BeanParam RequestParams requestParams, AssetQuery query);/**- * Retrieve public assets using an {@link AbstractAssetQuery}.+ * Retrieve public assets using an {@link AssetQuery}.* <p>* Allows un-authenticated 'public' users to query public assets for a realm.*/@@ -238,5 +241,17 @@ public interface AssetResource {@Produces(APPLICATION_JSON)@SuccessStatusCode(200)@SuppressWarnings("unusable-by-js")- Asset[] queryPublicAssets(@BeanParam RequestParams requestParams, AbstractAssetQuery query);+ Asset[] queryPublicAssets(@BeanParam RequestParams requestParams, AssetQuery query);++ /**+ * Retrieve public assets using an {@link AssetQuery} as a JSON serialized query parameter.+ * <p>+ * Allows un-authenticated 'public' users to query public assets for a realm.+ */+ @GET+ @Path("public/query")+ @Produces(APPLICATION_JSON)+ @SuccessStatusCode(200)+ @SuppressWarnings("unusable-by-js")+ Asset[] queryPublicAssets(@BeanParam RequestParams requestParams, @QueryParam("q") String q);}diff --git a/model/src/main/java/org/openremote/model/asset/AbstractAssetQuery.java b/model/src/main/java/org/openremote/model/asset/AbstractAssetQuery.javaindex 8ecb32f3e..fc793219e 100644--- a/model/src/main/java/org/openremote/model/asset/AbstractAssetQuery.java+++ b/model/src/main/java/org/openremote/model/asset/AbstractAssetQuery.java@@ -22,7 +22,9 @@ package org.openremote.model.asset;import com.fasterxml.jackson.annotation.JsonSubTypes;import com.fasterxml.jackson.annotation.JsonTypeInfo;import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.MetaItemDescriptor;+import java.util.Arrays;import java.util.Locale;/**@@ -40,34 +42,43 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {ALL}+ public enum Access {+ PRIVATE_READ,+ RESTRICTED_READ,+ PUBLIC_READ+ }+public static class Select {- public Include include = Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES;- public boolean filterProtected;+ public Include include;public boolean recursive;+ public Access access;public String[] attributeNames;- public boolean publicOnly;public Select() {}public Select(Include include) {- this(include, false);+ this(include, Access.PRIVATE_READ);}- public Select(Include include, boolean filterProtected) {- this(include, filterProtected, false);+ public Select(Include include, Access access) {+ this(include, false, access);}- public Select(Include include, boolean filterProtected, boolean recursive) {- this(include, filterProtected, recursive, (String[]) null);+ public Select(Include include, boolean recursive, Access access) {+ this(include, recursive, access, (String[]) null);}- public Select(Include include, boolean filterProtected, boolean recursive, String... attributeNames) {+ public Select(Include include, boolean recursive, String... attributeNames) {+ this(include, recursive, Access.PRIVATE_READ, attributeNames);+ }++ public Select(Include include, boolean recursive, Access access, String... attributeNames) {if (include == null) {include = Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES;}this.include = include;- this.filterProtected = filterProtected;+ this.access = access;this.recursive = recursive;this.attributeNames = attributeNames;}@@ -77,13 +88,8 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {return this;}- public Select publicOnly(boolean publicOnly) {- this.publicOnly = publicOnly;- return this;- }-- public Select filterProtected(boolean filterProtected) {- this.filterProtected = filterProtected;+ public Select filterAccess(Access access) {+ this.access = access;return this;}@@ -91,6 +97,16 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {this.attributeNames = attributeNames;return this;}++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "include=" + include ++ ", recursive=" + recursive ++ ", access=" + access ++ ", attributeNames=" + Arrays.toString(attributeNames) ++ '}';+ }}public enum Match {@@ -187,6 +203,15 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {s = s.toUpperCase(Locale.ROOT);return s;}++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "match=" + match ++ ", caseSensitive=" + caseSensitive ++ ", value='" + value + '\'' ++ '}';+ }}public static class BooleanPredicate implements ValuePredicate {@@ -203,6 +228,13 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {this.predicate = predicate;return this;}++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "predicate=" + predicate ++ '}';+ }}public static class StringArrayPredicate implements ValuePredicate {@@ -219,6 +251,13 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {this.predicates = predicates;return this;}++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "predicates=" + Arrays.toString(predicates) ++ '}';+ }}public static class DateTimePredicate implements ValuePredicate {@@ -261,6 +300,16 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {this.rangeValue = beforeValue;return this;}++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "operatorMatch=" + operatorMatch ++ ", dateFormat='" + dateFormat + '\'' ++ ", value='" + value + '\'' ++ ", rangeValue='" + rangeValue + '\'' ++ '}';+ }}public static class NumberPredicate implements ValuePredicate {@@ -312,6 +361,16 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {this.rangeValue = rangeValue;return this;}++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "value=" + value ++ ", rangeValue=" + rangeValue ++ ", operatorMatch=" + operatorMatch ++ ", numberType=" + numberType ++ '}';+ }}public static class ParentPredicate {@@ -348,6 +407,15 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {this.noParent = noParent;return this;}++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "id='" + id + '\'' ++ ", type='" + type + '\'' ++ ", noParent=" + noParent ++ '}';+ }}public static class PathPredicate {@@ -368,6 +436,13 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {public boolean hasPath() {return path != null && path.length > 0;}++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "path=" + Arrays.toString(path) ++ '}';+ }}public static class TenantPredicate {@@ -390,6 +465,14 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {this.realm = name;return this;}++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "realmId='" + realmId + '\'' ++ ", realm='" + realm + '\'' ++ '}';+ }}public static class AttributeMetaPredicate {@@ -403,8 +486,8 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {this.itemNamePredicate = itemNamePredicate;}- public AttributeMetaPredicate(AssetMeta assetMeta) {- this.itemNamePredicate = new StringPredicate(assetMeta.getUrn());+ public AttributeMetaPredicate(MetaItemDescriptor metaItemDescriptor) {+ this.itemNamePredicate = new StringPredicate(metaItemDescriptor.getUrn());}public AttributeMetaPredicate(ValuePredicate itemValuePredicate) {@@ -416,8 +499,8 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {this.itemValuePredicate = itemValuePredicate;}- public AttributeMetaPredicate(AssetMeta assetMeta, ValuePredicate itemValuePredicate) {- this(new StringPredicate(assetMeta.getUrn()), itemValuePredicate);+ public AttributeMetaPredicate(MetaItemDescriptor metaItemDescriptor, ValuePredicate itemValuePredicate) {+ this(new StringPredicate(metaItemDescriptor.getUrn()), itemValuePredicate);}public AttributeMetaPredicate itemName(StringPredicate itemNamePredicate) {@@ -425,14 +508,22 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {return this;}- public AttributeMetaPredicate itemName(AssetMeta assetMeta) {- return itemName(new StringPredicate(assetMeta.getUrn()));+ public AttributeMetaPredicate itemName(MetaItemDescriptor metaItemDescriptor) {+ return itemName(new StringPredicate(metaItemDescriptor.getUrn()));}public AttributeMetaPredicate itemValue(ValuePredicate itemValuePredicate) {this.itemValuePredicate = itemValuePredicate;return this;}++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "itemNamePredicate=" + itemNamePredicate ++ ", itemValuePredicate=" + itemValuePredicate ++ '}';+ }}public static class AttributeRefPredicate extends AttributeMetaPredicate {@@ -461,8 +552,8 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {));}- public AttributeRefPredicate(AssetMeta assetMeta, String entityId, String attributeName) {- this(assetMeta.getUrn(), entityId, attributeName);+ public AttributeRefPredicate(MetaItemDescriptor metaItemDescriptor, String entityId, String attributeName) {+ this(metaItemDescriptor.getUrn(), entityId, attributeName);}public AttributeRefPredicate(StringPredicate name, AttributeRef attributeRef) {@@ -474,8 +565,8 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {));}- public AttributeRefPredicate(AssetMeta assetMeta, AttributeRef attributeRef) {- this(new StringPredicate(assetMeta.getUrn()), attributeRef);+ public AttributeRefPredicate(MetaItemDescriptor metaItemDescriptor, AttributeRef attributeRef) {+ this(new StringPredicate(metaItemDescriptor.getUrn()), attributeRef);}}@@ -490,8 +581,8 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {this.itemNamePredicate = itemNamePredicate;}- public AttributePredicate(AssetMeta assetMeta) {- this.itemNamePredicate = new StringPredicate(assetMeta.getUrn());+ public AttributePredicate(MetaItemDescriptor metaItemDescriptor) {+ this.itemNamePredicate = new StringPredicate(metaItemDescriptor.getUrn());}public AttributePredicate(ValuePredicate itemValuePredicate) {@@ -503,8 +594,8 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {this.itemValuePredicate = itemValuePredicate;}- public AttributePredicate(AssetMeta assetMeta, ValuePredicate itemValuePredicate) {- this(new StringPredicate(assetMeta.getUrn()), itemValuePredicate);+ public AttributePredicate(MetaItemDescriptor metaItemDescriptor, ValuePredicate itemValuePredicate) {+ this(new StringPredicate(metaItemDescriptor.getUrn()), itemValuePredicate);}public AttributePredicate itemName(StringPredicate itemNamePredicate) {@@ -512,14 +603,22 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {return this;}- public AttributePredicate itemName(AssetMeta assetMeta) {- return itemName(new StringPredicate(assetMeta.getUrn()));+ public AttributePredicate itemName(MetaItemDescriptor metaItemDescriptor) {+ return itemName(new StringPredicate(metaItemDescriptor.getUrn()));}public AttributePredicate itemValue(ValuePredicate itemValuePredicate) {this.itemValuePredicate = itemValuePredicate;return this;}++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "itemNamePredicate=" + itemNamePredicate ++ ", itemValuePredicate=" + itemValuePredicate ++ '}';+ }}public static class AttributePredicateArray {@@ -536,6 +635,13 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {this.predicates = predicates;return this;}++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "predicates=" + Arrays.toString(predicates) ++ '}';+ }}public static class OrderBy {@@ -572,10 +678,18 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {this.descending = descending;return this;}++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "property=" + property ++ ", descending=" + descending ++ '}';+ }}// Projection- public Select select = new Select();+ public Select select;// Restriction predicatespublic String id;@@ -589,7 +703,7 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {public AttributePredicateArray attributePredicateArray;// Ordering- public OrderBy orderBy = new OrderBy(OrderBy.Property.CREATED_ON);+ public OrderBy orderBy;protected AbstractAssetQuery() {}@@ -668,4 +782,21 @@ public class AbstractAssetQuery<CHILD extends AbstractAssetQuery<CHILD>> {this.orderBy = orderBy;return (CHILD) this;}++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "select=" + select ++ ", id='" + id + '\'' ++ ", namePredicate=" + namePredicate ++ ", parentPredicate=" + parentPredicate ++ ", pathPredicate=" + pathPredicate ++ ", tenantPredicate=" + tenantPredicate ++ ", userId='" + userId + '\'' ++ ", type=" + type ++ ", attributeMetaPredicate=" + attributeMetaPredicate ++ ", attributePredicateArray=" + attributePredicateArray ++ ", orderBy=" + orderBy ++ '}';+ }}diff --git a/model/src/main/java/org/openremote/model/asset/Asset.java b/model/src/main/java/org/openremote/model/asset/Asset.javaindex 9214ba6a3..d0c0a70d3 100644--- a/model/src/main/java/org/openremote/model/asset/Asset.java+++ b/model/src/main/java/org/openremote/model/asset/Asset.java@@ -36,9 +36,11 @@ import javax.validation.constraints.NotNull;import javax.validation.constraints.Size;import java.math.BigDecimal;import java.math.RoundingMode;-import java.util.*;+import java.util.Arrays;+import java.util.Date;+import java.util.List;+import java.util.Optional;import java.util.function.Predicate;-import java.util.function.UnaryOperator;import java.util.stream.Collectors;import java.util.stream.Stream;@@ -66,8 +68,8 @@ import static org.openremote.model.asset.AssetAttribute.*;* <p>* The {@link #type} of the asset is an arbitrary string, it should be a URI, thus avoiding* collisions and representing "ownership" of asset type. Well-known asset types handled by- * the core platform are defined in {@link AssetType}, third-party extensions can defined- * their own asset types.+ * the core platform are defined in {@link AssetType}, third-party extensions can define+ * their own asset types in their own namespace, e.g. <code>urn:mynamespace:myassettype</code>* <p>* The {@link #path} is a list of parent asset identifiers, starting with the identifier of* this asset, followed by parent asset identifiers, and ending with the identifier of the@@ -81,12 +83,8 @@ import static org.openremote.model.asset.AssetAttribute.*;* {@link ObjectValue} model. Use the {@link Attribute} etc. class to work with this API.* This property can be empty when certain optimized loading operations are used.* <p>- * Constructors can filter attributes of an asset as to only contain protected attributes,- * and their protected metadata (see {@link AssetMeta#PROTECTED}, {@link AssetMeta.Access}).- * <p>- * Note that third-party metadata items (not in the- * {@link org.openremote.model.Constants#NAMESPACE}) are never included on- * a protected attribute!+ * For more details on restricted access of user-assigned assets, see {@link UserAsset}.+ * </p>* <p>* Example JSON representation of an asset tree:* <blockquote><pre>{@code@@ -186,7 +184,7 @@ import static org.openremote.model.asset.AssetAttribute.*;"value": "Current Temp"},{- "name": "urn:openremote:asset:meta:protected",+ "name": "urn:openremote:asset:meta:accessRestrictedRead","value": true},{@@ -243,6 +241,9 @@ public class Asset implements IdentifiableEntity {@Column(name = "ASSET_TYPE", nullable = false, updatable = false)protected String type;+ @Column(name = "ACCESS_PUBLIC_READ", nullable = false)+ protected boolean accessPublicRead;+@Column(name = "PARENT_ID", length = 36)protected String parentId;@@ -286,7 +287,7 @@ public class Asset implements IdentifiableEntity {}public Asset(String name, String type) {- this(name, type, null, null);+ this(name, type, false, null, null);}public Asset(@NotNull String name, @NotNull AssetType type, Asset parent) {@@ -294,18 +295,19 @@ public class Asset implements IdentifiableEntity {}public Asset(@NotNull String name, @NotNull String type, Asset parent) {- this(name, type, parent, null);+ this(name, type, false, parent, null);}public Asset(@NotNull String name, @NotNull AssetType type, Asset parent, @NotNull String realmId) {- this(name, type.getValue(), parent, realmId);+ this(name, type.getValue(), false, parent, realmId);}- public Asset(@NotNull String name, @NotNull String type, Asset parent, @NotNull String realmId) {+ public Asset(@NotNull String name, @NotNull String type, boolean accessPublicRead, Asset parent, @NotNull String realmId) {setRealmId(realmId);setName(name);setType(type);setParent(parent);+ setAccessPublicRead(accessPublicRead);// Initialise realm from parent// TODO: Need to look at this - can child have a different realm to the parent?@@ -316,11 +318,11 @@ public class Asset implements IdentifiableEntity {}}- public Asset(String id, long version, Date createdOn, String name, String type,+ public Asset(String id, long version, Date createdOn, String name, String type, boolean accessPublicRead,String parentId, String parentName, String parentType,String realmId, String tenantRealm, String tenantDisplayName,String[] path, ObjectValue attributes) {- this(name, type, null, realmId);+ this(name, type, accessPublicRead, null, realmId);this.id = id;this.version = version;this.createdOn = createdOn;@@ -412,6 +414,14 @@ public class Asset implements IdentifiableEntity {setType(type != null ? type.getValue() : null);}+ public boolean isAccessPublicRead() {+ return accessPublicRead;+ }++ public void setAccessPublicRead(boolean accessPublicRead) {+ this.accessPublicRead = accessPublicRead;+ }+public void setParent(Asset parent) {if (parent == null) {parentId = null;@@ -610,6 +620,7 @@ public class Asset implements IdentifiableEntity {", createdOn=" + createdOn +", name='" + name + '\'' +", type='" + type + '\'' ++ ", accessPublicRead='" + accessPublicRead + '\'' +", parentId='" + parentId + '\'' +", parentName='" + parentName + '\'' +", parentType='" + parentType + '\'' +diff --git a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java b/model/src/main/java/org/openremote/model/asset/AssetAttribute.javaindex c93e025a8..22c24d3e8 100644--- a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java+++ b/model/src/main/java/org/openremote/model/asset/AssetAttribute.java@@ -274,20 +274,28 @@ public class AssetAttribute extends Attribute {}}- public boolean isProtected() {+ public boolean isAccessRestrictedRead() {return getMetaStream()- .filter(isMetaNameEqualTo(PROTECTED))+ .filter(isMetaNameEqualTo(AssetMeta.ACCESS_RESTRICTED_READ)).findFirst().map(metaItem -> metaItem.getValueAsBoolean().orElse(false)).orElse(false);}- public void setProtected(boolean protect) {- if (protect) {- replaceMetaByName(getMeta(), PROTECTED, Values.create(true));- } else {- getMeta().removeIf(isMetaNameEqualTo(PROTECTED));- }+ public boolean isAccessRestrictedWrite() {+ return getMetaStream()+ .filter(isMetaNameEqualTo(AssetMeta.ACCESS_RESTRICTED_WRITE))+ .findFirst()+ .map(metaItem -> metaItem.getValueAsBoolean().orElse(false))+ .orElse(false);+ }++ public boolean isAccessPublicRead() {+ return getMetaStream()+ .filter(isMetaNameEqualTo(AssetMeta.ACCESS_PUBLIC_READ))+ .findFirst()+ .map(metaItem -> metaItem.getValueAsBoolean().orElse(false))+ .orElse(false);}public boolean isReadOnly() {diff --git a/model/src/main/java/org/openremote/model/asset/AssetMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.javaindex 600131913..ea5cdb521 100644--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java@@ -25,21 +25,20 @@ 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;-import java.util.List;import java.util.Optional;import java.util.function.Function;import static org.openremote.model.Constants.ASSET_META_NAMESPACE;import static org.openremote.model.attribute.MetaItem.MetaItemFailureReason.META_ITEM_VALUE_MISMATCH;+import static org.openremote.model.attribute.MetaItemDescriptor.Access.ACCESS_PRIVATE;import static org.openremote.model.util.TextUtil.REGEXP_PATTERN_DOUBLE;-import static org.openremote.model.util.TextUtil.isNullOrEmpty;/*** Asset attribute meta item name is an arbitrary string. It should be URI. This enum contains* the well-known URIs for functionality we can depend on in our platform.* <p>+ * A custom project can add its own asset meta items through {@link AssetModelProvider}.+ * <p>* TODO https://people.eecs.berkeley.edu/~arka/papers/buildsys2015_metadatasurvey.pdf*/public enum AssetMeta implements MetaItemDescriptor {@@ -49,7 +48,8 @@ public enum AssetMeta implements MetaItemDescriptor {* The attribute value is a protocol URN.*/PROTOCOL_CONFIGURATION(- ASSET_META_NAMESPACE + ":protocolConfiguration", new Access(false, false, true),+ ASSET_META_NAMESPACE + ":protocolConfiguration",+ ACCESS_PRIVATE,ValueType.BOOLEAN,null,null,@@ -62,7 +62,7 @@ public enum AssetMeta implements MetaItemDescriptor {*/AGENT_LINK(ASSET_META_NAMESPACE + ":agentLink",- new Access(false, false, true),+ ACCESS_PRIVATE,ValueType.ARRAY,null,null,@@ -80,7 +80,7 @@ public enum AssetMeta implements MetaItemDescriptor {*/ATTRIBUTE_LINK(ASSET_META_NAMESPACE + ":attributeLink",- new Access(false, false, true),+ ACCESS_PRIVATE,ValueType.OBJECT,null,null,@@ -109,7 +109,7 @@ public enum AssetMeta implements MetaItemDescriptor {*/SHOW_ON_DASHBOARD(ASSET_META_NAMESPACE + ":showOnDashboard",- new Access(true, true, true),+ new Access(true, false, true),ValueType.BOOLEAN,null,null,@@ -153,8 +153,9 @@ public enum AssetMeta implements MetaItemDescriptor {false),/**- * Marks the attribute as read-only for clients. South-bound changes of the attribute are not possible.- * North-bound attribute updates made by protocols and changes made by rules are possible.+ * Marks the attribute as read-only for non-superuser clients. South-bound {@link AttributeEvent}s+ * by regular or restricted users are ignored. North-bound {@link AttributeEvent}s made by protocols and+ * rules engine are possible.*/READ_ONLY(ASSET_META_NAMESPACE + ":readOnly",@@ -166,12 +167,37 @@ public enum AssetMeta implements MetaItemDescriptor {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+ * Marks the attribute as readable by restricted clients and therefore users who are linked to+ * the asset, see {@link UserAsset}.+ */+ ACCESS_RESTRICTED_READ(+ ASSET_META_NAMESPACE + ":accessRestrictedRead",+ ACCESS_PRIVATE,+ ValueType.BOOLEAN,+ null,+ null,+ Values.create(true),+ true),++ /**+ * Marks the attribute as writable by restricted clients and therefore users who are linked to+ * the asset, see {@link UserAsset}.+ */+ ACCESS_RESTRICTED_WRITE(+ ASSET_META_NAMESPACE + ":accessRestrictedWrite",+ ACCESS_PRIVATE,+ ValueType.BOOLEAN,+ null,+ null,+ Values.create(true),+ true),++ /**+ * Marks the attribute as readable by unauthenticated public clients.*/- PROTECTED(- ASSET_META_NAMESPACE + ":protected",- new Access(false, false, true),+ ACCESS_PUBLIC_READ(+ ASSET_META_NAMESPACE + ":accessPublicRead",+ ACCESS_PRIVATE,ValueType.BOOLEAN,null,null,@@ -345,14 +371,17 @@ public enum AssetMeta implements MetaItemDescriptor {this.patternFailureMessage = patternFailureMessage;}+ @Overridepublic String getUrn() {return urn;}+ @Overridepublic Access getAccess() {return access;}+ @Overridepublic ValueType getValueType() {return valueType;}@@ -367,6 +396,7 @@ public enum AssetMeta implements MetaItemDescriptor {return pattern;}+ @Overridepublic String getPatternFailureMessage() {return patternFailureMessage;}@@ -381,109 +411,13 @@ public enum AssetMeta implements MetaItemDescriptor {return Optional.ofNullable(validator);}+ @Overridepublic Value getInitialValue() {return initialValue;}- /**- * Indicates that the value of this asset meta should not be changed.- */+ @Overridepublic boolean isValueFixed() {return valueFixed;}-- public boolean isRestricted() {- return access != null && access.restricted;- }-- public static AssetMeta[] unRestricted() {- 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 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().restricted;- }- return false;- }-- public static Optional<AssetMeta> getAssetMeta(String urn) {- if (isNullOrEmpty(urn))- return Optional.empty();-- for (AssetMeta assetMeta : values()) {- if (assetMeta.getUrn().equals(urn))- return Optional.of(assetMeta);- }- return Optional.empty();- }-- /**- * Some well-known items can be protected readable.- *- * @see Access#protectedRead- */- public static boolean isMetaItemProtectedReadable(MetaItem metaItem) {- return getAssetMeta(metaItem.getName().orElse(null))- .map(meta -> meta.getAccess().protectedRead)- .orElse(false);- }-- /**- * Some well-known items can be protected writable.- *- * @see Access#protectedWrite- */- public static boolean isMetaItemProtectedWritable(MetaItem metaItem) {- return getAssetMeta(metaItem.getName().orElse(null))- .map(meta -> meta.getAccess().protectedWrite)- .orElse(false);- }-- public static class Access {-- /**- * When restricted clients read protected asset attributes, should this meta item be included?- */- final public boolean protectedRead;-- /**- * When restricted clients write protected asset attributes, should this meta item be included?- */- final public boolean protectedWrite;-- /**- * Can a user add this meta item when editing an asset?- */- final public boolean restricted;-- public Access(boolean protectedRead, boolean protectedWrite, boolean restricted) {- this.protectedRead = protectedRead;- this.protectedWrite = protectedWrite;- this.restricted = restricted;- }- }--}diff --git a/model/src/main/java/org/openremote/model/asset/AssetModelProvider.java b/model/src/main/java/org/openremote/model/asset/AssetModelProvider.javanew file mode 100644index 000000000..b9b027bf5--- /dev/null+++ b/model/src/main/java/org/openremote/model/asset/AssetModelProvider.java@@ -0,0 +1,31 @@+/*+ * 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.MetaItemDescriptor;++/**+ * Extend the asset model in custom projects.+ */+public interface AssetModelProvider {++ MetaItemDescriptor[] getMetaItemDescriptors();++}diff --git a/model/src/main/java/org/openremote/model/asset/DefaultAssetModelProvider.java b/model/src/main/java/org/openremote/model/asset/DefaultAssetModelProvider.javanew file mode 100644index 000000000..472424c9b--- /dev/null+++ b/model/src/main/java/org/openremote/model/asset/DefaultAssetModelProvider.java@@ -0,0 +1,38 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.model.asset;++import org.openremote.model.attribute.MetaItemDescriptor;++/**+ * The built-in and well-known asset model.+ */+public class DefaultAssetModelProvider implements AssetModelProvider {++ @Override+ public MetaItemDescriptor[] getMetaItemDescriptors() {+ return AssetMeta.values();+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{}";+ }+}diff --git a/model/src/main/java/org/openremote/model/asset/UserAsset.java b/model/src/main/java/org/openremote/model/asset/UserAsset.javaindex 6d50c6ecf..6d6cc5d8e 100644--- a/model/src/main/java/org/openremote/model/asset/UserAsset.java+++ b/model/src/main/java/org/openremote/model/asset/UserAsset.java@@ -20,6 +20,7 @@package org.openremote.model.asset;import org.hibernate.annotations.Formula;+import org.openremote.model.attribute.MetaItemDescriptor;import javax.persistence.*;import java.io.Serializable;@@ -28,22 +29,31 @@ import java.util.Date;/*** An asset can be linked to many users, and a user can have links to many assets.* <p>- * If a user has linked assets, it's a <em>restricted</em> user. Such a user can only- * access its assigned assets and their protected data, and it has a limited- * set of client operations available:+ * If a user has linked assets, it's a <em>restricted</em> user. When a client authenticates+ * with such a user, the client can only access the assigned/linked assets of that user, and+ * the available operations are limited:* <ul>* <li>- * When a restricted user client loads asset data, only protected asset details are included.+ * When a restricted client reads assets, only dynamic attributes with+ * {@link AssetMeta#ACCESS_RESTRICTED_READ} and attribute meta items with {@link MetaItemDescriptor.Access#restrictedRead}+ * are included.* </li>* <li>- * When a restricted user client updates asset data, only a subset of protected data can be changed.+ * When a restricted client updates existing assets, new dynamic attributes can be added, but+ * only attributes with {@link AssetMeta#ACCESS_RESTRICTED_WRITE} can be updated or deleted. Any new attributes+ * are automatically set with {@link AssetMeta#ACCESS_RESTRICTED_READ} and {@link AssetMeta#ACCESS_RESTRICTED_WRITE},+ * thus ensuring that a restricted client can fully access its own attributes. Any added, updated, or removed meta+ * items of attributes must be {@link MetaItemDescriptor.Access#restrictedWrite}.* </li>* <li>- * A restricted user client can not create or delete assets.+ * A restricted client can not create or delete assets. A restricted client can not change the name, parent, or+ * realm of an asset. A restricted user can not make an asset public. A restricted user can change the location of an asset.* </li>* </ul>- * Asset attribute data can be protected with {@link AssetMeta#PROTECTED} and {@link AssetMeta.Access},- * it is filtered in {@link AssetQuery.Select#filterProtected}.+ * <p>+ * Note that third-party metadata items (not in the {@link org.openremote.model.Constants#NAMESPACE}) are never+ * included by default in restricted read/write asset operations. To include them, provide meta item descriptors and+ * desired access permissions through the {@link AssetModelProvider} SPI.*/@Entity@Table(name = "USER_ASSET")diff --git a/model/src/main/java/org/openremote/model/attribute/Attribute.java b/model/src/main/java/org/openremote/model/attribute/Attribute.javaindex da5c62545..89693abf2 100644--- a/model/src/main/java/org/openremote/model/attribute/Attribute.java+++ b/model/src/main/java/org/openremote/model/attribute/Attribute.java@@ -170,6 +170,12 @@ public abstract class Attribute extends AbstractValueTimestampHolder {.findFirst();}+ public MetaItem[] getMetaItems(String metaName) {+ return getMetaStream()+ .filter(metaItem -> metaItem.getName().filter(s -> s.equals(metaName)).isPresent())+ .toArray(MetaItem[]::new);+ }+public Optional<MetaItem> getMetaItem(HasUniqueResourceName hasUniqueResourceName) {return getMetaItem(hasUniqueResourceName.getUrn());}diff --git a/model/src/main/java/org/openremote/model/attribute/MetaItem.java b/model/src/main/java/org/openremote/model/attribute/MetaItem.javaindex bd1fc4a29..83b8098f1 100644--- a/model/src/main/java/org/openremote/model/attribute/MetaItem.java+++ b/model/src/main/java/org/openremote/model/attribute/MetaItem.java@@ -67,10 +67,10 @@ public class MetaItem extends AbstractValueHolder {setValue(value);}- public MetaItem(AssetMeta assetMeta) {+ public MetaItem(MetaItemDescriptor metaItemDescriptor) {super(Values.createObject());- setName(assetMeta.getUrn());- setValue(assetMeta.getInitialValue());+ setName(metaItemDescriptor.getUrn());+ setValue(metaItemDescriptor.getInitialValue());}public MetaItem(HasUniqueResourceName hasUniqueResourceName, Value value) {@@ -227,27 +227,6 @@ public class MetaItem extends AbstractValueHolder {.forEach(metaItems::add);}- /**- * Merges two Collections of MetaItem of items that are write protected true.- *- * @param metaItems the original collection. The new values will be added to this collection- * @param newMetaItems the collection with new values- * @param removeMissing if set to true, then the missing items from newMetaItems will be removed from metaItems- * @param <T>- */- public static <T extends Collection<MetaItem>> void mergeMeta(T metaItems, T newMetaItems, boolean removeMissing) {- metaItems.forEach(metaItem -> {- Optional<MetaItem> newMetaItem = newMetaItems.stream().filter(isMetaNameEqualTo(metaItem.getName().orElse(null))).findFirst();- newMetaItem.ifPresent(nMetaItem -> {- metaItem.setValue(nMetaItem.getValue().orElse(null));- });- });- newMetaItems.stream().filter(newMetaItem -> !metaItems.contains(newMetaItem)).forEach(metaItems::add);- if (removeMissing) {- metaItems.stream().filter(metaItem -> !newMetaItems.contains(metaItem)).forEach(metaItems::remove);- }- }-public static <T extends Collection<MetaItem>> void replaceMetaByName(T metaItems, HasUniqueResourceName hasUniqueResourceName, MetaItem newMetaItem) {replaceMetaByName(metaItems, hasUniqueResourceName.getUrn(), newMetaItem);}diff --git a/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptor.java b/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptor.javaindex 135012688..629185920 100644--- a/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptor.java+++ b/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptor.java@@ -26,6 +26,7 @@ import org.openremote.model.ValidationFailure;import org.openremote.model.value.Value;import org.openremote.model.value.ValueType;+import java.util.Objects;import java.util.Optional;import java.util.function.Function;@@ -33,6 +34,61 @@ import java.util.function.Function;@JsonDeserialize(as = MetaItemDescriptorImpl.class)public interface MetaItemDescriptor extends HasUniqueResourceName {+ /**+ * Control access to meta items when attributes are read/written. The default is+ * read/write access by regular and super-users only, meta items are considered private.+ */+ class Access {++ public static Access ACCESS_PRIVATE = new Access();++ /**+ * When restricted clients read attributes of the authenticated user's linked+ * assets, should this meta item be included?+ */+ public boolean restrictedRead;++ /**+ * When restricted clients write attributes of the authenticated user's linked+ * assets, should this meta item be included?+ */+ public boolean restrictedWrite;++ /**+ * When public clients read asset attributes, should this meta item be+ * included? Note that public clients can not write asset attributes.+ */+ public boolean publicRead;++ /**+ * Private access only.+ */+ public Access() {+ this(false, false, false);+ }++ public Access(boolean restrictedRead, boolean restrictedWrite, boolean publicRead) {+ this.restrictedRead = restrictedRead;+ this.restrictedWrite = restrictedWrite;+ this.publicRead = publicRead;+ }++ @Override+ public boolean equals(Object o) {+ if (this == o) return true;+ if (o == null || getClass() != o.getClass()) return false;+ Access access = (Access) o;+ return restrictedRead == access.restrictedRead &&+ restrictedWrite == access.restrictedWrite &&+ publicRead == access.publicRead;+ }++ @Override+ public int hashCode() {+ return Objects.hash(restrictedRead, restrictedWrite, publicRead);+ }+ }+enum PatternFailure {INTEGER,INTEGER_NON_ZERO,@@ -56,41 +112,48 @@ public interface MetaItemDescriptor extends HasUniqueResourceName {ValueType getValueType();/**- * Indicates if this meta item is always required+ * Access permissions for read/write operations performed by restricted or public clients.+ */+ Access getAccess();++ /**+ * Indicates if this meta item is always required.+ * <p>+ * TODO Currently not used.*/boolean isRequired();/**- * A regex pattern that can be used for basic validation+ * A regex pattern that can be used for basic validation, can be <code>null</code> to disable validation.*/String getPattern();/*** Get a parameter to show as part of validation feedback for when the pattern matching fails- * e.g. Meta Item value must be 'Positive Integer'.+ * e.g. Meta Item value must be 'Positive Integer'. Can be <code>null</code> if validation is disabled.* <p>* Values defined in {@link PatternFailure} should support localisation.*/String getPatternFailureMessage();/**- * Gets the maximum number of these meta items allowed per attribute+ * Gets the maximum number of these meta items allowed per attribute.*/Integer getMaxPerAttribute();/**- * Gets the initial value for new instances of this meta item+ * Gets the initial value for new instances of this meta item, can be <code>null</code>.*/Value getInitialValue();/**- * Indicates if the value of this meta item is fixed+ * Indicates if the value of this meta item is fixed and can't be edited.*/boolean isValueFixed();/*** Get optional validation function; this allows {@link MetaItemDescriptor} implementations to do more advanced- * validation. If defined this takes priority over all other value checks+ * validation. If defined this takes priority over all other value checks.*/Optional<Function<Value, Optional<ValidationFailure>>> getValidator();}diff --git a/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptorImpl.java b/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptorImpl.javaindex a30e6874a..95939d78c 100644--- a/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptorImpl.java+++ b/model/src/main/java/org/openremote/model/attribute/MetaItemDescriptorImpl.java@@ -34,6 +34,7 @@ public class MetaItemDescriptorImpl implements MetaItemDescriptor {protected final String name;protected final String urn;protected final ValueType valueType;+ protected final Access access;protected final boolean required;protected final String pattern;protected final Integer maxPerAttribute;@@ -41,10 +42,23 @@ public class MetaItemDescriptorImpl implements MetaItemDescriptor {protected final boolean valueFixed;protected final String patternFailureMessage;+ public MetaItemDescriptorImpl(String name,+ String urn,+ ValueType valueType,+ boolean required,+ String pattern,+ String patternFailureMessage,+ Integer maxPerAttribute,+ Value initialValue,+ boolean valueFixed) {+ this(name, urn, valueType, Access.ACCESS_PRIVATE,required, pattern, patternFailureMessage, maxPerAttribute, initialValue, valueFixed);+ }+@JsonCreatorpublic MetaItemDescriptorImpl(@JsonProperty("name") String name,@JsonProperty("urn") String urn,@JsonProperty("valueType") ValueType valueType,+ @JsonProperty("access") Access access,@JsonProperty("required") boolean required,@JsonProperty("pattern") String pattern,@JsonProperty("patternFailureMessage") String patternFailureMessage,@@ -54,6 +68,7 @@ public class MetaItemDescriptorImpl implements MetaItemDescriptor {this.name = name;this.urn = urn;this.valueType = valueType;+ this.access = access;this.required = required;this.pattern = pattern;this.patternFailureMessage = patternFailureMessage;@@ -77,6 +92,11 @@ public class MetaItemDescriptorImpl implements MetaItemDescriptor {return valueType;}+ @Override+ public Access getAccess() {+ return access;+ }+@Overridepublic boolean isRequired() {return required;@@ -112,4 +132,20 @@ public class MetaItemDescriptorImpl implements MetaItemDescriptor {public Optional<Function<Value, Optional<ValidationFailure>>> getValidator() {return Optional.empty();}++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "name='" + name + '\'' ++ ", urn='" + urn + '\'' ++ ", valueType=" + valueType ++ ", access=" + access ++ ", required=" + required ++ ", pattern='" + pattern + '\'' ++ ", maxPerAttribute=" + maxPerAttribute ++ ", initialValue=" + initialValue ++ ", valueFixed=" + valueFixed ++ ", patternFailureMessage='" + patternFailureMessage + '\'' ++ '}';+ }}diff --git a/model/src/main/java/org/openremote/model/value/ObjectValue.java b/model/src/main/java/org/openremote/model/value/ObjectValue.javaindex 69abac59b..0abead749 100644--- a/model/src/main/java/org/openremote/model/value/ObjectValue.java+++ b/model/src/main/java/org/openremote/model/value/ObjectValue.java@@ -72,5 +72,8 @@ public interface ObjectValue extends Value {ObjectValue deepCopy();+ /**+ * @param ignoreKeys Keys to ignore in comparison.+ */boolean equalsIgnoreKeys(ObjectValue that, String... ignoreKeys);}diff --git a/model/src/main/resources/META-INF/services/org.openremote.model.asset.AssetModelProvider b/model/src/main/resources/META-INF/services/org.openremote.model.asset.AssetModelProvidernew file mode 100644index 000000000..07d17d416--- /dev/null+++ b/model/src/main/resources/META-INF/services/org.openremote.model.asset.AssetModelProvider@@ -0,0 +1 @@+org.openremote.model.asset.DefaultAssetModelProvider\ No newline at end of filediff --git a/profile/dev-testing.yml b/profile/dev-testing.ymlindex 41068bb3f..965e894ed 100644--- a/profile/dev-testing.yml+++ b/profile/dev-testing.yml@@ -25,6 +25,17 @@ services:depends_on:postgresql:condition: service_healthy+ # Give more resources in dev mode+ mem_limit: 800m+ memswap_limit: 800m+ environment:+ JAVA_OPTS: '-Xms400m -Xmx400m+ -XX:CompressedClassSpaceSize=50m -XX:MaxMetaspaceSize=175m+ -XX:InitialCodeCacheSize=50m -XX:ReservedCodeCacheSize=50m+ -XX:MaxDirectMemorySize=50m+ -XX:NativeMemoryTracking=summary+ -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/javadump.core.hprof+ -Djava.net.preferIPv4Stack=true -Djboss.modules.system.pkgs=org.jboss.byteman -Djava.awt.headless=true'postgresql:extends:diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovyindex c652d5b5a..5858efebc 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy@@ -109,9 +109,9 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTraittestAsset.setRealmId("thisdoesnotexistitreallydoesnt")assetResource.update(null, testAsset.id, testAsset)- then: "the request should be bad"+ then: "the request should be forbidden"ex = thrown()- ex.response.status == 400+ ex.response.status == 403when: "an asset is updated with a non-existent parent"testAsset = assetResource.get(null, testAsset.getId())diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovyindex c2c34637a..948033067 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy@@ -20,9 +20,12 @@ import static org.openremote.container.util.MapAccess.getStringimport static org.openremote.manager.server.setup.AbstractKeycloakSetup.KEYCLOAK_PASSWORDimport static org.openremote.manager.server.setup.AbstractKeycloakSetup.KEYCLOAK_PASSWORD_DEFAULTimport static org.openremote.model.Constants.*+import static org.openremote.model.asset.AssetMeta.ABOUTimport static org.openremote.model.asset.AssetMeta.LABEL+import static org.openremote.model.asset.AssetMeta.PROTOCOL_CONFIGURATION+import static org.openremote.model.asset.AssetMeta.STORE_DATA_POINTS+import static org.openremote.model.attribute.AttributeType.BOOLEANimport static org.openremote.model.attribute.AttributeType.NUMBER-import static org.openremote.model.attribute.AttributeType.TEMPERATURE_CELCIUSimport static org.openremote.model.attribute.MetaItem.isMetaNameEqualToclass AssetPermissionsTest extends Specification implements ManagerContainerTrait {@@ -137,6 +140,14 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraitestAsset.realmId == keycloakDemoSetup.masterTenant.idtestAsset.parentId == null+ when: "an asset is made public"+ testAsset.setAccessPublicRead(true)+ assetResource.update(null, testAsset.id, testAsset)+ testAsset = assetResource.get(null, testAsset.getId())++ then: "the asset should be updated"+ testAsset.accessPublicRead+when: "an asset is updated with a new parent in the authenticated realm"testAsset.setParentId(managerDemoSetup.groundFloorId)assetResource.update(null, testAsset.id, testAsset)@@ -653,22 +664,22 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiwhen: "a user asset is retrieved by ID in the authenticated realm"apartment1Livingroom = assetResource.get(null, managerDemoSetup.apartment1LivingroomId)- then: "the protected asset details should be available"+ then: "the restricted asset details should be available"apartment1Livingroom.id == managerDemoSetup.apartment1LivingroomIdapartment1Livingroom.name == "Living Room"- def protectedAttributes = apartment1Livingroom.getAttributesList()- protectedAttributes.size() == 7+ def resultAttributes = apartment1Livingroom.getAttributesList()+ resultAttributes.size() == 7def currentTemperature = apartment1Livingroom.getAttribute("currentTemperature").get()currentTemperature.getType().get() == AttributeType.TEMPERATURE_CELCIUS!currentTemperature.getValue().isPresent()- Meta protectedMeta = currentTemperature.getMeta()- protectedMeta.size() == 6- protectedMeta.stream().filter(isMetaNameEqualTo(AssetMeta.LABEL)).findFirst().get().getValueAsString().get() == "Current temperature"- protectedMeta.stream().filter(isMetaNameEqualTo(AssetMeta.READ_ONLY)).findFirst().get().getValueAsBoolean().get()- protectedMeta.stream().filter(isMetaNameEqualTo(AssetMeta.RULE_STATE)).findFirst().get().getValueAsBoolean().get()- protectedMeta.stream().filter(isMetaNameEqualTo(AssetMeta.STORE_DATA_POINTS)).findFirst().get().getValueAsBoolean().get()- protectedMeta.stream().filter(isMetaNameEqualTo(AssetMeta.SHOW_ON_DASHBOARD)).findFirst().get().getValueAsBoolean().get()- protectedMeta.stream().filter(isMetaNameEqualTo(AssetMeta.FORMAT)).findFirst().get().getValueAsString().get() == "%0.1f C"+ Meta resultMeta = currentTemperature.getMeta()+ resultMeta.size() == 6+ resultMeta.stream().filter(isMetaNameEqualTo(AssetMeta.LABEL)).findFirst().get().getValueAsString().get() == "Current temperature"+ resultMeta.stream().filter(isMetaNameEqualTo(AssetMeta.READ_ONLY)).findFirst().get().getValueAsBoolean().get()+ resultMeta.stream().filter(isMetaNameEqualTo(AssetMeta.RULE_STATE)).findFirst().get().getValueAsBoolean().get()+ resultMeta.stream().filter(isMetaNameEqualTo(STORE_DATA_POINTS)).findFirst().get().getValueAsBoolean().get()+ resultMeta.stream().filter(isMetaNameEqualTo(AssetMeta.SHOW_ON_DASHBOARD)).findFirst().get().getValueAsBoolean().get()+ resultMeta.stream().filter(isMetaNameEqualTo(AssetMeta.FORMAT)).findFirst().get().getValueAsString().get() == "%0.1f C"when: "an asset is retrieved by ID in a foreign realm"assetResource.get(null, managerDemoSetup.thingId)@@ -692,10 +703,37 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraitestAsset = assetResource.get(null, managerDemoSetup.apartment1LivingroomId)testAsset.setParentId(null)assetResource.update(null, testAsset.id, testAsset)+ testAsset = assetResource.get(null, managerDemoSetup.apartment1LivingroomId)- then: "a bad request error should occur"- ex = thrown()- ex.response.status == 400+ then: "the update should be ignored"+ assert testAsset.getParentId() == managerDemoSetup.apartment1Id++ when: "an asset is moved to a new parent in the authenticated realm"+ testAsset = assetResource.get(null, managerDemoSetup.apartment1LivingroomId)+ testAsset.setParentId(managerDemoSetup.apartment2Id)+ assetResource.update(null, testAsset.id, testAsset)+ testAsset = assetResource.get(null, managerDemoSetup.apartment1LivingroomId)++ then: "the update should be ignored"+ assert testAsset.getParentId() == managerDemoSetup.apartment1Id++ when: "an asset is made public"+ testAsset = assetResource.get(null, managerDemoSetup.apartment1LivingroomId)+ testAsset.setAccessPublicRead(true)+ assetResource.update(null, testAsset.id, testAsset)+ testAsset = assetResource.get(null, managerDemoSetup.apartment1LivingroomId)++ then: "the update should be ignored"+ assert !testAsset.isAccessPublicRead()++ when: "an asset is renamed"+ testAsset = assetResource.get(null, managerDemoSetup.apartment1LivingroomId)+ testAsset.setName("Ignored")+ assetResource.update(null, testAsset.id, testAsset)+ testAsset = assetResource.get(null, managerDemoSetup.apartment1LivingroomId)++ then: "the update should be ignored"+ assert testAsset.getName() == "Living Room"when: "an asset is created in the authenticated realm"testAsset = new Asset("Test Room", AssetType.ROOM, null, keycloakDemoSetup.customerATenant.id)@@ -727,23 +765,13 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiex = thrown()ex.response.status == 404- when: "a protected read-only asset attribute is written on a user asset"+ when: "a restricted read-only asset attribute is written on a user asset"assetResource.writeAttributeValue(null, managerDemoSetup.apartment1LivingroomId, "currentTemperature", Values.create(22.123).toJson())then: "the request should be forbidden"ex = thrown()ex.response.status == 403- when: "a protected asset attribute is written on a user asset"- assetResource.writeAttributeValue(null, managerDemoSetup.apartment1LivingroomId, "targetTemperature", Values.create(22.123).toJson())-- then: "result should match"- conditions.eventually {- def asset = assetResource.get(null, managerDemoSetup.apartment1LivingroomId)- assert asset.getAttribute("targetTemperature").get().getValue().isPresent()- assert asset.getAttribute("targetTemperature").get().getValue().get().toJson() == Values.create(22.123).toJson()- }-when: "an attribute is written on a non-existent user asset"assetResource.writeAttributeValue(null, "doesnotexist", "lightSwitch", Values.create(false).toJson())@@ -772,44 +800,109 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiex = thrown()ex.response.status == 403- when: "an non-protected asset attribute is updated"- testAsset = assetResource.get(null, managerDemoSetup.apartment1LivingroomId)- testAsset.replaceAttribute(new AssetAttribute("motionSensor", NUMBER)- .addMeta(new MetaItem(LABEL, Values.create("Motion Sensor")))- )- assetResource.update(null, testAsset.id, testAsset)+ when: "a non-writable attribute value is written on a user asset"+ assetResource.writeAttributeValue(null, managerDemoSetup.apartment1KitchenId, "presenceDetected", Values.create(true).toJson())- then: "a conflict error should occur"+ then: "access should be forbidden"ex = thrown()- ex.response.status == 409+ ex.response.status == 403- when: "an non protected writable meta item is added"- testAsset = assetResource.get(null, managerDemoSetup.apartment1LivingroomId)- testAsset.replaceAttribute(new AssetAttribute("currentTemperature", TEMPERATURE_CELCIUS)- .addMeta(new MetaItem(AssetMeta.PATTERN))- )+ when: "a non-writable attribute value is updated on a user asset"+ testAsset = assetResource.get(null, managerDemoSetup.apartment1KitchenId)+ testAsset.getAttribute("presenceDetected").get().setValue(Values.create(true))assetResource.update(null, testAsset.id, testAsset)+ testAsset = assetResource.get(null, managerDemoSetup.apartment1KitchenId)- then: "a bad request error should occur"- ex = thrown()- ex.response.status == 400+ then: "the update should be ignored"+ assert !testAsset.getAttribute("presenceDetected").get().getValue().isPresent()- when: "an asset attribute is updated"- testAsset = assetResource.get(null, managerDemoSetup.apartment1LivingroomId)- def temperatureAttr = testAsset.attributesStream.filter { assetAttr -> assetAttr.name.get().equalsIgnoreCase("targetTemperature") }.findFirst().orElse(null)- assert temperatureAttr != null- def labelMeta = temperatureAttr.getMetaItem(LABEL).orElse(null)- assert labelMeta != null- labelMeta.setValue(Values.create("Target Temperature"))+ when: "a non-writable attribute is updated on a user asset"+ testAsset = assetResource.get(null, managerDemoSetup.apartment1KitchenId)+ testAsset.replaceAttribute(new AssetAttribute("presenceDetected", BOOLEAN, Values.create(true)))+ assetResource.update(null, testAsset.id, testAsset)+ testAsset = assetResource.get(null, managerDemoSetup.apartment1KitchenId)++ then: "the update should be ignored"+ assert !testAsset.getAttribute("presenceDetected").get().getValue().isPresent()++ when: "a non-writable attribute's meta item value is updated"+ testAsset = assetResource.get(null, managerDemoSetup.apartment1KitchenId)+ testAsset.getAttribute("presenceDetected").orElse(null).getMetaItem(STORE_DATA_POINTS).orElse(null).setValue(Values.create(false))+ assetResource.update(null, testAsset.id, testAsset)++ then: "the update should be ignored"+ assert testAsset.getAttribute("presenceDetected").get().getMetaItem(STORE_DATA_POINTS).get().getValue().get()++ when: "a non-writable attribute's meta item value is added"+ testAsset = assetResource.get(null, managerDemoSetup.apartment1KitchenId)+ testAsset.getAttribute("presenceDetected").orElse(null).addMeta(new MetaItem(ABOUT, Values.create("Ignored")))+ assetResource.update(null, testAsset.id, testAsset)+ testAsset = assetResource.get(null, managerDemoSetup.apartment1KitchenId)++ then: "the update should be ignored"+ assert !testAsset.getAttribute("presenceDetected").get().getMetaItem(ABOUT).isPresent()++ when: "a new attribute is added on a user asset"+ testAsset = assetResource.get(null, managerDemoSetup.apartment1KitchenId)+ testAsset.addAttributes(new AssetAttribute("myCustomAttribute", NUMBER, Values.create(123)))+ assetResource.update(null, testAsset.id, testAsset)+ testAsset = assetResource.get(null, managerDemoSetup.apartment1KitchenId)++ then: "result should match"+ assert testAsset.getAttribute("myCustomAttribute").get().getValue().get() == Values.create(123)++ when: "a writable attribute value is written on a user asset"+ assetResource.writeAttributeValue(null, managerDemoSetup.apartment1KitchenId, "myCustomAttribute", Values.create(456).toJson())++ then: "result should match"+ conditions.eventually {+ testAsset = assetResource.get(null, managerDemoSetup.apartment1KitchenId)+ assert testAsset.getAttribute("myCustomAttribute").get().getValue().get() == Values.create(456)+ }++ when: "a writable attribute has a non-writable meta item"+ testAsset = assetResource.get(null, managerDemoSetup.apartment1KitchenId)+ testAsset.getAttribute("myCustomAttribute").get().addMeta(new MetaItem(PROTOCOL_CONFIGURATION, Values.create("Ignored")))+ testAsset = assetResource.get(null, managerDemoSetup.apartment1KitchenId)+ assetResource.update(null, testAsset.id, testAsset)++ then: "the update should be ignored"+ assert !testAsset.getAttribute("presenceDetected").get().getMetaItem(PROTOCOL_CONFIGURATION).isPresent()++ when: "a writable attribute has a writable meta item"+ testAsset = assetResource.get(null, managerDemoSetup.apartment1KitchenId)+ testAsset.getAttribute("myCustomAttribute").get().addMeta(new MetaItem(LABEL, Values.create("My label")))+ assetResource.update(null, testAsset.id, testAsset)+ testAsset = assetResource.get(null, managerDemoSetup.apartment1KitchenId)++ then: "the result should match"+ assert testAsset.getAttribute("myCustomAttribute").get().getMetaItem(LABEL).get().getValue().get() == Values.create("My label")++ when: "a writable attribute has a writable meta item value update"+ testAsset = assetResource.get(null, managerDemoSetup.apartment1KitchenId)+ testAsset.getAttribute("myCustomAttribute").get().getMetaItem(LABEL).get().setValue(Values.create("My label update"))+ assetResource.update(null, testAsset.id, testAsset)+ testAsset = assetResource.get(null, managerDemoSetup.apartment1KitchenId)++ then: "the result should match"+ assert testAsset.getAttribute("myCustomAttribute").get().getMetaItem(LABEL).get().getValue().get() == Values.create("My label update")++ when: "a writable attribute replaces a writable meta item with several new items"+ testAsset = assetResource.get(null, managerDemoSetup.apartment1KitchenId)+ testAsset.getAttribute("myCustomAttribute").get().getMeta().removeIf(isMetaNameEqualTo(LABEL))+ testAsset.getAttribute("myCustomAttribute").get().addMeta(+ new MetaItem(LABEL, Values.create("Label1")),+ new MetaItem(LABEL, Values.create("Label2")),+ new MetaItem(LABEL, Values.create("Label3")),+ )assetResource.update(null, testAsset.id, testAsset)+ testAsset = assetResource.get(null, managerDemoSetup.apartment1KitchenId)- then: "no error should occur"- def updatedAsset = assetResource.get(null, managerDemoSetup.apartment1LivingroomId)- def updatedAttribute = updatedAsset.getAttribute("targetTemperature")- assert updatedAttribute.isPresent()- def updatedMetaItem = updatedAttribute.get().getMetaItem(LABEL)- assert updatedMetaItem.isPresent()- assert updatedMetaItem.get().valueAsString.get() == "Target Temperature"+ then: "the result should match"+ assert testAsset.getAttribute("myCustomAttribute").get().getMetaItems(LABEL.getUrn()).length == 3+ assert testAsset.getAttribute("myCustomAttribute").get().getMetaItems(LABEL.getUrn())[0].getValue().get() == Values.create("Label1")+ assert testAsset.getAttribute("myCustomAttribute").get().getMetaItems(LABEL.getUrn())[1].getValue().get() == Values.create("Label2")+ assert testAsset.getAttribute("myCustomAttribute").get().getMetaItems(LABEL.getUrn())[2].getValue().get() == Values.create("Label3")cleanup: "the server should be stopped"stopContainer(container)diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetPublicQueryTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetPublicQueryTest.groovynew file mode 100644index 000000000..22273da58--- /dev/null+++ b/test/src/test/groovy/org/openremote/test/assets/AssetPublicQueryTest.groovy@@ -0,0 +1,99 @@+package org.openremote.test.assets++import org.openremote.container.Container+import org.openremote.container.persistence.PersistenceService+import org.openremote.manager.server.asset.AssetStorageService+import org.openremote.manager.server.asset.ServerAsset+import org.openremote.manager.server.setup.SetupService+import org.openremote.manager.server.setup.builtin.KeycloakDemoSetup+import org.openremote.manager.server.setup.builtin.ManagerDemoSetup+import org.openremote.manager.shared.asset.AssetResource+import org.openremote.model.asset.AssetAttribute+import org.openremote.model.asset.AssetQuery+import org.openremote.model.attribute.MetaItem+import org.openremote.model.value.Values+import org.openremote.test.ManagerContainerTrait+import spock.lang.Shared+import spock.lang.Specification++import static org.openremote.model.Constants.MASTER_REALM+import static org.openremote.model.asset.AbstractAssetQuery.*+import static org.openremote.model.asset.AssetMeta.ACCESS_PUBLIC_READ+import static org.openremote.model.asset.AssetMeta.LABEL+import static org.openremote.model.asset.AssetType.THING+import static org.openremote.model.attribute.AttributeType.NUMBER++class AssetPublicQueryTest extends Specification implements ManagerContainerTrait {++ @Shared+ static Container container+ @Shared+ static ManagerDemoSetup managerDemoSetup+ @Shared+ static KeycloakDemoSetup keycloakDemoSetup+ @Shared+ static AssetStorageService assetStorageService+ @Shared+ static PersistenceService persistenceService+ @Shared+ static AssetResource assetResource++ @Shared+ static String somePublicAssetId++ def setupSpec() {+ given: "the server container is started"+ def serverPort = findEphemeralPort()+ container = startContainer(defaultConfig(serverPort), defaultServices())+ managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)+ keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)+ assetStorageService = container.getService(AssetStorageService.class)+ persistenceService = container.getService(PersistenceService.class)+ assetResource = getClientTarget(serverUri(serverPort), MASTER_REALM).proxy(AssetResource.class)++ ServerAsset somePublicAsset = new ServerAsset("Some Public Asset", THING)+ somePublicAsset.setParentId(managerDemoSetup.smartOfficeId)+ somePublicAsset.setAccessPublicRead(true)+ somePublicAsset.setAttributes(+ new AssetAttribute("somePrivateAttribute", NUMBER, Values.create(123)).addMeta(+ new MetaItem(LABEL, Values.create("Some Private Attribute"))+ ),+ new AssetAttribute("somePublicAttribute", NUMBER, Values.create(456)).addMeta(+ new MetaItem(LABEL, Values.create("Some Public Attribute")),+ new MetaItem(ACCESS_PUBLIC_READ, Values.create(true))+ ),+ )++ somePublicAsset = assetStorageService.merge(somePublicAsset)+ somePublicAssetId = somePublicAsset.getId()+ }++ def cleanupSpec() {+ given: "the server should be stopped"+ stopContainer(container)+ }++ def "Query public assets"() {++ when: "a query for all public assets is executed"+ def assets = assetResource.queryPublicAssets(null,+ new AssetQuery()+ .select(new Select(Include.ALL, Access.PUBLIC_READ))+ .tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.id))+ )++ then: "the result should match"+ assets.size() == 1+ assets[0].id == somePublicAssetId+ assets[0].name == "Some Public Asset"+ assets[0].wellKnownType == THING+ assets[0].parentId == managerDemoSetup.smartOfficeId+ assets[0].realmId == keycloakDemoSetup.masterTenant.id+ assets[0].tenantRealm == keycloakDemoSetup.masterTenant.realm+ assets[0].tenantDisplayName == keycloakDemoSetup.masterTenant.displayName+ !assets[0].getAttribute("somePrivateAttribute").isPresent()+ assets[0].getAttribute("somePublicAttribute").get().getValue().get() == Values.create(456)+ assets[0].getAttribute("somePublicAttribute").get().getMeta().size() == 1+ assets[0].getAttribute("somePublicAttribute").get().getMetaItem(LABEL).get().getValueAsString().get() == "Some Public Attribute"+ }+}diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovyindex c120bc719..8d1994b12 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy@@ -18,6 +18,8 @@ import javax.persistence.EntityManagerimport java.util.function.Functionimport static org.openremote.model.asset.AbstractAssetQuery.*+import static org.openremote.model.asset.AbstractAssetQuery.Access.PRIVATE_READ+import static org.openremote.model.asset.AbstractAssetQuery.Access.RESTRICTED_READimport static org.openremote.model.asset.AbstractAssetQuery.OrderBy.Property.CREATED_ONimport static org.openremote.model.asset.AbstractAssetQuery.OrderBy.Property.NAMEimport static org.openremote.model.asset.AssetType.THING@@ -97,7 +99,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {when: "a user filtering query is executed that returns only IDs, names and attribute names and limits to protected attributes and meta"assets = assetStorageService.findAll(new AssetQuery()- .select(new Select(Include.ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES, true))+ .select(new Select(Include.ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES, RESTRICTED_READ)).userId(keycloakDemoSetup.testuser3Id))@@ -117,7 +119,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {when: "a query is executed that returns a protected attribute without any other meta items"assets = assetStorageService.findAll(new AssetQuery()- .select(new Select(Include.ALL_EXCEPT_PATH, true))+ .select(new Select(Include.ALL_EXCEPT_PATH, RESTRICTED_READ)).id(managerDemoSetup.apartment2LivingroomId))@@ -133,7 +135,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {assets = assetStorageService.findAll(new AssetQuery().id(managerDemoSetup.smartHomeId)- .select(new Select(Include.ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES, false, true))+ .select(new Select(Include.ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES, true, RESTRICTED_READ)).orderBy(new OrderBy(CREATED_ON)))@@ -223,7 +225,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {when: "a query is executed"asset = assetStorageService.find(new AssetQuery()- .select(new Select(Include.ALL, false))+ .select(new Select(Include.ALL)).id(managerDemoSetup.smartOfficeId))@@ -271,7 +273,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {when: "a query is executed"assets = assetStorageService.findAll(new AssetQuery()- .select(new Select(Include.ALL, false))+ .select(new Select(Include.ALL)).parent(new ParentPredicate(true)).tenant(new TenantPredicate(keycloakDemoSetup.masterTenant.id)))@@ -383,7 +385,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {when: "a query is executed"assets = assetStorageService.findAll(- new AssetQuery().select(new Select(Include.ALL, true)).userId(keycloakDemoSetup.testuser3Id)+ new AssetQuery().select(new Select(Include.ALL, RESTRICTED_READ)).userId(keycloakDemoSetup.testuser3Id))then: "result should match"@@ -400,7 +402,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {when: "a query is executed"assets = assetStorageService.findAll(- new AssetQuery().select(new Select(Include.ALL, true)).userId(keycloakDemoSetup.testuser2Id)+ new AssetQuery().select(new Select(Include.ALL, RESTRICTED_READ)).userId(keycloakDemoSetup.testuser2Id))then: "result should match"@@ -561,7 +563,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {def asset = assetStorageService.find(new AssetQuery().id(managerDemoSetup.apartment1LivingroomId)- .select(new Select(Include.ALL, false, false, "co2Level", "lastPresenceDetected", "motionSensor"))+ .select(new Select(Include.ALL, false, PRIVATE_READ, "co2Level", "lastPresenceDetected", "motionSensor")))then: "result should match"@@ -590,7 +592,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {asset = assetStorageService.find(new AssetQuery().id(managerDemoSetup.apartment1LivingroomId)- .select(new Select(Include.ALL, false, false, "co2Level", "lastPresenceDetected", "motionSensor").filterProtected(true))+ .select(new Select(Include.ALL, false, RESTRICTED_READ, "co2Level", "lastPresenceDetected", "motionSensor")))then: "result should contain only matches that are protected"