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
Implemented rules deployment model and web API, started on rules manager UI
Christian Bauerf65187f9b0e4
diff --git a/manager/client/src/main/java/org/openremote/manager/client/ManagerActivityMapper.java b/manager/client/src/main/java/org/openremote/manager/client/ManagerActivityMapper.javaindex 833b8e22f..cb7c0b1ad 100644--- a/manager/client/src/main/java/org/openremote/manager/client/ManagerActivityMapper.java+++ b/manager/client/src/main/java/org/openremote/manager/client/ManagerActivityMapper.java@@ -1,5 +1,5 @@/*- * Copyright 2016, OpenRemote Inc.+ * Copyright 2017, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -45,8 +45,12 @@ import org.openremote.manager.client.map.MapPlace;import org.openremote.manager.client.mvp.AppActivity;import org.openremote.manager.client.mvp.AppActivityMapper;import org.openremote.manager.client.mvp.RoleRequiredException;-import org.openremote.manager.client.rules.RulesActivity;-import org.openremote.manager.client.rules.RulesPlace;+import org.openremote.manager.client.rules.RulesGlobalActivity;+import org.openremote.manager.client.rules.RulesGlobalPlace;+import org.openremote.manager.client.rules.asset.RulesAssetActivity;+import org.openremote.manager.client.rules.asset.RulesAssetPlace;+import org.openremote.manager.client.rules.tenant.RulesTenantActivity;+import org.openremote.manager.client.rules.tenant.RulesTenantPlace;import org.openremote.manager.client.service.SecurityService;import org.openremote.manager.client.user.UserAccountActivity;import org.openremote.manager.client.user.UserAccountPlace;@@ -64,7 +68,9 @@ public class ManagerActivityMapper implements AppActivityMapper {protected final Provider<AssetsDashboardActivity> assetsDashboardActivityProvider;protected final Provider<AssetActivity> assetActivityProvider;protected final Provider<MapActivity> mapActivityProvider;- protected final Provider<RulesActivity> rulesActivityProvider;+ protected final Provider<RulesGlobalActivity> rulesGlobalActivityProvider;+ protected final Provider<RulesTenantActivity> rulesTenantActivityProvider;+ protected final Provider<RulesAssetActivity> rulesAssetActivityProvider;protected final Provider<FlowsActivity> flowsActivityProvider;protected final Provider<AdminOverviewActivity> adminOverviewActivityProvider;protected final Provider<AdminTenantsActivity> adminTenantsActivityProvider;@@ -80,7 +86,9 @@ public class ManagerActivityMapper implements AppActivityMapper {Provider<AssetsDashboardActivity> assetsDashboardActivityProvider,Provider<AssetActivity> assetActivityProvider,Provider<MapActivity> mapActivityProvider,- Provider<RulesActivity> rulesActivityProvider,+ Provider<RulesGlobalActivity> rulesGlobalActivityProvider,+ Provider<RulesTenantActivity> rulesTenantActivityProvider,+ Provider<RulesAssetActivity> rulesAssetActivityProvider,Provider<FlowsActivity> flowsActivityProvider,Provider<AdminOverviewActivity> adminOverviewActivityProvider,Provider<AdminTenantsActivity> adminTenantsActivityProvider,@@ -94,7 +102,9 @@ public class ManagerActivityMapper implements AppActivityMapper {this.assetsDashboardActivityProvider = assetsDashboardActivityProvider;this.assetActivityProvider = assetActivityProvider;this.mapActivityProvider = mapActivityProvider;- this.rulesActivityProvider= rulesActivityProvider;+ this.rulesGlobalActivityProvider = rulesGlobalActivityProvider;+ this.rulesTenantActivityProvider = rulesTenantActivityProvider;+ this.rulesAssetActivityProvider = rulesAssetActivityProvider;this.flowsActivityProvider = flowsActivityProvider;this.adminOverviewActivityProvider = adminOverviewActivityProvider;this.adminTenantsActivityProvider = adminTenantsActivityProvider;@@ -115,8 +125,14 @@ public class ManagerActivityMapper implements AppActivityMapper {if (place instanceof MapPlace) {return mapActivityProvider.get().init(securityService, (MapPlace) place);}- if (place instanceof RulesPlace) {- return rulesActivityProvider.get().init(securityService, (RulesPlace) place);+ if (place instanceof RulesGlobalPlace) {+ return rulesGlobalActivityProvider.get().init(securityService, (RulesGlobalPlace) place);+ }+ if (place instanceof RulesTenantPlace) {+ return rulesTenantActivityProvider.get().init(securityService, (RulesTenantPlace) place);+ }+ if (place instanceof RulesAssetPlace) {+ return rulesAssetActivityProvider.get().init(securityService, (RulesAssetPlace) place);}if (place instanceof FlowsPlace) {return flowsActivityProvider.get().init(securityService, (FlowsPlace) place);diff --git a/manager/client/src/main/java/org/openremote/manager/client/ManagerHistoryMapper.java b/manager/client/src/main/java/org/openremote/manager/client/ManagerHistoryMapper.javaindex 3b4fcc6fa..e28851641 100644--- a/manager/client/src/main/java/org/openremote/manager/client/ManagerHistoryMapper.java+++ b/manager/client/src/main/java/org/openremote/manager/client/ManagerHistoryMapper.java@@ -1,5 +1,5 @@/*- * Copyright 2016, OpenRemote Inc.+ * Copyright 2017, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -30,7 +30,9 @@ import org.openremote.manager.client.assets.AssetsDashboardPlace;import org.openremote.manager.client.assets.asset.AssetPlace;import org.openremote.manager.client.flows.FlowsPlace;import org.openremote.manager.client.map.MapPlace;-import org.openremote.manager.client.rules.RulesPlace;+import org.openremote.manager.client.rules.RulesGlobalPlace;+import org.openremote.manager.client.rules.asset.RulesAssetPlace;+import org.openremote.manager.client.rules.tenant.RulesTenantPlace;import org.openremote.manager.client.user.UserAccountPlace;@WithTokenizers(@@ -38,7 +40,9 @@ import org.openremote.manager.client.user.UserAccountPlace;MapPlace.Tokenizer.class,AssetsDashboardPlace.Tokenizer.class,AssetPlace.Tokenizer.class,- RulesPlace.Tokenizer.class,+ RulesGlobalPlace.Tokenizer.class,+ RulesTenantPlace.Tokenizer.class,+ RulesAssetPlace.Tokenizer.class,FlowsPlace.Tokenizer.class,AdminOverviewPlace.Tokenizer.class,AdminTenantsPlace.Tokenizer.class,diff --git a/manager/client/src/main/java/org/openremote/manager/client/app/FooterViewImpl.java b/manager/client/src/main/java/org/openremote/manager/client/app/FooterViewImpl.javaindex efde67b9b..af3ccf794 100644--- a/manager/client/src/main/java/org/openremote/manager/client/app/FooterViewImpl.java+++ b/manager/client/src/main/java/org/openremote/manager/client/app/FooterViewImpl.java@@ -20,27 +20,36 @@package org.openremote.manager.client.app;import com.google.gwt.core.client.GWT;+import com.google.gwt.event.dom.client.ClickEvent;import com.google.gwt.place.shared.Place;import com.google.gwt.uibinder.client.UiBinder;+import com.google.gwt.uibinder.client.UiField;+import com.google.gwt.uibinder.client.UiHandler;import com.google.gwt.user.client.ui.Composite;import com.google.gwt.user.client.ui.HTMLPanel;import com.google.inject.Inject;import org.openremote.manager.client.i18n.ManagerMessages;+import org.openremote.manager.client.map.MapViewImpl;+import org.openremote.manager.client.widget.PushButton;public class FooterViewImpl extends Composite implements FooterView {interface UI extends UiBinder<HTMLPanel, FooterViewImpl> {}- private static UI ui = GWT.create(UI.class);+ @UiField+ PushButton fullscreenButton;private Presenter presenter;private ManagerMessages messages;+@Injectpublic FooterViewImpl(ManagerMessages messages) {this.messages = messages;++ FooterViewImpl.UI ui = GWT.create(FooterViewImpl.UI.class);initWidget(ui.createAndBindUi(this));}@@ -49,9 +58,39 @@ public class FooterViewImpl extends Composite implements FooterView {this.presenter = presenter;}-@Overridepublic void onPlaceChange(Place place) {// TODO}++ @UiHandler("fullscreenButton")+ public void onFullscreenClicked(ClickEvent e) {+ toggleFullscreen();+ }++ protected native void toggleFullscreen() /*-{+ var doc = $wnd.document;+ if (!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {+ if (doc.documentElement.requestFullscreen) {+ doc.documentElement.requestFullscreen();+ } else if (doc.documentElement.msRequestFullscreen) {+ doc.documentElement.msRequestFullscreen();+ } else if (doc.documentElement.mozRequestFullScreen) {+ doc.documentElement.mozRequestFullScreen();+ } else if (doc.documentElement.webkitRequestFullscreen) {+ doc.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);+ }+ } else {+ if (doc.exitFullscreen) {+ doc.exitFullscreen();+ } else if (doc.msExitFullscreen) {+ doc.msExitFullscreen();+ } else if (doc.mozCancelFullScreen) {+ doc.mozCancelFullScreen();+ } else if (doc.webkitExitFullscreen) {+ doc.webkitExitFullscreen();+ }+ }++ }-*/;}\ No newline at end of filediff --git a/manager/client/src/main/java/org/openremote/manager/client/app/FooterViewImpl.ui.xml b/manager/client/src/main/java/org/openremote/manager/client/app/FooterViewImpl.ui.xmlindex 76a060528..edac4e5b0 100644--- a/manager/client/src/main/java/org/openremote/manager/client/app/FooterViewImpl.ui.xml+++ b/manager/client/src/main/java/org/openremote/manager/client/app/FooterViewImpl.ui.xml@@ -1,18 +1,34 @@-<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'- xmlns:g='urn:import:com.google.gwt.user.client.ui'>+<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"+ xmlns:g="urn:import:com.google.gwt.user.client.ui"+ xmlns:w="urn:import:org.openremote.manager.client.widget"><ui:style>.footer {- font-size: x-small;+ font-size: small;padding: 0.4em;}++ .navItem {+ margin: 0 1em;+ }++ .brand {+ font-size: x-small;+ }</ui:style><ui:with field="managerMessages" type="org.openremote.manager.client.i18n.ManagerMessages"/><ui:with field="widgetStyle" type="org.openremote.manager.client.style.WidgetStyle"/>- <g:HTMLPanel styleName="flex layout end-justified horizontal" addStyleNames="{style.footer} {widgetStyle.Footer}">- <div class="{widgetStyle.Hyperlink}">+ <g:HTMLPanel styleName="flex layout horizontal end-justified center" addStyleNames="{style.footer} {widgetStyle.Footer}">++ <w:PushButton+ ui:field="fullscreenButton"+ addStyleNames="{style.navItem} {widgetStyle.SecondaryNavItem}"+ icon="expand"+ text="{managerMessages.fullscreen}"/>++ <div class="{widgetStyle.Hyperlink} {style.brand}"><g:Anchor href="http://openremote.com/">© OpenRemote Inc.</g:Anchor></div></g:HTMLPanel>diff --git a/manager/client/src/main/java/org/openremote/manager/client/app/HeaderPresenter.java b/manager/client/src/main/java/org/openremote/manager/client/app/HeaderPresenter.javaindex 0d01905ff..75a9c9e39 100644--- a/manager/client/src/main/java/org/openremote/manager/client/app/HeaderPresenter.java+++ b/manager/client/src/main/java/org/openremote/manager/client/app/HeaderPresenter.java@@ -32,7 +32,8 @@ import org.openremote.manager.client.event.bus.EventBus;import org.openremote.manager.client.event.bus.EventRegistration;import org.openremote.manager.client.flows.FlowsPlace;import org.openremote.manager.client.map.MapPlace;-import org.openremote.manager.client.rules.RulesPlace;+import org.openremote.manager.client.rules.RulesGlobalPlace;+import org.openremote.manager.client.rules.asset.RulesAssetPlace;import org.openremote.manager.client.service.SecurityService;import org.openremote.manager.client.user.UserControls;import org.openremote.model.Constants;@@ -109,8 +110,11 @@ public class HeaderPresenter implements HeaderView.Presenter {@Overridepublic void navigateRules() {- placeController.goTo(new RulesPlace());-+ if (selectedAssetId != null) {+ placeController.goTo(new RulesAssetPlace(selectedAssetId));+ } else {+ placeController.goTo(new RulesGlobalPlace());+ }}@Overridediff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/AssetsDashboardImpl.ui.xml b/manager/client/src/main/java/org/openremote/manager/client/assets/AssetsDashboardImpl.ui.xmlindex 71deef497..1d9c19465 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/AssetsDashboardImpl.ui.xml+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/AssetsDashboardImpl.ui.xml@@ -29,12 +29,6 @@<g:HTMLPanelstyleName="layout horizontal center end-justified {style.assetsControls} {widgetStyle.SecondaryNavHorizontal}">- <w:Hyperlink- addStyleNames="{style.navItem} {widgetStyle.SecondaryNavItem}"- icon="edit"- targetHistoryToken="assets:"- text="{managerMessages.editDashboard}"/>-<w:HyperlinkaddStyleNames="{style.navItem} {widgetStyle.SecondaryNavItem}"icon="plus-square"diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/AssetsModule.java b/manager/client/src/main/java/org/openremote/manager/client/assets/AssetsModule.javaindex dda507888..16ad0e948 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/AssetsModule.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/AssetsModule.java@@ -29,7 +29,6 @@ import org.openremote.manager.client.assets.browser.AssetBrowser;import org.openremote.manager.client.assets.browser.AssetBrowserImpl;import org.openremote.manager.client.assets.browser.AssetBrowserPresenter;import org.openremote.manager.shared.asset.AssetResource;-import org.openremote.manager.shared.connector.ConnectorResource;public class AssetsModule extends AbstractGinModule {@@ -54,16 +53,4 @@ public class AssetsModule extends AbstractGinModule {public static native AssetResource getNativeAssetResource() /*-{return $wnd.AssetResource;}-*/;--- @Provides- @Singleton- public ConnectorResource getConnectorResource() {- return getNativeConnectorResource();- }-- public static native ConnectorResource getNativeConnectorResource() /*-{- return $wnd.ConnectorResource;- }-*/;-}diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/agent/AgentAttributesEditor.java b/manager/client/src/main/java/org/openremote/manager/client/assets/agent/AgentAttributesEditor.javaindex b59e52065..942ff5173 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/agent/AgentAttributesEditor.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/agent/AgentAttributesEditor.java@@ -23,20 +23,16 @@ import com.google.gwt.text.shared.AbstractRenderer;import org.openremote.manager.client.Environment;import org.openremote.manager.client.event.ServerSendEvent;import org.openremote.manager.client.widget.*;-import org.openremote.model.Consumer;import org.openremote.manager.shared.agent.Agent;import org.openremote.manager.shared.agent.RefreshInventoryEvent;-import org.openremote.model.asset.Asset;import org.openremote.manager.shared.connector.Connector;-import org.openremote.manager.shared.connector.ConnectorResource;import org.openremote.manager.shared.event.ui.ShowInfoEvent;import org.openremote.model.Attribute;import org.openremote.model.Attributes;+import org.openremote.model.asset.Asset;-import java.util.Arrays;import java.util.List;-import static org.openremote.manager.client.http.RequestExceptionHandler.handleRequestException;import static org.openremote.manager.shared.connector.Connector.ASSET_ATTRIBUTE_CONNECTOR;public class AgentAttributesEditor extends AttributesEditor<AttributesEditor.Style> {@@ -44,9 +40,6 @@ public class AgentAttributesEditor extends AttributesEditor<AttributesEditor.Styfinal protected Agent agent;final protected Asset agentAsset;- final protected ConnectorResource connectorResource;- final protected ConnectorArrayMapper connectorArrayMapper;-final protected FormGroup connectorListBoxGroup = new FormGroup();final protected FormValueListBox<Connector> connectorListBox;@@ -63,16 +56,11 @@ public class AgentAttributesEditor extends AttributesEditor<AttributesEditor.StyContainer<AttributesEditor.Style> container,Attributes attributes,boolean isCreateAsset,- Asset agentAsset,- ConnectorResource connectorResource,- ConnectorArrayMapper connectorArrayMapper) {+ Asset agentAsset) {super(environment, container, attributes);this.agentAsset = agentAsset;this.agent = new Agent(attributes, isCreateAsset);- this.connectorResource = connectorResource;- this.connectorArrayMapper = connectorArrayMapper;-connectorListBox = createConnectorListBox();FormLabel connectorListBoxLabel = new FormLabel();connectorListBoxLabel.setText(environment.getMessages().connector());@@ -96,6 +84,7 @@ public class AgentAttributesEditor extends AttributesEditor<AttributesEditor.StyactionsField.add(refreshInventoryButton);container.getFormView().setFormBusy(true);+/*loadConnectors(connectors -> {availableConnectors = Arrays.asList(connectors);@@ -120,6 +109,7 @@ public class AgentAttributesEditor extends AttributesEditor<AttributesEditor.Stycontainer.getFormView().setFormBusy(false);//clearBuild();});+*/}@Override@@ -198,16 +188,6 @@ public class AgentAttributesEditor extends AttributesEditor<AttributesEditor.Sty// clearBuild();}- protected void loadConnectors(Consumer<Connector[]> onSuccess) {- environment.getRequestService().execute(- connectorArrayMapper,- connectorResource::getConnectors,- 200,- onSuccess::accept,- ex -> handleRequestException(ex, environment)- );- }-protected Connector getConnector() {Connector assignedConnector = null;for (Connector connector : availableConnectors) {diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetActivity.java b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetActivity.javaindex 3ceb46ecc..3a6415cc7 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetActivity.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/asset/AssetActivity.java@@ -23,21 +23,19 @@ import com.google.gwt.user.client.ui.AcceptsOneWidget;import org.openremote.manager.client.Environment;import org.openremote.manager.client.assets.AssetMapper;import org.openremote.manager.client.assets.AssetsDashboardPlace;-import org.openremote.manager.client.assets.agent.ConnectorArrayMapper;import org.openremote.manager.client.assets.browser.AssetBrowser;import org.openremote.manager.client.assets.browser.AssetBrowsingActivity;import org.openremote.manager.client.event.bus.EventBus;import org.openremote.manager.client.event.bus.EventRegistration;import org.openremote.manager.client.interop.elemental.JsonObjectMapper;import org.openremote.manager.client.widget.AttributesEditor;-import org.openremote.model.asset.Asset;-import org.openremote.model.asset.AssetInfo;import org.openremote.manager.shared.asset.AssetResource;-import org.openremote.model.asset.AssetType;-import org.openremote.manager.shared.connector.ConnectorResource;import org.openremote.manager.shared.event.ui.ShowInfoEvent;import org.openremote.manager.shared.map.MapResource;import org.openremote.model.Attributes;+import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AssetInfo;+import org.openremote.model.asset.AssetType;import javax.inject.Inject;import java.util.Arrays;@@ -55,9 +53,6 @@ public class AssetActivityfinal protected MapResource mapResource;final protected JsonObjectMapper jsonObjectMapper;- final protected ConnectorArrayMapper connectorArrayMapper;- final protected ConnectorResource connectorResource;-protected boolean isCreateAsset;protected double[] selectedCoordinates;protected String realm;@@ -72,14 +67,10 @@ public class AssetActivityAssetResource assetResource,AssetMapper assetMapper,MapResource mapResource,- JsonObjectMapper jsonObjectMapper,- ConnectorArrayMapper connectorArrayMapper,- ConnectorResource connectorResource) {+ JsonObjectMapper jsonObjectMapper) {super(environment, view, assetBrowserPresenter, assetResource, assetMapper);this.mapResource = mapResource;this.jsonObjectMapper = jsonObjectMapper;- this.connectorArrayMapper = connectorArrayMapper;- this.connectorResource = connectorResource;}@Overridediff --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 060f9aca6..c60013f55 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@@ -31,8 +31,7 @@ import java.util.Date;public interface AssetView extends AssetBrowsingView<AssetView.Presenter>, FormView {- interface- Presenter extends AssetBrowsingView.Presenter {+ interface Presenter extends AssetBrowsingView.Presenter {void beginParentSelection();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 e47c226f8..41a56e66e 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@@ -226,10 +226,10 @@</w:label><w:field><w:FormField addStyleNames="larger">- <g:FlowPanel styleName="layout horizontal center">+ <g:FlowPanel styleName="flex layout horizontal center"><w:FormValueListBox ui:field="typeListBox"/><w:FormInputText ui:field="typeInput"- addStyleNames="{style.typeInput}"+ addStyleNames="flex"visible="false"/></g:FlowPanel></w:FormField>diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowsingActivity.java b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowsingActivity.javaindex b2834aa08..734959fef 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowsingActivity.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetBrowsingActivity.java@@ -83,7 +83,6 @@ abstract public class AssetBrowsingActivity<V extends AssetBrowsingView, T extenreturn this;}-@Overridepublic void start(AcceptsOneWidget container, EventBus eventBus, Collection<EventRegistration> registrations) {//noinspection uncheckeddiff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetCell.java b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetCell.javaindex e57094aa4..a2f71ce69 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetCell.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/browser/AssetCell.java@@ -83,14 +83,14 @@ class AssetCell extends AbstractSafeHtmlCell<AssetInfo> {return "group";case BUILDING:return "building";+ case RESIDENCE:+ return "cubes";case FLOOR:return "server";-/* TODOcase AGENT:- return "cubes";- case DEVICE:+ return "gears";+ case THING:return "gear";-*/default:return "cube";}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 2fb01485f..67a1f3322 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@@ -287,4 +287,7 @@ public interface ManagerMessages extends Messages {String enterNameAndSelectType();+ String fullscreen();++ String editGlobalRules();}diff --git a/manager/client/src/main/java/org/openremote/manager/client/map/MapViewImpl.java b/manager/client/src/main/java/org/openremote/manager/client/map/MapViewImpl.javaindex 233493c18..4f5655b6c 100644--- a/manager/client/src/main/java/org/openremote/manager/client/map/MapViewImpl.java+++ b/manager/client/src/main/java/org/openremote/manager/client/map/MapViewImpl.java@@ -77,9 +77,6 @@ public class MapViewImpl extends Composite implements MapView {@UiFieldMapWidget mapWidget;- @UiField- PushButton fullscreenButton;-final AssetBrowser assetBrowser;final Provider<MapInfoPanel> infoPanelProvider;final MapInfoPanel infoPanel1;@@ -171,11 +168,6 @@ public class MapViewImpl extends Composite implements MapView {mapWidget.flyTo(coordinates);}- @UiHandler("fullscreenButton")- public void onFullscreenClicked(ClickEvent e) {- toggleFullscreen();- }-protected void showInfoPanels() {/* TODO There is a timing issue with the position when the map widget is initialized for the first timeinfoPanel1.showTopLeftOf(mapWidget, 10, 10);@@ -187,30 +179,4 @@ public class MapViewImpl extends Composite implements MapView {infoPanel1.hide();infoPanel2.hide();}-- protected native void toggleFullscreen() /*-{- var doc = $wnd.document;- if (!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {- if (doc.documentElement.requestFullscreen) {- doc.documentElement.requestFullscreen();- } else if (doc.documentElement.msRequestFullscreen) {- doc.documentElement.msRequestFullscreen();- } else if (doc.documentElement.mozRequestFullScreen) {- doc.documentElement.mozRequestFullScreen();- } else if (doc.documentElement.webkitRequestFullscreen) {- doc.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);- }- } else {- if (doc.exitFullscreen) {- doc.exitFullscreen();- } else if (doc.msExitFullscreen) {- doc.msExitFullscreen();- } else if (doc.mozCancelFullScreen) {- doc.mozCancelFullScreen();- } else if (doc.webkitExitFullscreen) {- doc.webkitExitFullscreen();- }- }-- }-*/;}diff --git a/manager/client/src/main/java/org/openremote/manager/client/map/MapViewImpl.ui.xml b/manager/client/src/main/java/org/openremote/manager/client/map/MapViewImpl.ui.xmlindex 1598c271e..2c556bb8b 100644--- a/manager/client/src/main/java/org/openremote/manager/client/map/MapViewImpl.ui.xml+++ b/manager/client/src/main/java/org/openremote/manager/client/map/MapViewImpl.ui.xml@@ -52,18 +52,6 @@<g:HTMLPanelstyleName="layout horizontal center end-justified {style.mapControls} {widgetStyle.SecondaryNavHorizontal}">- <w:Hyperlink- addStyleNames="{style.navItem} {widgetStyle.SecondaryNavItem}"- icon="map"- targetHistoryToken="map:"- text="Show all assets"/>-- <w:PushButton- ui:field="fullscreenButton"- addStyleNames="{style.navItem} {widgetStyle.SecondaryNavItem}"- icon="expand"- text="Fullscreen"/>-<w:HyperlinkaddStyleNames="{style.navItem} {widgetStyle.SecondaryNavItem}"icon="plus-square"diff --git a/manager/client/src/main/java/org/openremote/manager/client/rules/RulesActivity.java b/manager/client/src/main/java/org/openremote/manager/client/rules/RulesActivity.javadeleted file mode 100644index 2d7d22612..000000000--- a/manager/client/src/main/java/org/openremote/manager/client/rules/RulesActivity.java+++ /dev/null@@ -1,72 +0,0 @@-/*- * Copyright 2016, OpenRemote Inc.- *- * See the CONTRIBUTORS.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.manager.client.rules;--import com.google.gwt.place.shared.PlaceController;-import com.google.gwt.user.client.ui.AcceptsOneWidget;-import elemental.client.Browser;-import org.openremote.manager.client.event.bus.EventBus;-import org.openremote.manager.client.event.bus.EventRegistration;-import org.openremote.manager.client.mvp.AppActivity;-import org.openremote.manager.client.service.SecurityService;--import javax.inject.Inject;-import java.util.Collection;-import java.util.logging.Logger;--public class RulesActivity- extends AppActivity<RulesPlace>- implements RulesView.Presenter {-- private static final Logger LOG = Logger.getLogger(RulesActivity.class.getName());-- final RulesView view;- final PlaceController placeController;- final EventBus eventBus;- final SecurityService securityService;-- @Inject- public RulesActivity(RulesView view,- PlaceController placeController,- EventBus eventBus,- SecurityService securityService) {- this.view = view;- this.placeController = placeController;- this.eventBus = eventBus;- this.securityService = securityService;- }-- @Override- protected AppActivity<RulesPlace> init(RulesPlace place) {- return this;- }-- @Override- public void start(AcceptsOneWidget container, EventBus eventBus, Collection<EventRegistration> registrations) {- container.setWidget(view.asWidget());- view.setPresenter(this);- }-- @Override- public String getFrameSource() {- LOG.warning("TODO: Rules iframe handling not implemented for 'localhost', use http://<Your Docker Host>:8084/ instead.");- return "http://" + Browser.getWindow().getLocation().getHostname() + ":8084/?logLevel=OFF#shell";- }-}diff --git a/manager/client/src/main/java/org/openremote/manager/client/rules/RulesGlobalActivity.java b/manager/client/src/main/java/org/openremote/manager/client/rules/RulesGlobalActivity.javanew file mode 100644index 000000000..8c0b00874--- /dev/null+++ b/manager/client/src/main/java/org/openremote/manager/client/rules/RulesGlobalActivity.java@@ -0,0 +1,72 @@+/*+ * 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.rules;++import org.openremote.manager.client.Environment;+import org.openremote.manager.client.assets.AssetMapper;+import org.openremote.manager.client.assets.browser.AssetBrowser;+import org.openremote.manager.client.assets.browser.AssetBrowsingActivity;+import org.openremote.manager.client.rules.asset.RulesAssetPlace;+import org.openremote.manager.client.rules.tenant.RulesTenantPlace;+import org.openremote.manager.shared.asset.AssetResource;+import org.openremote.model.asset.AssetInfo;++import javax.inject.Inject;+import java.util.logging.Logger;++public class RulesGlobalActivity+ extends AssetBrowsingActivity<RulesGlobalView, RulesGlobalPlace>+ implements RulesGlobalView.Presenter {++ private static final Logger LOG = Logger.getLogger(RulesGlobalActivity.class.getName());++ @Inject+ public RulesGlobalActivity(Environment environment,+ RulesGlobalView view,+ AssetBrowser.Presenter assetBrowserPresenter,+ AssetResource assetResource,+ AssetMapper assetMapper) {+ super(environment, view, assetBrowserPresenter, assetResource, assetMapper);+ }++ @Override+ public void onStop() {+ super.onStop();+ getView().setPresenter(null);+ }++ @Override+ protected void onAssetLoaded() {+ }++ @Override+ protected void onAssetsDeselected() {+ }++ @Override+ protected void onAssetSelectionChange(AssetInfo selectedAssetInfo) {+ environment.getPlaceController().goTo(new RulesAssetPlace(selectedAssetInfo.getId()));+ }++ @Override+ protected void onTenantSelected(String id, String realm) {+ environment.getPlaceController().goTo(new RulesTenantPlace(realm));+ }+}diff --git a/manager/client/src/main/java/org/openremote/manager/client/rules/RulesGlobalPlace.java b/manager/client/src/main/java/org/openremote/manager/client/rules/RulesGlobalPlace.javanew file mode 100644index 000000000..11d073857--- /dev/null+++ b/manager/client/src/main/java/org/openremote/manager/client/rules/RulesGlobalPlace.java@@ -0,0 +1,41 @@+/*+ * 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.rules;++import com.google.gwt.place.shared.PlaceTokenizer;+import com.google.gwt.place.shared.Prefix;+import org.openremote.manager.client.assets.browser.AssetBrowsingPlace;++public class RulesGlobalPlace extends AssetBrowsingPlace implements RulesPlace {++ @Prefix("rules")+ public static class Tokenizer implements PlaceTokenizer<RulesGlobalPlace> {++ @Override+ public RulesGlobalPlace getPlace(String token) {+ return new RulesGlobalPlace();+ }++ @Override+ public String getToken(RulesGlobalPlace place) {+ return "";+ }+ }+}diff --git a/manager/client/src/main/java/org/openremote/manager/client/rules/RulesView.java b/manager/client/src/main/java/org/openremote/manager/client/rules/RulesGlobalView.javasimilarity index 80%rename from manager/client/src/main/java/org/openremote/manager/client/rules/RulesView.javarename to manager/client/src/main/java/org/openremote/manager/client/rules/RulesGlobalView.javaindex 71cfd8841..e117049ef 100644--- a/manager/client/src/main/java/org/openremote/manager/client/rules/RulesView.java+++ b/manager/client/src/main/java/org/openremote/manager/client/rules/RulesGlobalView.java@@ -19,12 +19,11 @@*/package org.openremote.manager.client.rules;-import com.google.gwt.user.client.ui.IsWidget;+import org.openremote.manager.client.assets.browser.AssetBrowsingView;-public interface RulesView extends IsWidget {+public interface RulesGlobalView extends AssetBrowsingView<RulesGlobalView.Presenter> {- interface Presenter {- String getFrameSource();+ interface Presenter extends AssetBrowsingView.Presenter {}void setPresenter(Presenter presenter);diff --git a/manager/client/src/main/java/org/openremote/manager/client/rules/RulesGlobalViewImpl.java b/manager/client/src/main/java/org/openremote/manager/client/rules/RulesGlobalViewImpl.javanew file mode 100644index 000000000..85078a45b--- /dev/null+++ b/manager/client/src/main/java/org/openremote/manager/client/rules/RulesGlobalViewImpl.java@@ -0,0 +1,76 @@+/*+ * 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.rules;++import com.google.gwt.core.client.GWT;+import com.google.gwt.uibinder.client.UiBinder;+import com.google.gwt.uibinder.client.UiField;+import com.google.gwt.user.client.ui.Composite;+import com.google.gwt.user.client.ui.HTMLPanel;+import com.google.gwt.user.client.ui.SimplePanel;+import org.openremote.manager.client.assets.browser.AssetBrowser;+import org.openremote.manager.client.i18n.ManagerMessages;+import org.openremote.manager.client.style.FormTreeStyle;+import org.openremote.manager.client.widget.FlexSplitPanel;++import javax.inject.Inject;+import java.util.logging.Logger;++public class RulesGlobalViewImpl extends Composite implements RulesGlobalView {++ private static final Logger LOG = Logger.getLogger(RulesGlobalViewImpl.class.getName());++ interface UI extends UiBinder<FlexSplitPanel, RulesGlobalViewImpl> {+ }++ @UiField+ ManagerMessages managerMessages;++ @UiField+ HTMLPanel sidebarContainer;++ @UiField+ SimplePanel rulesContentContainer;++ final AssetBrowser assetBrowser;+ final FormTreeStyle formTreeStyle;++ Presenter presenter;++ @Inject+ public RulesGlobalViewImpl(AssetBrowser assetBrowser, FormTreeStyle formTreeStyle) {+ this.assetBrowser = assetBrowser;+ this.formTreeStyle = formTreeStyle;++ RulesGlobalViewImpl.UI ui = GWT.create(RulesGlobalViewImpl.UI.class);+ initWidget(ui.createAndBindUi(this));+ }++ @Override+ public void setPresenter(Presenter presenter) {+ this.presenter = presenter;+ if (presenter != null) {+ assetBrowser.asWidget().removeFromParent();+ sidebarContainer.add(assetBrowser.asWidget());+ } else {+ sidebarContainer.clear();+ }+ }+}diff --git a/manager/client/src/main/java/org/openremote/manager/client/rules/RulesGlobalViewImpl.ui.xml b/manager/client/src/main/java/org/openremote/manager/client/rules/RulesGlobalViewImpl.ui.xmlnew file mode 100644index 000000000..02cb65c07--- /dev/null+++ b/manager/client/src/main/java/org/openremote/manager/client/rules/RulesGlobalViewImpl.ui.xml@@ -0,0 +1,51 @@+<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"+ xmlns:g="urn:import:com.google.gwt.user.client.ui"+ xmlns:w="urn:import:org.openremote.manager.client.widget">++ <ui:with field="managerMessages" type="org.openremote.manager.client.i18n.ManagerMessages"/>+ <ui:with field="widgetStyle" type="org.openremote.manager.client.style.WidgetStyle"/>++ <ui:style>+ .rulesControls {++ }++ .navItem {+ margin: 0 1em;+ }+ </ui:style>++ <w:FlexSplitPanel handleStyle="{widgetStyle.SplitPanelHandle}"+ firstPanelWidth="250"+ firstPanelMinWidth="250"+ secondPanelMinWidth="600">+ <w:first>+ <g:HTMLPanel ui:field="sidebarContainer"+ styleName="flex layout vertical {widgetStyle.SidebarContent}"/>+ </w:first>+ <w:second>+ <g:HTMLPanel styleName="flex layout vertical">++ <g:HTMLPanel+ styleName="layout horizontal center end-justified {style.rulesControls} {widgetStyle.SecondaryNavHorizontal}">++ <w:Hyperlink+ addStyleNames="{style.navItem} {widgetStyle.SecondaryNavItem}"+ icon="chain"+ targetHistoryToken="rules:"+ text="{managerMessages.editGlobalRules}"/>++ </g:HTMLPanel>++ <g:HTMLPanel styleName="flex {widgetStyle.MainContent}">+ <g:SimplePanel ui:field="rulesContentContainer">+ <g:Label text="Global Rules"/>+ </g:SimplePanel>+ </g:HTMLPanel>++ </g:HTMLPanel>++ </w:second>+ </w:FlexSplitPanel>++</ui:UiBinder>\ No newline at end of filediff --git a/manager/client/src/main/java/org/openremote/manager/client/rules/RulesModule.java b/manager/client/src/main/java/org/openremote/manager/client/rules/RulesModule.javaindex b0bbc9885..4a0a2f06c 100644--- a/manager/client/src/main/java/org/openremote/manager/client/rules/RulesModule.java+++ b/manager/client/src/main/java/org/openremote/manager/client/rules/RulesModule.java@@ -1,5 +1,5 @@/*- * Copyright 2016, OpenRemote Inc.+ * Copyright 2017, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -21,13 +21,25 @@ package org.openremote.manager.client.rules;import com.google.gwt.inject.client.AbstractGinModule;import com.google.inject.Singleton;+import org.openremote.manager.client.rules.asset.RulesAssetActivity;+import org.openremote.manager.client.rules.asset.RulesAssetView;+import org.openremote.manager.client.rules.asset.RulesAssetViewImpl;+import org.openremote.manager.client.rules.tenant.RulesTenantActivity;+import org.openremote.manager.client.rules.tenant.RulesTenantView;+import org.openremote.manager.client.rules.tenant.RulesTenantViewImpl;public class RulesModule extends AbstractGinModule {@Overrideprotected void configure() {- bind(RulesView.class).to(RulesViewImpl.class).in(Singleton.class);- bind(RulesActivity.class);+ bind(RulesGlobalView.class).to(RulesGlobalViewImpl.class).in(Singleton.class);+ bind(RulesGlobalActivity.class);++ bind(RulesTenantView.class).to(RulesTenantViewImpl.class).in(Singleton.class);+ bind(RulesTenantActivity.class);++ bind(RulesAssetView.class).to(RulesAssetViewImpl.class).in(Singleton.class);+ bind(RulesAssetActivity.class);}}diff --git a/manager/client/src/main/java/org/openremote/manager/client/rules/RulesPlace.java b/manager/client/src/main/java/org/openremote/manager/client/rules/RulesPlace.javaindex 8551139e1..d291c5f0b 100644--- a/manager/client/src/main/java/org/openremote/manager/client/rules/RulesPlace.java+++ b/manager/client/src/main/java/org/openremote/manager/client/rules/RulesPlace.java@@ -1,5 +1,5 @@/*- * Copyright 2016, OpenRemote Inc.+ * Copyright 2017, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -19,23 +19,6 @@*/package org.openremote.manager.client.rules;-import com.google.gwt.place.shared.Place;-import com.google.gwt.place.shared.PlaceTokenizer;-import com.google.gwt.place.shared.Prefix;+public interface RulesPlace {-public class RulesPlace extends Place {-- @Prefix("rules")- public static class Tokenizer implements PlaceTokenizer<RulesPlace> {-- @Override- public RulesPlace getPlace(String token) {- return new RulesPlace();- }-- @Override- public String getToken(RulesPlace place) {- return "";- }- }}diff --git a/manager/client/src/main/java/org/openremote/manager/client/rules/RulesViewImpl.java b/manager/client/src/main/java/org/openremote/manager/client/rules/RulesViewImpl.javadeleted file mode 100644index deeb31fbc..000000000--- a/manager/client/src/main/java/org/openremote/manager/client/rules/RulesViewImpl.java+++ /dev/null@@ -1,68 +0,0 @@-/*- * Copyright 2016, OpenRemote Inc.- *- * See the CONTRIBUTORS.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.manager.client.rules;--import com.google.gwt.core.client.GWT;-import com.google.gwt.dom.client.IFrameElement;-import com.google.gwt.uibinder.client.UiBinder;-import com.google.gwt.uibinder.client.UiField;-import com.google.gwt.user.client.ui.HTMLPanel;-import com.google.gwt.user.client.ui.Widget;-import org.openremote.manager.client.util.Timeout;--import javax.inject.Inject;-import java.util.logging.Logger;--public class RulesViewImpl implements RulesView {-- private static final Logger LOG = Logger.getLogger(RulesViewImpl.class.getName());-- interface UI extends UiBinder<HTMLPanel, RulesViewImpl> {- }-- private UI ui = GWT.create(UI.class);- private HTMLPanel root;-- Presenter presenter;-- @UiField- IFrameElement frame;-- @Inject- public RulesViewImpl() {- root = ui.createAndBindUi(this);- }-- @Override- public void setPresenter(Presenter presenter) {- this.presenter = presenter;- frame.setSrc(presenter.getFrameSource());-- // TODO ouch- Timeout.debounce("setiframefocus", () -> {- frame.focus();- }, 1000);- }-- @Override- public Widget asWidget() {- return root;- }-}diff --git a/manager/client/src/main/java/org/openremote/manager/client/rules/RulesViewImpl.ui.xml b/manager/client/src/main/java/org/openremote/manager/client/rules/RulesViewImpl.ui.xmldeleted file mode 100644index 2678dd8ad..000000000--- a/manager/client/src/main/java/org/openremote/manager/client/rules/RulesViewImpl.ui.xml+++ /dev/null@@ -1,10 +0,0 @@-<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"- xmlns:g="urn:import:com.google.gwt.user.client.ui">-- <g:HTMLPanel styleName="flex layout vertical">- <iframe ui:field="frame"- class="flex"- style="width:100%; height:100%;border:0;"/>- </g:HTMLPanel>--</ui:UiBinder>\ No newline at end of filediff --git a/manager/client/src/main/java/org/openremote/manager/client/rules/asset/RulesAssetActivity.java b/manager/client/src/main/java/org/openremote/manager/client/rules/asset/RulesAssetActivity.javanew file mode 100644index 000000000..27ff56057--- /dev/null+++ b/manager/client/src/main/java/org/openremote/manager/client/rules/asset/RulesAssetActivity.java@@ -0,0 +1,114 @@+/*+ * 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.rules.asset;++import com.google.gwt.user.client.ui.AcceptsOneWidget;+import org.openremote.manager.client.Environment;+import org.openremote.manager.client.assets.AssetMapper;+import org.openremote.manager.client.assets.browser.AssetBrowser;+import org.openremote.manager.client.assets.browser.AssetBrowsingActivity;+import org.openremote.manager.client.event.bus.EventBus;+import org.openremote.manager.client.event.bus.EventRegistration;+import org.openremote.manager.client.rules.tenant.RulesTenantPlace;+import org.openremote.manager.shared.asset.AssetResource;+import org.openremote.model.asset.AssetInfo;++import javax.inject.Inject;+import java.util.Collection;+import java.util.logging.Logger;++public class RulesAssetActivity+ extends AssetBrowsingActivity<RulesAssetView, RulesAssetPlace>+ implements RulesAssetView.Presenter {++ private static final Logger LOG = Logger.getLogger(RulesAssetActivity.class.getName());++ @Inject+ public RulesAssetActivity(Environment environment,+ RulesAssetView view,+ AssetBrowser.Presenter assetBrowserPresenter,+ AssetResource assetResource,+ AssetMapper assetMapper) {+ super(environment, view, assetBrowserPresenter, assetResource, assetMapper);+ }++ @Override+ public void start(AcceptsOneWidget container, EventBus eventBus, Collection<EventRegistration> registrations) {+ super.start(container, eventBus, registrations);+ }++ @Override+ protected void startCreateAsset() {+ super.startCreateAsset();+ }++ @Override+ protected void onAssetLoaded() {+ view.setName(asset.getName());+ view.setFormBusy(false);+ }++ @Override+ protected void onAssetsDeselected() {+ }++ @Override+ protected void onAssetSelectionChange(AssetInfo selectedAssetInfo) {+ environment.getPlaceController().goTo(new RulesAssetPlace(selectedAssetInfo.getId()));+ }++ @Override+ protected void onTenantSelected(String id, String realm) {+ environment.getPlaceController().goTo(new RulesTenantPlace(realm));+ }++ @Override+ protected void onBeforeAssetLoad() {+ view.setFormBusy(true);+ }++ @Override+ public void onStop() {+ super.onStop();+ clearViewFieldErrors();+ view.setPresenter(null);+ view.clearFormMessages();+ }++ @Override+ public void update() {++ }++ @Override+ public void create() {++ }++ @Override+ public void delete() {++ }++ protected void clearViewFieldErrors() {+ // TODO: Validation+ }++}diff --git a/manager/client/src/main/java/org/openremote/manager/client/rules/asset/RulesAssetPlace.java b/manager/client/src/main/java/org/openremote/manager/client/rules/asset/RulesAssetPlace.javanew file mode 100644index 000000000..23ce96b79--- /dev/null+++ b/manager/client/src/main/java/org/openremote/manager/client/rules/asset/RulesAssetPlace.java@@ -0,0 +1,49 @@+/*+ * 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.rules.asset;++import com.google.gwt.place.shared.PlaceTokenizer;+import com.google.gwt.place.shared.Prefix;+import org.openremote.manager.client.assets.browser.AssetBrowsingPlace;+import org.openremote.manager.client.rules.RulesPlace;++public class RulesAssetPlace extends AssetBrowsingPlace implements RulesPlace {++ public RulesAssetPlace(String assetId) {+ super(assetId);+ }++ public RulesAssetPlace() {+ }++ @Prefix("rulesAsset")+ public static class Tokenizer implements PlaceTokenizer<RulesAssetPlace> {++ @Override+ public RulesAssetPlace getPlace(String token) {+ return new RulesAssetPlace(token != null && token.length() > 0 ? token : null);+ }++ @Override+ public String getToken(RulesAssetPlace place) {+ return place.getAssetId() != null ? place.getAssetId() : "";+ }+ }+}diff --git a/manager/client/src/main/java/org/openremote/manager/client/rules/asset/RulesAssetView.java b/manager/client/src/main/java/org/openremote/manager/client/rules/asset/RulesAssetView.javanew file mode 100644index 000000000..0467c05e0--- /dev/null+++ b/manager/client/src/main/java/org/openremote/manager/client/rules/asset/RulesAssetView.java@@ -0,0 +1,45 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.client.rules.asset;++import org.openremote.manager.client.assets.browser.AssetBrowsingView;+import org.openremote.manager.client.widget.FormView;++public interface RulesAssetView extends AssetBrowsingView<RulesAssetView.Presenter>, FormView {++ interface Presenter extends AssetBrowsingView.Presenter {+ void update();++ void create();++ void delete();+ }++ void setName(String name);++ String getName();++ void enableCreate(boolean enable);++ void enableUpdate(boolean enable);++ void enableDelete(boolean enable);++}diff --git a/manager/client/src/main/java/org/openremote/manager/client/rules/asset/RulesAssetViewImpl.java b/manager/client/src/main/java/org/openremote/manager/client/rules/asset/RulesAssetViewImpl.javanew file mode 100644index 000000000..321580d98--- /dev/null+++ b/manager/client/src/main/java/org/openremote/manager/client/rules/asset/RulesAssetViewImpl.java@@ -0,0 +1,170 @@+/*+ * 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.rules.asset;++import com.google.gwt.core.client.GWT;+import com.google.gwt.event.dom.client.ClickEvent;+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.ui.HTMLPanel;+import com.google.gwt.user.client.ui.TextBox;+import com.google.inject.Provider;+import org.openremote.manager.client.app.dialog.ConfirmationDialog;+import org.openremote.manager.client.assets.browser.AssetBrowser;+import org.openremote.manager.client.widget.*;++import javax.inject.Inject;+import java.util.logging.Logger;++public class RulesAssetViewImpl extends FormViewImpl implements RulesAssetView {++ private static final Logger LOG = Logger.getLogger(RulesAssetViewImpl.class.getName());++ interface UI extends UiBinder<FlexSplitPanel, RulesAssetViewImpl> {+ }++ interface Style extends CssResource {++ String navItem();++ String formMessages();++ }++ @UiField+ Style style;++ @UiField+ FlexSplitPanel splitPanel;++ @UiField+ HTMLPanel sidebarContainer;++ /* ############################################################################ */++ @UiField+ FormGroup nameGroup;+ @UiField+ TextBox nameInput;++ /* ############################################################################ */++ @UiField+ Form submitForm;+ @UiField+ FormGroup submitButtonGroup;+ @UiField+ PushButton createButton;+ @UiField+ PushButton updateButton;+ @UiField+ PushButton deleteButton;++ final AssetBrowser assetBrowser;+ Presenter presenter;++ @Inject+ public RulesAssetViewImpl(AssetBrowser assetBrowser, Provider<ConfirmationDialog> confirmationDialogProvider) {+ super(confirmationDialogProvider);+ this.assetBrowser = assetBrowser;++ UI ui = GWT.create(UI.class);+ initWidget(ui.createAndBindUi(this));+ }++ @Override+ public void setPresenter(Presenter presenter) {+ this.presenter = presenter;++ // Restore initial state of view+ sidebarContainer.clear();+ nameInput.setReadOnly(false);+ nameInput.setValue(null);++ setOpaque(false);++ if (presenter != null) {+ assetBrowser.asWidget().removeFromParent();+ sidebarContainer.add(assetBrowser.asWidget());+ }+ }++ @Override+ public void setFormBusy(boolean busy) {+ super.setFormBusy(busy);+ submitForm.setBusy(busy);+ }++ /* ############################################################################ */++ @Override+ public void setName(String name) {+ nameInput.setValue(name);+ }++ @Override+ public String getName() {+ return nameInput.getValue().length() > 0 ? nameInput.getValue() : null;+ }++ /* ############################################################################ */++ @Override+ public void enableCreate(boolean enable) {+ createButton.setVisible(enable);+ }++ @Override+ public void enableUpdate(boolean enable) {+ updateButton.setVisible(enable);+ }++ @Override+ public void enableDelete(boolean enable) {+ deleteButton.setVisible(enable);+ }++ @UiHandler("updateButton")+ void updateClicked(ClickEvent e) {+ if (presenter != null)+ presenter.update();+ }++ @UiHandler("createButton")+ void createClicked(ClickEvent e) {+ if (presenter != null)+ presenter.create();+ }++ @UiHandler("deleteButton")+ void deleteClicked(ClickEvent e) {+ if (presenter != null)+ presenter.delete();+ }++ /* ############################################################################ */++ protected void setOpaque(boolean opaque) {+ nameGroup.setOpaque(opaque);+ submitButtonGroup.setOpaque(opaque);+ }+}diff --git a/manager/client/src/main/java/org/openremote/manager/client/rules/asset/RulesAssetViewImpl.ui.xml b/manager/client/src/main/java/org/openremote/manager/client/rules/asset/RulesAssetViewImpl.ui.xmlnew file mode 100644index 000000000..03e11870d--- /dev/null+++ b/manager/client/src/main/java/org/openremote/manager/client/rules/asset/RulesAssetViewImpl.ui.xml@@ -0,0 +1,101 @@+<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"+ xmlns:g="urn:import:com.google.gwt.user.client.ui"+ xmlns:w="urn:import:org.openremote.manager.client.widget">++ <ui:with field="managerMessages" type="org.openremote.manager.client.i18n.ManagerMessages"/>+ <ui:with field="widgetStyle" type="org.openremote.manager.client.style.WidgetStyle"/>++ <ui:style field="style" type="org.openremote.manager.client.rules.asset.RulesAssetViewImpl.Style">+ .navItem {+ margin: 0 1em;+ }++ .formMessages {+ max-width: 30em;+ }+ </ui:style>++ <w:FlexSplitPanel ui:field="splitPanel"+ handleStyle="{widgetStyle.SplitPanelHandle}"+ firstPanelWidth="250"+ firstPanelMinWidth="250"+ secondPanelMinWidth="1000">++ <w:first>+ <g:HTMLPanel ui:field="sidebarContainer"+ styleName="flex layout vertical {widgetStyle.SidebarContent}"/>+ </w:first>++ <w:second>+ <g:HTMLPanel styleName="flex layout vertical">+ <g:HTMLPanel+ styleName="layout horizontal center end-justified {widgetStyle.SecondaryNavHorizontal}">++ <w:Hyperlink+ addStyleNames="{style.navItem} {widgetStyle.SecondaryNavItem}"+ icon="chain"+ targetHistoryToken="rules:"+ text="{managerMessages.editGlobalRules}"/>++ </g:HTMLPanel>++ <div class="flex layout vertical {widgetStyle.MainContent}">++ <g:FlowPanel+ styleName="flex-none layout horizontal {style.formMessages} {widgetStyle.FormMessages} success"+ visible="false">+ <w:IconLabel icon="check"+ addStyleNames="{widgetStyle.MessagesIcon}"/>+ <g:FlowPanel ui:field="formMessagesSuccess"/>+ </g:FlowPanel>++ <g:FlowPanel+ styleName="flex-none layout horizontal {style.formMessages} {widgetStyle.FormMessages} error"+ visible="false">+ <w:IconLabel icon="warning"+ addStyleNames="{widgetStyle.MessagesIcon}"/>+ <g:FlowPanel ui:field="formMessagesError"/>+ </g:FlowPanel>++ <w:Form ui:field="form" addStyleNames="flex">+ <w:FormGroup ui:field="nameGroup">+ <w:label>+ <w:FormLabel text="{managerMessages.assetName}"/>+ </w:label>+ <w:field>+ <w:FormField addStyleNames="larger">+ <w:FormInputText ui:field="nameInput" addStyleNames="flex"/>+ </w:FormField>+ </w:field>+ </w:FormGroup>+ </w:Form>+++ <g:HTMLPanel styleName="flex-none layout horizontal">+ <w:Form ui:field="submitForm" addStyleNames="flex">+ <w:FormGroup ui:field="submitButtonGroup">+ <w:field>+ <w:FormField>+ <w:FormButton ui:field="updateButton" primary="true"+ text="{managerMessages.updateAsset}" visible="false"+ icon="save"/>+ <w:FormButton ui:field="createButton" primary="true"+ text="{managerMessages.createAsset}" visible="false"+ icon="save"/>+ <w:FormButton ui:field="deleteButton" danger="true"+ text="{managerMessages.deleteAsset}" visible="false"+ icon="trash"/>+ </w:FormField>+ </w:field>+ </w:FormGroup>+ </w:Form>+ </g:HTMLPanel>++ </div>++ </g:HTMLPanel>+ </w:second>++ </w:FlexSplitPanel>++</ui:UiBinder>\ No newline at end of filediff --git a/manager/client/src/main/java/org/openremote/manager/client/rules/tenant/RulesTenantActivity.java b/manager/client/src/main/java/org/openremote/manager/client/rules/tenant/RulesTenantActivity.javanew file mode 100644index 000000000..f39d629d1--- /dev/null+++ b/manager/client/src/main/java/org/openremote/manager/client/rules/tenant/RulesTenantActivity.java@@ -0,0 +1,125 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.client.rules.tenant;++import com.google.gwt.user.client.ui.AcceptsOneWidget;+import org.openremote.manager.client.Environment;+import org.openremote.manager.client.assets.AssetMapper;+import org.openremote.manager.client.assets.browser.AssetBrowser;+import org.openremote.manager.client.assets.browser.AssetBrowsingActivity;+import org.openremote.manager.client.event.bus.EventBus;+import org.openremote.manager.client.event.bus.EventRegistration;+import org.openremote.manager.client.mvp.AppActivity;+import org.openremote.manager.client.rules.asset.RulesAssetPlace;+import org.openremote.manager.shared.asset.AssetResource;+import org.openremote.model.asset.AssetInfo;++import javax.inject.Inject;+import java.util.Collection;+import java.util.logging.Logger;++public class RulesTenantActivity+ extends AssetBrowsingActivity<RulesTenantView, RulesTenantPlace>+ implements RulesTenantView.Presenter {++ private static final Logger LOG = Logger.getLogger(RulesTenantActivity.class.getName());++ String realm;++ @Inject+ public RulesTenantActivity(Environment environment,+ RulesTenantView view,+ AssetBrowser.Presenter assetBrowserPresenter,+ AssetResource assetResource,+ AssetMapper assetMapper) {+ super(environment, view, assetBrowserPresenter, assetResource, assetMapper);+ }++ @Override+ protected AppActivity<RulesTenantPlace> init(RulesTenantPlace place) {+ this.realm = place.getRealm();+ return super.init(place);+ }++ @Override+ public void start(AcceptsOneWidget container, EventBus eventBus, Collection<EventRegistration> registrations) {+ super.start(container, eventBus, registrations);++ view.setFormBusy(true);+ view.setName(realm);+ view.setFormBusy(false);+ }++ @Override+ protected void startCreateAsset() {+ }++ @Override+ protected void onAssetLoaded() {+ }++ @Override+ protected void onAssetsDeselected() {+ }++ @Override+ protected void onAssetSelectionChange(AssetInfo selectedAssetInfo) {+ environment.getPlaceController().goTo(new RulesAssetPlace(selectedAssetInfo.getId()));+ }++ @Override+ protected void onTenantSelected(String id, String realm) {+ if (this.realm == null || !this.realm.equals(realm)) {+ environment.getPlaceController().goTo(new RulesTenantPlace(realm));+ }+ }++ @Override+ protected void onBeforeAssetLoad() {+ }++ @Override+ public void onStop() {+ super.onStop();+ clearViewFieldErrors();+ view.setPresenter(null);+ view.clearFormMessages();+ }++ @Override+ public void update() {++ }++ @Override+ public void create() {++ }++ @Override+ public void delete() {++ }++ protected void clearViewFieldErrors() {+ // TODO: Validation+ }++}diff --git a/manager/client/src/main/java/org/openremote/manager/client/rules/tenant/RulesTenantPlace.java b/manager/client/src/main/java/org/openremote/manager/client/rules/tenant/RulesTenantPlace.javanew file mode 100644index 000000000..209999ec6--- /dev/null+++ b/manager/client/src/main/java/org/openremote/manager/client/rules/tenant/RulesTenantPlace.java@@ -0,0 +1,52 @@+/*+ * 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.rules.tenant;++import com.google.gwt.place.shared.PlaceTokenizer;+import com.google.gwt.place.shared.Prefix;+import org.openremote.manager.client.assets.browser.AssetBrowsingPlace;+import org.openremote.manager.client.rules.RulesPlace;++public class RulesTenantPlace extends AssetBrowsingPlace implements RulesPlace {++ final String realm;++ public RulesTenantPlace(String realm) {+ this.realm = realm;+ }++ public String getRealm() {+ return realm;+ }++ @Prefix("rulesTenant")+ public static class Tokenizer implements PlaceTokenizer<RulesTenantPlace> {++ @Override+ public RulesTenantPlace getPlace(String token) {+ return new RulesTenantPlace(token != null && token.length() > 0 ? token : null);+ }++ @Override+ public String getToken(RulesTenantPlace place) {+ return place.getRealm() != null ? place.getRealm() : "";+ }+ }+}diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/agent/ConnectorArrayMapper.java b/manager/client/src/main/java/org/openremote/manager/client/rules/tenant/RulesTenantView.javasimilarity index 55%rename from manager/client/src/main/java/org/openremote/manager/client/assets/agent/ConnectorArrayMapper.javarename to manager/client/src/main/java/org/openremote/manager/client/rules/tenant/RulesTenantView.javaindex a80912f62..605821b64 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/agent/ConnectorArrayMapper.java+++ b/manager/client/src/main/java/org/openremote/manager/client/rules/tenant/RulesTenantView.java@@ -17,18 +17,29 @@* You should have received a copy of the GNU Affero General Public License* along with this program. If not, see <http://www.gnu.org/licenses/>.*/-package org.openremote.manager.client.assets.agent;--import com.github.nmorel.gwtjackson.client.ObjectMapper;-import com.github.nmorel.gwtjackson.client.annotation.JsonMixIns;-import org.openremote.manager.client.interop.jackson.DefaultJsonMixin;-import org.openremote.manager.shared.connector.Connector;-import org.openremote.manager.shared.http.EntityReader;-import org.openremote.manager.shared.http.EntityWriter;--@JsonMixIns({@JsonMixIns.JsonMixIn(target = Connector.class, mixIn = DefaultJsonMixin.class)})-public interface ConnectorArrayMapper- extends ObjectMapper<Connector[]>,- EntityReader<Connector[]>,- EntityWriter<Connector[]> {+package org.openremote.manager.client.rules.tenant;++import org.openremote.manager.client.assets.browser.AssetBrowsingView;+import org.openremote.manager.client.widget.FormView;++public interface RulesTenantView extends AssetBrowsingView<RulesTenantView.Presenter>, FormView {++ interface Presenter extends AssetBrowsingView.Presenter {+ void update();++ void create();++ void delete();+ }++ void setName(String name);++ String getName();++ void enableCreate(boolean enable);++ void enableUpdate(boolean enable);++ void enableDelete(boolean enable);+}diff --git a/manager/client/src/main/java/org/openremote/manager/client/rules/tenant/RulesTenantViewImpl.java b/manager/client/src/main/java/org/openremote/manager/client/rules/tenant/RulesTenantViewImpl.javanew file mode 100644index 000000000..04c8d7c17--- /dev/null+++ b/manager/client/src/main/java/org/openremote/manager/client/rules/tenant/RulesTenantViewImpl.java@@ -0,0 +1,170 @@+/*+ * 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.rules.tenant;++import com.google.gwt.core.client.GWT;+import com.google.gwt.event.dom.client.ClickEvent;+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.ui.HTMLPanel;+import com.google.gwt.user.client.ui.TextBox;+import com.google.inject.Provider;+import org.openremote.manager.client.app.dialog.ConfirmationDialog;+import org.openremote.manager.client.assets.browser.AssetBrowser;+import org.openremote.manager.client.widget.*;++import javax.inject.Inject;+import java.util.logging.Logger;++public class RulesTenantViewImpl extends FormViewImpl implements RulesTenantView {++ private static final Logger LOG = Logger.getLogger(RulesTenantViewImpl.class.getName());++ interface UI extends UiBinder<FlexSplitPanel, RulesTenantViewImpl> {+ }++ interface Style extends CssResource {++ String navItem();++ String formMessages();++ }++ @UiField+ Style style;++ @UiField+ FlexSplitPanel splitPanel;++ @UiField+ HTMLPanel sidebarContainer;++ /* ############################################################################ */++ @UiField+ FormGroup nameGroup;+ @UiField+ TextBox nameInput;++ /* ############################################################################ */++ @UiField+ Form submitForm;+ @UiField+ FormGroup submitButtonGroup;+ @UiField+ PushButton createButton;+ @UiField+ PushButton updateButton;+ @UiField+ PushButton deleteButton;++ final AssetBrowser assetBrowser;+ Presenter presenter;++ @Inject+ public RulesTenantViewImpl(AssetBrowser assetBrowser, Provider<ConfirmationDialog> confirmationDialogProvider) {+ super(confirmationDialogProvider);+ this.assetBrowser = assetBrowser;++ UI ui = GWT.create(UI.class);+ initWidget(ui.createAndBindUi(this));+ }++ @Override+ public void setPresenter(Presenter presenter) {+ this.presenter = presenter;++ // Restore initial state of view+ sidebarContainer.clear();+ nameInput.setReadOnly(false);+ nameInput.setValue(null);++ setOpaque(false);++ if (presenter != null) {+ assetBrowser.asWidget().removeFromParent();+ sidebarContainer.add(assetBrowser.asWidget());+ }+ }++ @Override+ public void setFormBusy(boolean busy) {+ super.setFormBusy(busy);+ submitForm.setBusy(busy);+ }++ /* ############################################################################ */++ @Override+ public void setName(String name) {+ nameInput.setValue(name);+ }++ @Override+ public String getName() {+ return nameInput.getValue().length() > 0 ? nameInput.getValue() : null;+ }++ /* ############################################################################ */++ @Override+ public void enableCreate(boolean enable) {+ createButton.setVisible(enable);+ }++ @Override+ public void enableUpdate(boolean enable) {+ updateButton.setVisible(enable);+ }++ @Override+ public void enableDelete(boolean enable) {+ deleteButton.setVisible(enable);+ }++ @UiHandler("updateButton")+ void updateClicked(ClickEvent e) {+ if (presenter != null)+ presenter.update();+ }++ @UiHandler("createButton")+ void createClicked(ClickEvent e) {+ if (presenter != null)+ presenter.create();+ }++ @UiHandler("deleteButton")+ void deleteClicked(ClickEvent e) {+ if (presenter != null)+ presenter.delete();+ }++ /* ############################################################################ */++ protected void setOpaque(boolean opaque) {+ nameGroup.setOpaque(opaque);+ submitButtonGroup.setOpaque(opaque);+ }+}diff --git a/manager/client/src/main/java/org/openremote/manager/client/rules/tenant/RulesTenantViewImpl.ui.xml b/manager/client/src/main/java/org/openremote/manager/client/rules/tenant/RulesTenantViewImpl.ui.xmlnew file mode 100644index 000000000..e65594119--- /dev/null+++ b/manager/client/src/main/java/org/openremote/manager/client/rules/tenant/RulesTenantViewImpl.ui.xml@@ -0,0 +1,101 @@+<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"+ xmlns:g="urn:import:com.google.gwt.user.client.ui"+ xmlns:w="urn:import:org.openremote.manager.client.widget">++ <ui:with field="managerMessages" type="org.openremote.manager.client.i18n.ManagerMessages"/>+ <ui:with field="widgetStyle" type="org.openremote.manager.client.style.WidgetStyle"/>++ <ui:style field="style" type="org.openremote.manager.client.rules.tenant.RulesTenantViewImpl.Style">+ .navItem {+ margin: 0 1em;+ }++ .formMessages {+ max-width: 30em;+ }+ </ui:style>++ <w:FlexSplitPanel ui:field="splitPanel"+ handleStyle="{widgetStyle.SplitPanelHandle}"+ firstPanelWidth="250"+ firstPanelMinWidth="250"+ secondPanelMinWidth="1000">++ <w:first>+ <g:HTMLPanel ui:field="sidebarContainer"+ styleName="flex layout vertical {widgetStyle.SidebarContent}"/>+ </w:first>++ <w:second>+ <g:HTMLPanel styleName="flex layout vertical">+ <g:HTMLPanel+ styleName="layout horizontal center end-justified {widgetStyle.SecondaryNavHorizontal}">++ <w:Hyperlink+ addStyleNames="{style.navItem} {widgetStyle.SecondaryNavItem}"+ icon="chain"+ targetHistoryToken="rules:"+ text="{managerMessages.editGlobalRules}"/>++ </g:HTMLPanel>++ <div class="flex layout vertical {widgetStyle.MainContent}">++ <g:FlowPanel+ styleName="flex-none layout horizontal {style.formMessages} {widgetStyle.FormMessages} success"+ visible="false">+ <w:IconLabel icon="check"+ addStyleNames="{widgetStyle.MessagesIcon}"/>+ <g:FlowPanel ui:field="formMessagesSuccess"/>+ </g:FlowPanel>++ <g:FlowPanel+ styleName="flex-none layout horizontal {style.formMessages} {widgetStyle.FormMessages} error"+ visible="false">+ <w:IconLabel icon="warning"+ addStyleNames="{widgetStyle.MessagesIcon}"/>+ <g:FlowPanel ui:field="formMessagesError"/>+ </g:FlowPanel>++ <w:Form ui:field="form" addStyleNames="flex">+ <w:FormGroup ui:field="nameGroup">+ <w:label>+ <w:FormLabel text="{managerMessages.realm}"/>+ </w:label>+ <w:field>+ <w:FormField addStyleNames="larger">+ <w:FormInputText ui:field="nameInput" addStyleNames="flex"/>+ </w:FormField>+ </w:field>+ </w:FormGroup>+ </w:Form>+++ <g:HTMLPanel styleName="flex-none layout horizontal">+ <w:Form ui:field="submitForm" addStyleNames="flex">+ <w:FormGroup ui:field="submitButtonGroup">+ <w:field>+ <w:FormField>+ <w:FormButton ui:field="updateButton" primary="true"+ text="{managerMessages.updateAsset}" visible="false"+ icon="save"/>+ <w:FormButton ui:field="createButton" primary="true"+ text="{managerMessages.createAsset}" visible="false"+ icon="save"/>+ <w:FormButton ui:field="deleteButton" danger="true"+ text="{managerMessages.deleteAsset}" visible="false"+ icon="trash"/>+ </w:FormField>+ </w:field>+ </w:FormGroup>+ </w:Form>+ </g:HTMLPanel>++ </div>++ </g:HTMLPanel>+ </w:second>++ </w:FlexSplitPanel>++</ui:UiBinder>\ No newline at end of filediff --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 da211d776..b427a1544 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@@ -4,6 +4,7 @@ rules = Rulesflows = Appsadmin = Systemlogout = Logout+fullscreen=FullscreenmapLoading = Loading map, please wait...editAccount = Edit my accountmanageTenants = Manage tenants@@ -59,9 +60,11 @@ roleLabel[read] = READ ALL DATAroleLabel[read-admin] = Read system settings, tenants, and usersroleLabel[read-map] = View MaproleLabel[read-assets] = Read asset data+roleLabel[read-rules] = Read rule definitionsroleLabel[write] = WRITE ALL DATAroleLabel[write-admin] = Write system settings, tenants, and usersroleLabel[write-assets] = Write asset data+roleLabel[write-rules] = Write rules datanoteRolesAfterCreate = You can assign access roles after creating the user.showMoreAssets=Show more assetsemptyAsset= No assets found.@@ -144,3 +147,4 @@ newAttribute=New attributeattributes=Asset attributesattributeName=Attribute nameenterNameAndSelectType=Please enter a name and select a type.+editGlobalRules=Edit global rulesdiff --git a/manager/server/src/main/java/org/openremote/manager/server/Main.java b/manager/server/src/main/java/org/openremote/manager/server/Main.javaindex 6793aa6db..525602d21 100644--- a/manager/server/src/main/java/org/openremote/manager/server/Main.java+++ b/manager/server/src/main/java/org/openremote/manager/server/Main.java@@ -33,6 +33,7 @@ import org.openremote.manager.server.event.EventService;import org.openremote.manager.server.i18n.I18NService;import org.openremote.manager.server.map.MapService;import org.openremote.manager.server.rules.AssetRulesService;+import org.openremote.manager.server.rules.RulesStorageService;import org.openremote.manager.server.security.ManagerIdentityService;import org.openremote.manager.server.setup.SetupService;import org.openremote.manager.server.web.ManagerWebService;@@ -49,11 +50,12 @@ public class Main {{addAll(Arrays.asList(new I18NService(),+ new PersistenceService(),new MessageBrokerSetupService(),new ManagerIdentityService(),- new PersistenceService(),new SetupService(),new EventService(),+ new RulesStorageService(),new AssetRulesService(),new AssetStorageService(),new AssetDatapointService(),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 d8e8dd0d7..7854e8418 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@@ -21,7 +21,6 @@ package org.openremote.manager.server.asset;import elemental.json.JsonValue;import org.openremote.container.web.WebResource;-import org.openremote.manager.server.security.ManagerIdentityService;import org.openremote.manager.shared.asset.AssetResource;import org.openremote.manager.shared.http.RequestParams;import org.openremote.model.asset.Asset;@@ -40,11 +39,9 @@ public class AssetResourceImpl extends WebResource implements AssetResource {private static final Logger LOG = Logger.getLogger(AssetResourceImpl.class.getName());- protected final ManagerIdentityService identityService;protected final AssetStorageService assetStorageService;- public AssetResourceImpl(ManagerIdentityService identityService, AssetStorageService assetStorageService) {- this.identityService = identityService;+ public AssetResourceImpl(AssetStorageService assetStorageService) {this.assetStorageService = assetStorageService;}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 af1b78383..90e6211c7 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@@ -59,6 +59,7 @@ public class AssetStorageServiceprotected EventService eventService;protected PersistenceService persistenceService;+ protected ManagerIdentityService managerIdentityService;protected AssetListenerSubscriptions assetListenerSubscriptions;final protected Function<AttributeRef, ProtocolConfiguration> agentLinkResolver = agentLink -> {// Resolve the agent and the protocol configuration@@ -75,6 +76,7 @@ public class AssetStorageServicepublic void init(Container container) throws Exception {eventService = container.getService(EventService.class);persistenceService = container.getService(PersistenceService.class);+ managerIdentityService = container.getService(ManagerIdentityService.class);// TODO None of this is secure or considers the realm of an asset or the logged-in user's realmassetListenerSubscriptions = new AssetListenerSubscriptions(eventService) {@@ -87,7 +89,7 @@ public class AssetStorageServicecontainer.getService(MessageBrokerSetupService.class).getContext().addRoutes(this);container.getService(WebService.class).getApiSingletons().add(- new AssetResourceImpl(container.getService(ManagerIdentityService.class), this)+ new AssetResourceImpl(this));}@@ -327,7 +329,7 @@ public class AssetStorageServicepublic ServerAsset merge(ServerAsset asset) {return persistenceService.doReturningTransaction(em -> {// Validate realm- if (!isRealmActive(asset.getRealm())) {+ if (!managerIdentityService.isTenantActive(asset.getRealm())) {throw new IllegalStateException("Realm not found: " + asset.getRealm());}// Validate parent@@ -395,17 +397,6 @@ public class AssetStorageServicereturn asset;}- protected boolean isRealmActive(String realm) {- return persistenceService.doReturningTransaction(entityManager -> {- // TODO Should also check NOT_BEFORE?- @SuppressWarnings("unchecked")- List<Object[]> result = entityManager.createNativeQuery(- "SELECT ID FROM REALM WHERE ENABLED = TRUE AND NAME = :realm"- ).setParameter("realm", realm).getResultList();- return result.size() > 0;- });- }-protected boolean storeAttribute(String assetId, Attribute attribute) {return persistenceService.doReturningTransaction(entityManager ->entityManager.unwrap(Session.class).doReturningWork(connection -> {diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesResourceImpl.javanew file mode 100644index 000000000..31815b6b1--- /dev/null+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesResourceImpl.java@@ -0,0 +1,282 @@+/*+ * 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.rules;++import org.openremote.container.web.WebResource;+import org.openremote.manager.server.asset.AssetStorageService;+import org.openremote.manager.shared.http.RequestParams;+import org.openremote.manager.shared.rules.AssetRulesDefinition;+import org.openremote.manager.shared.rules.GlobalRulesDefinition;+import org.openremote.manager.shared.rules.RulesResource;+import org.openremote.manager.shared.rules.TenantRulesDefinition;+import org.openremote.model.asset.Asset;+import org.openremote.model.asset.ProtectedAssetInfo;++import javax.ws.rs.BeanParam;+import javax.ws.rs.WebApplicationException;+import javax.ws.rs.core.Response;+import java.util.List;++import static javax.ws.rs.core.Response.Status.BAD_REQUEST;+import static javax.ws.rs.core.Response.Status.NOT_FOUND;++public class RulesResourceImpl extends WebResource implements RulesResource {++ final protected RulesStorageService rulesStorageService;+ final protected AssetStorageService assetStorageService;++ public RulesResourceImpl(RulesStorageService rulesStorageService, AssetStorageService assetStorageService) {+ this.rulesStorageService = rulesStorageService;+ this.assetStorageService = assetStorageService;+ }++ /* ################################################################################################# */++ @Override+ public GlobalRulesDefinition[] getGlobalDefinitions(@BeanParam RequestParams requestParams) {+ if (!isSuperUser()) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }+ List<GlobalRulesDefinition> result = rulesStorageService.findGlobalDefinitions();+ return result.toArray(new GlobalRulesDefinition[result.size()]);+ }++ @Override+ public TenantRulesDefinition[] getTenantDefinitions(@BeanParam RequestParams requestParams, String realm) {+ if (!isRealmAccessibleByUser(realm) || isRestrictedUser()) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }+ List<TenantRulesDefinition> result = rulesStorageService.findTenantDefinitions(realm);+ return result.toArray(new TenantRulesDefinition[result.size()]);+ }++ @Override+ public AssetRulesDefinition[] getAssetDefinitions(@BeanParam RequestParams requestParams, String assetId) {+ Asset asset = assetStorageService.find(assetId);+ if (asset == null)+ return new AssetRulesDefinition[0];++ String realm = asset.getRealm();+ if (!isRealmAccessibleByUser(realm)) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }+ if (isRestrictedUser()) {+ checkProtectedAccess(assetId);+ }+ List<AssetRulesDefinition> result = rulesStorageService.findAssetDefinitions(realm, assetId);+ return result.toArray(new AssetRulesDefinition[result.size()]);+ }++ /* ################################################################################################# */++ @Override+ public void createGlobalDefinition(@BeanParam RequestParams requestParams, GlobalRulesDefinition rulesDefinition) {+ if (!isSuperUser()) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }+ rulesDefinition = rulesStorageService.merge(rulesDefinition);+ }++ @Override+ public GlobalRulesDefinition getGlobalDefinition(@BeanParam RequestParams requestParams, Long id) {+ if (!isSuperUser()) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }+ GlobalRulesDefinition existingDefinition = rulesStorageService.findById(GlobalRulesDefinition.class, id);+ if (existingDefinition == null) {+ throw new WebApplicationException(NOT_FOUND);+ }+ return existingDefinition;+ }++ @Override+ public void updateGlobalDefinition(@BeanParam RequestParams requestParams, Long id, GlobalRulesDefinition rulesDefinition) {+ if (!isSuperUser()) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }+ GlobalRulesDefinition existingDefinition = rulesStorageService.findById(GlobalRulesDefinition.class, id);+ if (existingDefinition == null)+ throw new WebApplicationException(NOT_FOUND);+ rulesDefinition = rulesStorageService.merge(rulesDefinition);+ }++ @Override+ public void deleteGlobalDefinition(@BeanParam RequestParams requestParams, Long id) {+ if (!isSuperUser()) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }+ rulesStorageService.delete(GlobalRulesDefinition.class, id);+ }++ /* ################################################################################################# */++ @Override+ public void createTenantDefinition(@BeanParam RequestParams requestParams, TenantRulesDefinition rulesDefinition) {+ String realm = rulesDefinition.getRealm();+ if (realm == null || realm.length() == 0) {+ throw new WebApplicationException(BAD_REQUEST);+ }+ if (!isRealmAccessibleByUser(realm) || isRestrictedUser()) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }+ rulesDefinition = rulesStorageService.merge(rulesDefinition);+ }++ @Override+ public TenantRulesDefinition getTenantDefinition(@BeanParam RequestParams requestParams, Long id) {+ TenantRulesDefinition existingDefinition = rulesStorageService.findById(TenantRulesDefinition.class, id);+ if (existingDefinition == null) {+ throw new WebApplicationException(NOT_FOUND);+ }+ if (!isRealmAccessibleByUser(existingDefinition.getRealm()) || isRestrictedUser()) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }+ return existingDefinition;+ }++ @Override+ public void updateTenantDefinition(@BeanParam RequestParams requestParams, Long id, TenantRulesDefinition rulesDefinition) {+ TenantRulesDefinition existingDefinition = rulesStorageService.findById(TenantRulesDefinition.class, id);+ if (existingDefinition == null) {+ throw new WebApplicationException(NOT_FOUND);+ }+ if (!isRealmAccessibleByUser(existingDefinition.getRealm()) || isRestrictedUser()) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }+ if (!id.equals(rulesDefinition.getId())) {+ throw new WebApplicationException("Requested ID and definition ID don't match", BAD_REQUEST);+ }+ if (!existingDefinition.getRealm().equals(rulesDefinition.getRealm())) {+ throw new WebApplicationException("Requested realm and existing definition realm must match", BAD_REQUEST);+ }+ rulesDefinition = rulesStorageService.merge(rulesDefinition);+ }++ @Override+ public void deleteTenantDefinition(@BeanParam RequestParams requestParams, Long id) {+ TenantRulesDefinition existingDefinition = rulesStorageService.findById(TenantRulesDefinition.class, id);+ if (existingDefinition == null) {+ return;+ }+ if (!isRealmAccessibleByUser(existingDefinition.getRealm()) || isRestrictedUser()) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }+ rulesStorageService.delete(TenantRulesDefinition.class, id);+ }++ /* ################################################################################################# */++ @Override+ public void createAssetDefinition(@BeanParam RequestParams requestParams, AssetRulesDefinition rulesDefinition) {+ String assetId = rulesDefinition.getAssetId();+ if (assetId == null || assetId.length() == 0) {+ throw new WebApplicationException("Missing asset identifier value", BAD_REQUEST);+ }+ Asset asset = assetStorageService.find(assetId);+ if (asset == null) {+ throw new WebApplicationException(NOT_FOUND);+ }+ if (!isRealmAccessibleByUser(asset.getRealm())) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }+ if (isRestrictedUser()) {+ checkProtectedAccess(assetId);+ }+ rulesDefinition = rulesStorageService.merge(rulesDefinition);+ }++ @Override+ public AssetRulesDefinition getAssetDefinition(@BeanParam RequestParams requestParams, Long id) {+ AssetRulesDefinition existingDefinition = rulesStorageService.findById(AssetRulesDefinition.class, id);+ if (existingDefinition == null) {+ throw new WebApplicationException(NOT_FOUND);+ }+ Asset asset = assetStorageService.find(existingDefinition.getAssetId());+ if (asset == null) {+ throw new WebApplicationException(NOT_FOUND);+ }+ if (!isRealmAccessibleByUser(asset.getRealm())) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }+ if (isRestrictedUser()) {+ checkProtectedAccess(asset.getId());+ }+ return existingDefinition;+ }++ @Override+ public void updateAssetDefinition(@BeanParam RequestParams requestParams, Long id, AssetRulesDefinition rulesDefinition) {+ AssetRulesDefinition existingDefinition = rulesStorageService.findById(AssetRulesDefinition.class, id);+ if (existingDefinition == null) {+ throw new WebApplicationException(NOT_FOUND);+ }+ Asset asset = assetStorageService.find(existingDefinition.getAssetId());+ if (asset == null) {+ throw new WebApplicationException(NOT_FOUND);+ }+ if (!isRealmAccessibleByUser(asset.getRealm())) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }+ if (isRestrictedUser()) {+ checkProtectedAccess(asset.getId());+ }+ if (!id.equals(rulesDefinition.getId())) {+ throw new WebApplicationException("Requested ID and definition ID don't match", BAD_REQUEST);+ }+ if (!existingDefinition.getAssetId().equals(rulesDefinition.getAssetId())) {+ throw new WebApplicationException("Can't update asset ID, delete and create the definition to reassign", BAD_REQUEST);+ }+ rulesDefinition = rulesStorageService.merge(rulesDefinition);+ }++ @Override+ public void deleteAssetDefinition(@BeanParam RequestParams requestParams, Long id) {+ AssetRulesDefinition existingDefinition = rulesStorageService.findById(AssetRulesDefinition.class, id);+ if (existingDefinition == null) {+ return;+ }+ Asset asset = assetStorageService.find(existingDefinition.getAssetId());+ if (asset == null) {+ throw new WebApplicationException(NOT_FOUND);+ }+ if (!isRealmAccessibleByUser(asset.getRealm())) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }+ if (isRestrictedUser()) {+ checkProtectedAccess(asset.getId());+ }+ rulesStorageService.delete(AssetRulesDefinition.class, id);+ }++ /* ################################################################################################# */++ protected void checkProtectedAccess(String assetId) {+ boolean foundProtected = false;+ ProtectedAssetInfo[] protectedAssets =+ assetStorageService.findProtectedOfUser(getAuthenticatedRealm(), getUsername());+ for (ProtectedAssetInfo protectedAsset : protectedAssets) {+ if (protectedAsset.getId().equals(assetId))+ foundProtected = true;+ }+ if (!foundProtected) {+ throw new WebApplicationException(Response.Status.FORBIDDEN);+ }+ }+}diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesStorageService.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesStorageService.javanew file mode 100644index 000000000..cdfa2b8b5--- /dev/null+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesStorageService.java@@ -0,0 +1,117 @@+/*+ * 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.rules;++import org.openremote.container.Container;+import org.openremote.container.ContainerService;+import org.openremote.container.persistence.PersistenceService;+import org.openremote.container.web.WebService;+import org.openremote.manager.server.asset.AssetStorageService;+import org.openremote.manager.shared.rules.AssetRulesDefinition;+import org.openremote.manager.shared.rules.GlobalRulesDefinition;+import org.openremote.manager.shared.rules.RulesDefinition;+import org.openremote.manager.shared.rules.TenantRulesDefinition;++import java.util.List;+import java.util.logging.Logger;++public class RulesStorageService implements ContainerService {++ private static final Logger LOG = Logger.getLogger(RulesStorageService.class.getName());++ protected PersistenceService persistenceService;++ @Override+ public void init(Container container) throws Exception {+ persistenceService = container.getService(PersistenceService.class);++ container.getService(WebService.class).getApiSingletons().add(+ new RulesResourceImpl(this, container.getService(AssetStorageService.class))+ );+ }++ @Override+ public void start(Container container) throws Exception {+ }++ @Override+ public void stop(Container container) throws Exception {++ }++ public List<GlobalRulesDefinition> findGlobalDefinitions() {+ return persistenceService.doReturningTransaction(entityManager ->+ entityManager.createQuery(+ "select new org.openremote.manager.shared.rules.GlobalRulesDefinition(" ++ "rd.id, rd.version, rd.createdOn, rd.lastModified, rd.name, rd.enabled" ++ ") " ++ "from GlobalRulesDefinition rd " ++ "order by rd.createdOn asc",+ GlobalRulesDefinition.class+ ).getResultList()+ );+ }++ public List<TenantRulesDefinition> findTenantDefinitions(String realm) {+ return persistenceService.doReturningTransaction(entityManager ->+ entityManager.createQuery(+ "select new org.openremote.manager.shared.rules.TenantRulesDefinition(" ++ "rd.id, rd.version, rd.createdOn, rd.lastModified, rd.name, rd.enabled, rd.realm" ++ ") " ++ "from TenantRulesDefinition rd " ++ "where rd.realm = :realm " ++ "order by rd.createdOn asc",+ TenantRulesDefinition.class+ ).setParameter("realm", realm).getResultList()+ );+ }++ public List<AssetRulesDefinition> findAssetDefinitions(String realm, String assetId) {+ return persistenceService.doReturningTransaction(entityManager ->+ entityManager.createQuery(+ "select new org.openremote.manager.shared.rules.AssetRulesDefinition(" ++ "rd.id, rd.version, rd.createdOn, rd.lastModified, rd.name, rd.enabled, rd.assetId" ++ ") " ++ "from AssetRulesDefinition rd, Asset a " ++ "where rd.assetId = :assetId and rd.assetId = a.id and a.realm = :realm " ++ "order by rd.createdOn asc",+ AssetRulesDefinition.class+ ).setParameter("realm", realm).setParameter("assetId", assetId).getResultList()+ );+ }++ public <T extends RulesDefinition> T findById(Class<T> rulesDefinitionType, Long id) {+ return persistenceService.doReturningTransaction(em -> em.find(rulesDefinitionType, id));+ }++ public <T extends RulesDefinition> T merge(T rulesDefinition) {+ return persistenceService.doReturningTransaction(entityManager ->+ entityManager.merge(rulesDefinition)+ );+ }++ public <T extends RulesDefinition> void delete(Class<T> rulesDefinitionType, Long id) {+ persistenceService.doTransaction(entityManager -> {+ RulesDefinition rulesDefinition = entityManager.find(rulesDefinitionType, id);+ if (rulesDefinition != null)+ entityManager.remove(rulesDefinition);+ });+ }+}diff --git a/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.javaindex 572e1eb3c..ec31803e8 100644--- a/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java@@ -25,6 +25,7 @@ import org.keycloak.representations.idm.ProtocolMapperRepresentation;import org.keycloak.representations.idm.RealmRepresentation;import org.keycloak.representations.idm.RoleRepresentation;import org.openremote.container.Container;+import org.openremote.container.persistence.PersistenceService;import org.openremote.container.security.IdentityService;import org.openremote.container.security.KeycloakResource;import org.openremote.container.web.WebService;@@ -45,6 +46,7 @@ public class ManagerIdentityService extends IdentityService {private static final Logger LOG = Logger.getLogger(ManagerIdentityService.class.getName());protected boolean devMode;+ protected PersistenceService persistenceService;public ManagerIdentityService() {super(Constants.KEYCLOAK_CLIENT_ID);@@ -55,6 +57,7 @@ public class ManagerIdentityService extends IdentityService {super.init(container);this.devMode = container.isDevMode();+ this.persistenceService = container.getService(PersistenceService.class);enableAuthProxy(container.getService(WebService.class));@@ -122,6 +125,18 @@ public class ManagerIdentityService extends IdentityService {);}+ public boolean isTenantActive(String realm) {+ // We use a direct database query, faster than calling Keycloak through HTTP+ return persistenceService.doReturningTransaction(entityManager -> {+ // TODO Should also check NOT_BEFORE?+ @SuppressWarnings("unchecked")+ List<Object[]> result = entityManager.createNativeQuery(+ "SELECT ID FROM REALM WHERE ENABLED = TRUE AND NAME = :realm"+ ).setParameter("realm", realm).getResultList();+ return result.size() > 0;+ });+ }+public void configureRealm(RealmRepresentation realmRepresentation) {configureRealm(realmRepresentation, ACCESS_TOKEN_LIFESPAN_SECONDS);}@@ -177,7 +192,6 @@ public class ManagerIdentityService extends IdentityService {}public void addDefaultMappers(ProtocolMappersResource protocolMappers) {-// Link between user and asset ("ownership")ProtocolMapperRepresentation userAssetMapper = new ProtocolMapperRepresentation();userAssetMapper.setProtocol("openid-connect");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 9a32f0b5e..b480aa801 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@@ -23,17 +23,20 @@ import com.vividsolutions.jts.geom.GeometryFactory;import org.openremote.container.Container;import org.openremote.container.persistence.PersistenceService;import org.openremote.manager.server.asset.AssetStorageService;+import org.openremote.manager.server.rules.RulesStorageService;public abstract class AbstractManagerSetup implements Setup {final protected PersistenceService persistenceService;final protected AssetStorageService assetStorageService;+ final protected RulesStorageService rulesStorageService;final protected GeometryFactory geometryFactory = new GeometryFactory();final protected SetupService setupService;public AbstractManagerSetup(Container container) {this.persistenceService = container.getService(PersistenceService.class);this.assetStorageService = container.getService(AssetStorageService.class);+ this.rulesStorageService = container.getService(RulesStorageService.class);this.setupService = container.getService(SetupService.class);}diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakDemoSetup.javaindex fa2499ce2..c0b2fc4f8 100644--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakDemoSetup.java+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/KeycloakDemoSetup.java@@ -37,9 +37,9 @@ import java.util.logging.Logger;* We have the following demo users:* <ul>* <li><code>admin</code> - The superuser in the "master" realm with all access</li>- * <li><code>testuser1</code> - (Password: testuser1) A user in the "master" realm with read/write access to assets</li>+ * <li><code>testuser1</code> - (Password: testuser1) A user in the "master" realm with read/write access to assets and rules</li>* <li><code>testuser2</code> - (Password: testuser2) A user in the "customerA" realm with only read access to assets</li>- * <li><code>testuser3</code> - (Password: testuser3) A user in the "customerA" realm with read/write access to a restricted set of "home" assets</li>+ * <li><code>testuser3</code> - (Password: testuser3) A user in the "customerA" realm with read/write access to a restricted set of assets and their rules</li>* </ul>*/public class KeycloakDemoSetup extends AbstractKeycloakSetup {@@ -87,7 +87,9 @@ public class KeycloakDemoSetup extends AbstractKeycloakSetup {masterUsersResource.get(testuser1.getId()).roles().clientLevel(masterClientObjectId).add(Arrays.asList(masterRolesResource.get(ClientRole.READ_MAP.getValue()).toRepresentation(),masterRolesResource.get(ClientRole.READ_ASSETS.getValue()).toRepresentation(),- masterRolesResource.get(ClientRole.WRITE_ASSETS.getValue()).toRepresentation()+ masterRolesResource.get(ClientRole.READ_RULES.getValue()).toRepresentation(),+ masterRolesResource.get(ClientRole.WRITE_ASSETS.getValue()).toRepresentation(),+ masterRolesResource.get(ClientRole.WRITE_RULES.getValue()).toRepresentation()));LOG.info("Added demo user '" + testuser1.getUsername() + "' with password '" + testuser1Credentials.getValue() + "'");@@ -137,7 +139,9 @@ public class KeycloakDemoSetup extends AbstractKeycloakSetup {customerAUsersResource.get(testuser3.getId()).roles().clientLevel(customerAClientObjectId).add(Arrays.asList(customerARolesResource.get(ClientRole.READ_MAP.getValue()).toRepresentation(),customerARolesResource.get(ClientRole.READ_ASSETS.getValue()).toRepresentation(),- customerARolesResource.get(ClientRole.WRITE_ASSETS.getValue()).toRepresentation()+ customerARolesResource.get(ClientRole.WRITE_RULES.getValue()).toRepresentation(),+ customerARolesResource.get(ClientRole.WRITE_ASSETS.getValue()).toRepresentation(),+ customerARolesResource.get(ClientRole.READ_RULES.getValue()).toRepresentation()));LOG.info("Added demo user '" + testuser3.getUsername() + "' with password '" + testuser3Credentials.getValue() + "'");}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 6b8083a18..5bd628471 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@@ -21,17 +21,25 @@ package org.openremote.manager.server.setup.builtin;import com.vividsolutions.jts.geom.Coordinate;import elemental.json.Json;+import org.apache.commons.io.IOUtils;import org.openremote.agent3.protocol.simulator.SimulatorProtocol;import org.openremote.container.Container;import org.openremote.manager.server.agent.AgentAttributes;import org.openremote.manager.server.agent.ThingAttributes;import org.openremote.manager.server.asset.ServerAsset;import org.openremote.manager.server.setup.AbstractManagerSetup;+import org.openremote.manager.shared.rules.AssetRulesDefinition;+import org.openremote.manager.shared.rules.GlobalRulesDefinition;+import org.openremote.manager.shared.rules.RulesDefinition;+import org.openremote.manager.shared.rules.TenantRulesDefinition;import org.openremote.model.*;import org.openremote.model.asset.*;import org.openremote.model.units.AttributeUnits;import org.openremote.model.units.ColorRGB;+import java.io.InputStream;+import java.nio.charset.Charset;+import static org.openremote.model.Constants.*;import static org.openremote.model.AttributeType.*;import static org.openremote.model.asset.AssetMeta.*;@@ -167,8 +175,8 @@ public class ManagerDemoSetup extends AbstractManagerSetup {new Attribute("light1Color", INTEGER_ARRAY, new ColorRGB(88, 123, 88).asJsonValue()).setMeta(new Meta().add(new MetaItem(- AssetMeta.UNITS,- Json.create(AttributeUnits.COLOR_RGB.toString())+ AssetMeta.UNITS,+ Json.create(AttributeUnits.COLOR_RGB.toString()))).add(new MetaItem(AssetMeta.DESCRIPTION,@@ -204,7 +212,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {SimulatorProtocol.META_NAME_ELEMENT, Json.create("decimal"))).add(new MetaItem(- AssetMeta.STORE_DATA_POINTS.getName(), Json.create(true)+ AssetMeta.STORE_DATA_POINTS.getName(), Json.create(true)))));@@ -301,5 +309,46 @@ public class ManagerDemoSetup extends AbstractManagerSetup {apartment3Livingroom.setType(ROOM);apartment3Livingroom = assetStorageService.merge(apartment3Livingroom);apartment3LivingroomId = apartment3Livingroom.getId();++ // ################################ Rules demo data ###################################++ try (InputStream inputStream = ManagerDemoSetup.class.getResourceAsStream("/demo/rules/SomeGlobalDemoRules.drl")) {+ String rules = IOUtils.toString(inputStream, Charset.forName("utf-8"));+ RulesDefinition rulesDefinition = new GlobalRulesDefinition("Some global demo rules", rules);+ rulesStorageService.merge(rulesDefinition);+ }++ try (InputStream inputStream = ManagerDemoSetup.class.getResourceAsStream("/demo/rules/SomeTenantDemoRules.drl")) {+ String rules = IOUtils.toString(inputStream, Charset.forName("utf-8"));+ RulesDefinition rulesDefinition = new TenantRulesDefinition("Some master tenant demo rules", Constants.MASTER_REALM, rules);+ rulesStorageService.merge(rulesDefinition);+ }++ try (InputStream inputStream = ManagerDemoSetup.class.getResourceAsStream("/demo/rules/SomeTenantDemoRules.drl")) {+ String rules = IOUtils.toString(inputStream, Charset.forName("utf-8"));+ RulesDefinition rulesDefinition = new TenantRulesDefinition("Some customerA tenant demo rules", "customerA", rules);+ rulesDefinition.setEnabled(false);+ rulesStorageService.merge(rulesDefinition);+ }++ try (InputStream inputStream = ManagerDemoSetup.class.getResourceAsStream("/demo/rules/SomeAssetDemoRules.drl")) {+ String rules = IOUtils.toString(inputStream, Charset.forName("utf-8"));+ RulesDefinition rulesDefinition = new AssetRulesDefinition("Some apartment 1 demo rules", apartment1Id , rules);+ rulesStorageService.merge(rulesDefinition);+ }++ try (InputStream inputStream = ManagerDemoSetup.class.getResourceAsStream("/demo/rules/SomeAssetDemoRules.drl")) {+ String rules = IOUtils.toString(inputStream, Charset.forName("utf-8"));+ RulesDefinition rulesDefinition = new AssetRulesDefinition("Some apartment 2 demo rules", apartment2Id , rules);+ rulesDefinition.setEnabled(false);+ rulesStorageService.merge(rulesDefinition);+ }++ try (InputStream inputStream = ManagerDemoSetup.class.getResourceAsStream("/demo/rules/SomeAssetDemoRules.drl")) {+ String rules = IOUtils.toString(inputStream, Charset.forName("utf-8"));+ RulesDefinition rulesDefinition = new AssetRulesDefinition("Some apartment 3 demo rules", apartment3Id , rules);+ rulesStorageService.merge(rulesDefinition);+ }+}}diff --git a/manager/server/src/main/resources/LoadScript.sql b/manager/server/src/main/resources/LoadScript.sqlnew file mode 100644index 000000000..d5a530bca--- /dev/null+++ b/manager/server/src/main/resources/LoadScript.sql@@ -0,0 +1,2 @@+alter table REALM_RULES add foreign key(REALM) references REALM(NAME) on update cascade on delete cascade;+alter table ASSET_RULES add foreign key(ASSET_ID) references ASSET(ID) on delete cascade;diff --git a/manager/server/src/main/resources/META-INF/persistence.xml b/manager/server/src/main/resources/META-INF/persistence.xmlindex 60103a139..c8b8d263b 100644--- a/manager/server/src/main/resources/META-INF/persistence.xml+++ b/manager/server/src/main/resources/META-INF/persistence.xml@@ -11,13 +11,18 @@<class>org.openremote.manager.server.asset.ServerAsset</class><class>org.openremote.model.datapoint.AssetDatapoint</class>+ <class>org.openremote.manager.shared.rules.GlobalRulesDefinition</class>+ <class>org.openremote.manager.shared.rules.TenantRulesDefinition</class>+ <class>org.openremote.manager.shared.rules.AssetRulesDefinition</class><exclude-unlisted-classes>true</exclude-unlisted-classes>+<properties><property name="hibernate.format_sql" value="true"/><property name="hibernate.use_sql_comments" value="true"/><property name="hibernate.archive.autodetection" value="none"/><property name="hibernate.current_session_context_class" value="thread"/>+ <property name="javax.persistence.sql-load-script-source" value="LoadScript.sql"/></properties></persistence-unit>diff --git a/manager/server/src/main/resources/demo/rules/SomeAssetDemoRules.drl b/manager/server/src/main/resources/demo/rules/SomeAssetDemoRules.drlnew file mode 100644index 000000000..d0c077705--- /dev/null+++ b/manager/server/src/main/resources/demo/rules/SomeAssetDemoRules.drl@@ -0,0 +1,12 @@+package org.openremote.test.rules;++import org.openremote.agent.sensor.*;++global org.openremote.agent.rules.SwitchFacade switches;++rule "Modify Switch State"+when+ $switch : SwitchSensorState(sensorID == 123)+then+ switches.name($switch.getSensorName()).off();+enddiff --git a/manager/server/src/main/resources/demo/rules/SomeGlobalDemoRules.drl b/manager/server/src/main/resources/demo/rules/SomeGlobalDemoRules.drlnew file mode 100644index 000000000..d0c077705--- /dev/null+++ b/manager/server/src/main/resources/demo/rules/SomeGlobalDemoRules.drl@@ -0,0 +1,12 @@+package org.openremote.test.rules;++import org.openremote.agent.sensor.*;++global org.openremote.agent.rules.SwitchFacade switches;++rule "Modify Switch State"+when+ $switch : SwitchSensorState(sensorID == 123)+then+ switches.name($switch.getSensorName()).off();+enddiff --git a/manager/server/src/main/resources/demo/rules/SomeTenantDemoRules.drl b/manager/server/src/main/resources/demo/rules/SomeTenantDemoRules.drlnew file mode 100644index 000000000..d0c077705--- /dev/null+++ b/manager/server/src/main/resources/demo/rules/SomeTenantDemoRules.drl@@ -0,0 +1,12 @@+package org.openremote.test.rules;++import org.openremote.agent.sensor.*;++global org.openremote.agent.rules.SwitchFacade switches;++rule "Modify Switch State"+when+ $switch : SwitchSensorState(sensorID == 123)+then+ switches.name($switch.getSensorName()).off();+enddiff --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 38c57ee36..4dd9cae8b 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@@ -138,6 +138,7 @@ public interface AssetResource {* authenticated realm, or if the user is restricted and the asset to update is not in the set of linked* assets of the restricted user. A 400 status is returned if the update was not successful, e.g. because* the given value does not match the attribute's type.+ * // TODO Consider attribute state class instead, and test this*/@PUT@Path("{assetId}/attribute/{attributeName}")diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/http/SuccessStatusCode.java b/manager/shared/src/main/java/org/openremote/manager/shared/http/SuccessStatusCode.javaindex d2aac1cf7..040d103bb 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/http/SuccessStatusCode.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/http/SuccessStatusCode.java@@ -28,5 +28,5 @@ import java.lang.annotation.*;@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface SuccessStatusCode {- int value() default 200;+ int value();}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/rules/AssetRulesDefinition.java b/manager/shared/src/main/java/org/openremote/manager/shared/rules/AssetRulesDefinition.javanew file mode 100644index 000000000..67cb29b76--- /dev/null+++ b/manager/shared/src/main/java/org/openremote/manager/shared/rules/AssetRulesDefinition.java@@ -0,0 +1,58 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.shared.rules;++import javax.persistence.Column;+import javax.persistence.Entity;+import javax.persistence.Table;+import java.util.Date;++/**+ * Rules that can only be triggered by asset modifications in a particular+ * asset subtree, and can only modify asset data in a particular asset subtree.+ */+@Entity+@Table(name = "ASSET_RULES")+public class AssetRulesDefinition extends RulesDefinition {++ @Column(name = "ASSET_ID", nullable = false)+ public String assetId;++ public AssetRulesDefinition() {+ }++ public AssetRulesDefinition(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String assetId) {+ super(id, version, createdOn, lastModified, name, enabled);+ this.assetId = assetId;+ }++ public AssetRulesDefinition(String name, String assetId, String rules) {+ super(name, rules);+ this.assetId = assetId;+ }++ public String getAssetId() {+ return assetId;+ }++ public void setAssetId(String assetId) {+ this.assetId = assetId;+ }+}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/rules/GlobalRulesDefinition.java b/manager/shared/src/main/java/org/openremote/manager/shared/rules/GlobalRulesDefinition.javanew file mode 100644index 000000000..1e745306c--- /dev/null+++ b/manager/shared/src/main/java/org/openremote/manager/shared/rules/GlobalRulesDefinition.java@@ -0,0 +1,43 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.shared.rules;++import javax.persistence.Entity;+import javax.persistence.Table;+import java.util.Date;++/**+ * Rules that apply to all realms and assets, for the whole system.+ */+@Entity+@Table(name = "GLOBAL_RULES")+public class GlobalRulesDefinition extends RulesDefinition {++ public GlobalRulesDefinition() {+ }++ public GlobalRulesDefinition(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled) {+ super(id, version, createdOn, lastModified, name, enabled);+ }++ public GlobalRulesDefinition(String name, String rules) {+ super(name, rules);+ }+}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/rules/RulesDefinition.java b/manager/shared/src/main/java/org/openremote/manager/shared/rules/RulesDefinition.javanew file mode 100644index 000000000..e51832dd2--- /dev/null+++ b/manager/shared/src/main/java/org/openremote/manager/shared/rules/RulesDefinition.java@@ -0,0 +1,154 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.shared.rules;++import javax.persistence.*;+import javax.validation.constraints.NotNull;++import java.util.Date;++import static org.openremote.model.Constants.PERSISTENCE_SEQUENCE_ID_GENERATOR;++/**+ * Rules can be defined in three scopes: global, for a realm, for an asset sub-tree.+ */+@MappedSuperclass+public abstract class RulesDefinition {++ public enum DeploymentStatus {+ /**+ * Rule definition compiled successfully but is not running, due to failure of other definitions in same scope.+ */+ READY,++ /**+ * Rule definition has been compiled and is running.+ */+ DEPLOYED,++ /**+ * Rule definition did not compile successfully.+ */+ FAILED+ }++ @Id+ @Column(name = "ID")+ @GeneratedValue(generator = PERSISTENCE_SEQUENCE_ID_GENERATOR)+ protected Long id;++ @Version+ @Column(name = "OBJ_VERSION", nullable = false)+ protected long version;++ @Temporal(TemporalType.TIMESTAMP)+ @Column(name = "CREATED_ON", updatable = false, nullable = false)+ @org.hibernate.annotations.CreationTimestamp+ protected Date createdOn = new Date();++ @Temporal(TemporalType.TIMESTAMP)+ @Column(name = "LAST_MODIFIED", nullable = false)+ protected Date lastModified;++ @NotNull+ @Column(name = "NAME", nullable = false)+ protected String name;++ @Column(name = "ENABLED", nullable = false)+ protected boolean enabled = true;++ @Lob+ @Column(name = "RULES", nullable = false)+ protected String rules;++ @Transient+ protected DeploymentStatus deploymentStatus;++ public RulesDefinition() {+ }++ public RulesDefinition(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled) {+ this.id = id;+ this.version = version;+ this.createdOn = createdOn;+ this.lastModified = lastModified;+ this.name = name;+ this.enabled = enabled;+ }++ public RulesDefinition(String name, String rules) {+ this.name = name;+ this.rules = rules;+ }++ public Long getId() {+ return id;+ }++ public long getVersion() {+ return version;+ }++ public Date getCreatedOn() {+ return createdOn;+ }++ @PreUpdate+ @PrePersist+ public void setLastModified() {+ this.lastModified = new Date();+ }++ public Date getLastModified() {+ return lastModified;+ }++ public String getName() {+ return name;+ }++ public void setName(String name) {+ this.name = name;+ }++ public boolean isEnabled() {+ return enabled;+ }++ public void setEnabled(boolean enabled) {+ this.enabled = enabled;+ }++ public String getRules() {+ return rules;+ }++ public void setRules(String rules) {+ this.rules = rules;+ }++ public DeploymentStatus getDeploymentStatus() {+ return deploymentStatus;+ }++ public void setDeploymentStatus(DeploymentStatus deploymentStatus) {+ this.deploymentStatus = deploymentStatus;+ }+}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/rules/RulesResource.java b/manager/shared/src/main/java/org/openremote/manager/shared/rules/RulesResource.javanew file mode 100644index 000000000..3494d8f91--- /dev/null+++ b/manager/shared/src/main/java/org/openremote/manager/shared/rules/RulesResource.java@@ -0,0 +1,218 @@+/*+ * Copyright 2016, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.shared.rules;++import jsinterop.annotations.JsType;+import org.openremote.manager.shared.http.RequestParams;+import org.openremote.manager.shared.http.SuccessStatusCode;++import javax.annotation.security.RolesAllowed;+import javax.ws.rs.*;++import static javax.ws.rs.core.MediaType.APPLICATION_JSON;++@Path("rules")+@JsType(isNative = true)+public interface RulesResource {++ /**+ * Retrieve global rules. Only the superuser can perform this operation, a 403 status is+ * returned if a regular user tries to access global rule definitions.+ */+ @GET+ @Produces(APPLICATION_JSON)+ @SuccessStatusCode(200)+ @RolesAllowed({"read:rules"})+ GlobalRulesDefinition[] getGlobalDefinitions(@BeanParam RequestParams requestParams);++ /**+ * Retrieve rules of a tenant. The superuser can retrieve rules of all realms, a 403 status+ * is returned if a regular user tries to access rule definitions outside of its authenticated realm.+ * An empty result will be returned if the realm can not be found.+ */+ @GET+ @Path("tenant/for/{realm}")+ @Produces(APPLICATION_JSON)+ @SuccessStatusCode(200)+ @RolesAllowed({"read:rules"})+ TenantRulesDefinition[] getTenantDefinitions(@BeanParam RequestParams requestParams, @PathParam("realm") String realm);++ /**+ * Retrieve rules of an asset. The superuser can retrieve rules of all realms and assets, a 403 status+ * is returned if a regular user tries to access rule definitions outside of its authenticated realm, or+ * if the user is restricted and the asset is not one of its linked assets. An empty result will be returned+ * if the asset can not be found.+ */+ @GET+ @Path("asset/for/{assetId}")+ @Produces(APPLICATION_JSON)+ @SuccessStatusCode(200)+ @RolesAllowed({"read:rules"})+ AssetRulesDefinition[] getAssetDefinitions(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId);++ /* ################################################################################################# */++ /**+ * Create a global rules definition. Only the superuser can perform this operation, a 403 status is+ * returned if a regular user tries to access global rule definitions.+ */+ @POST+ @Consumes(APPLICATION_JSON)+ @Produces(APPLICATION_JSON)+ @SuccessStatusCode(204)+ @RolesAllowed({"write:rules"})+ void createGlobalDefinition(@BeanParam RequestParams requestParams, GlobalRulesDefinition rulesDefinition);++ /**+ * Retrieve a global rules definition. Only the superuser can perform this operation, a 403 status is+ * returned if a regular user tries to access global rule definitions.+ */+ @GET+ @Path("{id}")+ @Produces(APPLICATION_JSON)+ @SuccessStatusCode(200)+ @RolesAllowed({"read:rules"})+ GlobalRulesDefinition getGlobalDefinition(@BeanParam RequestParams requestParams, @PathParam("id") Long id);++ /**+ * Update a global rules definition. Only the superuser can perform this operation, a 403 status is+ * returned if a regular user tries to access global rule definitions.+ */+ @PUT+ @Path("{id}")+ @Consumes(APPLICATION_JSON)+ @SuccessStatusCode(204)+ @RolesAllowed({"write:rules"})+ void updateGlobalDefinition(@BeanParam RequestParams requestParams, @PathParam("id") Long id, GlobalRulesDefinition rulesDefinition);++ /**+ * Deletes a global rules definition. Only the superuser can perform this operation, a 403 status is+ * returned if a regular user tries to access global rule definitions.+ */+ @DELETE+ @Path("{id}")+ @Produces(APPLICATION_JSON)+ @SuccessStatusCode(204)+ @RolesAllowed({"write:rules"})+ void deleteGlobalDefinition(@BeanParam RequestParams requestParams, @PathParam("id") Long id);++ /* ################################################################################################# */++ /**+ * Create a tenant rules definition. The superuser can create rules in all realms, a 403 status+ * is returned if a regular user tries to access rule definitions outside of its authenticated realm,+ * or if the user is restricted.+ */+ @POST+ @Path("tenant")+ @Consumes(APPLICATION_JSON)+ @Produces(APPLICATION_JSON)+ @SuccessStatusCode(204)+ @RolesAllowed({"write:rules"})+ void createTenantDefinition(@BeanParam RequestParams requestParams, TenantRulesDefinition rulesDefinition);++ /**+ * Retrieve a tenant rules definition. The superuser can retrieve rules of all realms, a 403 status+ * is returned if a regular user tries to access rule definitions outside of its authenticated realm, or+ * if the user is restricted.+ */+ @GET+ @Path("tenant/{id}")+ @Produces(APPLICATION_JSON)+ @SuccessStatusCode(200)+ @RolesAllowed({"read:rules"})+ TenantRulesDefinition getTenantDefinition(@BeanParam RequestParams requestParams, @PathParam("id") Long id);++ /**+ * Update a tenant rules definition. The superuser can update rules of all realms, a 403 status+ * is returned if a regular user tries to access rule definitions outside of its authenticated realm,+ * or if the user is restricted.+ */+ @PUT+ @Path("tenant/{id}")+ @Consumes(APPLICATION_JSON)+ @SuccessStatusCode(204)+ @RolesAllowed({"write:rules"})+ void updateTenantDefinition(@BeanParam RequestParams requestParams, @PathParam("id") Long id, TenantRulesDefinition rulesDefinition);++ /**+ * Delete a tenant rules definition. The superuser can delete rules of all realms, a 403 status+ * is returned if a regular user tries to access rule definitions outside of its authenticated realm,+ * or if the user is restricted.+ */+ @DELETE+ @Path("tenant/{id}")+ @Produces(APPLICATION_JSON)+ @SuccessStatusCode(204)+ @RolesAllowed({"write:rules"})+ void deleteTenantDefinition(@BeanParam RequestParams requestParams, @PathParam("id") Long id);++ /* ################################################################################################# */++ /**+ * Create an asset rules definition. The superuser can create rules for all assets, a 403 status+ * is returned if a regular user tries to access rule definitions outside of its authenticated realm,+ * or if the user is restricted and does not have access to the asset.+ */+ @POST+ @Path("asset")+ @Consumes(APPLICATION_JSON)+ @Produces(APPLICATION_JSON)+ @SuccessStatusCode(204)+ @RolesAllowed({"write:rules"})+ void createAssetDefinition(@BeanParam RequestParams requestParams, AssetRulesDefinition rulesDefinition);++ /**+ * Retrieve an asset rules definition. The superuser can retrieve rules of all assets, a 403 status+ * is returned if a regular user tries to access rule definitions outside of its authenticated realm, or+ * if the user is restricted and does not have access to the asset.+ */+ @GET+ @Path("asset/{id}")+ @Produces(APPLICATION_JSON)+ @SuccessStatusCode(200)+ @RolesAllowed({"write:rules"})+ AssetRulesDefinition getAssetDefinition(@BeanParam RequestParams requestParams, @PathParam("id") Long id);++ /**+ * Update an asset rules definition. The superuser can update rules of all assets, a 403 status+ * is returned if a regular user tries to access rule definitions outside of its authenticated realm,+ * or if the user is restricted and does not have access to the asset.+ */+ @PUT+ @Path("asset/{id}")+ @Consumes(APPLICATION_JSON)+ @SuccessStatusCode(204)+ @RolesAllowed({"write:rules"})+ void updateAssetDefinition(@BeanParam RequestParams requestParams, @PathParam("id") Long id, AssetRulesDefinition rulesDefinition);++ /**+ * Delete an asset rules definition. The superuser can delete rules of all assets, a 403 status+ * is returned if a regular user tries to access rule definitions outside of its authenticated realm,+ * or if the user is restricted and does not have access to the asset.+ */+ @DELETE+ @Path("asset/{id}")+ @Produces(APPLICATION_JSON)+ @SuccessStatusCode(204)+ @RolesAllowed({"write:rules"})+ void deleteAssetDefinition(@BeanParam RequestParams requestParams, @PathParam("id") Long id);++}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/rules/TenantRulesDefinition.java b/manager/shared/src/main/java/org/openremote/manager/shared/rules/TenantRulesDefinition.javanew file mode 100644index 000000000..bed1ede5b--- /dev/null+++ b/manager/shared/src/main/java/org/openremote/manager/shared/rules/TenantRulesDefinition.java@@ -0,0 +1,58 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.shared.rules;++import javax.persistence.Column;+import javax.persistence.Entity;+import javax.persistence.Table;+import java.util.Date;++/**+ * Rules that can only be triggered by asset modifications in a particular+ * realm, and can only modify asset data in a particular realm.+ */+@Entity+@Table(name = "REALM_RULES")+public class TenantRulesDefinition extends RulesDefinition {++ @Column(name = "REALM", nullable = false)+ public String realm;++ public TenantRulesDefinition() {+ }++ public TenantRulesDefinition(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String realm) {+ super(id, version, createdOn, lastModified, name, enabled);+ this.realm = realm;+ }++ public TenantRulesDefinition(String name, String realm, String rules) {+ super(name, rules);+ this.realm = realm;+ }++ public String getRealm() {+ return realm;+ }++ public void setRealm(String realm) {+ this.realm = realm;+ }+}diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/security/ClientRole.java b/manager/shared/src/main/java/org/openremote/manager/shared/security/ClientRole.javaindex 1090f5518..677c071ab 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/security/ClientRole.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/security/ClientRole.java@@ -32,19 +32,23 @@ public enum ClientRole {READ_ADMIN("read:admin", "Read system settings, tenants, and users"),READ_MAP("read:map", "View map"),READ_ASSETS("read:assets", "Read asset data"),+ READ_RULES("read:rules", "Read rule definitions"),WRITE_ADMIN("write:admin", "Write system settings, tenants, and users"),WRITE_ASSETS("write:assets", "Write asset data"),+ WRITE_RULES("write:rules", "Write rule definitions"),READ("read", "Read all data", new ClientRole[]{READ_ADMIN,READ_MAP,- READ_ASSETS+ READ_ASSETS,+ READ_RULES}),WRITE("write", "Write all data", new ClientRole[]{WRITE_ADMIN,- WRITE_ASSETS+ WRITE_ASSETS,+ WRITE_RULES});final protected String value;diff --git a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovyindex 3f1417348..e3efffed4 100644--- a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy+++ b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy@@ -8,6 +8,7 @@ import org.openremote.container.message.MessageBrokerSetupServiceimport org.openremote.container.persistence.PersistenceServiceimport org.openremote.manager.server.asset.AssetProcessingServiceimport org.openremote.manager.server.rules.AssetRulesService+import org.openremote.manager.server.rules.RulesStorageServiceimport org.openremote.manager.server.setup.SetupServiceimport org.openremote.manager.server.agent.AgentServiceimport org.openremote.manager.server.asset.AssetStorageService@@ -23,11 +24,12 @@ trait ManagerContainerTrait extends ContainerTrait {static Iterable<ContainerService> defaultServices(Iterable<ContainerService> additionalServices) {[new I18NService(),+ new PersistenceService(),new MessageBrokerSetupService(),new ManagerIdentityService(),- new PersistenceService(),new SetupService(),new EventService(),+ new RulesStorageService(),new AssetRulesService(),new AssetStorageService(),new AssetDatapointService(),diff --git a/manager/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovy b/manager/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovyindex e2f484836..14bb1d3a6 100644--- a/manager/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovy@@ -155,6 +155,8 @@ class AdminTenantsActivityTest extends Specification implements ManagerContainer{},{},{},+ {},+ {},{adminTenantsActivity = new AdminTenantsActivity(environment, adminView, adminNavigationPresenter, adminTenantsView, tenantResource, tenantArrayMapperdiff --git a/manager/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy b/manager/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovyindex 16098d1bc..26f6ef367 100644--- a/manager/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy@@ -171,6 +171,8 @@ class AdminUsersActivityTest extends Specification implements ManagerContainerTr{},{},{},+ {},+ {},{adminUsersActivity = new AdminUsersActivity(environment, adminView, adminNavigationPresenter, adminUsersView, tenantResource, tenantArrayMapper, userResource, userArrayMapperdiff --git a/manager/test/src/test/groovy/org/openremote/test/rules/RulesPermissionsTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/RulesPermissionsTest.groovynew file mode 100644index 000000000..8ca941b17--- /dev/null+++ b/manager/test/src/test/groovy/org/openremote/test/rules/RulesPermissionsTest.groovy@@ -0,0 +1,855 @@+package org.openremote.test.rules++import org.openremote.manager.server.setup.SetupService+import org.openremote.manager.server.setup.builtin.ManagerDemoSetup+import org.openremote.manager.shared.rules.AssetRulesDefinition+import org.openremote.manager.shared.rules.GlobalRulesDefinition+import org.openremote.manager.shared.rules.RulesResource+import org.openremote.manager.shared.rules.TenantRulesDefinition+import org.openremote.test.ManagerContainerTrait+import spock.lang.Specification++import javax.ws.rs.WebApplicationException++import static org.openremote.container.util.MapAccess.getString+import static org.openremote.manager.server.setup.AbstractKeycloakSetup.SETUP_KEYCLOAK_ADMIN_PASSWORD+import static org.openremote.manager.server.setup.AbstractKeycloakSetup.SETUP_KEYCLOAK_ADMIN_PASSWORD_DEFAULT+import static org.openremote.model.Constants.*++class RulesPermissionsTest extends Specification implements ManagerContainerTrait {++ def "Access rules as superuser"() {+ given: "the server container is started"+ def serverPort = findEphemeralPort()+ def container = startContainer(defaultConfig(serverPort), defaultServices())+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)++ and: "an authenticated admin user"+ def realm = MASTER_REALM+ def accessToken = authenticate(+ container,+ realm,+ KEYCLOAK_CLIENT_ID,+ MASTER_REALM_ADMIN_USER,+ getString(container.getConfig(), SETUP_KEYCLOAK_ADMIN_PASSWORD, SETUP_KEYCLOAK_ADMIN_PASSWORD_DEFAULT)+ ).token++ and: "the rules resource"+ def client = createClient(container).build()+ def serverUri = serverUri(serverPort)+ def rulesResource = getClientTarget(client, serverUri, realm, accessToken).proxy(RulesResource.class)++ /* ############################################## READ ####################################### */++ when: "the global rules are retrieved"+ def ruleDefinitions = rulesResource.getGlobalDefinitions(null)++ then: "result should match"+ ruleDefinitions.length == 1+ ruleDefinitions[0].name == "Some global demo rules"+ ruleDefinitions[0].rules == null // Don't retrieve the (large) rules data when getting a list of rule definitions++ when: "some tenant rules are retrieved"+ ruleDefinitions = rulesResource.getTenantDefinitions(null, MASTER_REALM)++ then: "result should match"+ ruleDefinitions.length == 1+ ruleDefinitions[0].name == "Some master tenant demo rules"++ when: "some tenant rules in a non-authenticated realm are retrieved"+ ruleDefinitions = rulesResource.getTenantDefinitions(null, "customerA")++ then: "result should match"+ ruleDefinitions.length == 1+ ruleDefinitions[0].name == "Some customerA tenant demo rules"+ !ruleDefinitions[0].enabled++ when: "some asset rules are retrieved"+ ruleDefinitions = rulesResource.getAssetDefinitions(null, managerDemoSetup.apartment1Id)++ then: "result should match"+ ruleDefinitions.length == 1+ ruleDefinitions[0].name == "Some apartment 1 demo rules"++ /* ############################################## WRITE ####################################### */++ when: "global rules definitions is created"+ def globalRulesDefinition = new GlobalRulesDefinition("Test global definition", "ThisShouldBeDRL")+ rulesResource.createGlobalDefinition(null, globalRulesDefinition)+ def rulesDefinitionId = rulesResource.getGlobalDefinitions(null)[1].id+ globalRulesDefinition = rulesResource.getGlobalDefinition(null, rulesDefinitionId)+ def lastModified = globalRulesDefinition.lastModified++ then: "result should match"+ globalRulesDefinition.id == rulesDefinitionId+ globalRulesDefinition.version == 0+ globalRulesDefinition.createdOn.time < System.currentTimeMillis()+ lastModified.time < System.currentTimeMillis()+ globalRulesDefinition.name == "Test global definition"+ globalRulesDefinition.rules == "ThisShouldBeDRL"++ when: "a global rules definition is updated"+ globalRulesDefinition.name = "Renamed test global definition"+ globalRulesDefinition.rules = "ThisShouldBeDRLAsWell"+ rulesResource.updateGlobalDefinition(null, rulesDefinitionId, globalRulesDefinition)+ globalRulesDefinition = rulesResource.getGlobalDefinition(null, rulesDefinitionId)++ then: "result should match"+ globalRulesDefinition.id == rulesDefinitionId+ globalRulesDefinition.version > 0+ globalRulesDefinition.createdOn.time < System.currentTimeMillis()+ globalRulesDefinition.lastModified.time > lastModified.time+ globalRulesDefinition.name == "Renamed test global definition"+ globalRulesDefinition.rules == "ThisShouldBeDRLAsWell"++ when: "a global rules definition is deleted"+ rulesResource.deleteGlobalDefinition(null, rulesDefinitionId)+ globalRulesDefinition = rulesResource.getGlobalDefinition(null, rulesDefinitionId)++ then: "the result should be not found"+ WebApplicationException ex = thrown()+ ex.response.status == 404++ when: "a non-existent global rules definition is updated"+ rulesResource.updateGlobalDefinition(null, 1234567890l, globalRulesDefinition)++ then: "the result should be not found"+ ex = thrown()+ ex.response.status == 404++ when: "a tenant rules definition is created in the authenticated realm"+ def tenantRulesDefinition = new TenantRulesDefinition("Test tenant definition", MASTER_REALM, "ThisShouldBeDRL")+ rulesResource.createTenantDefinition(null, tenantRulesDefinition)+ rulesDefinitionId = rulesResource.getTenantDefinitions(null, MASTER_REALM)[1].id+ tenantRulesDefinition = rulesResource.getTenantDefinition(null, rulesDefinitionId)+ lastModified = tenantRulesDefinition.lastModified++ then: "result should match"+ tenantRulesDefinition.id == rulesDefinitionId+ tenantRulesDefinition.version == 0+ tenantRulesDefinition.createdOn.time < System.currentTimeMillis()+ lastModified.time < System.currentTimeMillis()+ tenantRulesDefinition.name == "Test tenant definition"+ tenantRulesDefinition.rules == "ThisShouldBeDRL"+ tenantRulesDefinition.realm == MASTER_REALM++ when: "a tenant rules definition is updated"+ tenantRulesDefinition.name = "Renamed test tenant definition"+ tenantRulesDefinition.rules = "ThisShouldBeDRLAsWell"+ rulesResource.updateTenantDefinition(null, rulesDefinitionId, tenantRulesDefinition)+ tenantRulesDefinition = rulesResource.getTenantDefinition(null, rulesDefinitionId)++ then: "result should match"+ tenantRulesDefinition.id == rulesDefinitionId+ tenantRulesDefinition.version == 1+ tenantRulesDefinition.createdOn.time < System.currentTimeMillis()+ lastModified.time < System.currentTimeMillis()+ tenantRulesDefinition.name == "Renamed test tenant definition"+ tenantRulesDefinition.rules == "ThisShouldBeDRLAsWell"+ tenantRulesDefinition.realm == MASTER_REALM++ when: "a tenant rules definition is updated with an invalid realm"+ tenantRulesDefinition.realm = "thisdoesnotexist"+ rulesResource.updateTenantDefinition(null, rulesDefinitionId, tenantRulesDefinition)++ then: "the request should be bad"+ ex = thrown()+ ex.response.status == 400++ when: "a tenant rules definition is updated with an invalid id"+ tenantRulesDefinition.realm = MASTER_REALM+ tenantRulesDefinition.id = 1234567890l+ rulesResource.updateTenantDefinition(null, rulesDefinitionId, tenantRulesDefinition)++ then: "the request should be bad"+ ex = thrown()+ ex.response.status == 400++ when: "a non-existent tenant rules definition is updated"+ rulesResource.updateTenantDefinition(null, 1234567890l, tenantRulesDefinition)++ then: "the result should be not found"+ ex = thrown()+ ex.response.status == 404++ when: "a tenant rules definition is deleted"+ rulesResource.deleteTenantDefinition(null, rulesDefinitionId)+ tenantRulesDefinition = rulesResource.getTenantDefinition(null, rulesDefinitionId)++ then: "the result should be not found"+ ex = thrown()+ ex.response.status == 404++ when: "a tenant rules definition is created in a non-authenticated realm"+ tenantRulesDefinition = new TenantRulesDefinition("Test tenant definition", "customerA", "ThisShouldBeDRL")+ rulesResource.createTenantDefinition(null, tenantRulesDefinition)+ rulesDefinitionId = rulesResource.getTenantDefinitions(null, "customerA")[1].id+ tenantRulesDefinition = rulesResource.getTenantDefinition(null, rulesDefinitionId)+ lastModified = tenantRulesDefinition.lastModified++ then: "result should match"+ tenantRulesDefinition.id == rulesDefinitionId+ tenantRulesDefinition.version == 0+ tenantRulesDefinition.createdOn.time < System.currentTimeMillis()+ lastModified.time < System.currentTimeMillis()+ tenantRulesDefinition.name == "Test tenant definition"+ tenantRulesDefinition.rules == "ThisShouldBeDRL"+ tenantRulesDefinition.realm == "customerA"++ when: "an asset rules definition is created in the authenticated realm"+ def assetRulesDefinition = new AssetRulesDefinition("Test asset definition", managerDemoSetup.smartOfficeId, "ThisShouldBeDRL")+ rulesResource.createAssetDefinition(null, assetRulesDefinition)+ rulesDefinitionId = rulesResource.getAssetDefinitions(null, managerDemoSetup.smartOfficeId)[0].id+ assetRulesDefinition = rulesResource.getAssetDefinition(null, rulesDefinitionId)+ lastModified = assetRulesDefinition.lastModified++ then: "result should match"+ assetRulesDefinition.id == rulesDefinitionId+ assetRulesDefinition.version == 0+ assetRulesDefinition.createdOn.time < System.currentTimeMillis()+ lastModified.time < System.currentTimeMillis()+ assetRulesDefinition.name == "Test asset definition"+ assetRulesDefinition.rules == "ThisShouldBeDRL"+ assetRulesDefinition.assetId == managerDemoSetup.smartOfficeId++ when: "an asset rules definition is updated"+ assetRulesDefinition.name = "Renamed test asset definition"+ assetRulesDefinition.rules = "ThisShouldBeDRLAsWell"+ rulesResource.updateAssetDefinition(null, rulesDefinitionId, assetRulesDefinition)+ assetRulesDefinition = rulesResource.getAssetDefinition(null, rulesDefinitionId)++ then: "result should match"+ assetRulesDefinition.id == rulesDefinitionId+ assetRulesDefinition.version == 1+ assetRulesDefinition.createdOn.time < System.currentTimeMillis()+ lastModified.time < System.currentTimeMillis()+ assetRulesDefinition.name == "Renamed test asset definition"+ assetRulesDefinition.rules == "ThisShouldBeDRLAsWell"+ assetRulesDefinition.assetId == managerDemoSetup.smartOfficeId++ when: "an asset rules definition is updated with an invalid asset ID"+ assetRulesDefinition.assetId = "thisdoesnotexist"+ rulesResource.updateAssetDefinition(null, rulesDefinitionId, assetRulesDefinition)++ then: "the request should be bad"+ ex = thrown()+ ex.response.status == 400++ when: "an asset rules definition is updated with an invalid id"+ assetRulesDefinition.assetId = managerDemoSetup.smartOfficeId+ assetRulesDefinition.id = 1234567890l+ rulesResource.updateAssetDefinition(null, rulesDefinitionId, assetRulesDefinition)++ then: "the request should be bad"+ ex = thrown()+ ex.response.status == 400++ when: "a non-existent asset rules definition is updated"+ rulesResource.updateAssetDefinition(null, 1234567890l, assetRulesDefinition)++ then: "the result should be not found"+ ex = thrown()+ ex.response.status == 404++ when: "an asset rules definition is deleted"+ rulesResource.deleteAssetDefinition(null, rulesDefinitionId)+ assetRulesDefinition = rulesResource.getAssetDefinition(null, rulesDefinitionId)++ then: "the result should be not found"+ ex = thrown()+ ex.response.status == 404++ when: "an asset rules definition is created in a non-authenticated realm"+ assetRulesDefinition = new AssetRulesDefinition("Test asset definition", managerDemoSetup.apartment1Id, "ThisShouldBeDRL")+ rulesResource.createAssetDefinition(null, assetRulesDefinition)+ rulesDefinitionId = rulesResource.getAssetDefinitions(null, managerDemoSetup.apartment1Id)[1].id+ assetRulesDefinition = rulesResource.getAssetDefinition(null, rulesDefinitionId)+ lastModified = assetRulesDefinition.lastModified++ then: "result should match"+ assetRulesDefinition.id == rulesDefinitionId+ assetRulesDefinition.version == 0+ assetRulesDefinition.createdOn.time < System.currentTimeMillis()+ lastModified.time < System.currentTimeMillis()+ assetRulesDefinition.name == "Test asset definition"+ assetRulesDefinition.rules == "ThisShouldBeDRL"+ assetRulesDefinition.assetId == managerDemoSetup.apartment1Id++ cleanup: "the server should be stopped"+ stopContainer(container)+ }++ def "Access rules as testuser1"() {++ given: "the server container is started"+ def serverPort = findEphemeralPort()+ def container = startContainer(defaultConfig(serverPort), defaultServices())+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)++ and: "an authenticated test user"+ def realm = MASTER_REALM+ def accessToken = authenticate(+ container,+ realm,+ KEYCLOAK_CLIENT_ID,+ "testuser1",+ "testuser1"+ ).token++ and: "the asset resource"+ def client = createClient(container).build()+ def serverUri = serverUri(serverPort)+ def rulesResource = getClientTarget(client, serverUri, realm, accessToken).proxy(RulesResource.class)++ /* ############################################## READ ####################################### */++ when: "the global rules are retrieved"+ def ruleDefinitions = rulesResource.getGlobalDefinitions(null)++ then: "access should be forbidden"+ WebApplicationException ex = thrown()+ ex.response.status == 403++ when: "some tenant rules are retrieved"+ ruleDefinitions = rulesResource.getTenantDefinitions(null, MASTER_REALM)++ then: "result should match"+ ruleDefinitions.length == 1+ ruleDefinitions[0].name == "Some master tenant demo rules"++ when: "some tenant rules in a non-authenticated realm are retrieved"+ ruleDefinitions = rulesResource.getTenantDefinitions(null, "customerA")++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "some asset rules in a non-authenticated realm are retrieved"+ ruleDefinitions = rulesResource.getAssetDefinitions(null, managerDemoSetup.apartment1Id)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ /* ############################################## WRITE ####################################### */++ when: "a global rule is created"+ def ruleDefinition = new GlobalRulesDefinition("Test definition", "ThisShouldBeDRL")+ rulesResource.createGlobalDefinition(null, ruleDefinition)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "a global rule is updated"+ rulesResource.updateGlobalDefinition(null, 1234567890l, ruleDefinition)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "a global rule is deleted"+ rulesResource.deleteGlobalDefinition(null, 1234567890l)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "a tenant rules definition is created in the authenticated realm"+ def tenantRulesDefinition = new TenantRulesDefinition("Test tenant definition", MASTER_REALM, "ThisShouldBeDRL")+ rulesResource.createTenantDefinition(null, tenantRulesDefinition)+ def rulesDefinitionId = rulesResource.getTenantDefinitions(null, MASTER_REALM)[1].id+ tenantRulesDefinition = rulesResource.getTenantDefinition(null, rulesDefinitionId)+ def lastModified = tenantRulesDefinition.lastModified++ then: "result should match"+ tenantRulesDefinition.id == rulesDefinitionId+ tenantRulesDefinition.version == 0+ tenantRulesDefinition.createdOn.time < System.currentTimeMillis()+ lastModified.time < System.currentTimeMillis()+ tenantRulesDefinition.name == "Test tenant definition"+ tenantRulesDefinition.rules == "ThisShouldBeDRL"+ tenantRulesDefinition.realm == MASTER_REALM++ when: "a tenant rules definition is updated"+ tenantRulesDefinition.name = "Renamed test tenant definition"+ tenantRulesDefinition.rules = "ThisShouldBeDRLAsWell"+ rulesResource.updateTenantDefinition(null, rulesDefinitionId, tenantRulesDefinition)+ tenantRulesDefinition = rulesResource.getTenantDefinition(null, rulesDefinitionId)++ then: "result should match"+ tenantRulesDefinition.id == rulesDefinitionId+ tenantRulesDefinition.version == 1+ tenantRulesDefinition.createdOn.time < System.currentTimeMillis()+ lastModified.time < System.currentTimeMillis()+ tenantRulesDefinition.name == "Renamed test tenant definition"+ tenantRulesDefinition.rules == "ThisShouldBeDRLAsWell"+ tenantRulesDefinition.realm == MASTER_REALM++ when: "a tenant rules definition is updated with an invalid realm"+ tenantRulesDefinition.realm = "thisdoesnotexist"+ rulesResource.updateTenantDefinition(null, rulesDefinitionId, tenantRulesDefinition)++ then: "the request should be bad"+ ex = thrown()+ ex.response.status == 400++ when: "a tenant rules definition is updated with an invalid id"+ tenantRulesDefinition.realm = MASTER_REALM+ tenantRulesDefinition.id = 1234567890l+ rulesResource.updateTenantDefinition(null, rulesDefinitionId, tenantRulesDefinition)++ then: "the request should be bad"+ ex = thrown()+ ex.response.status == 400++ when: "a non-existent tenant rules definition is updated"+ rulesResource.updateTenantDefinition(null, 1234567890l, tenantRulesDefinition)++ then: "the result should be not found"+ ex = thrown()+ ex.response.status == 404++ when: "a tenant rules definition is deleted"+ rulesResource.deleteTenantDefinition(null, rulesDefinitionId)+ tenantRulesDefinition = rulesResource.getTenantDefinition(null, rulesDefinitionId)++ then: "the result should be not found"+ ex = thrown()+ ex.response.status == 404++ when: "a tenant rules definition is created in a non-authenticated realm"+ tenantRulesDefinition = new TenantRulesDefinition("Test tenant definition", "customerA", "ThisShouldBeDRL")+ rulesResource.createTenantDefinition(null, tenantRulesDefinition)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "an asset rules definition is created in the authenticated realm"+ def assetRulesDefinition = new AssetRulesDefinition("Test asset definition", managerDemoSetup.smartOfficeId, "ThisShouldBeDRL")+ rulesResource.createAssetDefinition(null, assetRulesDefinition)+ rulesDefinitionId = rulesResource.getAssetDefinitions(null, managerDemoSetup.smartOfficeId)[0].id+ assetRulesDefinition = rulesResource.getAssetDefinition(null, rulesDefinitionId)+ lastModified = assetRulesDefinition.lastModified++ then: "result should match"+ assetRulesDefinition.id == rulesDefinitionId+ assetRulesDefinition.version == 0+ assetRulesDefinition.createdOn.time < System.currentTimeMillis()+ lastModified.time < System.currentTimeMillis()+ assetRulesDefinition.name == "Test asset definition"+ assetRulesDefinition.rules == "ThisShouldBeDRL"+ assetRulesDefinition.assetId == managerDemoSetup.smartOfficeId++ when: "an asset rules definition is updated"+ assetRulesDefinition.name = "Renamed test asset definition"+ assetRulesDefinition.rules = "ThisShouldBeDRLAsWell"+ rulesResource.updateAssetDefinition(null, rulesDefinitionId, assetRulesDefinition)+ assetRulesDefinition = rulesResource.getAssetDefinition(null, rulesDefinitionId)++ then: "result should match"+ assetRulesDefinition.id == rulesDefinitionId+ assetRulesDefinition.version == 1+ assetRulesDefinition.createdOn.time < System.currentTimeMillis()+ lastModified.time < System.currentTimeMillis()+ assetRulesDefinition.name == "Renamed test asset definition"+ assetRulesDefinition.rules == "ThisShouldBeDRLAsWell"+ assetRulesDefinition.assetId == managerDemoSetup.smartOfficeId++ when: "an asset rules definition is updated with an invalid asset ID"+ assetRulesDefinition.assetId = "thisdoesnotexist"+ rulesResource.updateAssetDefinition(null, rulesDefinitionId, assetRulesDefinition)++ then: "the request should be bad"+ ex = thrown()+ ex.response.status == 400++ when: "an asset rules definition is updated with an invalid id"+ assetRulesDefinition.assetId = managerDemoSetup.smartOfficeId+ assetRulesDefinition.id = 1234567890l+ rulesResource.updateAssetDefinition(null, rulesDefinitionId, assetRulesDefinition)++ then: "the request should be bad"+ ex = thrown()+ ex.response.status == 400++ when: "a non-existent asset rules definition is updated"+ rulesResource.updateAssetDefinition(null, 1234567890l, assetRulesDefinition)++ then: "the result should be not found"+ ex = thrown()+ ex.response.status == 404++ when: "an asset rules definition is deleted"+ rulesResource.deleteAssetDefinition(null, rulesDefinitionId)+ assetRulesDefinition = rulesResource.getAssetDefinition(null, rulesDefinitionId)++ then: "the result should be not found"+ ex = thrown()+ ex.response.status == 404++ when: "an asset rules definition is created in a non-authenticated realm"+ assetRulesDefinition = new AssetRulesDefinition("Test asset definition", managerDemoSetup.apartment1Id, "ThisShouldBeDRL")+ rulesResource.createAssetDefinition(null, assetRulesDefinition)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ cleanup: "the server should be stopped"+ stopContainer(container)+ }++ def "Access rules as testuser2"() {++ given: "the server container is started"+ def serverPort = findEphemeralPort()+ def container = startContainer(defaultConfig(serverPort), defaultServices())+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)++ and: "an authenticated test user"+ def realm = "customerA"+ def accessToken = authenticate(+ container,+ realm,+ KEYCLOAK_CLIENT_ID,+ "testuser2",+ "testuser2"+ ).token++ and: "the asset resource"+ def client = createClient(container).build()+ def serverUri = serverUri(serverPort)+ def rulesResource = getClientTarget(client, serverUri, realm, accessToken).proxy(RulesResource.class)++ /* ############################################## READ ####################################### */++ when: "the global rules are retrieved"+ def ruleDefinitions = rulesResource.getGlobalDefinitions(null)++ then: "access should be forbidden"+ WebApplicationException ex = thrown()+ ex.response.status == 403++ when: "some tenant rules in a non-authenticated realm are retrieved"+ ruleDefinitions = rulesResource.getTenantDefinitions(null, MASTER_REALM)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "some tenant rules in the authenticated realm are retrieved"+ ruleDefinitions = rulesResource.getTenantDefinitions(null, "customerA")++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "some asset rules in the authenticated realm are retrieved"+ ruleDefinitions = rulesResource.getAssetDefinitions(null, managerDemoSetup.apartment1Id)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ /* ############################################## WRITE ####################################### */++ when: "a global rule is created"+ def ruleDefinition = new GlobalRulesDefinition("Test definition", "ThisShouldBeDRL")+ rulesResource.createGlobalDefinition(null, ruleDefinition)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "a global rule is updated"+ rulesResource.updateGlobalDefinition(null, 1234567890l, ruleDefinition)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "a global rule is deleted"+ rulesResource.deleteGlobalDefinition(null, 1234567890l)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "a tenant rules definition is created in the authenticated realm"+ def tenantRulesDefinition = new TenantRulesDefinition("Test tenant definition", "customerA", "ThisShouldBeDRL")+ rulesResource.createTenantDefinition(null, tenantRulesDefinition)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "a tenant rules definition is updated"+ rulesResource.updateTenantDefinition(null, 1234567890l, tenantRulesDefinition)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "a tenant rules definition is deleted"+ rulesResource.deleteTenantDefinition(null, 1234567890l)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "a tenant rules definition is created in a non-authenticated realm"+ tenantRulesDefinition = new TenantRulesDefinition("Test tenant definition", "customerB", "ThisShouldBeDRL")+ rulesResource.createTenantDefinition(null, tenantRulesDefinition)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "a tenant rules definition is created in the authenticated realm"+ def assetRulesDefinition = new AssetRulesDefinition("Test asset definition", "customerA", "ThisShouldBeDRL")+ rulesResource.createAssetDefinition(null, assetRulesDefinition)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "a tenant rules definition is updated"+ rulesResource.updateAssetDefinition(null, 1234567890l, assetRulesDefinition)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "a tenant rules definition is deleted"+ rulesResource.deleteAssetDefinition(null, 1234567890l)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "a tenant rules definition is created in a non-authenticated realm"+ assetRulesDefinition = new AssetRulesDefinition("Test asset definition", "customerB", "ThisShouldBeDRL")+ rulesResource.createAssetDefinition(null, assetRulesDefinition)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ cleanup: "the server should be stopped"+ stopContainer(container)+ }++ def "Access rules as testuser3"() {++ given: "the server container is started"+ def serverPort = findEphemeralPort()+ def container = startContainer(defaultConfig(serverPort), defaultServices())+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)++ and: "an authenticated test user"+ def realm = "customerA"+ def accessToken = authenticate(+ container,+ realm,+ KEYCLOAK_CLIENT_ID,+ "testuser3",+ "testuser3"+ ).token++ and: "the asset resource"+ def client = createClient(container).build()+ def serverUri = serverUri(serverPort)+ def rulesResource = getClientTarget(client, serverUri, realm, accessToken).proxy(RulesResource.class)++ /* ############################################## READ ####################################### */++ when: "the global rules are retrieved"+ def ruleDefinitions = rulesResource.getGlobalDefinitions(null)++ then: "access should be forbidden"+ WebApplicationException ex = thrown()+ ex.response.status == 403++ when: "some tenant rules in a non-authenticated realm are retrieved"+ ruleDefinitions = rulesResource.getTenantDefinitions(null, MASTER_REALM)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "some tenant rules in the authenticated realm are retrieved"+ ruleDefinitions = rulesResource.getTenantDefinitions(null, "customerA")++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "some asset rules of a protected assigned asset are retrieved"+ ruleDefinitions = rulesResource.getAssetDefinitions(null, managerDemoSetup.apartment1Id)++ then: "result should match"+ ruleDefinitions.length == 1+ ruleDefinitions[0].name == "Some apartment 1 demo rules"++ when: "some asset rules of a protected assigned asset are retrieved"+ ruleDefinitions = rulesResource.getAssetDefinitions(null, managerDemoSetup.apartment2Id)++ then: "result should match"+ ruleDefinitions.length == 1+ ruleDefinitions[0].name == "Some apartment 2 demo rules"++ when: "some asset rules of a protected but not assigned asset are retrieved"+ ruleDefinitions = rulesResource.getAssetDefinitions(null, managerDemoSetup.apartment3Id)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ /* ############################################## WRITE ####################################### */++ when: "a global rule is created"+ def ruleDefinition = new GlobalRulesDefinition("Test definition", "ThisShouldBeDRL")+ rulesResource.createGlobalDefinition(null, ruleDefinition)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "a global rule is updated"+ rulesResource.updateGlobalDefinition(null, 1234567890l, ruleDefinition)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "a global rule is deleted"+ rulesResource.deleteGlobalDefinition(null, 1234567890l)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "a tenant rules definition is created in the authenticated realm"+ def tenantRulesDefinition = new TenantRulesDefinition("Test tenant definition", "customerA", "ThisShouldBeDRL")+ rulesResource.createTenantDefinition(null, tenantRulesDefinition)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "a tenant rules definition is updated"+ rulesResource.updateTenantDefinition(null, 1234567890l, tenantRulesDefinition)++ then: "result should be not found"+ ex = thrown()+ ex.response.status == 404++ when: "a tenant rules definition is deleted"+ rulesResource.deleteTenantDefinition(null, 1234567890l)+ tenantRulesDefinition = rulesResource.getTenantDefinition(null, 1234567890l)++ then: "the result should be not found"+ ex = thrown()+ ex.response.status == 404++ when: "a tenant rules definition is created in a non-authenticated realm"+ tenantRulesDefinition = new TenantRulesDefinition("Test tenant definition", "customerB", "ThisShouldBeDRL")+ rulesResource.createTenantDefinition(null, tenantRulesDefinition)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "an asset rules definition is created in the authenticated realm"+ def assetRulesDefinition = new AssetRulesDefinition("Test asset definition", managerDemoSetup.apartment1Id, "ThisShouldBeDRL")+ rulesResource.createAssetDefinition(null, assetRulesDefinition)+ def rulesDefinitionId = rulesResource.getAssetDefinitions(null, managerDemoSetup.apartment1Id)[1].id+ assetRulesDefinition = rulesResource.getAssetDefinition(null, rulesDefinitionId)+ def lastModified = assetRulesDefinition.lastModified++ then: "result should match"+ assetRulesDefinition.id == rulesDefinitionId+ assetRulesDefinition.version == 0+ assetRulesDefinition.createdOn.time < System.currentTimeMillis()+ lastModified.time < System.currentTimeMillis()+ assetRulesDefinition.name == "Test asset definition"+ assetRulesDefinition.rules == "ThisShouldBeDRL"+ assetRulesDefinition.assetId == managerDemoSetup.apartment1Id++ when: "an asset rules definition is updated"+ assetRulesDefinition.name = "Renamed test asset definition"+ assetRulesDefinition.rules = "ThisShouldBeDRLAsWell"+ rulesResource.updateAssetDefinition(null, rulesDefinitionId, assetRulesDefinition)+ assetRulesDefinition = rulesResource.getAssetDefinition(null, rulesDefinitionId)++ then: "result should match"+ assetRulesDefinition.id == rulesDefinitionId+ assetRulesDefinition.version == 1+ assetRulesDefinition.createdOn.time < System.currentTimeMillis()+ lastModified.time < System.currentTimeMillis()+ assetRulesDefinition.name == "Renamed test asset definition"+ assetRulesDefinition.rules == "ThisShouldBeDRLAsWell"+ assetRulesDefinition.assetId == managerDemoSetup.apartment1Id++ when: "an asset rules definition is updated with a changed asset ID"+ assetRulesDefinition.assetId = managerDemoSetup.apartment3Id+ rulesResource.updateAssetDefinition(null, rulesDefinitionId, assetRulesDefinition)++ then: "the request should be bad"+ ex = thrown()+ ex.response.status == 400++ when: "an asset rules definition is updated with a changed invalid asset ID"+ assetRulesDefinition.assetId = "thisdoesnotexist"+ rulesResource.updateAssetDefinition(null, rulesDefinitionId, assetRulesDefinition)++ then: "the request should be bad"+ ex = thrown()+ ex.response.status == 400++ when: "an asset rules definition is updated with an invalid id"+ assetRulesDefinition.assetId = managerDemoSetup.apartment1Id+ assetRulesDefinition.id = 1234567890l+ rulesResource.updateAssetDefinition(null, rulesDefinitionId, assetRulesDefinition)++ then: "the request should be bad"+ ex = thrown()+ ex.response.status == 400++ when: "a non-existent asset rules definition is updated"+ rulesResource.updateAssetDefinition(null, 1234567890l, assetRulesDefinition)++ then: "the result should be not found"+ ex = thrown()+ ex.response.status == 404++ when: "an asset rules definition is deleted"+ rulesResource.deleteAssetDefinition(null, rulesDefinitionId)+ assetRulesDefinition = rulesResource.getAssetDefinition(null, rulesDefinitionId)++ then: "the result should be not found"+ ex = thrown()+ ex.response.status == 404++ when: "an asset rules definition is created in the authenticated realm but on a forbidden asset "+ assetRulesDefinition = new AssetRulesDefinition("Test asset definition", managerDemoSetup.apartment3Id, "ThisShouldBeDRL")+ rulesResource.createAssetDefinition(null, assetRulesDefinition)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ when: "an asset rules definition is created in a non-authenticated realm"+ assetRulesDefinition = new AssetRulesDefinition("Test asset definition", managerDemoSetup.smartOfficeId, "ThisShouldBeDRL")+ rulesResource.createAssetDefinition(null, assetRulesDefinition)++ then: "access should be forbidden"+ ex = thrown()+ ex.response.status == 403++ cleanup: "the server should be stopped"+ stopContainer(container)+ }+}diff --git a/model/src/main/java/org/openremote/model/asset/AssetMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.javaindex 422479ab5..542b3e2f7 100644--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java@@ -26,6 +26,7 @@ import org.openremote.model.MetaItem;import org.openremote.model.units.AttributeUnits;import java.util.ArrayList;+import java.util.Comparator;import java.util.List;import static org.openremote.model.Constants.ASSET_META_NAMESPACE;@@ -109,7 +110,7 @@ public enum AssetMeta {*/STORE_DATA_POINTS(ASSET_META_NAMESPACE + ":storeDataPoints", new Access(true, false, true), JsonType.BOOLEAN),- VALUE_TIMESTAMP(ASSET_META_NAMESPACE + ":valueTimestamp", new Access(true, false, true), JsonType.NUMBER);+ VALUE_TIMESTAMP(ASSET_META_NAMESPACE + ":valueTimestamp", new Access(true, false, false), JsonType.NUMBER);final protected String name;final protected Access access;@@ -139,6 +140,9 @@ public enum AssetMeta {if (meta.getAccess().editable)list.add(meta);}++ list.sort(Comparator.comparing(Enum::name));+return list.toArray(new AssetMeta[list.size()]);}diff --git a/model/src/main/java/org/openremote/model/asset/AssetType.java b/model/src/main/java/org/openremote/model/asset/AssetType.javaindex 924ca12d4..898fc59ab 100644--- a/model/src/main/java/org/openremote/model/asset/AssetType.java+++ b/model/src/main/java/org/openremote/model/asset/AssetType.java@@ -24,6 +24,8 @@ import elemental.json.JsonObject;import org.openremote.model.*;import java.util.ArrayList;+import java.util.Collections;+import java.util.Comparator;import java.util.List;import static org.openremote.model.Constants.ASSET_NAMESPACE;@@ -114,6 +116,14 @@ public enum AssetType {if (assetType.isEditable())list.add(assetType);}++ list.sort(Comparator.comparing(Enum::name));+ if (list.contains(CUSTOM)) {+ // CUSTOM should be first+ list.remove(CUSTOM);+ list.add(0, CUSTOM);+ }+return list.toArray(new AssetType[list.size()]);}