Skip to content

armgit / core

Public Imported from GitHub
0

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

Various cleanups and fixes:

Rich Turner01059313254c
diff --git a/agent/src/main/java/org/openremote/agent/protocol/Protocol.java b/agent/src/main/java/org/openremote/agent/protocol/Protocol.java
index 1a3020295..5159a8072 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/Protocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/Protocol.java
@@ -78,11 +78,6 @@ import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
* a linked attributes' value by sending an {@link AttributeEvent} messages on the
* {@link #SENSOR_QUEUE}, including the source protocol name in header {@link #SENSOR_QUEUE_SOURCE_PROTOCOL}.
* <p>
- * As well as an {@link AssetMeta#AGENT_LINK} meta item; if an attribute also has an {@link AssetMeta#LOCATION_LINK}
- * meta item then the protocol should push location data into the {@link Asset} location property (if the protocol and
- * device support it and the attribute is correctly configured to receive location data and the value must be of type
- * {@link ArrayValue} and contain two {@link NumberValue}s representing longitude and latitude in that order.
- * <p>
* If the user writes a new value into the linked attribute, the protocol translates this value
* change into a device (or service) action. Write operations on attributes linked to a protocol
* configuration can be consumed by the protocol on the {@link #ACTUATOR_TOPIC} where the message
diff --git a/client/src/main/java/org/openremote/app/client/assets/asset/AbstractAssetActivity.java b/client/src/main/java/org/openremote/app/client/assets/asset/AbstractAssetActivity.java
index f9c102af7..fe371d91b 100644
--- a/client/src/main/java/org/openremote/app/client/assets/asset/AbstractAssetActivity.java
+++ b/client/src/main/java/org/openremote/app/client/assets/asset/AbstractAssetActivity.java
@@ -204,9 +204,9 @@ public abstract class AbstractAssetActivity<V
view.getAssetNavigation().setEnabled(assetId != null);
view.setName(asset.getName());
view.setCreatedOn(asset.getCreatedOn());
- view.setLocation(asset.getPoint());
+ view.setLocation(asset.getCoordinates());
view.showDroppedPin(asset.getGeoFeature(20));
- view.flyTo(asset.getPoint());
+ view.flyTo(asset.getCoordinates());
view.setAccessPublicRead(asset.isAccessPublicRead());
}
diff --git a/client/src/main/java/org/openremote/app/client/assets/asset/AssetEditActivity.java b/client/src/main/java/org/openremote/app/client/assets/asset/AssetEditActivity.java
index ce8daa1bf..8971776dd 100644
--- a/client/src/main/java/org/openremote/app/client/assets/asset/AssetEditActivity.java
+++ b/client/src/main/java/org/openremote/app/client/assets/asset/AssetEditActivity.java
@@ -191,7 +191,7 @@ public class AssetEditActivity
@Override
public void onMapClicked(double lng, double lat) {
- selectedCoordinates = new GeoJSONPoint(new double[]{lng, lat});
+ selectedCoordinates = new GeoJSONPoint(lng, lat);
view.hideMapPopup();
view.showMapPopup(lng, lat, environment.getMessages().selectedLocation());
view.setLocation(selectedCoordinates);
@@ -463,7 +463,7 @@ public class AssetEditActivity
if (selectedCoordinates != null) {
view.flyTo(selectedCoordinates);
} else if (asset.getCoordinates() != null) {
- view.flyTo(asset.getPoint());
+ view.flyTo(asset.getCoordinates());
}
}
@@ -662,7 +662,7 @@ public class AssetEditActivity
asset.setType(view.getType());
}
if (selectedCoordinates != null) {
- asset.setCoordinates(new double[]{selectedCoordinates.getLongitude(), selectedCoordinates.getLatitude()});
+ asset.setCoordinates(selectedCoordinates);
}
}
diff --git a/client/src/main/java/org/openremote/app/client/assets/asset/AssetEditImpl.java b/client/src/main/java/org/openremote/app/client/assets/asset/AssetEditImpl.java
index 153911d6e..8daa7a95f 100644
--- a/client/src/main/java/org/openremote/app/client/assets/asset/AssetEditImpl.java
+++ b/client/src/main/java/org/openremote/app/client/assets/asset/AssetEditImpl.java
@@ -44,6 +44,7 @@ import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetType;
import org.openremote.model.asset.AssetTypeDescriptor;
import org.openremote.model.geo.GeoJSON;
+import org.openremote.model.geo.GeoJSONFeatureCollection;
import org.openremote.model.geo.GeoJSONPoint;
import org.openremote.model.util.Pair;
import org.openremote.model.value.ObjectValue;
@@ -256,7 +257,7 @@ public class AssetEditImpl extends FormViewImpl implements AssetEdit {
typeInput.setReadOnly(false);
typeInput.setVisible(false);
customTypeInfoLabel.setVisible(false);
- showDroppedPin(GeoJSON.EMPTY_FEATURE_COLLECTION);
+ showDroppedPin(GeoJSONFeatureCollection.EMPTY);
hideMapPopup();
setDisabled(false);
attributeViewContainer.clear();
diff --git a/client/src/main/java/org/openremote/app/client/assets/asset/AssetViewActivity.java b/client/src/main/java/org/openremote/app/client/assets/asset/AssetViewActivity.java
index 495ed4570..f979f7b6a 100644
--- a/client/src/main/java/org/openremote/app/client/assets/asset/AssetViewActivity.java
+++ b/client/src/main/java/org/openremote/app/client/assets/asset/AssetViewActivity.java
@@ -164,7 +164,7 @@ public class AssetViewActivity
@Override
public void centerMap() {
- view.flyTo(asset.getPoint());
+ view.flyTo(asset.getCoordinates());
}
@Override
diff --git a/client/src/main/java/org/openremote/app/client/assets/asset/AssetViewImpl.java b/client/src/main/java/org/openremote/app/client/assets/asset/AssetViewImpl.java
index 1706d47c3..9122d4998 100644
--- a/client/src/main/java/org/openremote/app/client/assets/asset/AssetViewImpl.java
+++ b/client/src/main/java/org/openremote/app/client/assets/asset/AssetViewImpl.java
@@ -44,6 +44,7 @@ import org.openremote.model.Constants;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetType;
import org.openremote.model.geo.GeoJSON;
+import org.openremote.model.geo.GeoJSONFeatureCollection;
import org.openremote.model.geo.GeoJSONPoint;
import org.openremote.model.value.ObjectValue;
@@ -227,7 +228,7 @@ public class AssetViewImpl extends Composite implements AssetView {
locationGroup.setVisible(false);
locationOutput.setCoordinates(null, null);
mapWidget.setVisible(false);
- showDroppedPin(GeoJSON.EMPTY_FEATURE_COLLECTION);
+ showDroppedPin(GeoJSONFeatureCollection.EMPTY);
accessPublicReadGroup.setVisible(false);
accessPublicReadCheckBox.setValue(false);
diff --git a/client/src/main/java/org/openremote/app/client/interop/jackson/PositionDeserializer.java b/client/src/main/java/org/openremote/app/client/interop/jackson/PositionDeserializer.java
new file mode 100644
index 000000000..a025ebcf3
--- /dev/null
+++ b/client/src/main/java/org/openremote/app/client/interop/jackson/PositionDeserializer.java
@@ -0,0 +1,48 @@
+/*
+ * 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.app.client.interop.jackson;
+
+import com.github.nmorel.gwtjackson.client.JsonDeserializationContext;
+import com.github.nmorel.gwtjackson.client.JsonDeserializer;
+import com.github.nmorel.gwtjackson.client.JsonDeserializerParameters;
+import com.github.nmorel.gwtjackson.client.stream.JsonReader;
+import com.github.nmorel.gwtjackson.client.stream.JsonToken;
+import org.openremote.model.geo.Position;
+
+public class PositionDeserializer extends JsonDeserializer<Position> {
+
+ @Override
+ protected Position doDeserialize(JsonReader jsonReader, JsonDeserializationContext jsonDeserializationContext, JsonDeserializerParameters jsonDeserializerParameters) {
+
+ if ( JsonToken.BEGIN_ARRAY == jsonReader.peek() ) {
+ jsonReader.beginArray();
+ Double[] values = new Double[3];
+ int index = 0;
+ while ( JsonToken.END_ARRAY != jsonReader.peek() && index < 3 ) {
+ values[index++] = jsonReader.nextDouble();
+ }
+ jsonReader.endArray();
+
+ return new Position(values[0], values[1], values[2]);
+ }
+
+ return null;
+ }
+}
diff --git a/client/src/main/java/org/openremote/app/client/interop/jackson/PositionSerializer.java b/client/src/main/java/org/openremote/app/client/interop/jackson/PositionSerializer.java
new file mode 100644
index 000000000..ba23fc36e
--- /dev/null
+++ b/client/src/main/java/org/openremote/app/client/interop/jackson/PositionSerializer.java
@@ -0,0 +1,40 @@
+/*
+ * 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.app.client.interop.jackson;
+
+import com.github.nmorel.gwtjackson.client.JsonSerializationContext;
+import com.github.nmorel.gwtjackson.client.JsonSerializer;
+import com.github.nmorel.gwtjackson.client.JsonSerializerParameters;
+import com.github.nmorel.gwtjackson.client.stream.JsonWriter;
+import org.openremote.model.geo.Position;
+
+public class PositionSerializer extends JsonSerializer<Position> {
+
+ @Override
+ protected void doSerialize(JsonWriter jsonWriter, Position position, JsonSerializationContext jsonSerializationContext, JsonSerializerParameters jsonSerializerParameters) {
+ jsonWriter.beginArray();
+ jsonWriter.value(position.getX());
+ jsonWriter.value(position.getY());
+ if (position.hasZ()) {
+ jsonWriter.value(position.getZ());
+ }
+ jsonWriter.endArray();
+ }
+}
diff --git a/client/src/main/java/org/openremote/app/client/interop/jackson/SerializationConfiguration.java b/client/src/main/java/org/openremote/app/client/interop/jackson/SerializationConfiguration.java
index be590d7bc..4fc5fbaa9 100644
--- a/client/src/main/java/org/openremote/app/client/interop/jackson/SerializationConfiguration.java
+++ b/client/src/main/java/org/openremote/app/client/interop/jackson/SerializationConfiguration.java
@@ -23,6 +23,7 @@ import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.github.nmorel.gwtjackson.client.AbstractConfiguration;
import org.openremote.model.ValidationFailure;
import org.openremote.model.attribute.MetaItemDescriptor;
+import org.openremote.model.geo.Position;
import org.openremote.model.value.*;
/**
@@ -46,5 +47,6 @@ public class SerializationConfiguration extends AbstractConfiguration {
type(NumberValue.class).serializer(ModelValueSerializer.class).deserializer(ModelValueDeserializer.class);
type(StringValue.class).serializer(ModelValueSerializer.class).deserializer(ModelValueDeserializer.class);
type(BooleanValue.class).serializer(ModelValueSerializer.class).deserializer(ModelValueDeserializer.class);
+ type(Position.class).serializer(PositionSerializer.class).deserializer(PositionDeserializer.class);
}
}
diff --git a/client/src/main/java/org/openremote/app/client/map/MapActivity.java b/client/src/main/java/org/openremote/app/client/map/MapActivity.java
index e08095e4e..295b4ef6e 100644
--- a/client/src/main/java/org/openremote/app/client/map/MapActivity.java
+++ b/client/src/main/java/org/openremote/app/client/map/MapActivity.java
@@ -42,6 +42,8 @@ import org.openremote.model.map.MapResource;
import org.openremote.model.value.Values;
import javax.inject.Inject;
+import java.math.BigDecimal;
+import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
@@ -189,7 +191,7 @@ public class MapActivity extends AssetBrowsingActivity<MapPlace> implements MapV
if (asset.hasGeoFeature()) {
GeoJSON geoFeature = asset.getGeoFeature(30);
view.showDroppedPin(geoFeature);
- view.flyTo(asset.getPoint());
+ view.flyTo(asset.getCoordinates());
}
}
@@ -206,14 +208,24 @@ public class MapActivity extends AssetBrowsingActivity<MapPlace> implements MapV
.sorted(Comparator.comparing(MapInfoItem::getLabel))
.collect(Collectors.toList());
if (asset.hasGeoFeature()) {
+
+
infoItems.add(0, new MapInfoItem(
"map-marker",
environment.getMessages().location(),
null,
- Values.create(asset.getCoordinatesLabel())
+ Values.create(getCoordinatesLabel())
));
}
view.showInfoItems(infoItems);
}
+ /**
+ * Flip longitude and latitude here for display. Rounding to 5 decimal places gives us precision of about 1 meter.
+ */
+ protected String getCoordinatesLabel() {
+ return
+ new BigDecimal(asset.getCoordinates().getY()).setScale(5, RoundingMode.HALF_UP) + " " +
+ new BigDecimal(asset.getCoordinates().getX()).setScale(5, RoundingMode.HALF_UP) + " Lat|Lng";
+ }
}
diff --git a/client/src/main/java/org/openremote/app/client/map/MapViewImpl.java b/client/src/main/java/org/openremote/app/client/map/MapViewImpl.java
index 7718a5093..b257891b4 100644
--- a/client/src/main/java/org/openremote/app/client/map/MapViewImpl.java
+++ b/client/src/main/java/org/openremote/app/client/map/MapViewImpl.java
@@ -34,6 +34,7 @@ import org.openremote.app.client.widget.FlexSplitPanel;
import org.openremote.app.client.widget.Hyperlink;
import org.openremote.app.client.widget.MapWidget;
import org.openremote.model.geo.GeoJSON;
+import org.openremote.model.geo.GeoJSONFeatureCollection;
import org.openremote.model.geo.GeoJSONPoint;
import org.openremote.model.value.ObjectValue;
@@ -90,7 +91,7 @@ public class MapViewImpl extends Composite implements MapView {
viewAssetLink.setVisible(false);
viewAssetLink.setTargetHistoryToken("");
*/
- showDroppedPin(GeoJSON.EMPTY_FEATURE_COLLECTION);
+ showDroppedPin(GeoJSONFeatureCollection.EMPTY);
mapInfoPanel.close();
diff --git a/client/src/main/java/org/openremote/app/client/widget/FormOutputLocation.java b/client/src/main/java/org/openremote/app/client/widget/FormOutputLocation.java
index fdeb29420..cab0f88ad 100644
--- a/client/src/main/java/org/openremote/app/client/widget/FormOutputLocation.java
+++ b/client/src/main/java/org/openremote/app/client/widget/FormOutputLocation.java
@@ -53,7 +53,7 @@ public class FormOutputLocation extends Composite {
}
public boolean setCoordinates(String noLocationText, GeoJSONPoint point) {
- if (point != null && point.hasCoordinates()) {
+ if (point != null) {
this.coordinates = point;
toggleButton.setVisible(true);
update();
@@ -68,11 +68,11 @@ public class FormOutputLocation extends Composite {
// TODO: This assumes 0 is Lng and 1 is Lat, which is true for PostGIS backend
// Rounding to 5 decimals gives us precision of about 1 meter, should be enough
if (reversed) {
- coordinatesLabel.setText(round(coordinates.getLongitude(), 5) + " " + round(coordinates.getLatitude(), 5));
+ coordinatesLabel.setText(round(coordinates.getX(), 5) + " " + round(coordinates.getY(), 5));
toggleButton.getUpFace().setText("Lng | Lat");
toggleButton.getDownFace().setText("Lng | Lat");
} else {
- coordinatesLabel.setText(round(coordinates.getLatitude(), 5) + " " + round(coordinates.getLongitude(), 5));
+ coordinatesLabel.setText(round(coordinates.getY(), 5) + " " + round(coordinates.getX(), 5));
toggleButton.getUpFace().setText("Lat | Lng");
toggleButton.getDownFace().setText("Lat | Lng");
}
diff --git a/client/src/main/java/org/openremote/app/client/widget/MapWidget.java b/client/src/main/java/org/openremote/app/client/widget/MapWidget.java
index fd335eb21..141e12ca8 100644
--- a/client/src/main/java/org/openremote/app/client/widget/MapWidget.java
+++ b/client/src/main/java/org/openremote/app/client/widget/MapWidget.java
@@ -24,6 +24,7 @@ import com.google.gwt.user.client.ui.FlowPanel;
import elemental2.dom.DomGlobal;
import org.openremote.app.client.interop.mapbox.*;
import org.openremote.model.geo.GeoJSON;
+import org.openremote.model.geo.GeoJSONFeatureCollection;
import org.openremote.model.geo.GeoJSONPoint;
import org.openremote.model.value.ArrayValue;
import org.openremote.model.value.ObjectValue;
@@ -227,18 +228,18 @@ public class MapWidget extends FlowPanel {
if (mapboxMap.getSource(featureSourceId) == null)
throw new IllegalArgumentException("Map has no such feature source: " + featureSourceId);
LOG.fine("Showing feature on source '" + featureSourceId + "': " + geoFeature);
- mapboxMap.getSource(featureSourceId).setData(geoFeature.getObjectValue().asAny());
+ mapboxMap.getSource(featureSourceId).setData(geoFeature.toValue().asAny());
}
public void flyTo(GeoJSONPoint point) {
if (!isMapReady())
throw new IllegalStateException("Map not ready");
- if (point == null || !point.hasCoordinates())
+ if (point == null)
return;
ObjectValue options = Values.createObject();
ArrayValue center = Values.createArray();
- center.set(0, point.getLongitude());
- center.set(1, point.getLatitude());
+ center.set(0, point.getX());
+ center.set(1, point.getY());
options.put("center", center);
mapboxMap.flyTo(options.asAny());
}
@@ -265,7 +266,7 @@ public class MapWidget extends FlowPanel {
protected ObjectValue prepareSourceOptions(String featureSourceId) {
ObjectValue sourceOptions = Values.createObject();
// Initialize with empty collection
- ObjectValue initialData = GeoJSON.EMPTY_FEATURE_COLLECTION.getObjectValue();
+ ObjectValue initialData = GeoJSONFeatureCollection.EMPTY.toValue();
LOG.fine("Preparing initial data on feature source: " + featureSourceId);
sourceOptions.put("type", create("geojson"));
sourceOptions.put("data", initialData);
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
index 7149690ad..4d219da67 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
@@ -37,10 +37,7 @@ import org.openremote.manager.rules.RulesService;
import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.model.Constants;
import org.openremote.model.ValidationFailure;
-import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.AssetAttribute;
-import org.openremote.model.asset.AssetResource;
-import org.openremote.model.asset.AssetType;
+import org.openremote.model.asset.*;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeEvent.Source;
import org.openremote.model.attribute.AttributeExecuteStatus;
@@ -49,6 +46,7 @@ import org.openremote.model.value.Value;
import org.openremote.model.value.Values;
import javax.persistence.EntityManager;
+import javax.ws.rs.WebApplicationException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@@ -56,6 +54,8 @@ import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
+import static javax.ws.rs.core.Response.Status.FORBIDDEN;
+import static javax.ws.rs.core.Response.Status.NOT_FOUND;
import static org.openremote.container.concurrent.GlobalLock.withLock;
import static org.openremote.manager.asset.AssetProcessingException.Reason.*;
import static org.openremote.manager.event.ClientEventService.CLIENT_EVENT_TOPIC;
@@ -273,6 +273,63 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
if (oldAttribute == null)
throw new AssetProcessingException(ATTRIBUTE_NOT_FOUND);
+ switch (source) {
+ case CLIENT:
+
+ AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);
+ if (authContext == null) {
+ // Check attribute has public write flag
+ if (!oldAttribute.getMetaItem(AssetMeta.ACCESS_PUBLIC_WRITE).isPresent()) {
+ throw new AssetProcessingException(NO_AUTH_CONTEXT);
+ }
+ // Check read-only
+ if (oldAttribute.isReadOnly()) {
+ throw new AssetProcessingException(INSUFFICIENT_ACCESS);
+ }
+ } else {
+ // Check realm, must be accessible
+ if (!identityService.getIdentityProvider().isTenantActiveAndAccessible(authContext,
+ asset)) {
+ throw new AssetProcessingException(INSUFFICIENT_ACCESS);
+ }
+
+ // Check read-only
+ if (oldAttribute.isReadOnly() && !authContext.isSuperUser()) {
+ throw new AssetProcessingException(INSUFFICIENT_ACCESS);
+ }
+
+ // Regular user must have write assets role
+ if (!authContext.hasResourceRoleOrIsSuperUser(ClientRole.WRITE_ASSETS.getValue(),
+ Constants.KEYCLOAK_CLIENT_ID)) {
+ throw new AssetProcessingException(INSUFFICIENT_ACCESS);
+ }
+
+ // Check restricted user
+ if (identityService.getIdentityProvider().isRestrictedUser(authContext.getUserId())) {
+ // Must be asset linked to user
+ if (!assetStorageService.isUserAsset(authContext.getUserId(),
+ event.getEntityId())) {
+ throw new AssetProcessingException(INSUFFICIENT_ACCESS);
+ }
+ // Must be writable by restricted client
+ if (!oldAttribute.isAccessRestrictedWrite()) {
+ throw new AssetProcessingException(INSUFFICIENT_ACCESS);
+ }
+ }
+ }
+ break;
+
+ case SENSOR:
+ Optional<AssetAttribute> protocolConfiguration =
+ getAgentLink(oldAttribute).flatMap(agentService::getProtocolConfiguration);
+
+ // Sensor event must be for an attribute linked to a protocol configuration
+ if (!protocolConfiguration.isPresent()) {
+ throw new AssetProcessingException(INVALID_AGENT_LINK);
+ }
+ break;
+ }
+
// Agent attributes can't be updated with events
if (asset.getWellKnownType() == AssetType.AGENT) {
throw new AssetProcessingException(ILLEGAL_AGENT_UPDATE);
@@ -291,8 +348,8 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
//Check if attribute is well known and the value is valid
AssetModel.getAttributeDescriptor(oldAttribute.name).ifPresent(wellKnownAttribute -> {
- //Check if the value is valid
- wellKnownAttribute.getType()
+ // Check if the value is valid
+ wellKnownAttribute.getValueType()
.isValidValue(event.getValue().orElseThrow(() -> new AssetProcessingException(INVALID_VALUE_FOR_WELL_KNOWN_ATTRIBUTE)))
.ifPresent(validationFailure -> {
throw new AssetProcessingException(
@@ -301,52 +358,6 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
});
});
- switch (source) {
- case CLIENT:
- AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);
- if (authContext == null) {
- throw new AssetProcessingException(NO_AUTH_CONTEXT);
- }
-
- // Check realm, must be accessible
- if (!identityService.getIdentityProvider().isTenantActiveAndAccessible(authContext, asset)) {
- throw new AssetProcessingException(INSUFFICIENT_ACCESS);
- }
-
- // Check read-only
- if (oldAttribute.isReadOnly() && !authContext.isSuperUser()) {
- throw new AssetProcessingException(INSUFFICIENT_ACCESS);
- }
-
- // Regular user must have write assets role
- if (!authContext.hasResourceRoleOrIsSuperUser(ClientRole.WRITE_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {
- throw new AssetProcessingException(INSUFFICIENT_ACCESS);
- }
-
- // Check restricted user
- if (identityService.getIdentityProvider().isRestrictedUser(authContext.getUserId())) {
- // Must be asset linked to user
- if (!assetStorageService.isUserAsset(authContext.getUserId(), event.getEntityId())) {
- throw new AssetProcessingException(INSUFFICIENT_ACCESS);
- }
- // Must be writable by restricted client
- if (!oldAttribute.isAccessRestrictedWrite()) {
- throw new AssetProcessingException(INSUFFICIENT_ACCESS);
- }
- }
- break;
-
- case SENSOR:
- Optional<AssetAttribute> protocolConfiguration =
- getAgentLink(oldAttribute).flatMap(agentService::getProtocolConfiguration);
-
- // Sensor event must be for an attribute linked to a protocol configuration
- if (!protocolConfiguration.isPresent()) {
- throw new AssetProcessingException(INVALID_AGENT_LINK);
- }
- break;
- }
-
// Either use the timestamp of the event or set event time to processing time
long processingTime = timerService.getCurrentTimeMillis();
long eventTime = event.getTimestamp() > 0 ? event.getTimestamp() : processingTime;
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
index 80662e15a..af81c704c 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
@@ -337,14 +337,14 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
asset.getAttributesStream().forEach(assetAttribute -> {
AssetModel.getAttributeDescriptor(assetAttribute.name).ifPresent(wellKnownAttribute -> {
//Check if the type matches
- if (!wellKnownAttribute.getType().equals(assetAttribute.getTypeOrThrow())) {
+ if (!wellKnownAttribute.getValueType().equals(assetAttribute.getTypeOrThrow())) {
throw new IllegalStateException(
String.format("Well known attribute isn't of the correct type. Attribute name: %s. Expected type: %s",
- assetAttribute.name, wellKnownAttribute.getType().name()));
+ assetAttribute.name, wellKnownAttribute.getValueType().name()));
}
//Check if the value is valid
- wellKnownAttribute.getType()
+ wellKnownAttribute.getValueType()
.isValidValue(assetAttribute.getValue().orElseThrow(() -> new IllegalStateException("Value is empty for " + assetAttribute.name)))
.ifPresent(validationFailure -> {
throw new IllegalStateException(
@@ -599,51 +599,4 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
return result;
}
-
- @Override
- public void updateLocation(RequestParams requestParams, String assetId, GeoJSONPoint location) {
- try {
- Asset asset = get(requestParams, assetId);
- updateAssetLocation(asset, location);
- } catch (IllegalStateException ex) {
- throw new WebApplicationException(ex, BAD_REQUEST);
- }
- }
-
- @Override
- public void updatePublicAssetLocation(RequestParams requestParams, String assetId, GeoJSONPoint location) {
- try {
- Asset asset = assetStorageService.find(assetId, true);
-
- if (asset == null) {
- throw new WebApplicationException(NOT_FOUND);
- }
-
- //TODO do we need a PUBLIC_WRITE metaitem?
- if (!asset.isAccessPublicRead()) {
- throw new WebApplicationException(FORBIDDEN);
- }
-
- updateAssetLocation(asset, location);
- } catch (IllegalStateException ex) {
- throw new WebApplicationException(ex, BAD_REQUEST);
- }
- }
-
- protected void updateAssetLocation(Asset asset, GeoJSONPoint location) {
- Value locationValue = Optional.ofNullable(location)
- .map(loc -> {
- ObjectValue objValue = Values.createObject();
- objValue.put("latitude", loc.getLatitude());
- objValue.put("longitude", loc.getLongitude());
- return objValue;
- })
- .orElse(null);
-
- AssetAttribute locationAttribute = asset.getAttribute(AttributeType.LOCATION)
- .orElse(AssetAttribute.createWithDescriptor(AttributeType.LOCATION));
- locationAttribute.setValue(locationValue);
- asset.replaceAttribute(locationAttribute);
- assetStorageService.merge(asset);
- }
}
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
index f625a5788..391445a74 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
@@ -82,6 +82,7 @@ import static org.openremote.model.util.TextUtil.isNullOrEmpty;
public class AssetStorageService extends RouteBuilder implements ContainerService {
protected class PreparedAssetQuery {
+
final protected String querySql;
final protected List<ParameterBinder> binders;
@@ -112,12 +113,13 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
clientEventService = container.getService(ClientEventService.class);
clientEventService.addSubscriptionAuthorizer((auth, subscription) ->
- (subscription.isEventType(AssetTreeModifiedEvent.class) || subscription.isEventType(LocationEvent.class))
- && identityService.getIdentityProvider().canSubscribeWith(
- auth,
- subscription.getFilter() instanceof TenantFilter ? ((TenantFilter) subscription.getFilter()) : null,
- ClientRole.READ_ASSETS)
- );
+ (subscription.isEventType(AssetTreeModifiedEvent.class) || subscription.isEventType(
+ LocationEvent.class))
+ && identityService.getIdentityProvider().canSubscribeWith(
+ auth,
+ subscription.getFilter() instanceof TenantFilter ? ((TenantFilter) subscription.getFilter()) : null,
+ ClientRole.READ_ASSETS)
+ );
container.getService(WebService.class).getApiSingletons().add(
new AssetResourceImpl(
@@ -126,13 +128,13 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
this,
container.getService(MessageBrokerService.class)
)
- );
+ );
container.getService(WebService.class).getApiSingletons().add(
new ConsoleResourceImpl(container.getService(TimerService.class),
- identityService,
- this)
- );
+ identityService,
+ this)
+ );
container.getService(MessageBrokerSetupService.class).getContext().addRoutes(this);
}
@@ -186,7 +188,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
event.getAssetId(),
true,
identityService.getIdentityProvider().isRestrictedUser(authContext.getUserId()) ? RESTRICTED_READ : PRIVATE_READ
- );
+ );
if (asset != null) {
replyWithAttributeEvents(sessionKey, asset, event.getAttributeNames());
}
@@ -218,12 +220,13 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
/**
* @param loadComplete If the whole asset data (including path and attributes) should be loaded.
- * @param access The required access permissions of the asset data.
+ * @param access The required access permissions of the asset data.
*/
public Asset find(String assetId, boolean loadComplete, Access access) {
if (assetId == null)
throw new IllegalArgumentException("Can't query null asset identifier");
- return find(new AssetQuery().select(new Select(loadComplete ? ALL : ALL_EXCEPT_PATH_AND_ATTRIBUTES, access)).id(assetId));
+ return find(new AssetQuery().select(new Select(loadComplete ? ALL : ALL_EXCEPT_PATH_AND_ATTRIBUTES, access)).id(
+ assetId));
}
public Asset find(BaseAssetQuery query) {
@@ -251,7 +254,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
// TODO: Do this in a loop in reasonably sized batches
return persistenceService.doReturningTransaction(em -> {
- List<Object[]> result = em.createQuery("select a.id, a.name from Asset a where a.id in :ids", Object[].class)
+ List<Object[]> result = em.createQuery("select a.id, a.name from Asset a where a.id in :ids",
+ Object[].class)
.setParameter("ids", Arrays.asList(ids))
.getResultList();
List<String> names = new ArrayList<>();
@@ -276,7 +280,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
/**
- * @param overrideVersion If <code>true</code>, the merge will override the data in the database, independent of version.
+ * @param overrideVersion If <code>true</code>, the merge will override the data in the database, independent of
+ * version.
* @return The current stored asset state.
* @throws IllegalArgumentException if the realm or parent is illegal, or other asset constraint is violated.
*/
@@ -294,8 +299,9 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
/**
- * @param overrideVersion If <code>true</code>, the merge will override the data in the database, independent of version.
- * @param userName the user which this asset needs to be assigned to.
+ * @param overrideVersion If <code>true</code>, the merge will override the data in the database, independent of
+ * version.
+ * @param userName the user which this asset needs to be assigned to.
* @return The current stored asset state.
* @throws IllegalArgumentException if the realm or parent is illegal, or other asset constraint is violated.
*/
@@ -389,8 +395,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
Asset asset = em.find(Asset.class, assetId);
if (asset != null) {
List<Asset> children = findAll(em, new AssetQuery()
- .parent(new AssetQuery.ParentPredicate(asset.getId()))
- );
+ .parent(new AssetQuery.ParentPredicate(asset.getId()))
+ );
if (children.size() > 0)
return false;
LOG.fine("Removing: " + asset);
@@ -419,83 +425,63 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
return persistenceService.doReturningTransaction(entityManager -> {
if (isNullOrEmpty(userId) && isNullOrEmpty(assetId)) {
return entityManager.createQuery(
- "select ua from UserAsset ua where ua.id.realmId = :realmId order by ua.createdOn desc", UserAsset.class
- ).setParameter("realmId", realmId).getResultList();
+ "select ua from UserAsset ua where ua.id.realmId = :realmId order by ua.createdOn desc",
+ UserAsset.class
+ ).setParameter("realmId", realmId).getResultList();
} else if (isNullOrEmpty(assetId)) {
return entityManager.createQuery(
- "select ua from UserAsset ua where ua.id.realmId = :realmId and ua.id.userId = :userId order by ua.createdOn desc", UserAsset.class
- ).setParameter("realmId", realmId).setParameter("userId", userId).getResultList();
+ "select ua from UserAsset ua where ua.id.realmId = :realmId and ua.id.userId = :userId order by ua.createdOn desc",
+ UserAsset.class
+ ).setParameter("realmId", realmId).setParameter("userId",
+ userId).getResultList();
} else if (isNullOrEmpty(userId)) {
return entityManager.createQuery(
- "select ua from UserAsset ua where ua.id.realmId = :realmId and ua.id.assetId = :assetId order by ua.createdOn desc", UserAsset.class
- ).setParameter("realmId", realmId).setParameter("assetId", assetId).getResultList();
+ "select ua from UserAsset ua where ua.id.realmId = :realmId and ua.id.assetId = :assetId order by ua.createdOn desc",
+ UserAsset.class
+ ).setParameter("realmId", realmId).setParameter("assetId",
+ assetId).getResultList();
} else {
return entityManager.createQuery(
- "select ua from UserAsset ua where ua.id.realmId = :realmId and ua.id.userId = :userId and ua.id.assetId = :assetId order by ua.createdOn desc", UserAsset.class
- ).setParameter("realmId", realmId).setParameter("userId", userId).setParameter("assetId", assetId).getResultList();
+ "select ua from UserAsset ua where ua.id.realmId = :realmId and ua.id.userId = :userId and ua.id.assetId = :assetId order by ua.createdOn desc",
+ UserAsset.class
+ ).setParameter("realmId", realmId).setParameter("userId",
+ userId).setParameter(
+ "assetId",
+ assetId).getResultList();
}
});
}
/**
- * Also marks the user as restricted, manages {@link UserConfiguration#isRestricted()}.
+ * This used to automatically make the user restricted as well but this has been disabled as it no longer fitted
+ * with use cases.
*/
public void storeUserAsset(UserAsset userAsset) {
persistenceService.doTransaction(entityManager -> storeUserAsset(entityManager, userAsset));
}
/**
- * Also marks the user as unrestricted if no assets are linked to the user, manages {@link UserConfiguration#isRestricted()}.
+ * This used to automatically unrestrict a user if no assets are linked to the them anymore but this has been
+ * disabled as it no longer fitted with use cases.
*/
public void deleteUserAsset(String realmId, String userId, String assetId) {
persistenceService.doTransaction(entityManager -> {
UserAsset userAsset = entityManager.find(UserAsset.class, new UserAsset.Id(realmId, userId, assetId));
if (userAsset != null)
entityManager.remove(userAsset);
-
- // If there are no more assets linked to this user
- long count = entityManager.createQuery(
- "select count(ua) from UserAsset ua where ua.id.userId = :userId", Long.class
- ).setParameter("userId", userId).getSingleResult();
- if (count == 0) {
- // The user must be configured as not restricted
- UserConfiguration userConfiguration = getUserConfiguration(entityManager, userAsset.getId().getUserId());
- userConfiguration.setRestricted(false);
- mergeUserConfiguration(entityManager, userConfiguration);
- }
});
}
protected void storeUserAsset(EntityManager entityManager, UserAsset userAsset) {
- // The user must be configured as restricted
- UserConfiguration userConfiguration = getUserConfiguration(entityManager, userAsset.getId().getUserId());
- userConfiguration.setRestricted(true);
- mergeUserConfiguration(entityManager, userConfiguration);
-
userAsset.setCreatedOn(new Date(timerService.getCurrentTimeMillis()));
entityManager.merge(userAsset);
}
- protected UserConfiguration getUserConfiguration(EntityManager em, String userId) {
- UserConfiguration userConfiguration = em.find(UserConfiguration.class, userId);
- if (userConfiguration == null) {
- userConfiguration = new UserConfiguration(userId);
- userConfiguration = mergeUserConfiguration(em, userConfiguration);
- }
- return userConfiguration;
- }
-
- protected UserConfiguration mergeUserConfiguration(EntityManager em, UserConfiguration userConfiguration) {
- if (userConfiguration.getUserId() == null || userConfiguration.getUserId().length() == 0) {
- throw new IllegalArgumentException("User ID must be set on: " + userConfiguration);
- }
- return em.merge(userConfiguration);
- }
-
/* ####################################################################################### */
protected interface ParameterBinder extends Consumer<PreparedStatement> {
+
@Override
default void accept(PreparedStatement st) {
try {
@@ -515,8 +501,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
em,
new AssetQuery().select(
new Select(loadComplete ? ALL : ALL_EXCEPT_PATH_AND_ATTRIBUTES, access)
- ).id(assetId)
- );
+ ).id(assetId)
+ );
}
protected List<Asset> findAll(EntityManager em, BaseAssetQuery query) {
@@ -597,7 +583,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
boolean recursive = query.select.recursive;
sb.append("select A.ID as ID, A.NAME as NAME, A.ACCESS_PUBLIC_READ as ACCESS_PUBLIC_READ");
- sb.append(", A.CREATED_ON AS CREATED_ON, A.ASSET_TYPE AS ASSET_TYPE, A.PARENT_ID AS PARENT_ID, A.REALM_ID AS REALM_ID");
+ sb.append(
+ ", A.CREATED_ON AS CREATED_ON, A.ASSET_TYPE AS ASSET_TYPE, A.PARENT_ID AS PARENT_ID, A.REALM_ID AS REALM_ID");
if (include == AssetQuery.Include.ONLY_ID_AND_NAME) {
return sb.toString();
@@ -659,7 +646,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
} else if (access != PRIVATE_READ) {
// Use sub-select for processing the attributes the meta inside each attribute is replaced with filtered meta
// (coalesce null to empty array because jsonb_set() with null will clear the whole object)
- sb.append("select json_object_agg(AX.key, jsonb_set(AX.value, '{meta}', coalesce(AMF.VALUE, jsonb_build_array()), false)) from jsonb_each(A.attributes) as AX");
+ sb.append(
+ "select json_object_agg(AX.key, jsonb_set(AX.value, '{meta}', coalesce(AMF.VALUE, jsonb_build_array()), false)) from jsonb_each(A.attributes) as AX");
// Use implicit inner join on meta array set to only select attributes with a non-private access meta item
sb.append(", jsonb_array_elements(AX.VALUE #> '{meta}') as AM");
// Use subquery to filter out meta items not marked as non-private access
@@ -812,8 +800,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
if (query.location instanceof RadialLocationPredicate) {
RadialLocationPredicate location = (RadialLocationPredicate) query.location;
sb.append(" and ST_Distance_Sphere(ST_MakePoint(");
- sb.append("(A.attributes -> 'location' -> 'value' ->> 'longitude')::numeric");
- sb.append(", (A.attributes -> 'location' -> 'value' ->> 'latitude')::numeric");
+ sb.append("(A.attributes #>> '{location,value,coordinates,0}')::numeric");
+ sb.append(", (A.attributes #>> '{location,value,coordinates,1}')::numeric");
sb.append("), ST_MakePoint(");
sb.append(location.lng);
sb.append(",");
@@ -824,8 +812,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
RectangularLocationPredicate location = (RectangularLocationPredicate) query.location;
sb.append(location.negated ? " and NOT" : " and");
sb.append(" ST_Within(ST_MakePoint(");
- sb.append("(A.attributes -> 'location' -> 'value' ->> 'longitude')::numeric");
- sb.append(", (A.attributes -> 'location' -> 'value' ->> 'latitude')::numeric");
+ sb.append("(A.attributes #>> '{location,value,coordinates,0}')::numeric");
+ sb.append(", (A.attributes #>> '{location,value,coordinates,1}')::numeric");
sb.append(")");
sb.append(", ST_MakeEnvelope(");
sb.append(location.lngMin);
@@ -940,9 +928,9 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
if (attributeMetaPredicate.itemNamePredicate != null) {
attributeMetaBuilder.append(attributeMetaPredicate.itemNamePredicate.caseSensitive
- ? " and AM.VALUE #>> '{name}'"
- : " and upper(AM.VALUE #>> '{name}')"
- );
+ ? " and AM.VALUE #>> '{name}'"
+ : " and upper(AM.VALUE #>> '{name}')"
+ );
switch (attributeMetaPredicate.itemNamePredicate.match) {
case EXACT:
attributeMetaBuilder.append(" = ? ");
@@ -963,9 +951,9 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
if (attributeMetaPredicate.itemValuePredicate instanceof AssetQuery.StringPredicate) {
AssetQuery.StringPredicate stringPredicate = (AssetQuery.StringPredicate) attributeMetaPredicate.itemValuePredicate;
attributeMetaBuilder.append(stringPredicate.caseSensitive
- ? " and AM.VALUE #>> '{value}'"
- : " and upper(AM.VALUE #>> '{value}')"
- );
+ ? " and AM.VALUE #>> '{value}'"
+ : " and upper(AM.VALUE #>> '{value}')"
+ );
switch (stringPredicate.match) {
case EXACT:
attributeMetaBuilder.append(" = ? ");
@@ -991,9 +979,9 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
for (int i = 0; i < stringArrayPredicate.predicates.length; i++) {
AssetQuery.StringPredicate stringPredicate = stringArrayPredicate.predicates[i];
attributeMetaBuilder.append(stringPredicate.caseSensitive
- ? " and AM.VALUE #> '{value}' ->> " + i
- : " and upper(AM.VALUE #> '{value}' ->> " + i + ")"
- );
+ ? " and AM.VALUE #> '{value}' ->> " + i
+ : " and upper(AM.VALUE #> '{value}' ->> " + i + ")"
+ );
switch (stringPredicate.match) {
case EXACT:
attributeMetaBuilder.append(" = ? ");
@@ -1021,9 +1009,9 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
if (attributePredicate.name != null) {
attributeBuilder.append(attributePredicate.name.caseSensitive
- ? " and AX.key"
- : " and upper(AX.key)"
- );
+ ? " and AX.key"
+ : " and upper(AX.key)"
+ );
switch (attributePredicate.name.match) {
case EXACT:
@@ -1046,9 +1034,9 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
if (attributePredicate.value instanceof AssetQuery.StringPredicate) {
AssetQuery.StringPredicate stringPredicate = (AssetQuery.StringPredicate) attributePredicate.value;
attributeBuilder.append(stringPredicate.caseSensitive
- ? " and AX.VALUE #>> '{value}'"
- : " and upper(AX.VALUE #>> '{value}')"
- );
+ ? " and AX.VALUE #>> '{value}'"
+ : " and upper(AX.VALUE #>> '{value}')"
+ );
switch (stringPredicate.match) {
case EXACT:
attributeBuilder.append(" = ? ");
@@ -1074,9 +1062,9 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
for (int i = 0; i < stringArrayPredicate.predicates.length; i++) {
AssetQuery.StringPredicate stringPredicate = stringArrayPredicate.predicates[i];
attributeBuilder.append(stringPredicate.caseSensitive
- ? " and AX.VALUE #> '{value}' ->> " + i
- : " and upper(AX.VALUE #> '{value}' ->> " + i + ")"
- );
+ ? " and AX.VALUE #> '{value}' ->> " + i
+ : " and upper(AX.VALUE #> '{value}' ->> " + i + ")"
+ );
switch (stringPredicate.match) {
case EXACT:
attributeBuilder.append(" = ? ");
@@ -1219,7 +1207,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
rs.getString("PARENT_ID"), rs.getString("PARENT_NAME"), rs.getString("PARENT_TYPE"),
rs.getString("REALM_ID"), rs.getString("TENANT_NAME"), rs.getString("TENANT_DISPLAY_NAME"),
path != null ? (String[]) path.getArray() : null,
- attributes != null && attributes.length() > 0 ? Values.instance().<ObjectValue>parse(attributes).orElse(null)
+ attributes != null && attributes.length() > 0 ? Values.instance().<ObjectValue>parse(attributes).orElse(
+ null)
: null);
default:
throw new UnsupportedOperationException("Select include option not supported: " + query.select.include);
@@ -1238,14 +1227,14 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
if (!AssetAttribute.ATTRIBUTE_NAME_VALIDATOR.test(attributeName)) {
LOG.fine(
"Invalid attribute name (must match '" + AssetAttribute.ATTRIBUTE_NAME_PATTERN + "'): " + attributeName
- );
+ );
return false;
}
Array attributeValuePath = connection.createArrayOf(
"text",
new String[]{attributeName, "value"}
- );
+ );
statement.setArray(1, attributeValuePath);
PGobject pgJsonValue = new PGobject();
@@ -1258,7 +1247,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
Array attributeValueTimestampPath = connection.createArrayOf(
"text",
new String[]{attributeName, "valueTimestamp"}
- );
+ );
statement.setArray(3, attributeValueTimestampPath);
PGobject pgJsonValueTimestamp = new PGobject();
pgJsonValueTimestamp.setType("jsonb");
@@ -1271,9 +1260,9 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
int updatedRows = statement.executeUpdate();
LOG.fine("Stored asset '" + assetId
- + "' attribute '" + attributeName
- + "' (affected rows: " + updatedRows + ") value: "
- + (value != null ? value.toJson() : "null"));
+ + "' attribute '" + attributeName
+ + "' (affected rows: " + updatedRows + ") value: "
+ + (value != null ? value.toJson() : "null"));
return updatedRows == 1;
}
});
@@ -1285,17 +1274,20 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
case INSERT:
clientEventService.publishEvent(
new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(), asset.getRealmId(), asset.getId())
- );
+ );
if (asset.getParentId() != null) {
// Child asset created
clientEventService.publishEvent(
- new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(), asset.getRealmId(), asset.getParentId(), true)
- );
+ new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(),
+ asset.getRealmId(),
+ asset.getParentId(),
+ true)
+ );
} else {
// Child asset created (root asset)
clientEventService.publishEvent(
new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(), asset.getRealmId(), true)
- );
+ );
}
break;
case UPDATE:
@@ -1305,8 +1297,10 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
String currentName = persistenceEvent.getCurrentState("name");
if (!Objects.equals(previousName, currentName)) {
clientEventService.publishEvent(
- new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(), asset.getRealmId(), asset.getId())
- );
+ new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(),
+ asset.getRealmId(),
+ asset.getId())
+ );
break;
}
@@ -1315,8 +1309,10 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
String currentParentId = persistenceEvent.getCurrentState("parentId");
if (!Objects.equals(previousParentId, currentParentId)) {
clientEventService.publishEvent(
- new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(), asset.getRealmId(), asset.getId())
- );
+ new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(),
+ asset.getRealmId(),
+ asset.getId())
+ );
break;
}
@@ -1325,32 +1321,39 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
String currentRealmId = persistenceEvent.getCurrentState("realmId");
if (!Objects.equals(previousRealmId, currentRealmId)) {
clientEventService.publishEvent(
- new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(), asset.getRealmId(), asset.getId())
- );
+ new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(),
+ asset.getRealmId(),
+ asset.getId())
+ );
break;
}
// Did the location change?
- Stream<AssetAttribute> oldAttributes = attributesFromJson(persistenceEvent.getPreviousState("attributes"), asset.getId());
- Stream<AssetAttribute> currentAttributes = attributesFromJson(persistenceEvent.getCurrentState("attributes"), asset.getId());
+ Stream<AssetAttribute> oldAttributes = attributesFromJson(persistenceEvent.getPreviousState("attributes"),
+ asset.getId());
+ Stream<AssetAttribute> currentAttributes = attributesFromJson(persistenceEvent.getCurrentState(
+ "attributes"), asset.getId());
- Optional<AssetAttribute> oldLocation = oldAttributes.filter(assetAttribute -> assetAttribute.name.equals(AttributeType.LOCATION.getName())).findFirst();
- Optional<AssetAttribute> currentLocation = currentAttributes.filter(assetAttribute -> assetAttribute.name.equals(AttributeType.LOCATION.getName())).findFirst();
+ Optional<AssetAttribute> oldLocation = oldAttributes.filter(assetAttribute -> assetAttribute.name.equals(
+ AttributeType.LOCATION.getName())).findFirst();
+ Optional<AssetAttribute> currentLocation = currentAttributes.filter(assetAttribute -> assetAttribute.name.equals(
+ AttributeType.LOCATION.getName())).findFirst();
if (!(!oldLocation.isPresent() && !currentLocation.isPresent())) {
- if (!oldLocation.isPresent() || !currentLocation.isPresent() || !oldLocation.get().equals(currentLocation.get())) {
+ if (!oldLocation.isPresent() || !currentLocation.isPresent() || !oldLocation.get().equals(
+ currentLocation.get())) {
clientEventService.publishEvent(
new LocationEvent(asset.getId(),
- asset.getCoordinates(),
- timerService.getCurrentTimeMillis())
- );
+ asset.getCoordinates(),
+ timerService.getCurrentTimeMillis())
+ );
}
}
break;
case DELETE:
clientEventService.publishEvent(
new AssetTreeModifiedEvent(timerService.getCurrentTimeMillis(), asset.getRealmId(), asset.getId())
- );
+ );
break;
}
}
@@ -1368,7 +1371,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
protected static boolean calendarEventPredicateMatches(CalendarEventActivePredicate eventActivePredicate, Asset asset) {
return CalendarEventConfiguration.getCalendarEvent(asset)
- .map(calendarEvent -> calendarEventActiveOn(calendarEvent, new Date(1000L * eventActivePredicate.timestampSeconds)))
+ .map(calendarEvent -> calendarEventActiveOn(calendarEvent,
+ new Date(1000L * eventActivePredicate.timestampSeconds)))
.orElse(true);
}
@@ -1384,7 +1388,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
recurrence = new Recur(recurrenceRule.getFrequency().name(), recurrenceRule.getCount());
} else if (recurrenceRule.getUntil() != null) {
recurrence = new Recur(recurrenceRule.getFrequency().name(),
- new net.fortuna.ical4j.model.Date(recurrenceRule.getUntil()));
+ new net.fortuna.ical4j.model.Date(recurrenceRule.getUntil()));
} else {
recurrence = new Recur(recurrenceRule.getFrequency().name(), null);
}
@@ -1395,7 +1399,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
RRule rRule = new RRule(recurrence);
VEvent vEvent = new VEvent(new DateTime(calendarEvent.getStart()),
- new DateTime(calendarEvent.getEnd()), "");
+ new DateTime(calendarEvent.getEnd()), "");
vEvent.getProperties().add(rRule);
Period period = new Period(new DateTime(when), new Dur(0, 0, 1, 0));
PeriodRule periodRule = new PeriodRule(period);
diff --git a/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java b/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java
index 5b7825935..85a8632e2 100644
--- a/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java
+++ b/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java
@@ -24,6 +24,7 @@ import com.vividsolutions.jts.geom.Envelope;
import org.geotools.referencing.GeodeticCalculator;
import org.openremote.model.asset.BaseAssetQuery;
import org.openremote.model.asset.BaseAssetQuery.*;
+import org.openremote.model.geo.GeoJSONPoint;
import org.openremote.model.rules.AssetState;
import org.openremote.model.value.ObjectValue;
@@ -91,9 +92,10 @@ public class AssetQueryPredicate implements Predicate<AssetState> {
}
if (query.location != null) {
- ObjectValue objectValue = assetState.getValueAsObject().orElse(null);
- if (objectValue != null) {
- Coordinate coordinate = new Coordinate(objectValue.getNumber("latitude").orElse(0d), objectValue.getNumber("longitude").orElse(0d));
+ GeoJSONPoint coords = assetState.getValue().flatMap(GeoJSONPoint::fromValue).orElse(null);
+
+ if (coords != null) {
+ Coordinate coordinate = new Coordinate(coords.getY(), coords.getX());
return asPredicate(query.location).test(coordinate);
}
return false;
diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityService.java b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityService.java
index 0da258758..a11748393 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityService.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityService.java
@@ -20,10 +20,12 @@
package org.openremote.manager.security;
import org.openremote.container.Container;
+import org.openremote.container.persistence.PersistenceService;
import org.openremote.container.security.IdentityService;
import org.openremote.container.timer.TimerService;
import org.openremote.container.web.WebService;
+import javax.persistence.EntityManager;
import java.util.Locale;
import java.util.logging.Logger;
@@ -32,10 +34,12 @@ public class ManagerIdentityService extends IdentityService {
private static final Logger LOG = Logger.getLogger(ManagerIdentityService.class.getName());
protected ManagerIdentityProvider identityProvider;
+ protected PersistenceService persistenceService;
@Override
public void init(Container container) throws Exception {
super.init(container);
+ persistenceService = container.getService(PersistenceService.class);
container.getService(WebService.class).getApiSingletons().add(
new TenantResourceImpl(container.getService(TimerService.class), this)
@@ -69,6 +73,31 @@ public class ManagerIdentityService extends IdentityService {
return identityProvider;
}
+ public UserConfiguration getUserConfiguration(String userId) {
+ return persistenceService.doReturningTransaction(entityManager -> getUserConfiguration(entityManager, userId));
+ }
+
+ protected UserConfiguration getUserConfiguration(EntityManager em, String userId) {
+ UserConfiguration userConfiguration = em.find(UserConfiguration.class, userId);
+ if (userConfiguration == null) {
+ userConfiguration = new UserConfiguration(userId);
+ userConfiguration = mergeUserConfiguration(em, userConfiguration);
+ }
+ return userConfiguration;
+ }
+
+ public UserConfiguration mergeUserConfiguration(UserConfiguration userConfiguration) {
+ return persistenceService.doReturningTransaction(entityManager -> mergeUserConfiguration(entityManager, userConfiguration));
+ }
+
+ protected UserConfiguration mergeUserConfiguration(EntityManager em, UserConfiguration userConfiguration) {
+ if (userConfiguration.getUserId() == null || userConfiguration.getUserId().length() == 0) {
+ throw new IllegalArgumentException("User ID must be set on: " + userConfiguration);
+ }
+ return em.merge(userConfiguration);
+ }
+
+
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
diff --git a/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java b/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java
index e3f8d048f..ac41f3c21 100644
--- a/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java
+++ b/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java
@@ -23,6 +23,7 @@ import org.openremote.agent.protocol.simulator.SimulatorProtocol;
import org.openremote.container.Container;
import org.openremote.manager.asset.console.ConsoleResourceImpl;
import org.openremote.manager.rules.geofence.ORConsoleGeofenceAssetAdapter;
+import org.openremote.manager.security.UserConfiguration;
import org.openremote.manager.setup.AbstractManagerSetup;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetAttribute;
@@ -31,6 +32,7 @@ import org.openremote.model.asset.UserAsset;
import org.openremote.model.attribute.*;
import org.openremote.model.console.ConsoleConfiguration;
import org.openremote.model.console.ConsoleProvider;
+import org.openremote.model.geo.GeoJSONPoint;
import org.openremote.model.security.Tenant;
import org.openremote.model.simulator.element.ColorSimulatorElement;
import org.openremote.model.simulator.element.NumberSimulatorElement;
@@ -56,9 +58,9 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
public static final int DEMO_RULE_STATES_APARTMENT_1 = 37;
public static final int DEMO_RULE_STATES_APARTMENT_2 = 11;
public static final int DEMO_RULE_STATES_APARTMENT_3 = 0;
- public static final int DEMO_RULE_STATES_SMART_OFFICE = 2;
+ public static final int DEMO_RULE_STATES_SMART_OFFICE = 1;
public static final int DEMO_RULE_STATES_SMART_HOME = DEMO_RULE_STATES_APARTMENT_1 + DEMO_RULE_STATES_APARTMENT_2 + DEMO_RULE_STATES_APARTMENT_3;
- public static final int DEMO_RULE_STATES_CUSTOMER_A = DEMO_RULE_STATES_SMART_HOME;
+ public static final int DEMO_RULE_STATES_CUSTOMER_A = DEMO_RULE_STATES_SMART_HOME + 1; // 1 is for console location attribute
public static final int DEMO_RULE_STATES_GLOBAL = DEMO_RULE_STATES_CUSTOMER_A + DEMO_RULE_STATES_SMART_OFFICE;
public static final int DEMO_RULE_STATES_APARTMENT_1_WITH_SCENES = DEMO_RULE_STATES_APARTMENT_1 + 28;
public static final int DEMO_RULE_STATES_SMART_HOME_WITH_SCENES = DEMO_RULE_STATES_APARTMENT_1_WITH_SCENES + DEMO_RULE_STATES_APARTMENT_2 + DEMO_RULE_STATES_APARTMENT_3;
@@ -104,8 +106,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
// ################################ Demo assets for 'master' realm ###################################
- ObjectValue locationValue = Values.createObject().put("latitude", 51.44541688237109).put("longitude",
- 5.460315214821094);
+ ObjectValue locationValue = new GeoJSONPoint(5.460315214821094, 51.44541688237109).toValue();
Asset smartOffice = new Asset();
smartOffice.setRealmId(masterTenant.getId());
@@ -367,7 +368,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
// ################################ Demo assets for 'customerA' realm ###################################
- ObjectValue locationValueA = Values.createObject().put("latitude", 51.438000).put("longitude", 5.470945);
+ ObjectValue locationValueA = new GeoJSONPoint(5.470945, 51.438000).toValue();
Asset smartHome = new Asset();
smartHome.setRealmId(customerATenant.getId());
@@ -677,5 +678,11 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(),
keycloakDemoSetup.testuser3Id,
consoleId));
+
+ // ################################ Make users restricted ###################################
+
+ UserConfiguration testuser3Config = identityService.getUserConfiguration(keycloakDemoSetup.testuser3Id);
+ testuser3Config.setRestricted(true);
+ testuser3Config = identityService.mergeUserConfiguration(testuser3Config);
}
}
\ No newline at end of file
diff --git a/model/src/main/java/org/openremote/model/asset/Asset.java b/model/src/main/java/org/openremote/model/asset/Asset.java
index ec9d2c52e..2fafee1ae 100644
--- a/model/src/main/java/org/openremote/model/asset/Asset.java
+++ b/model/src/main/java/org/openremote/model/asset/Asset.java
@@ -29,6 +29,7 @@ import org.openremote.model.attribute.Attribute;
import org.openremote.model.attribute.AttributeDescriptor;
import org.openremote.model.geo.GeoJSON;
import org.openremote.model.geo.GeoJSONFeature;
+import org.openremote.model.geo.GeoJSONFeatureCollection;
import org.openremote.model.geo.GeoJSONPoint;
import org.openremote.model.util.ObservableList;
import org.openremote.model.util.TextUtil;
@@ -38,8 +39,6 @@ import org.openremote.model.value.Values;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
-import java.math.BigDecimal;
-import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@@ -632,82 +631,42 @@ public class Asset implements IdentifiableEntity {
// FUNCTIONAL METHODS BELOW
// ---------------------------------------------------
- //TODO return GeoJSONPoint and remove getPoint
/**
- * Complies to the GeoJSON specification RFC 7946, which means the first element in the array is longitude
- * and the second element is the latitude
+ * Complies to the GeoJSON specification RFC 7946
*/
- public double[] getCoordinates() {
+ public GeoJSONPoint getCoordinates() {
return getAttributesStream()
.filter(attribute -> attribute.getNameOrThrow().equals(LOCATION.getName()))
.findFirst()
- .flatMap(AbstractValueHolder::getValueAsObject)
- .map(obj -> {
- Optional<Double> lat = obj.getNumber("latitude");
- Optional<Double> lng = obj.getNumber("longitude");
- if (lat.isPresent() && lng.isPresent()) {
- return new double[]{lng.get(), lat.get()};
- }
-
- return null;
- })
+ .flatMap(AbstractValueHolder::getValue)
+ .flatMap(GeoJSONPoint::fromValue)
.orElse(null);
}
- public GeoJSONPoint getPoint() {
- if (!hasGeoFeature()) {
- return null;
- }
- return new GeoJSONPoint(getCoordinates());
- }
-
/**
- * Complies to the GeoJSON specification RFC 7946, which means the first element in {link #coordinates} should be longitude
- * and the second element should be latitude
+ * Complies to the GeoJSON specification RFC 7946
*/
- public void setCoordinates(double[] coordinates) {
- if (coordinates == null) {
- removeAttribute(LOCATION.getName());
- } else {
- AssetAttribute locationAttribute = getAttributesStream()
- .filter(attribute -> attribute.getNameOrThrow().equals(LOCATION.getName()))
- .findFirst().orElse(new AssetAttribute(LOCATION.getName(), LOCATION.getType()));
-
- ObjectValue objectValue = locationAttribute.getValueAsObject().orElse(Values.createObject());
- objectValue
- .put("latitude", coordinates[1])
- .put("longitude", coordinates[0]);
- locationAttribute.setValue(objectValue);
+ public void setCoordinates(GeoJSONPoint coordinates) {
+ AssetAttribute locationAttribute = getAttributesStream()
+ .filter(attribute -> attribute.getNameOrThrow().equals(LOCATION.getName()))
+ .findFirst().orElse(new AssetAttribute(LOCATION.getName(), LOCATION.getValueType()));
- replaceAttribute(locationAttribute);
- }
- }
-
- /**
- * - * This assumes {@link #getCoordinates} array index 0 is Lng and index 1 is Lat,
- * - * which is true for PostGIS backend. Because Lat/Lng is the 'right way', we flip
- * - * it here for display. Rounding to 5 decimal places gives us precision of about 1 meter.
- * -
- */
- public String getCoordinatesLabel() {
- return
- new BigDecimal(getCoordinates()[1]).setScale(5, RoundingMode.HALF_UP) + " " +
- new BigDecimal(getCoordinates()[0]).setScale(5, RoundingMode.HALF_UP) + " Lat|Lng";
+ locationAttribute.setValue(coordinates == null ? null : coordinates.toValue());
+ replaceAttribute(locationAttribute);
}
public boolean hasGeoFeature() {
- double[] coordinates = getCoordinates();
- return coordinates != null && coordinates.length == 2;
+ return getCoordinates() != null;
}
public GeoJSON getGeoFeature(int maxNameLength) {
if (!hasGeoFeature())
- return GeoJSON.EMPTY_FEATURE_COLLECTION;
- return new GeoJSON("FeatureCollection").setFeatures(
- new GeoJSONFeature("Feature")
+ return GeoJSONFeatureCollection.EMPTY;
+
+ return new GeoJSONFeatureCollection(
+ new GeoJSONFeature(getCoordinates())
.setProperty("id", getId())
.setProperty("title", TextUtil.ellipsize(getName(), maxNameLength))
- .setGeometry(getPoint())
);
}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java b/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
index 3d43dd212..62afbbf1f 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
@@ -57,6 +57,11 @@ public class AssetAttribute extends Attribute {
super(name, type);
}
+ public AssetAttribute(AttributeDescriptor attributeDescriptor) {
+ super(attributeDescriptor.getName(), attributeDescriptor.getValueType(), attributeDescriptor.getDefaultValue());
+ addMeta(attributeDescriptor.getDefaultMetaItems());
+ }
+
public AssetAttribute(String name, AttributeValueType type, Value value, long timestamp) {
super(name, type, value, timestamp);
}
@@ -496,7 +501,7 @@ public class AssetAttribute extends Attribute {
}
public static AssetAttribute createWithDescriptor(AttributeDescriptor descriptor, Value value) {
- return new AssetAttribute(descriptor.getName(), descriptor.getType(), Optional.ofNullable(value).orElse(descriptor.getDefaultValue()))
+ return new AssetAttribute(descriptor.getName(), descriptor.getValueType(), Optional.ofNullable(value).orElse(descriptor.getDefaultValue()))
.setMeta(descriptor.getDefaultMetaItems());
}
}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
index 72b4545ad..5a8dd863d 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
@@ -208,6 +208,18 @@ public enum AssetMeta implements MetaItemDescriptor {
Values.create(true),
true),
+ /**
+ * Marks the attribute as writable by unauthenticated public clients.
+ */
+ ACCESS_PUBLIC_WRITE(
+ ASSET_META_NAMESPACE + ":accessPublicWrite",
+ ACCESS_PRIVATE,
+ ValueType.BOOLEAN,
+ null,
+ null,
+ Values.create(true),
+ true),
+
// /**
// * RT: This wasn't used anywhere and not really sure when it would be useful so removing for now.
// */
diff --git a/model/src/main/java/org/openremote/model/asset/AssetResource.java b/model/src/main/java/org/openremote/model/asset/AssetResource.java
index 7e34d17a0..eb635b533 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetResource.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetResource.java
@@ -20,9 +20,11 @@
package org.openremote.model.asset;
import jsinterop.annotations.JsType;
+import org.openremote.model.attribute.AttributeType;
import org.openremote.model.geo.GeoJSONPoint;
import org.openremote.model.http.RequestParams;
import org.openremote.model.http.SuccessStatusCode;
+import org.openremote.model.value.ValueType;
import javax.annotation.security.RolesAllowed;
import javax.validation.Valid;
@@ -176,6 +178,10 @@ public interface AssetResource {
* asset in a realm different than its authenticated realm, or if the user is restricted and the asset to update is
* not in the set of linked assets of the restricted user.
* <p>
+ * If the asset or attribute doesn't exist then a 404 status is returned.
+ * <p>
+ * If an attribute is marked as {@link AssetMeta#ACCESS_PUBLIC_WRITE} then the attribute can be written publicly
+ * <p>
* This operation is ultimately asynchronous, any call will return before the actual attribute value is changed in
* any storage or downstream processors. Thus any constraint violation or processing error will not be returned from
* this method, query the system later to determine the actual state and outcome of the write operation. The version
@@ -186,7 +192,6 @@ public interface AssetResource {
@Path("{assetId}/attribute/{attributeName}")
@Consumes(APPLICATION_JSON)
@SuccessStatusCode(204)
- @RolesAllowed({"write:assets"})
@SuppressWarnings("unusable-by-js")
void writeAttributeValue(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId, @PathParam("attributeName") String attributeName, String rawJson);
@@ -262,27 +267,4 @@ public interface AssetResource {
@SuccessStatusCode(200)
@SuppressWarnings("unusable-by-js")
Asset[] getPublicAssets(@BeanParam RequestParams requestParams, @QueryParam("q") String q);
-
- /**
- * Updates the attribute "location" of the asset
- */
- @POST
- @Path("{assetId}/updateLocation")
- @Consumes(APPLICATION_JSON)
- @SuccessStatusCode(204)
- @RolesAllowed({"write:assets"})
- @SuppressWarnings("unusable-by-js")
- void updateLocation(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId, GeoJSONPoint location);
-
- /**
- * Updated the attribute "location" of the public asset
- * <p>
- * Allows un-authenticated 'public' users to update public assets for a realm.
- */
- @POST
- @Path("public/{assetId}/updateLocation")
- @Consumes(APPLICATION_JSON)
- @SuccessStatusCode(204)
- @SuppressWarnings("unusable-by-js")
- void updatePublicAssetLocation(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId, GeoJSONPoint location);
}
diff --git a/model/src/main/java/org/openremote/model/asset/LocationEvent.java b/model/src/main/java/org/openremote/model/asset/LocationEvent.java
index 7879970b7..7d358645d 100644
--- a/model/src/main/java/org/openremote/model/asset/LocationEvent.java
+++ b/model/src/main/java/org/openremote/model/asset/LocationEvent.java
@@ -22,6 +22,7 @@ package org.openremote.model.asset;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.openremote.model.event.shared.SharedEvent;
+import org.openremote.model.geo.GeoJSONPoint;
import java.util.Arrays;
@@ -31,18 +32,15 @@ import java.util.Arrays;
public class LocationEvent extends SharedEvent {
protected String assetId;
- protected double[] coordinates;
+ protected GeoJSONPoint coordinates;
@JsonCreator
public LocationEvent(
@JsonProperty("assetId") String assetId,
- @JsonProperty("coordinates") double[] coordinates,
+ @JsonProperty("coordinates") GeoJSONPoint coordinates,
@JsonProperty("timestamp") long timestamp
) {
super(timestamp);
- if (coordinates != null && coordinates.length != 2) {
- throw new IllegalArgumentException("Coordinates must contain exactly two values (longitude and latitude)");
- }
this.assetId = assetId;
this.coordinates = coordinates;
}
@@ -51,7 +49,7 @@ public class LocationEvent extends SharedEvent {
return assetId;
}
- public double[] getCoordinates() {
+ public GeoJSONPoint getCoordinates() {
return coordinates;
}
@@ -60,7 +58,7 @@ public class LocationEvent extends SharedEvent {
return getClass().getSimpleName() + "{" +
"timestamp=" + timestamp +
", assetId=" + assetId +
- ", coordinates=" + Arrays.toString(coordinates) +
+ ", coordinates=" + (coordinates == null ? "null" : coordinates.toValue()) +
"}";
}
}
diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeDescriptor.java b/model/src/main/java/org/openremote/model/attribute/AttributeDescriptor.java
index 0c6f2f1ea..08b501779 100644
--- a/model/src/main/java/org/openremote/model/attribute/AttributeDescriptor.java
+++ b/model/src/main/java/org/openremote/model/attribute/AttributeDescriptor.java
@@ -25,7 +25,7 @@ public interface AttributeDescriptor {
String getName();
- AttributeValueType getType();
+ AttributeValueType getValueType();
MetaItem[] getDefaultMetaItems();
diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeType.java b/model/src/main/java/org/openremote/model/attribute/AttributeType.java
index a397564ba..8d040b177 100644
--- a/model/src/main/java/org/openremote/model/attribute/AttributeType.java
+++ b/model/src/main/java/org/openremote/model/attribute/AttributeType.java
@@ -62,7 +62,7 @@ public enum AttributeType implements AttributeDescriptor {
}
@Override
- public AttributeValueType getType() {
+ public AttributeValueType getValueType() {
return attributeValueType;
}
diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeValueType.java b/model/src/main/java/org/openremote/model/attribute/AttributeValueType.java
index 30f4d4912..6498aa903 100644
--- a/model/src/main/java/org/openremote/model/attribute/AttributeValueType.java
+++ b/model/src/main/java/org/openremote/model/attribute/AttributeValueType.java
@@ -22,6 +22,7 @@ package org.openremote.model.attribute;
import org.openremote.model.ValidationFailure;
import org.openremote.model.ValueHolder;
import org.openremote.model.asset.AssetMeta;
+import org.openremote.model.geo.GeoJSONPoint;
import org.openremote.model.value.Value;
import org.openremote.model.value.ValueType;
import org.openremote.model.value.Values;
@@ -228,10 +229,13 @@ public enum AttributeValueType {
new MetaItem(FORMAT, Values.create("%0.1f deg"))
),
- LOCATION("map-marker", ValueType.OBJECT, value -> Values.getObject(value)
- .filter(object -> !object.hasKey("latitude") || !object.hasKey("longitude"))
- .map(object -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_INVALID))
- );
+ LOCATION("map-marker", ValueType.OBJECT, value -> {
+ if (value != null && !GeoJSONPoint.fromValue(value).isPresent()) {
+ return Optional.of(new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_INVALID));
+ }
+
+ return Optional.empty();
+ });
public static final String DEFAULT_ICON = "circle-thin";
diff --git a/model/src/main/java/org/openremote/model/console/ConsoleConfiguration.java b/model/src/main/java/org/openremote/model/console/ConsoleConfiguration.java
index 4a96c1ed7..4a2218218 100644
--- a/model/src/main/java/org/openremote/model/console/ConsoleConfiguration.java
+++ b/model/src/main/java/org/openremote/model/console/ConsoleConfiguration.java
@@ -66,10 +66,9 @@ public final class ConsoleConfiguration {
setConsolProviders(asset, providerMap);
asset.replaceAttribute(
- new AssetAttribute(AttributeType.LOCATION.getName(),
- AttributeType.LOCATION.getType())
+ new AssetAttribute(AttributeType.LOCATION)
.setMeta(new MetaItem(RULE_STATE))
- );
+ );
return asset;
}
diff --git a/model/src/main/java/org/openremote/model/geo/GeoJSON.java b/model/src/main/java/org/openremote/model/geo/GeoJSON.java
index a48876529..deae13e18 100644
--- a/model/src/main/java/org/openremote/model/geo/GeoJSON.java
+++ b/model/src/main/java/org/openremote/model/geo/GeoJSON.java
@@ -19,34 +19,28 @@
*/
package org.openremote.model.geo;
-import org.openremote.model.AbstractTypeHolder;
+import com.fasterxml.jackson.annotation.JsonSubTypes;
+import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.openremote.model.value.ArrayValue;
+import org.openremote.model.value.ObjectValue;
import org.openremote.model.value.Values;
-public class GeoJSON extends AbstractTypeHolder {
+@JsonSubTypes({
+ @JsonSubTypes.Type(value = GeoJSONFeatureCollection.class, name = GeoJSONFeatureCollection.TYPE),
+ @JsonSubTypes.Type(value = GeoJSONFeature.class, name = GeoJSONFeature.TYPE)
+})
+@JsonTypeInfo(
+ use = JsonTypeInfo.Id.NAME,
+ include = JsonTypeInfo.As.PROPERTY,
+ property = "type"
+)
+public abstract class GeoJSON {
- public static final GeoJSON EMPTY_FEATURE_COLLECTION = new GeoJSON("FeatureCollection").setEmptyFeatures();
+ protected String type;
- public GeoJSON(String type) {
- super(type);
+ protected GeoJSON(String type) {
+ this.type = type;
}
- public GeoJSON setFeatures(GeoJSONFeature... features) {
- if (features != null) {
- for (int i = 0; i < features.length; i++) {
- GeoJSONFeature feature = features[i];
- ArrayValue array = Values.createArray();
- array.set(i, feature.getObjectValue());
- objectValue.put("features", array);
- }
- } else {
- return setEmptyFeatures();
- }
- return this;
- }
-
- public GeoJSON setEmptyFeatures() {
- objectValue.put("features", Values.createArray());
- return this;
- }
+ public abstract ObjectValue toValue();
}
diff --git a/model/src/main/java/org/openremote/model/geo/GeoJSONFeature.java b/model/src/main/java/org/openremote/model/geo/GeoJSONFeature.java
index 47cd64895..4b90de817 100644
--- a/model/src/main/java/org/openremote/model/geo/GeoJSONFeature.java
+++ b/model/src/main/java/org/openremote/model/geo/GeoJSONFeature.java
@@ -19,35 +19,119 @@
*/
package org.openremote.model.geo;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
import org.openremote.model.AbstractTypeHolder;
import org.openremote.model.value.ObjectValue;
import org.openremote.model.value.Value;
import org.openremote.model.value.Values;
-public class GeoJSONFeature extends AbstractTypeHolder {
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
- public GeoJSONFeature(String type) {
- super(type);
+import static org.openremote.model.util.TextUtil.isNullOrEmpty;
+
+public class GeoJSONFeature extends GeoJSON {
+
+ public static final String TYPE = "Feature";
+ protected GeoJSONGeometry geometry;
+ protected Map<String, String> properties;
+
+ @JsonCreator
+ public GeoJSONFeature(@JsonProperty("geometry") GeoJSONGeometry geometry, @JsonProperty("properties") Map<String, String> properties) {
+ super(TYPE);
+ this.geometry = geometry;
+ this.properties = properties;
}
- public GeoJSONFeature setProperty(String name, String value) {
- return setProperty(name, Values.create(value));
+ public GeoJSONFeature(GeoJSONGeometry geometry) {
+ this(geometry, new HashMap<>());
+ }
+
+ public GeoJSONGeometry getGeometry() {
+ return geometry;
+ }
+
+ public void setGeometry(GeoJSONGeometry geometry) {
+ this.geometry = geometry;
}
- protected GeoJSONFeature setProperty(String name, Value value) {
- ObjectValue properties = objectValue.getObject("properties").orElse(Values.createObject());
+ public Map<String, String> getProperties() {
+ return properties;
+ }
+
+ public GeoJSONFeature setProperties(Map<String, String> properties) {
+ this.properties = properties;
+ return this;
+ }
+
+ public String getProperty(String name) {
+ return properties == null ? null : properties.get(name);
+ }
+
+ public GeoJSONFeature setProperty(String name, String value) {
+ if (properties == null) {
+ properties = new HashMap<>();
+ }
+
properties.put(name, value);
- if (!objectValue.hasKey("properties"))
- objectValue.put("properties", properties);
return this;
}
- public GeoJSONFeature setGeometry(GeoJSONPoint geometry) {
+ @Override
+ public ObjectValue toValue() {
+ ObjectValue objectValue = Values.createObject();
+ objectValue.put("type", type);
+ ObjectValue props = null;
+ ObjectValue geom = null;
+
+ if (properties != null && !properties.isEmpty()) {
+ props = Values.createObject();
+ ObjectValue finalProps = props;
+ properties.forEach((k, v ) -> finalProps.put(k, Values.create(v)));
+ }
+
+ objectValue.put("properties", props);
+
if (geometry != null) {
- objectValue.put("geometry", geometry.getObjectValue());
- } else {
- objectValue.remove("geometry");
+ geom = geometry.toValue();
}
- return this;
+
+ objectValue.put("geometry", geom);
+
+ return objectValue;
+ }
+
+ public static Optional<GeoJSONFeature> fromValue(Value value) {
+ return Values.getObject(value)
+ .map(obj -> {
+ String type = obj.getString("type").orElse(null);
+ GeoJSONGeometry geometry = null;
+ Map<String, String> properties = null;
+ ObjectValue geom = obj.getObject("geometry").orElse(null);
+ ObjectValue props = obj.getObject("properties").orElse(null);
+
+ if (isNullOrEmpty(type)) {
+ return null;
+ }
+
+ if (geom != null) {
+ String geomType = geom.getString("type").orElse("");
+ switch (geomType) {
+ case GeoJSONPoint.TYPE:
+ geometry = GeoJSONPoint.fromValue(geom).orElse(null);
+ break;
+ }
+ }
+
+ if (props != null) {
+ properties = new HashMap<>();
+ Map<String, String> finalProperties = properties;
+ props.stream().forEach(kvp -> Values.getString(kvp.value).ifPresent(v -> finalProperties.put(kvp.key, v)));
+ }
+
+ return new GeoJSONFeature(geometry, properties);
+ });
}
}
diff --git a/model/src/main/java/org/openremote/model/geo/GeoJSONFeatureCollection.java b/model/src/main/java/org/openremote/model/geo/GeoJSONFeatureCollection.java
new file mode 100644
index 000000000..d03b03023
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/geo/GeoJSONFeatureCollection.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.geo;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.openremote.model.value.ArrayValue;
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.Value;
+import org.openremote.model.value.Values;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+
+public class GeoJSONFeatureCollection extends GeoJSON {
+
+ public static final String TYPE = "FeatureCollection";
+ public static final GeoJSONFeatureCollection EMPTY = new GeoJSONFeatureCollection((List<GeoJSONFeature>)null);
+
+ protected List<GeoJSONFeature> features;
+
+ @JsonCreator
+ public GeoJSONFeatureCollection(@JsonProperty("features") GeoJSONFeature... features) {
+ this(Arrays.asList(features));
+ }
+
+ public GeoJSONFeatureCollection(List<GeoJSONFeature> features) {
+ super(TYPE);
+ this.features = features != null ? features : new ArrayList<>(0);
+ }
+
+ public GeoJSONFeature[] getFeatures() {
+ return features.toArray(new GeoJSONFeature[features.size()]);
+ }
+
+ @Override
+ public ObjectValue toValue() {
+ ObjectValue objectValue = Values.createObject();
+ objectValue.put("type", type);
+ ArrayValue feats = Values.createArray();
+ features.forEach(f -> feats.add(f.toValue()));
+ objectValue.put("features", feats);
+ return objectValue;
+ }
+
+ public static Optional<GeoJSONFeatureCollection> fromValue(Value value) {
+ return Values.getObject(value)
+ .map(obj -> {
+ String type = obj.getString("type").orElse(null);
+ if (!TYPE.equalsIgnoreCase(type)) {
+ return null;
+ }
+
+ ArrayList<GeoJSONFeature> features = new ArrayList<>();
+ obj.getArray("features").ifPresent(feats ->
+ feats.stream().forEach(v ->
+ GeoJSONFeature.fromValue(v)
+ .ifPresent(features::add)));
+ return new GeoJSONFeatureCollection(features);
+ });
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/geo/GeoJSONGeometry.java b/model/src/main/java/org/openremote/model/geo/GeoJSONGeometry.java
new file mode 100644
index 000000000..3b2839f68
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/geo/GeoJSONGeometry.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.geo;
+
+public abstract class GeoJSONGeometry extends GeoJSON {
+
+ protected GeoJSONGeometry(String type) {
+ super(type);
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/geo/GeoJSONPoint.java b/model/src/main/java/org/openremote/model/geo/GeoJSONPoint.java
index ac2c0820f..6cb7ec5dd 100644
--- a/model/src/main/java/org/openremote/model/geo/GeoJSONPoint.java
+++ b/model/src/main/java/org/openremote/model/geo/GeoJSONPoint.java
@@ -19,34 +19,93 @@
*/
package org.openremote.model.geo;
-import org.openremote.model.AbstractTypeHolder;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
import org.openremote.model.value.ArrayValue;
+import org.openremote.model.value.ObjectValue;
+import org.openremote.model.value.Value;
import org.openremote.model.value.Values;
-public class GeoJSONPoint extends AbstractTypeHolder {
+import java.util.Optional;
- public GeoJSONPoint() {
- super("Point");
+public class GeoJSONPoint extends GeoJSONGeometry {
+
+ public static final String TYPE = "Point";
+ protected Position coordinates;
+
+ @JsonCreator
+ public GeoJSONPoint(@JsonProperty("coordinates") Position coordinates) {
+ super(TYPE);
+ this.coordinates = coordinates;
}
- public GeoJSONPoint(double[] coordinates) {
- this();
- ArrayValue array = Values.createArray();
- for (int i = 0; i < coordinates.length; i++) {
- array.set(i, coordinates[i]);
- }
- objectValue.put("coordinates", array);
+ public GeoJSONPoint(double x, double y) {
+ this(new Position(x, y));
+ }
+
+ public GeoJSONPoint(double x, double y, double z) {
+ this(new Position(x, y, z));
+ }
+
+ public Position getCoordinates() {
+ return coordinates;
+ }
+
+ public double getX() {
+ return coordinates.getX();
}
- public boolean hasCoordinates() {
- return objectValue.getArray("coordinates").isPresent();
+ public double getY() {
+ return coordinates.getY();
}
- public double getLatitude() {
- return objectValue.getArray("coordinates").map(coordinates -> coordinates.getNumber(1).orElse(0d)).orElse(0d);
+ public Double getZ() {
+ return coordinates.getZ();
}
- public double getLongitude() {
- return objectValue.getArray("coordinates").map(coordinates -> coordinates.getNumber(0).orElse(0d)).orElse(0d);
+ public boolean hasZ() {
+ return coordinates.hasZ();
+ }
+
+ @Override
+ public ObjectValue toValue() {
+ ObjectValue objectValue = Values.createObject();
+ objectValue.put("type", type);
+ ArrayValue coords = Values.createArray();
+ coords.add(Values.create(getX()));
+ coords.add(Values.create(getY()));
+ if (hasZ()) {
+ coords.add(Values.create(getZ()));
+ }
+ objectValue.put("coordinates", coords);
+ return objectValue;
+ }
+
+ public static Optional<GeoJSONPoint> fromValue(Value value) {
+ return Values.getObject(value)
+ .map(obj -> {
+ String type = obj.getString("type").orElse(null);
+ if (!TYPE.equalsIgnoreCase(type)) {
+ return null;
+ }
+
+ ArrayValue coords = obj.getArray("coordinates").orElse(null);
+ if (coords == null || coords.length() < 2 || coords.length() > 3) {
+ return null;
+ }
+
+ Double x = coords.getNumber(0).orElse(null);
+ Double y = coords.getNumber(1).orElse(null);
+ Double z = coords.length() == 3 ? coords.getNumber(3).orElse(null) : null;
+
+ if (x == null || y == null) {
+ return null;
+ }
+ if (z == null) {
+ return new GeoJSONPoint(new Position(x, y));
+ } else {
+ return new GeoJSONPoint(new Position(x, y, z));
+ }
+ });
}
}
diff --git a/model/src/main/java/org/openremote/model/geo/Position.java b/model/src/main/java/org/openremote/model/geo/Position.java
new file mode 100644
index 000000000..c84b03499
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/geo/Position.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright 2017, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.geo;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.JsonDeserializer;
+import com.fasterxml.jackson.databind.JsonSerializer;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+
+import java.io.IOException;
+
+@JsonFormat
+@JsonSerialize(using = Position.PositionSerializer.class)
+@JsonDeserialize(using = Position.PositionDeserializer.class)
+public class Position {
+
+ public static class PositionSerializer extends JsonSerializer<Position> {
+
+ @Override
+ public void serialize(Position value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
+ gen.writeArray(value.values, 0, value.values.length);
+ }
+ }
+
+ public static class PositionDeserializer extends JsonDeserializer<Position> {
+
+ @Override
+ public Position deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
+ double[] values = p.getCodec().readValue(p, double[].class);
+ return new Position(values[0], values[1]);
+ }
+ }
+
+ protected double[] values;
+
+ public Position(double x, double y) {
+ values = new double[] {x, y};
+ }
+
+ public Position(double x, double y, double z) {
+ values = new double[] {x, y, z};
+ }
+
+ public double getX() {
+ return values[0];
+ }
+
+ public double getY() {
+ return values[1];
+ }
+
+ public Double getZ() {
+ return values.length == 3 ? values[2] : null;
+ }
+
+ public boolean hasZ() {
+ return values.length == 3;
+ }
+}
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
index 24b37eab4..92fdd2c8a 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
@@ -451,9 +451,11 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
)
then: "result should match"
- assets.length == 1
+ assets.length == 2
assets[0].id == managerDemoSetup.smartHomeId
assets[0].realmId == keycloakDemoSetup.customerATenant.id
+ assets[1].id == managerDemoSetup.consolesId
+ assets[1].realmId == keycloakDemoSetup.customerATenant.id
when: "the root assets of the given realm are retrieved"
assets = assetResource.queryAssets(null,
@@ -600,8 +602,8 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
apartment2.name == "Apartment 2"
Asset console = assets[5]
- console.id == managerDemoSetup.consolesId
- console.name == "Consoles"
+ console.id == managerDemoSetup.consoleId
+ console.name == "Demo Console"
when: "the root assets of a foreign realm are retrieved"
assets = assetResource.queryAssets(null,
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
index b3f7a8ffe..114506aea 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
@@ -16,6 +16,7 @@ import org.openremote.model.asset.CalendarEventConfiguration
import org.openremote.model.attribute.AttributeType
import org.openremote.model.calendar.CalendarEvent
import org.openremote.model.calendar.RecurrenceRule
+import org.openremote.model.geo.GeoJSONPoint
import org.openremote.model.value.Values
import org.openremote.test.ManagerContainerTrait
import spock.lang.Shared
@@ -399,7 +400,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
)
then: "result should match"
- assets.size() == 5
+ assets.size() == 6
assets.get(0).id == managerDemoSetup.apartment1Id
assets.get(1).id == managerDemoSetup.apartment1LivingroomId
assets.get(1).getAttributesList().size() == 5
@@ -410,6 +411,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
assets.get(2).id == managerDemoSetup.apartment1KitchenId
assets.get(3).id == managerDemoSetup.apartment1HallwayId
assets.get(4).id == managerDemoSetup.apartment2Id
+ assets.get(5).id == managerDemoSetup.consoleId
when: "a query is executed"
assets = assetStorageService.findAll(
@@ -674,7 +676,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
when: "one of the assets in the region is moved"
def lobby = assetStorageService.find(managerDemoSetup.lobbyId, true)
- lobby.replaceAttribute(createWithDescriptor(AttributeType.LOCATION, Values.createObject().put("latitude", 51.44593d).put("longitude", 5.46108d)))
+ lobby.setCoordinates(new GeoJSONPoint(5.46108d, 51.44593d))
lobby = assetStorageService.merge(lobby)
then: "the system should settle down"
@@ -807,7 +809,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
)
then: "the calendar event asset should not be included"
- assets.size() == 5
+ assets.size() == 4
!assets.any {it.name == "Lobby"}
when: "a calendar event filtering query is executed for a future event on a wrong day but correct time"
@@ -820,7 +822,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
)
then: "the calendar event asset should not be included"
- assets.size() == 5
+ assets.size() == 4
!assets.any {it.name == "Lobby"}
when: "a calendar event filtering query is executed inside a valid future event date and time"
@@ -832,20 +834,18 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
.orderBy(new OrderBy(NAME))
)
- then: "all 6 realm assets should be returned"
- assets.size() == 6
+ then: "all 5 realm assets should be returned"
+ assets.size() == 5
assets[0].id == managerDemoSetup.agentId
assets[0].name == "Demo Agent"
- assets[1].id == managerDemoSetup.consoleId
- assets[1].name == "Demo Android Console"
- assets[2].id == managerDemoSetup.thingId
- assets[2].name == "Demo Thing"
- assets[3].id == managerDemoSetup.groundFloorId
- assets[3].name == "Ground Floor"
- assets[4].id == managerDemoSetup.lobbyId
- assets[4].name == "Lobby"
- assets[5].id == managerDemoSetup.smartOfficeId
- assets[5].name == "Smart Office"
+ assets[1].id == managerDemoSetup.thingId
+ assets[1].name == "Demo Thing"
+ assets[2].id == managerDemoSetup.groundFloorId
+ assets[2].name == "Ground Floor"
+ assets[3].id == managerDemoSetup.lobbyId
+ assets[3].name == "Lobby"
+ assets[4].id == managerDemoSetup.smartOfficeId
+ assets[4].name == "Smart Office"
when: "a calendar event filtering query is executed for some time after the last occurrence"
assets = assetStorageService.findAll(
@@ -857,7 +857,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
)
then: "the calendar event asset should not be included"
- assets.size() == 5
+ assets.size() == 4
!assets.any {it.name == "Lobby"}
}
}
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy
index 8a346b058..ce60734ef 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy
@@ -106,7 +106,7 @@ class AssetUserLinkingTest extends Specification implements ManagerContainerTrai
userAssets = assetResource.getUserAssetLinks(null, keycloakDemoSetup.customerATenant.id, keycloakDemoSetup.testuser3Id, null)
then: "result should match"
- userAssets.length == 5
+ userAssets.length == 6
when: "the realm and user don't match"
assetResource.getUserAssetLinks(null, keycloakDemoSetup.customerBTenant.id, keycloakDemoSetup.testuser3Id, null)
@@ -164,7 +164,6 @@ class AssetUserLinkingTest extends Specification implements ManagerContainerTrai
userAssets = assetResource.getUserAssetLinks(null, keycloakDemoSetup.customerATenant.id, keycloakDemoSetup.testuser2Id, null)
then: "result should match"
- identityService.getIdentityProvider().isRestrictedUser(keycloakDemoSetup.testuser2Id)
userAssets.length == 1
userAssets.any {
it.id.realmId == keycloakDemoSetup.customerATenant.id &&
@@ -181,7 +180,6 @@ class AssetUserLinkingTest extends Specification implements ManagerContainerTrai
userAssets = assetResource.getUserAssetLinks(null, keycloakDemoSetup.customerATenant.id, keycloakDemoSetup.testuser2Id, null)
then: "result should match"
- !identityService.getIdentityProvider().isRestrictedUser(keycloakDemoSetup.testuser2Id)
userAssets.length == 0
cleanup: "the server should be stopped"
diff --git a/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovy b/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovy
index fe5ef7f04..744e8ffc5 100644
--- a/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovy
@@ -33,6 +33,7 @@ import org.openremote.model.attribute.AttributeRef
import org.openremote.model.attribute.MetaItem
import org.openremote.model.event.shared.EventSubscription
import org.openremote.model.event.shared.SharedEvent
+import org.openremote.model.geo.GeoJSONPoint
import org.openremote.model.value.Values
import org.openremote.test.ClientEventService
import org.openremote.test.GwtClientTrait
@@ -136,8 +137,7 @@ class ClientEventTest extends Specification implements ManagerContainerTrait, Gw
and: "an assets location is changed"
def asset = assetStorageService.find(managerDemoSetup.thingId, true)
- double[] coordinates = [120.1d, 50.43d]
- asset.setCoordinates(coordinates)
+ asset.setCoordinates(new GeoJSONPoint(120.1d, 50.43d))
asset = assetStorageService.merge(asset)
then: "the location event should have been received"
@@ -145,8 +145,8 @@ class ClientEventTest extends Specification implements ManagerContainerTrait, Gw
assert collectedSharedEvents.size() == 1
assert collectedSharedEvents[0] instanceof LocationEvent
assert (collectedSharedEvents[0] as LocationEvent).assetId == managerDemoSetup.thingId
- assert (collectedSharedEvents[0] as LocationEvent).coordinates[0] == 120.1d
- assert (collectedSharedEvents[0] as LocationEvent).coordinates[1] == 50.43d
+ assert (collectedSharedEvents[0] as LocationEvent).coordinates.x == 120.1d
+ assert (collectedSharedEvents[0] as LocationEvent).coordinates.y == 50.43d
}
when: "the assets location is set to null"
@@ -162,8 +162,7 @@ class ClientEventTest extends Specification implements ManagerContainerTrait, Gw
}
when: "the location is changed"
- coordinates = [-10.11d, -50.233d]
- asset.setCoordinates(coordinates)
+ asset.setCoordinates(new GeoJSONPoint(-10.11d, -50.233d))
asset = assetStorageService.merge(asset)
then: "the location event should have been received"
@@ -171,13 +170,12 @@ class ClientEventTest extends Specification implements ManagerContainerTrait, Gw
assert collectedSharedEvents.size() == 3
assert collectedSharedEvents[2] instanceof LocationEvent
assert (collectedSharedEvents[2] as LocationEvent).assetId == managerDemoSetup.thingId
- assert (collectedSharedEvents[2] as LocationEvent).coordinates[0] == -10.11d
- assert (collectedSharedEvents[2] as LocationEvent).coordinates[1] == -50.233d
+ assert (collectedSharedEvents[2] as LocationEvent).coordinates.x == -10.11d
+ assert (collectedSharedEvents[2] as LocationEvent).coordinates.y == -50.233d
}
when: "the location is set with the same value"
- coordinates = [-10.11d, -50.233d]
- asset.setCoordinates(coordinates)
+ asset.setCoordinates(new GeoJSONPoint(-10.11d, -50.233d))
asset = assetStorageService.merge(asset)
then: "no location event should have been received"
diff --git a/test/src/test/groovy/org/openremote/test/protocol/KNXProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/KNXProtocolTest.groovy
index 4ae9e833c..b3a361fee 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/KNXProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/KNXProtocolTest.groovy
@@ -19,6 +19,7 @@
*/
package org.openremote.test.protocol
+import org.apache.commons.lang3.SystemUtils
import org.openremote.model.asset.Asset
import tuwien.auto.calimero.server.knxnetip.DefaultServiceContainer
@@ -55,7 +56,8 @@ class KNXProtocolTest extends Specification implements ManagerContainerTrait {
def conditions = new PollingConditions(timeout: 10, initialDelay: 1, delay: 1)
and: "the KNX emulation server is started"
- def configUri = getClass().getResource("/org/openremote/test/protocol/knx/knx-server-config.xml").toURI().toString()
+ def configFile = SystemUtils.IS_OS_MAC ? "/org/openremote/test/protocol/knx/knx-server-config-mac.xml" : "/org/openremote/test/protocol/knx/knx-server-config.xml"
+ def configUri = getClass().getResource(configFile).toURI().toString()
def knxEmulationServer = new Launcher(configUri)
def sc = knxEmulationServer.xml.svcContainers.remove(0)
def sc2 = new DefaultServiceContainer(
@@ -157,8 +159,11 @@ class KNXProtocolTest extends Specification implements ManagerContainerTrait {
}
cleanup: "the server should be stopped"
+ if (knxEmulationServer != null) {
+ knxEmulationServer.quit()
+ }
stopContainer(container)
- knxEmulationServer.quit()
+
}
}
\ No newline at end of file
diff --git a/test/src/test/groovy/org/openremote/test/protocol/http/HttpServerProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/http/HttpServerProtocolTest.groovy
index 0cfef64ee..5e5a90a66 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/http/HttpServerProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/http/HttpServerProtocolTest.groovy
@@ -30,6 +30,7 @@ import org.openremote.model.asset.AssetAttribute
import org.openremote.model.asset.AssetType
import org.openremote.model.attribute.AttributeValueType
import org.openremote.model.attribute.MetaItem
+import org.openremote.model.geo.GeoJSONPoint
import org.openremote.model.value.ObjectValue
import org.openremote.model.value.Values
import org.openremote.test.ManagerContainerTrait
@@ -333,8 +334,7 @@ class HttpServerProtocolTest extends Specification implements ManagerContainerTr
testAsset.setAttributes(
new AssetAttribute("attribute1", AttributeValueType.STRING, Values.create("Test"))
)
- double[] coordinates = [1d, 2d]
- testAsset.setCoordinates(coordinates)
+ testAsset.setCoordinates(new GeoJSONPoint(1d, 2d))
authenticatedTestResource.postAsset(testAsset)
then: "the asset should be stored in the test protocol"
@@ -343,8 +343,8 @@ class HttpServerProtocolTest extends Specification implements ManagerContainerTr
assert testServerProtocol.resource1.postedAssets.get(0).name == "Test Asset"
assert testServerProtocol.resource1.postedAssets.get(0).hasTypeWellKnown()
assert testServerProtocol.resource1.postedAssets.get(0).wellKnownType == AssetType.THING
- assert testServerProtocol.resource1.postedAssets.get(0).coordinates[0] == 1d
- assert testServerProtocol.resource1.postedAssets.get(0).coordinates[1] == 2d
+ assert testServerProtocol.resource1.postedAssets.get(0).coordinates.x == 1d
+ assert testServerProtocol.resource1.postedAssets.get(0).coordinates.y == 2d
}
when: "the authenticated test resource is used to get an asset"
@@ -353,8 +353,8 @@ class HttpServerProtocolTest extends Specification implements ManagerContainerTr
then: "the asset should match the posted asset"
assert asset.name == testAsset.name
assert asset.wellKnownType == testAsset.wellKnownType
- assert asset.coordinates[0] == testAsset.coordinates[0]
- assert asset.coordinates[1] == testAsset.coordinates[1]
+ assert asset.coordinates.x == testAsset.coordinates.x
+ assert asset.coordinates.y == testAsset.coordinates.y
when: "the un-authenticated test resource is used to post an asset"
testResource.postAsset(testAsset)
@@ -392,8 +392,7 @@ class HttpServerProtocolTest extends Specification implements ManagerContainerTr
testAsset.setAttributes(
new AssetAttribute("attribute2", AttributeValueType.STRING, Values.create("Test"))
)
- coordinates = [3d, 4d]
- testAsset.setCoordinates(coordinates)
+ testAsset.setCoordinates(new GeoJSONPoint(3d, 4d))
authenticatedTestResource.postAsset(testAsset)
then: "the asset should be stored in the test protocol"
@@ -402,8 +401,8 @@ class HttpServerProtocolTest extends Specification implements ManagerContainerTr
assert testServerProtocol.resource1.postedAssets.get(1).name == "Test Asset 2"
assert testServerProtocol.resource1.postedAssets.get(1).hasTypeWellKnown()
assert testServerProtocol.resource1.postedAssets.get(1).wellKnownType == AssetType.THING
- assert testServerProtocol.resource1.postedAssets.get(1).coordinates[0] == 3d
- assert testServerProtocol.resource1.postedAssets.get(1).coordinates[1] == 4d
+ assert testServerProtocol.resource1.postedAssets.get(1).coordinates.x == 3d
+ assert testServerProtocol.resource1.postedAssets.get(1).coordinates.y == 4d
}
when: "the new test resource is used to get an asset"
@@ -412,8 +411,8 @@ class HttpServerProtocolTest extends Specification implements ManagerContainerTr
then: "the asset should match the posted asset"
assert asset.name == testAsset.name
assert asset.wellKnownType == testAsset.wellKnownType
- assert asset.coordinates[0] == testAsset.coordinates[0]
- assert asset.coordinates[1] == testAsset.coordinates[1]
+ assert asset.coordinates.x == testAsset.coordinates.x
+ assert asset.coordinates.y == testAsset.coordinates.y
when: "a protocol configuration is deleted"
agent.removeAttribute("protocolConfig")
diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy
index 8b7d93003..5858b6245 100644
--- a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy
@@ -1,8 +1,8 @@
package org.openremote.test.rules.residence
+import com.google.firebase.messaging.Message
import org.openremote.manager.asset.AssetProcessingService
import org.openremote.manager.asset.AssetStorageService
-import org.openremote.manager.notification.FCMBaseMessage
import org.openremote.manager.notification.FCMDeliveryService
import org.openremote.manager.notification.NotificationService
import org.openremote.manager.rules.RulesEngine
@@ -34,10 +34,7 @@ class ResidenceNotifyAlarmTriggerTest extends Specification implements ManagerCo
given: "the container environment is started"
def conditions = new PollingConditions(timeout: 15, delay: 1)
def serverPort = findEphemeralPort()
- def container = startContainerWithPseudoClock(defaultConfig(serverPort) << [
- (NOTIFICATION_FIREBASE_API_KEY): "test",
- (NOTIFICATION_FIREBASE_URL): "test"
- ], defaultServices())
+ def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())
def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
def rulesService = container.getService(RulesService.class)
@@ -48,8 +45,12 @@ class ResidenceNotifyAlarmTriggerTest extends Specification implements ManagerCo
and: "a mock FCM delivery service"
def mockFCMDeliveryService = Spy(FCMDeliveryService, constructorArgs: [container]) {
+ // Assume valid
+ isValid() >> {
+ return true
+ }
// Always "deliver" to FCM
- sendMessage(_ as FCMBaseMessage) >> {
+ sendMessage(_ as Message) >> {
return true
}
}
@@ -127,8 +128,7 @@ class ResidenceNotifyAlarmTriggerTest extends Specification implements ManagerCo
assert alerts[0].title == "Apartment Alarm"
assert alerts[0].message.startsWith("Aanwezigheid in Living Room")
assert alerts[0].actions.length() == 2
- assert alerts[0].actions.getObject(0).orElse(null) == new AlertAction("Details", ActionType.LINK).objectValue
- assert alerts[0].appUrl == "#security"
+ assert alerts[0].actions.getObject(0).orElse(null) == new AlertAction("Details", ActionType.LINK, "#security").objectValue
assert alerts[0].actions.getObject(1).orElse(null) == new AlertAction("Alarm uit", ActionType.ACTUATOR, managerDemoSetup.apartment1Id, "alarmEnabled", Values.create(false).toJson()).objectValue
}
diff --git a/test/src/test/groovy/org/openremote/test/user/NotificationServiceTest.groovy b/test/src/test/groovy/org/openremote/test/user/NotificationServiceTest.groovy
index 9d71b9160..2454955af 100644
--- a/test/src/test/groovy/org/openremote/test/user/NotificationServiceTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/user/NotificationServiceTest.groovy
@@ -1,5 +1,6 @@
package org.openremote.test.user
+import com.google.firebase.messaging.Message
import org.openremote.container.timer.TimerService
import org.openremote.manager.notification.FCMBaseMessage
import org.openremote.manager.notification.FCMDeliveryService
@@ -31,17 +32,18 @@ class NotificationServiceTest extends Specification implements ManagerContainerT
given: "the server container is started"
def serverPort = findEphemeralPort()
- def container = startContainer(defaultConfig(serverPort) << [
- (NOTIFICATION_FIREBASE_API_KEY): "test",
- (NOTIFICATION_FIREBASE_URL): "test"
- ], defaultServices())
+ def container = startContainer(defaultConfig(serverPort), defaultServices())
def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
and: "a mock FCM delivery service"
def mockFCMDeliveryService = Spy(FCMDeliveryService, constructorArgs: [container]) {
+ // Assume valid
+ isValid() >> {
+ return true
+ }
// Always "deliver" to FCM
- sendMessage(_ as FCMBaseMessage) >> {
+ sendMessage(_ as Message) >> {
return true
}
}
diff --git a/test/src/test/resources/org/openremote/test/protocol/knx/knx-server-config-mac.xml b/test/src/test/resources/org/openremote/test/protocol/knx/knx-server-config-mac.xml
new file mode 100644
index 000000000..72b270166
--- /dev/null
+++ b/test/src/test/resources/org/openremote/test/protocol/knx/knx-server-config-mac.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Calimero 2 server settings -->
+<knxServer name="knx-server" friendlyName="Calimero KNXnet/IP Test Server">
+
+ <!-- KNXnet/IP search & discovery -->
+ <discovery listenNetIf="lo0" outgoingNetIf="lo0" activate="false" />
+
+ <!-- Provides the KNXnet/IP-side configuration for access to one KNX subnet -->
+ <serviceContainer activate="true" routing="false" networkMonitoring="false" udpPort="3671" listenNetIf="lo0" reuseCtrlEP="false">
+ <knxAddress type="individual">1.1.1</knxAddress>
+ <knxSubnet type="user-supplied" class="org.openremote.test.KNXTestingNetworkLink">1.1.1</knxSubnet>
+
+ <!-- Additional KNX individual addresses assigned to KNXnet/IP connections (optional) -->
+ <additionalAddresses>
+ <knxAddress type="individual">1.1.10</knxAddress>
+ <knxAddress type="individual">1.1.11</knxAddress>
+ <knxAddress type="individual">1.1.12</knxAddress>
+ <knxAddress type="individual">1.1.13</knxAddress>
+ </additionalAddresses>
+ </serviceContainer>
+
+</knxServer>
diff --git a/test/src/test/resources/org/openremote/test/protocol/knx/knx-server-config.xml b/test/src/test/resources/org/openremote/test/protocol/knx/knx-server-config.xml
index 72b270166..f02f6936a 100644
--- a/test/src/test/resources/org/openremote/test/protocol/knx/knx-server-config.xml
+++ b/test/src/test/resources/org/openremote/test/protocol/knx/knx-server-config.xml
@@ -3,10 +3,10 @@
<knxServer name="knx-server" friendlyName="Calimero KNXnet/IP Test Server">
<!-- KNXnet/IP search & discovery -->
- <discovery listenNetIf="lo0" outgoingNetIf="lo0" activate="false" />
+ <discovery listenNetIf="lo" outgoingNetIf="lo" activate="false" />
<!-- Provides the KNXnet/IP-side configuration for access to one KNX subnet -->
- <serviceContainer activate="true" routing="false" networkMonitoring="false" udpPort="3671" listenNetIf="lo0" reuseCtrlEP="false">
+ <serviceContainer activate="true" routing="false" networkMonitoring="false" udpPort="3671" listenNetIf="lo" reuseCtrlEP="false">
<knxAddress type="individual">1.1.1</knxAddress>
<knxSubnet type="user-supplied" class="org.openremote.test.KNXTestingNetworkLink">1.1.1</knxSubnet>