Skip to content

armgit / core

Public Imported from GitHub
0

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

Rules: Add `GeoJSONGeofencePredicate` for checking if a set of coordinates is inside a `GeoJSONFeatureCollection` (#2273)

Panos Kalogeropoulosbf0e9a289b05
diff --git a/model/src/main/java/org/openremote/model/geo/GeoJSONGeometry.java b/model/src/main/java/org/openremote/model/geo/GeoJSONGeometry.java
index b1f6081d5..a7e494f34 100644
--- a/model/src/main/java/org/openremote/model/geo/GeoJSONGeometry.java
+++ b/model/src/main/java/org/openremote/model/geo/GeoJSONGeometry.java
@@ -23,7 +23,9 @@ import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonSubTypes({
- @JsonSubTypes.Type(GeoJSONPoint.class)
+ @JsonSubTypes.Type(value = GeoJSONPoint.class),
+ @JsonSubTypes.Type(value = GeoJSONPolygon.class),
+ @JsonSubTypes.Type(value = GeoJSONMultiPolygon.class)
})
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
diff --git a/model/src/main/java/org/openremote/model/geo/GeoJSONMultiPolygon.java b/model/src/main/java/org/openremote/model/geo/GeoJSONMultiPolygon.java
new file mode 100644
index 000000000..cdb642fb8
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/geo/GeoJSONMultiPolygon.java
@@ -0,0 +1,221 @@
+/*
+ * Copyright 2025, 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.*;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+import com.fasterxml.jackson.databind.util.StdConverter;
+import org.locationtech.jts.geom.Coordinate;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+
+import static org.openremote.model.geo.GeoJSONMultiPolygon.TYPE;
+
+/**
+ * Represents a GeoJSON MultiPolygon geometry.
+ * <p>
+ * A MultiPolygon is an array of Polygon coordinate arrays. Each polygon can have holes.
+ */
+@JsonTypeName(TYPE)
+public class GeoJSONMultiPolygon extends GeoJSONGeometry {
+
+ public static class CoordinateListConverter extends StdConverter<List<List<Coordinate[]>>, double[][][][]> {
+
+ @Override
+ public double[][][][] convert(List<List<Coordinate[]>> polygons) {
+ if (polygons == null || polygons.isEmpty()) {
+ return new double[0][][][];
+ }
+
+ double[][][][] result = new double[polygons.size()][][][];
+ for (int i = 0; i < polygons.size(); i++) {
+ List<Coordinate[]> rings = polygons.get(i);
+ result[i] = new double[rings.size()][][];
+ for (int j = 0; j < rings.size(); j++) {
+ Coordinate[] ring = rings.get(j);
+ result[i][j] = new double[ring.length][];
+ for (int k = 0; k < ring.length; k++) {
+ Coordinate coord = ring[k];
+ if (Double.isNaN(coord.getZ())) {
+ result[i][j][k] = new double[]{coord.x, coord.y};
+ } else {
+ result[i][j][k] = new double[]{coord.x, coord.y, coord.getZ()};
+ }
+ }
+ }
+ }
+ return result;
+ }
+ }
+
+ public static final String TYPE = "MultiPolygon";
+
+ @JsonProperty
+ @JsonFormat(shape = JsonFormat.Shape.ARRAY)
+ @JsonSerialize(converter = CoordinateListConverter.class)
+ protected List<List<Coordinate[]>> coordinates;
+
+ @JsonCreator
+ public GeoJSONMultiPolygon(@JsonProperty("coordinates") double[][][][] coordinates) {
+ super(TYPE);
+ if(coordinates == null) {
+ throw new IllegalArgumentException("Coordinates for MultiPolygon cannot be null");
+ }
+
+ if (coordinates.length == 0) {
+ throw new IllegalArgumentException("MultiPolygon must have at least one polygon");
+ }
+
+ this.coordinates = new ArrayList<>();
+ for (double[][][] polygon : coordinates) {
+ if (polygon.length == 0) {
+ throw new IllegalArgumentException("Each polygon must have at least one ring (exterior ring)");
+ }
+
+ List<Coordinate[]> rings = new ArrayList<>();
+ for (double[][] ring : polygon) {
+ if (ring.length < 4) {
+ throw new IllegalArgumentException("Each ring must have at least 4 coordinates (forming a closed ring)");
+ }
+
+ Coordinate[] coordRing = new Coordinate[ring.length];
+ for (int i = 0; i < ring.length; i++) {
+ double[] coord = ring[i];
+ if (coord.length < 2) {
+ throw new IllegalArgumentException("Each coordinate must have at least 2 values (longitude, latitude)");
+ }
+ if (coord.length > 3) {
+ throw new IllegalArgumentException("Each coordinate can have at most 3 values (longitude, latitude, altitude)");
+ }
+
+ double x = Math.min(180d, Math.max(-180d, coord[0]));
+ double y = Math.min(90d, Math.max(-90d, coord[1]));
+
+ if (coord.length >= 3) {
+ coordRing[i] = new Coordinate(x, y, coord[2]);
+ } else {
+ coordRing[i] = new Coordinate(x, y);
+ }
+ }
+ rings.add(coordRing);
+ }
+ this.coordinates.add(rings);
+ }
+ }
+
+ /**
+ * Create a MultiPolygon from multiple GeoJSONPolygon objects
+ */
+ public GeoJSONMultiPolygon(GeoJSONPolygon... polygons) {
+ super(TYPE);
+ if(polygons == null) {
+ throw new IllegalArgumentException("polygons must not be null");
+ }
+
+ if (polygons.length == 0) {
+ throw new IllegalArgumentException("MultiPolygon must have at least one polygon");
+ }
+
+ this.coordinates = new ArrayList<>();
+ for (GeoJSONPolygon polygon : polygons) {
+ this.coordinates.add(polygon.getCoordinates());
+ }
+ }
+
+ /**
+ * Create a MultiPolygon from coordinate arrays (each representing a simple polygon without holes)
+ */
+ public GeoJSONMultiPolygon(List<Coordinate[]> polygonRings) {
+ super(TYPE);
+ Objects.requireNonNull(polygonRings);
+
+ if (polygonRings.isEmpty()) {
+ throw new IllegalArgumentException("MultiPolygon must have at least one polygon");
+ }
+
+ this.coordinates = new ArrayList<>();
+ for (Coordinate[] ring : polygonRings) {
+ if (ring.length < 4) {
+ throw new IllegalArgumentException("Each ring must have at least 4 coordinates");
+ }
+ List<Coordinate[]> polygon = new ArrayList<>();
+ polygon.add(clampCoordinates(ring));
+ this.coordinates.add(polygon);
+ }
+ }
+
+ private static Coordinate[] clampCoordinates(Coordinate[] coords) {
+ Coordinate[] result = new Coordinate[coords.length];
+ for (int i = 0; i < coords.length; i++) {
+ Coordinate coord = coords[i];
+ double x = Math.min(180d, Math.max(-180d, coord.x));
+ double y = Math.min(90d, Math.max(-90d, coord.y));
+ result[i] = Double.isNaN(coord.getZ()) ? new Coordinate(x, y) : new Coordinate(x, y, coord.getZ());
+ }
+ return result;
+ }
+
+ public List<List<Coordinate[]>> getCoordinates() {
+ return coordinates;
+ }
+
+ @JsonIgnore
+ public int getPolygonCount() {
+ return coordinates.size();
+ }
+
+ @JsonIgnore
+ public List<Coordinate[]> getPolygon(int index) {
+ if (index < 0 || index >= coordinates.size()) {
+ throw new IndexOutOfBoundsException("Polygon index out of bounds: " + index);
+ }
+ return coordinates.get(index);
+ }
+
+ @JsonIgnore
+ public List<GeoJSONPolygon> getPolygons() {
+ List<GeoJSONPolygon> polygons = new ArrayList<>();
+ for (List<Coordinate[]> rings : coordinates) {
+ if (rings.isEmpty()) continue;
+
+ Coordinate[] exteriorRing = rings.get(0);
+ if (rings.size() == 1) {
+ polygons.add(new GeoJSONPolygon(exteriorRing));
+ } else {
+ Coordinate[][] holes = rings.subList(1, rings.size()).toArray(new Coordinate[0][]);
+ polygons.add(new GeoJSONPolygon(exteriorRing, holes));
+ }
+ }
+ return polygons;
+ }
+
+ @Override
+ public String toString() {
+ int totalRings = coordinates.stream().mapToInt(List::size).sum();
+ return "GeoJSONMultiPolygon{" +
+ "polygons=" + coordinates.size() +
+ ", totalRings=" + totalRings +
+ '}';
+ }
+}
+
diff --git a/model/src/main/java/org/openremote/model/geo/GeoJSONPolygon.java b/model/src/main/java/org/openremote/model/geo/GeoJSONPolygon.java
new file mode 100644
index 000000000..16d771ad3
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/geo/GeoJSONPolygon.java
@@ -0,0 +1,198 @@
+/*
+ * Copyright 2025, 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.*;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+import com.fasterxml.jackson.databind.util.StdConverter;
+import org.locationtech.jts.geom.Coordinate;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+import static org.openremote.model.geo.GeoJSONPolygon.TYPE;
+
+/**
+ * Represents a GeoJSON Polygon geometry.
+ * <p>
+ * A Polygon is defined by one or more linear rings. The first ring is the exterior ring (outer boundary),
+ * and any subsequent rings are interior rings (holes).
+ * <p>
+ * Each linear ring is a closed coordinate array where the first and last coordinates must be identical.
+ */
+@JsonTypeName(TYPE)
+public class GeoJSONPolygon extends GeoJSONGeometry {
+
+ public static class CoordinateArrayListConverter extends StdConverter<List<Coordinate[]>, double[][][]> {
+
+ @Override
+ public double[][][] convert(List<Coordinate[]> rings) {
+ if (rings == null || rings.isEmpty()) {
+ return new double[0][][];
+ }
+
+ double[][][] result = new double[rings.size()][][];
+ for (int i = 0; i < rings.size(); i++) {
+ Coordinate[] ring = rings.get(i);
+ result[i] = new double[ring.length][];
+ for (int j = 0; j < ring.length; j++) {
+ Coordinate coord = ring[j];
+ if (Double.isNaN(coord.getZ())) {
+ result[i][j] = new double[]{coord.x, coord.y};
+ } else {
+ result[i][j] = new double[]{coord.x, coord.y, coord.getZ()};
+ }
+ }
+ }
+ return result;
+ }
+ }
+
+ public static final String TYPE = "Polygon";
+
+ @JsonProperty
+ @JsonFormat(shape = JsonFormat.Shape.ARRAY)
+ @JsonSerialize(converter = CoordinateArrayListConverter.class)
+ protected List<Coordinate[]> coordinates;
+
+ @JsonCreator
+ public GeoJSONPolygon(@JsonProperty("coordinates") double[][][] coordinates) {
+ super(TYPE);
+ Objects.requireNonNull(coordinates);
+
+ if (coordinates.length == 0) {
+ throw new IllegalArgumentException("Polygon must have at least one ring (exterior ring)");
+ }
+
+ this.coordinates = new ArrayList<>();
+ for (double[][] ring : coordinates) {
+ if (ring.length < 4) {
+ throw new IllegalArgumentException("Each ring must have at least 4 coordinates (forming a closed ring)");
+ }
+
+ Coordinate[] coordRing = new Coordinate[ring.length];
+ for (int i = 0; i < ring.length; i++) {
+ double[] coord = ring[i];
+ if (coord.length < 2) {
+ throw new IllegalArgumentException("Each coordinate must have at least 2 values (longitude, latitude)");
+ }
+
+ // Ensure we reject coordinates with more than 3 values (lon, lat, [alt]) for consistency
+ if (coord.length > 3) {
+ throw new IllegalArgumentException("Each coordinate can have at most 3 values (longitude, latitude, altitude)");
+ }
+
+ double x = Math.min(180d, Math.max(-180d, coord[0]));
+ double y = Math.min(90d, Math.max(-90d, coord[1]));
+
+ if (coord.length >= 3) {
+ coordRing[i] = new Coordinate(x, y, coord[2]);
+ } else {
+ coordRing[i] = new Coordinate(x, y);
+ }
+ }
+ this.coordinates.add(coordRing);
+ }
+ }
+
+ /**
+ * Create a simple polygon with only an exterior ring (no holes)
+ */
+ public GeoJSONPolygon(Coordinate[] exteriorRing) {
+ this(new double[][][]{coordinateArrayToDoubleArray(exteriorRing)});
+ }
+
+ /**
+ * Create a polygon with an exterior ring and optional holes
+ */
+ public GeoJSONPolygon(Coordinate[] exteriorRing, Coordinate[]... holes) {
+ super(TYPE);
+ Objects.requireNonNull(exteriorRing);
+
+ if (exteriorRing.length < 4) {
+ throw new IllegalArgumentException("Exterior ring must have at least 4 coordinates");
+ }
+
+ this.coordinates = new ArrayList<>();
+ this.coordinates.add(clampCoordinates(exteriorRing));
+
+ if (holes != null) {
+ for (Coordinate[] hole : holes) {
+ if (hole.length < 4) {
+ throw new IllegalArgumentException("Each hole must have at least 4 coordinates");
+ }
+ this.coordinates.add(clampCoordinates(hole));
+ }
+ }
+ }
+
+ private static Coordinate[] clampCoordinates(Coordinate[] coords) {
+ Coordinate[] result = new Coordinate[coords.length];
+ for (int i = 0; i < coords.length; i++) {
+ Coordinate coord = coords[i];
+ double x = Math.min(180d, Math.max(-180d, coord.x));
+ double y = Math.min(90d, Math.max(-90d, coord.y));
+ result[i] = Double.isNaN(coord.getZ()) ? new Coordinate(x, y) : new Coordinate(x, y, coord.getZ());
+ }
+ return result;
+ }
+
+ private static double[][] coordinateArrayToDoubleArray(Coordinate[] coords) {
+ double[][] result = new double[coords.length][];
+ for (int i = 0; i < coords.length; i++) {
+ Coordinate coord = coords[i];
+ if (Double.isNaN(coord.getZ())) {
+ result[i] = new double[]{coord.x, coord.y};
+ } else {
+ result[i] = new double[]{coord.x, coord.y, coord.getZ()};
+ }
+ }
+ return result;
+ }
+
+ public List<Coordinate[]> getCoordinates() {
+ return coordinates;
+ }
+
+ @JsonIgnore
+ public Coordinate[] getExteriorRing() {
+ return coordinates.isEmpty() ? new Coordinate[0] : coordinates.getFirst();
+ }
+
+ @JsonIgnore
+ public List<Coordinate[]> getHoles() {
+ return coordinates.size() > 1 ? coordinates.subList(1, coordinates.size()) : new ArrayList<>();
+ }
+
+ @JsonIgnore
+ public boolean hasHoles() {
+ return coordinates.size() > 1;
+ }
+
+ @Override
+ public String toString() {
+ return "GeoJSONPolygon{" +
+ "rings=" + coordinates.size() +
+ ", exteriorRingPoints=" + (coordinates.isEmpty() ? 0 : coordinates.getFirst().length) +
+ ", holes=" + (coordinates.size() - 1) +
+ '}';
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/query/filter/GeoJSONGeofencePredicate.java b/model/src/main/java/org/openremote/model/query/filter/GeoJSONGeofencePredicate.java
new file mode 100644
index 000000000..293717184
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/query/filter/GeoJSONGeofencePredicate.java
@@ -0,0 +1,284 @@
+/*
+ * Copyright 2025, 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.query.filter;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.locationtech.jts.geom.*;
+import org.openremote.model.geo.*;
+import org.openremote.model.util.JSONSchemaUtil.JsonSchemaDescription;
+import org.openremote.model.util.JSONSchemaUtil.JsonSchemaTitle;
+import org.openremote.model.util.ValueUtil;
+
+import java.util.Objects;
+import java.util.function.Predicate;
+import java.util.function.Supplier;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * Predicate for GEO JSON point values; will return true if the point is within the specified GeoJSON geometry
+ * (Polygon, MultiPolygon, or Feature/FeatureCollection containing such geometries) unless negated. This allows for
+ * complex geofence shapes such as country borders.
+ */
+@JsonSchemaTitle("GeoJSON Geofence")
+@JsonSchemaDescription("Predicate for GeoJSON point values; will return true if the point is within the specified GeoJSON geometry (Polygon, MultiPolygon, or Feature/FeatureCollection containing such geometries) unless negated.")
+public class GeoJSONGeofencePredicate extends GeofencePredicate {
+
+ private static final Logger LOG = Logger.getLogger(GeoJSONGeofencePredicate.class.getName());
+ private static final GeometryFactory GEOMETRY_FACTORY = new GeometryFactory();
+
+ public static final String name = "geojson";
+
+ @JsonProperty
+ public String geoJSON;
+
+ // Cached geometry for performance
+ private transient Geometry cachedGeometry;
+
+ public GeoJSONGeofencePredicate() {
+ }
+
+ @JsonCreator
+ public GeoJSONGeofencePredicate(@JsonProperty("geoJSON") String geoJSON,
+ @JsonProperty("negated") boolean negated) {
+ this.geoJSON = geoJSON;
+ this.negated = negated;
+ }
+
+ public GeoJSONGeofencePredicate(@JsonProperty("geoJSON") String geoJSON) {
+ this(geoJSON, false);
+ }
+
+ @Override
+ public GeoJSONGeofencePredicate negate() {
+ negated = !negated;
+ return this;
+ }
+
+ public GeoJSONGeofencePredicate geoJSON(String geoJSON) {
+ this.geoJSON = geoJSON;
+ this.cachedGeometry = null; // Invalidate cache
+ return this;
+ }
+
+ public String getGeoJSON() {
+ return geoJSON;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ GeoJSONGeofencePredicate that = (GeoJSONGeofencePredicate) o;
+ return negated == that.negated &&
+ Objects.equals(geoJSON, that.geoJSON);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(name, negated, geoJSON);
+ }
+
+ @Override
+ public double[] getCentrePoint() {
+ try {
+ Geometry geometry = parseGeometry();
+ if (geometry != null) {
+ Point centroid = geometry.getCentroid();
+ return new double[]{centroid.getX(), centroid.getY()};
+ }
+ } catch (Exception e) {
+ LOG.log(Level.WARNING, "Failed to get centre point from GeoJSON", e);
+ }
+ return new double[]{0, 0};
+ }
+
+ /**
+ * Parse the GeoJSON string into a JTS Geometry using the GeoJSON model objects.
+ */
+ private Geometry parseGeometry() {
+ if (cachedGeometry != null) {
+ return cachedGeometry;
+ }
+
+ if (geoJSON == null || geoJSON.trim().isEmpty()) {
+ LOG.warning("GeoJSON is null or empty");
+ return null;
+ }
+
+ try {
+ // Try to deserialize as GeoJSON (handles Feature, FeatureCollection, or Geometry)
+ GeoJSON geoJSONObject = ValueUtil.parse(geoJSON, GeoJSON.class).orElse(null);
+
+ if (geoJSONObject == null) {
+ LOG.warning("Failed to parse GeoJSON");
+ return null;
+ }
+
+ Geometry geometry = convertToJTSGeometry(geoJSONObject);
+ cachedGeometry = geometry;
+ return geometry;
+
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE, "Failed to parse GeoJSON: " + geoJSON, e);
+ return null;
+ }
+ }
+
+ /**
+ * Convert a GeoJSON object to a JTS Geometry.
+ */
+ private Geometry convertToJTSGeometry(GeoJSON geoJSON) {
+ if (geoJSON instanceof GeoJSONFeatureCollection) {
+ return convertFeatureCollection((GeoJSONFeatureCollection) geoJSON);
+ } else if (geoJSON instanceof GeoJSONFeature) {
+ return convertFeature((GeoJSONFeature) geoJSON);
+ } else if (geoJSON instanceof GeoJSONGeometry) {
+ return convertGeometry((GeoJSONGeometry) geoJSON);
+ }
+
+ LOG.warning("Unknown GeoJSON type: " + geoJSON.getClass().getName());
+ return null;
+ }
+
+ /**
+ * Convert a GeoJSONFeatureCollection to a JTS Geometry (union of all features).
+ */
+ private Geometry convertFeatureCollection(GeoJSONFeatureCollection featureCollection) {
+ Geometry result = null;
+
+ for (GeoJSONFeature feature : featureCollection.getFeatures()) {
+ Geometry featureGeometry = convertFeature(feature);
+ if (featureGeometry != null) {
+ result = result == null ? featureGeometry : result.union(featureGeometry);
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Convert a GeoJSONFeature to a JTS Geometry.
+ */
+ private Geometry convertFeature(GeoJSONFeature feature) {
+ GeoJSONGeometry geometry = feature.getGeometry();
+ return geometry != null ? convertGeometry(geometry) : null;
+ }
+
+ /**
+ * Convert a GeoJSONGeometry to a JTS Geometry.
+ */
+ private Geometry convertGeometry(GeoJSONGeometry geometry) {
+ if (geometry instanceof GeoJSONPoint) {
+ return convertPoint((GeoJSONPoint) geometry);
+ } else if (geometry instanceof GeoJSONPolygon) {
+ return convertPolygon((GeoJSONPolygon) geometry);
+ } else if (geometry instanceof GeoJSONMultiPolygon) {
+ return convertMultiPolygon((GeoJSONMultiPolygon) geometry);
+ }
+
+ LOG.warning("Unsupported geometry type: " + geometry.getClass().getName());
+ return null;
+ }
+
+ /**
+ * Convert GeoJSONPoint to JTS Point.
+ */
+ private Point convertPoint(GeoJSONPoint point) {
+ return GEOMETRY_FACTORY.createPoint(point.getCoordinates());
+ }
+
+ /**
+ * Convert GeoJSONPolygon to JTS Polygon.
+ */
+ private Polygon convertPolygon(GeoJSONPolygon polygon) {
+ Coordinate[] exteriorCoords = polygon.getExteriorRing();
+ LinearRing shell = GEOMETRY_FACTORY.createLinearRing(exteriorCoords);
+
+ if (polygon.hasHoles()) {
+ java.util.List<Coordinate[]> holes = polygon.getHoles();
+ LinearRing[] holeRings = new LinearRing[holes.size()];
+ for (int i = 0; i < holes.size(); i++) {
+ holeRings[i] = GEOMETRY_FACTORY.createLinearRing(holes.get(i));
+ }
+ return GEOMETRY_FACTORY.createPolygon(shell, holeRings);
+ } else {
+ return GEOMETRY_FACTORY.createPolygon(shell);
+ }
+ }
+
+ /**
+ * Convert GeoJSONMultiPolygon to JTS MultiPolygon.
+ */
+ private MultiPolygon convertMultiPolygon(GeoJSONMultiPolygon multiPolygon) {
+ java.util.List<GeoJSONPolygon> polygons = multiPolygon.getPolygons();
+ Polygon[] jtsPolygons = new Polygon[polygons.size()];
+
+ for (int i = 0; i < polygons.size(); i++) {
+ jtsPolygons[i] = convertPolygon(polygons.get(i));
+ }
+
+ return GEOMETRY_FACTORY.createMultiPolygon(jtsPolygons);
+ }
+
+ @Override
+ public Predicate<Object> asPredicate(Supplier<Long> currentMillisSupplier) {
+ return obj -> {
+ if (obj == null) return false;
+
+ Coordinate coordinate;
+
+ if (obj instanceof Coordinate) {
+ coordinate = (Coordinate) obj;
+ } else {
+ coordinate = ValueUtil.getValue(obj, GeoJSONPoint.class)
+ .map(GeoJSONPoint::getCoordinates)
+ .orElse(null);
+ }
+
+ if (coordinate == null) {
+ return false;
+ }
+
+ // Clamp coordinates to valid ranges
+ coordinate = new Coordinate(
+ Math.min(180d, Math.max(-180d, coordinate.x)),
+ Math.min(90d, Math.max(-90d, coordinate.y))
+ );
+
+ Geometry geometry = parseGeometry();
+ if (geometry == null) {
+ LOG.warning("Failed to parse geometry for geofence check");
+ return false;
+ }
+
+ // Create a Point from the coordinate
+ Point point = GEOMETRY_FACTORY.createPoint(coordinate);
+
+ // Check if the point is within the geometry
+ boolean contains = geometry.contains(point);
+
+ // Return based on negation
+ return negated != contains;
+ };
+ }
+}
+
diff --git a/model/src/main/java/org/openremote/model/query/filter/ValuePredicate.java b/model/src/main/java/org/openremote/model/query/filter/ValuePredicate.java
index d553ba443..f6101779a 100644
--- a/model/src/main/java/org/openremote/model/query/filter/ValuePredicate.java
+++ b/model/src/main/java/org/openremote/model/query/filter/ValuePredicate.java
@@ -34,6 +34,7 @@ import java.util.function.Supplier;
@JsonSubTypes.Type(value = NumberPredicate.class, name = NumberPredicate.name),
@JsonSubTypes.Type(value = RadialGeofencePredicate.class, name = RadialGeofencePredicate.name),
@JsonSubTypes.Type(value = RectangularGeofencePredicate.class, name = RectangularGeofencePredicate.name),
+ @JsonSubTypes.Type(value = GeoJSONGeofencePredicate.class, name = GeoJSONGeofencePredicate.name),
@JsonSubTypes.Type(value = ArrayPredicate.class, name = ArrayPredicate.name),
@JsonSubTypes.Type(value = ValueAnyPredicate.class, name = ValueAnyPredicate.name),
@JsonSubTypes.Type(value = ValueEmptyPredicate.class, name = ValueEmptyPredicate.name),
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetQueryPredicateTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetQueryPredicateTest.groovy
index fa203dba8..62fb269f4 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetQueryPredicateTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetQueryPredicateTest.groovy
@@ -2,6 +2,7 @@ package org.openremote.test.assets
import org.locationtech.jts.geom.Coordinate
import org.openremote.model.query.filter.GeofencePredicate
+import org.openremote.model.query.filter.GeoJSONGeofencePredicate
import org.openremote.model.query.filter.RadialGeofencePredicate
import org.openremote.model.query.filter.RectangularGeofencePredicate
import spock.lang.Specification
@@ -24,10 +25,321 @@ class AssetQueryPredicateTest extends Specification {
GeofencePredicate geofencePredicate = new RadialGeofencePredicate(100, 51.423, 5.441)
GeofencePredicate geofencePredicateNegated = new RadialGeofencePredicate(100, 51.423, 5.441).negate()
def coordinatePredicate = geofencePredicate.asPredicate({ -> System.currentTimeMillis() })
- def coordinatePredicateNegated = coordinatePredicate.negate()
+ def coordinatePredicateNegated = geofencePredicateNegated.asPredicate({ -> System.currentTimeMillis() })
expect:
coordinatePredicate.test(new Coordinate(5.441, 51.423))
!coordinatePredicateNegated.test(new Coordinate(5.441, 51.423))
}
+
+ def "GeoJSON Polygon geofence test"() {
+ given: "A simple polygon representing a rectangular area around Vienna"
+ def polygonGeoJSON = '''
+ {
+ "type": "Polygon",
+ "coordinates": [
+ [
+ [16.2, 48.1],
+ [16.6, 48.1],
+ [16.6, 48.3],
+ [16.2, 48.3],
+ [16.2, 48.1]
+ ]
+ ]
+ }
+ '''
+ GeofencePredicate geofencePredicate = new GeoJSONGeofencePredicate(polygonGeoJSON)
+ def coordinatePredicate = geofencePredicate.asPredicate({ -> System.currentTimeMillis() })
+
+ expect: "Points inside the polygon should return true"
+ assert coordinatePredicate.test(new Coordinate(16.4, 48.2))
+ assert coordinatePredicate.test(new Coordinate(16.3, 48.15))
+
+ and: "Points outside the polygon should return false"
+ assert !coordinatePredicate.test(new Coordinate(16.0, 48.2))
+ assert !coordinatePredicate.test(new Coordinate(16.4, 48.5))
+ assert !coordinatePredicate.test(new Coordinate(17.0, 48.2))
+ }
+
+ def "GeoJSON Polygon with hole geofence test"() {
+ given: "A polygon with a hole (donut shape)"
+ def polygonWithHoleGeoJSON = '''
+ {
+ "type": "Polygon",
+ "coordinates": [
+ [
+ [16.2, 48.1],
+ [16.6, 48.1],
+ [16.6, 48.3],
+ [16.2, 48.3],
+ [16.2, 48.1]
+ ],
+ [
+ [16.3, 48.15],
+ [16.5, 48.15],
+ [16.5, 48.25],
+ [16.3, 48.25],
+ [16.3, 48.15]
+ ]
+ ]
+ }
+ '''
+ GeofencePredicate geofencePredicate = new GeoJSONGeofencePredicate(polygonWithHoleGeoJSON)
+ def coordinatePredicate = geofencePredicate.asPredicate({ -> System.currentTimeMillis() })
+
+ expect: "Points in the outer ring but not in the hole should return true"
+ assert coordinatePredicate.test(new Coordinate(16.25, 48.2))
+ assert coordinatePredicate.test(new Coordinate(16.55, 48.2))
+
+ and: "Points in the hole should return false"
+ assert !coordinatePredicate.test(new Coordinate(16.4, 48.2))
+
+ and: "Points outside should return false"
+ assert !coordinatePredicate.test(new Coordinate(16.0, 48.2))
+ }
+
+ def "GeoJSON MultiPolygon geofence test"() {
+ given: "A MultiPolygon representing two separate regions"
+ def multiPolygonGeoJSON = '''
+ {
+ "type": "MultiPolygon",
+ "coordinates": [
+ [
+ [
+ [16.2, 48.1],
+ [16.4, 48.1],
+ [16.4, 48.2],
+ [16.2, 48.2],
+ [16.2, 48.1]
+ ]
+ ],
+ [
+ [
+ [16.5, 48.1],
+ [16.7, 48.1],
+ [16.7, 48.2],
+ [16.5, 48.2],
+ [16.5, 48.1]
+ ]
+ ]
+ ]
+ }
+ '''
+ GeofencePredicate geofencePredicate = new GeoJSONGeofencePredicate(multiPolygonGeoJSON)
+ def coordinatePredicate = geofencePredicate.asPredicate({ -> System.currentTimeMillis() })
+
+ expect: "Points inside either polygon should return true"
+ assert coordinatePredicate.test(new Coordinate(16.3, 48.15))
+ assert coordinatePredicate.test(new Coordinate(16.6, 48.15))
+
+ and: "Points between the polygons should return false"
+ assert !coordinatePredicate.test(new Coordinate(16.45, 48.15))
+
+ and: "Points outside both polygons should return false"
+ assert !coordinatePredicate.test(new Coordinate(16.0, 48.15))
+ assert !coordinatePredicate.test(new Coordinate(16.8, 48.15))
+ }
+
+ def "GeoJSON Feature geofence test"() {
+ given: "A Feature containing a polygon geometry"
+ def featureGeoJSON = '''
+ {
+ "type": "Feature",
+ "properties": {
+ "name": "Vienna Region"
+ },
+ "geometry": {
+ "type": "Polygon",
+ "coordinates": [
+ [
+ [16.2, 48.1],
+ [16.6, 48.1],
+ [16.6, 48.3],
+ [16.2, 48.3],
+ [16.2, 48.1]
+ ]
+ ]
+ }
+ }
+ '''
+ GeofencePredicate geofencePredicate = new GeoJSONGeofencePredicate(featureGeoJSON)
+ def coordinatePredicate = geofencePredicate.asPredicate({ -> System.currentTimeMillis() })
+
+ expect: "Points inside the feature's geometry should return true"
+ assert coordinatePredicate.test(new Coordinate(16.4, 48.2))
+
+ and: "Points outside should return false"
+ assert !coordinatePredicate.test(new Coordinate(16.0, 48.2))
+ }
+
+ def "GeoJSON FeatureCollection geofence test"() {
+ given: "A FeatureCollection with multiple features"
+ def featureCollectionGeoJSON = '''
+ {
+ "type": "FeatureCollection",
+ "features": [
+ {
+ "type": "Feature",
+ "properties": {"name": "Region A"},
+ "geometry": {
+ "type": "Polygon",
+ "coordinates": [
+ [
+ [16.2, 48.1],
+ [16.4, 48.1],
+ [16.4, 48.2],
+ [16.2, 48.2],
+ [16.2, 48.1]
+ ]
+ ]
+ }
+ },
+ {
+ "type": "Feature",
+ "properties": {"name": "Region B"},
+ "geometry": {
+ "type": "Polygon",
+ "coordinates": [
+ [
+ [16.5, 48.1],
+ [16.7, 48.1],
+ [16.7, 48.2],
+ [16.5, 48.2],
+ [16.5, 48.1]
+ ]
+ ]
+ }
+ }
+ ]
+ }
+ '''
+ GeofencePredicate geofencePredicate = new GeoJSONGeofencePredicate(featureCollectionGeoJSON)
+ def coordinatePredicate = geofencePredicate.asPredicate({ -> System.currentTimeMillis() })
+
+ expect: "Points inside any feature should return true"
+ assert coordinatePredicate.test(new Coordinate(16.3, 48.15))
+ assert coordinatePredicate.test(new Coordinate(16.6, 48.15))
+
+ and: "Points outside all features should return false"
+ assert !coordinatePredicate.test(new Coordinate(16.45, 48.15))
+ assert !coordinatePredicate.test(new Coordinate(16.0, 48.15))
+ }
+
+ def "GeoJSON negated geofence test"() {
+ given: "A polygon geofence that is negated"
+ def polygonGeoJSON = '''
+ {
+ "type": "Polygon",
+ "coordinates": [
+ [
+ [16.2, 48.1],
+ [16.6, 48.1],
+ [16.6, 48.3],
+ [16.2, 48.3],
+ [16.2, 48.1]
+ ]
+ ]
+ }
+ '''
+ GeofencePredicate geofencePredicate = new GeoJSONGeofencePredicate(polygonGeoJSON).negate()
+ def coordinatePredicate = geofencePredicate.asPredicate({ -> System.currentTimeMillis() })
+
+ expect: "Points inside the polygon should return false (negated)"
+ assert !coordinatePredicate.test(new Coordinate(16.4, 48.2))
+
+ and: "Points outside the polygon should return true (negated)"
+ assert coordinatePredicate.test(new Coordinate(16.0, 48.2))
+ assert coordinatePredicate.test(new Coordinate(17.0, 48.2))
+ }
+
+ def "GeoJSON simplified Austria border test"() {
+ given: "A simplified polygon representing Austria's approximate borders"
+ def austriaGeoJSON = '''
+ {
+ "type": "Polygon",
+ "coordinates": [
+ [
+ [9.5, 46.4],
+ [17.2, 46.4],
+ [17.2, 49.0],
+ [9.5, 49.0],
+ [9.5, 46.4]
+ ]
+ ]
+ }
+ '''
+ GeofencePredicate geofencePredicate = new GeoJSONGeofencePredicate(austriaGeoJSON)
+ def coordinatePredicate = geofencePredicate.asPredicate({ -> System.currentTimeMillis() })
+
+ expect: "Vienna (16.37, 48.21) should be inside Austria"
+ assert coordinatePredicate.test(new Coordinate(16.37, 48.21))
+
+ and: "Salzburg (13.04, 47.81) should be inside Austria"
+ assert coordinatePredicate.test(new Coordinate(13.04, 47.81))
+
+ and: "Innsbruck (11.39, 47.27) should be inside Austria"
+ assert coordinatePredicate.test(new Coordinate(11.39, 47.27))
+
+ and: "Munich, Germany (11.58, 48.14) should be outside (in this simplified border)"
+ assert coordinatePredicate.test(new Coordinate(11.58, 48.14)) // Actually inside our simplified box
+
+ and: "Bratislava, Slovakia (17.11, 48.15) should be inside (border city)"
+ assert coordinatePredicate.test(new Coordinate(17.11, 48.15))
+
+ and: "Prague, Czech Republic (14.42, 50.08) should be outside Austria"
+ assert !coordinatePredicate.test(new Coordinate(14.42, 50.08))
+
+ and: "Rome, Italy (12.50, 41.90) should be outside Austria"
+ assert !coordinatePredicate.test(new Coordinate(12.50, 41.90))
+ }
+
+ def "GeoJSON centre point calculation test"() {
+ given: "A polygon geofence"
+ def polygonGeoJSON = '''
+ {
+ "type": "Polygon",
+ "coordinates": [
+ [
+ [16.0, 48.0],
+ [17.0, 48.0],
+ [17.0, 49.0],
+ [16.0, 49.0],
+ [16.0, 48.0]
+ ]
+ ]
+ }
+ '''
+ GeofencePredicate geofencePredicate = new GeoJSONGeofencePredicate(polygonGeoJSON)
+
+ when: "Getting the centre point"
+ def centrePoint = geofencePredicate.getCentrePoint()
+
+ then: "The centre point should be approximately at the centroid"
+ assert centrePoint != null
+ assert centrePoint.length == 2
+ assert Math.abs(centrePoint[0] - 16.5) < 0.1 // longitude
+ assert Math.abs(centrePoint[1] - 48.5) < 0.1 // latitude
+ }
+
+ def "GeoJSON invalid input handling test"() {
+ given: "Various invalid GeoJSON inputs"
+ def invalidInputs = [
+ null,
+ "",
+ "not json",
+ "{}",
+ '{"type": "Unknown"}',
+ '{"coordinates": [[0,0]]}' // missing type
+ ]
+
+ expect: "Predicates with invalid input should handle gracefully"
+ invalidInputs.each { invalidGeoJSON ->
+ def geofencePredicate = new GeoJSONGeofencePredicate(invalidGeoJSON)
+ def coordinatePredicate = geofencePredicate.asPredicate({ -> System.currentTimeMillis() })
+ // Should return false for any coordinate when GeoJSON is invalid
+ assert !coordinatePredicate.test(new Coordinate(16.4, 48.2))
+ }
+ }
}
+
+
diff --git a/test/src/test/groovy/org/openremote/test/model/GeoJSONPolygonTest.groovy b/test/src/test/groovy/org/openremote/test/model/GeoJSONPolygonTest.groovy
new file mode 100644
index 000000000..dd47dde43
--- /dev/null
+++ b/test/src/test/groovy/org/openremote/test/model/GeoJSONPolygonTest.groovy
@@ -0,0 +1,362 @@
+package org.openremote.test.model
+
+import org.locationtech.jts.geom.Coordinate
+import org.openremote.model.geo.GeoJSONMultiPolygon
+import org.openremote.model.geo.GeoJSONPolygon
+import org.openremote.model.util.ValueUtil
+import spock.lang.Specification
+
+class GeoJSONPolygonTest extends Specification {
+
+ def "Simple polygon serialization and deserialization"() {
+ given: "A simple rectangular polygon"
+ def exteriorRing = [
+ new Coordinate(16.2, 48.1),
+ new Coordinate(16.6, 48.1),
+ new Coordinate(16.6, 48.3),
+ new Coordinate(16.2, 48.3),
+ new Coordinate(16.2, 48.1)
+ ] as Coordinate[]
+
+ when: "Creating a GeoJSONPolygon"
+ def polygon = new GeoJSONPolygon(exteriorRing)
+
+ then: "It should be properly initialized"
+ assert polygon.getCoordinates().size() == 1
+ assert polygon.getExteriorRing().length == 5
+ assert !polygon.hasHoles()
+
+ when: "Serializing to JSON"
+ def json = ValueUtil.asJSON(polygon).orElse(null)
+
+ then: "JSON should be properly formatted"
+ assert json != null
+ def node = ValueUtil.JSON.readTree(json)
+ assert node.get("type").asText() == "Polygon"
+ assert node.has("coordinates")
+
+ when: "Deserializing from JSON"
+ def deserialized = ValueUtil.parse(json, GeoJSONPolygon.class).orElse(null)
+
+ then: "Should get the same polygon"
+ assert deserialized != null
+ assert deserialized.getCoordinates().size() == 1
+ assert deserialized.getExteriorRing().length == 5
+ }
+
+ def "Polygon with hole"() {
+ given: "A polygon with a hole (donut shape)"
+ def exteriorRing = [
+ new Coordinate(16.2, 48.1),
+ new Coordinate(16.6, 48.1),
+ new Coordinate(16.6, 48.3),
+ new Coordinate(16.2, 48.3),
+ new Coordinate(16.2, 48.1)
+ ] as Coordinate[]
+
+ def hole = [
+ new Coordinate(16.3, 48.15),
+ new Coordinate(16.5, 48.15),
+ new Coordinate(16.5, 48.25),
+ new Coordinate(16.3, 48.25),
+ new Coordinate(16.3, 48.15)
+ ] as Coordinate[]
+
+ when: "Creating a polygon with a hole"
+ def polygon = new GeoJSONPolygon(exteriorRing, [hole] as Coordinate[][])
+
+ then: "It should have both rings"
+ assert polygon.getCoordinates().size() == 2
+ assert polygon.hasHoles()
+ assert polygon.getHoles().size() == 1
+ assert polygon.getExteriorRing().length == 5
+
+ when: "Serializing and deserializing"
+ def json = ValueUtil.asJSON(polygon).orElse(null)
+ def deserialized = ValueUtil.parse(json, GeoJSONPolygon.class).orElse(null)
+
+ then: "Should preserve the structure"
+ assert deserialized != null
+ assert deserialized.getCoordinates().size() == 2
+ assert deserialized.hasHoles()
+ assert deserialized.getHoles().size() == 1
+ }
+
+ def "Polygon from double array constructor"() {
+ given: "Raw coordinate data as double arrays"
+ def coordinates = [
+ [
+ [16.2d, 48.1d],
+ [16.6d, 48.1d],
+ [16.6d, 48.3d],
+ [16.2d, 48.3d],
+ [16.2d, 48.1d]
+ ]
+ ] as double[][][]
+
+ when: "Creating polygon from raw data"
+ def polygon = new GeoJSONPolygon(coordinates)
+
+ then: "Should be properly initialized"
+ assert polygon.getCoordinates().size() == 1
+ assert polygon.getExteriorRing().length == 5
+ assert !polygon.hasHoles()
+ }
+
+ def "Polygon coordinate clamping"() {
+ given: "Coordinates with out-of-bounds values"
+ def exteriorRing = [
+ new Coordinate(-200.0, -100.0), // Out of bounds
+ new Coordinate(200.0, 100.0), // Out of bounds
+ new Coordinate(16.6, 48.3),
+ new Coordinate(16.2, 48.3),
+ new Coordinate(-200.0, -100.0)
+ ] as Coordinate[]
+
+ when: "Creating polygon"
+ def polygon = new GeoJSONPolygon(exteriorRing)
+
+ then: "Coordinates should be clamped"
+ def ring = polygon.getExteriorRing()
+ assert ring[0].x == -180.0d
+ assert ring[0].y == -90.0d
+ assert ring[1].x == 180.0d
+ assert ring[1].y == 90.0d
+ }
+
+ def "Polygon validation errors"() {
+ when: "Creating polygon with too few coordinates"
+ GeoJSONPolygon ignored1 = new GeoJSONPolygon([
+ new Coordinate(16.2, 48.1),
+ new Coordinate(16.6, 48.1),
+ new Coordinate(16.2, 48.1)
+ ] as Coordinate[])
+
+ then: "Should throw exception"
+ def ex1 = thrown(IllegalArgumentException)
+ assert ex1 != null
+
+ when: "Creating polygon from empty array"
+ GeoJSONPolygon ignored2 = new GeoJSONPolygon(new double[0][][])
+
+ then: "Should throw exception"
+ def ex2 = thrown(IllegalArgumentException)
+ assert ex2 != null
+ }
+
+ def "Polygon with 3D coordinates"() {
+ given: "Coordinates with elevation"
+ def exteriorRing = [
+ new Coordinate(16.2, 48.1, 200.0),
+ new Coordinate(16.6, 48.1, 250.0),
+ new Coordinate(16.6, 48.3, 300.0),
+ new Coordinate(16.2, 48.3, 250.0),
+ new Coordinate(16.2, 48.1, 200.0)
+ ] as Coordinate[]
+
+ when: "Creating and serializing polygon"
+ def polygon = new GeoJSONPolygon(exteriorRing)
+ def json = ValueUtil.asJSON(polygon).orElse(null)
+
+ then: "Should include Z coordinates in JSON"
+ assert json != null
+ assert json.contains("200")
+ assert json.contains("250")
+ assert json.contains("300")
+
+ when: "Deserializing"
+ def deserialized = ValueUtil.parse(json, GeoJSONPolygon.class).orElse(null)
+
+ then: "Should preserve Z coordinates"
+ assert deserialized != null
+ assert deserialized.getExteriorRing()[0].getZ() == 200.0d
+ assert deserialized.getExteriorRing()[1].getZ() == 250.0d
+ }
+}
+
+class GeoJSONMultiPolygonTest extends Specification {
+
+ def "Simple MultiPolygon serialization"() {
+ given: "Two separate polygons"
+ def polygon1 = [
+ new Coordinate(16.2, 48.1),
+ new Coordinate(16.4, 48.1),
+ new Coordinate(16.4, 48.2),
+ new Coordinate(16.2, 48.2),
+ new Coordinate(16.2, 48.1)
+ ] as Coordinate[]
+
+ def polygon2 = [
+ new Coordinate(16.5, 48.1),
+ new Coordinate(16.7, 48.1),
+ new Coordinate(16.7, 48.2),
+ new Coordinate(16.5, 48.2),
+ new Coordinate(16.5, 48.1)
+ ] as Coordinate[]
+
+ when: "Creating MultiPolygon"
+ def multiPolygon = new GeoJSONMultiPolygon([polygon1, polygon2])
+
+ then: "Should have two polygons"
+ assert multiPolygon.getPolygonCount() == 2
+ assert multiPolygon.getCoordinates().size() == 2
+
+ when: "Serializing to JSON"
+ def json = ValueUtil.asJSON(multiPolygon).orElse(null)
+
+ then: "JSON should be properly formatted"
+ assert json != null
+ def node = ValueUtil.JSON.readTree(json)
+ assert node.get("type").asText() == "MultiPolygon"
+ assert node.has("coordinates")
+
+ when: "Deserializing"
+ def deserialized = ValueUtil.parse(json, GeoJSONMultiPolygon.class).orElse(null)
+
+ then: "Should preserve structure"
+ assert deserialized != null
+ assert deserialized.getPolygonCount() == 2
+ }
+
+ def "MultiPolygon from GeoJSONPolygon objects"() {
+ given: "Two GeoJSONPolygon objects"
+ def exteriorRing1 = [
+ new Coordinate(16.2, 48.1),
+ new Coordinate(16.4, 48.1),
+ new Coordinate(16.4, 48.2),
+ new Coordinate(16.2, 48.2),
+ new Coordinate(16.2, 48.1)
+ ] as Coordinate[]
+
+ def exteriorRing2 = [
+ new Coordinate(16.5, 48.1),
+ new Coordinate(16.7, 48.1),
+ new Coordinate(16.7, 48.2),
+ new Coordinate(16.5, 48.2),
+ new Coordinate(16.5, 48.1)
+ ] as Coordinate[]
+
+ def polygon1 = new GeoJSONPolygon(exteriorRing1)
+ def polygon2 = new GeoJSONPolygon(exteriorRing2)
+
+ when: "Creating MultiPolygon from polygons"
+ def multiPolygon = new GeoJSONMultiPolygon(polygon1, polygon2)
+
+ then: "Should have two polygons"
+ assert multiPolygon.getPolygonCount() == 2
+ assert multiPolygon.getPolygons().size() == 2
+ }
+
+ def "MultiPolygon with polygons with holes"() {
+ given: "A polygon with a hole"
+ def exteriorRing = [
+ new Coordinate(16.2, 48.1),
+ new Coordinate(16.6, 48.1),
+ new Coordinate(16.6, 48.3),
+ new Coordinate(16.2, 48.3),
+ new Coordinate(16.2, 48.1)
+ ] as Coordinate[]
+
+ def hole = [
+ new Coordinate(16.3, 48.15),
+ new Coordinate(16.5, 48.15),
+ new Coordinate(16.5, 48.25),
+ new Coordinate(16.3, 48.25),
+ new Coordinate(16.3, 48.15)
+ ] as Coordinate[]
+
+ def polygon = new GeoJSONPolygon(exteriorRing, [hole] as Coordinate[][])
+
+ when: "Creating MultiPolygon with complex polygon"
+ def multiPolygon = new GeoJSONMultiPolygon(polygon)
+
+ then: "Should preserve polygon structure"
+ assert multiPolygon.getPolygonCount() == 1
+ assert multiPolygon.getPolygon(0).size() == 2 // exterior + hole
+
+ when: "Converting back to polygons"
+ def polygons = multiPolygon.getPolygons()
+
+ then: "Should preserve holes"
+ assert polygons.size() == 1
+ assert polygons[0].hasHoles()
+ }
+
+ def "MultiPolygon from raw double arrays"() {
+ given: "Raw coordinate data"
+ def coordinates = [
+ [
+ [
+ [16.2d, 48.1d],
+ [16.4d, 48.1d],
+ [16.4d, 48.2d],
+ [16.2d, 48.2d],
+ [16.2d, 48.1d]
+ ]
+ ],
+ [
+ [
+ [16.5d, 48.1d],
+ [16.7d, 48.1d],
+ [16.7d, 48.2d],
+ [16.5d, 48.2d],
+ [16.5d, 48.1d]
+ ]
+ ]
+ ] as double[][][][]
+
+ when: "Creating MultiPolygon"
+ def multiPolygon = new GeoJSONMultiPolygon(coordinates)
+
+ then: "Should be properly initialized"
+ assert multiPolygon.getPolygonCount() == 2
+ }
+
+ def "MultiPolygon validation errors"() {
+ when: "Creating empty MultiPolygon"
+ GeoJSONMultiPolygon ignored1 = new GeoJSONMultiPolygon(new double[0][][][])
+
+ then: "Should throw exception"
+ def ex1 = thrown(IllegalArgumentException)
+ assert ex1 != null
+
+ when: "Creating MultiPolygon with invalid polygon"
+ GeoJSONMultiPolygon ignored2 = new GeoJSONMultiPolygon([
+ [
+ new Coordinate(16.2, 48.1),
+ new Coordinate(16.4, 48.1),
+ new Coordinate(16.2, 48.1) // Only 3 coordinates
+ ] as Coordinate[]
+ ])
+
+ then: "Should throw exception"
+ def ex2 = thrown(IllegalArgumentException)
+ assert ex2 != null
+ }
+
+ def "MultiPolygon getPolygon bounds checking"() {
+ given: "A MultiPolygon with 2 polygons"
+ def polygon1 = [
+ new Coordinate(16.2, 48.1),
+ new Coordinate(16.4, 48.1),
+ new Coordinate(16.4, 48.2),
+ new Coordinate(16.2, 48.2),
+ new Coordinate(16.2, 48.1)
+ ] as Coordinate[]
+
+ def multiPolygon = new GeoJSONMultiPolygon([polygon1])
+
+ when: "Accessing valid index"
+ def polygon = multiPolygon.getPolygon(0)
+
+ then: "Should return polygon"
+ assert polygon != null
+ assert polygon.size() == 1
+
+ when: "Accessing invalid index"
+ multiPolygon.getPolygon(5)
+
+ then: "Should throw exception"
+ thrown(IndexOutOfBoundsException)
+ }
+}
diff --git a/ui/app/shared/locales/ar/or.json b/ui/app/shared/locales/ar/or.json
index 430559b94..484e7bd58 100644
--- a/ui/app/shared/locales/ar/or.json
+++ b/ui/app/shared/locales/ar/or.json
@@ -450,6 +450,10 @@
},
"BooleanPredicate": {
"description": ""
+ },
+ "GeoJSONGeofencePredicate": {
+ "label": "",
+ "description": ""
}
}
},
diff --git a/ui/app/shared/locales/cn/or.json b/ui/app/shared/locales/cn/or.json
index 5442e95d1..4a056c3c6 100644
--- a/ui/app/shared/locales/cn/or.json
+++ b/ui/app/shared/locales/cn/or.json
@@ -499,6 +499,10 @@
},
"BooleanPredicate": {
"description": ""
+ },
+ "GeoJSONGeofencePredicate": {
+ "label": "",
+ "description": ""
}
}
},
diff --git a/ui/app/shared/locales/de/or.json b/ui/app/shared/locales/de/or.json
index 9137fb156..467c8a8bb 100644
--- a/ui/app/shared/locales/de/or.json
+++ b/ui/app/shared/locales/de/or.json
@@ -545,6 +545,10 @@
},
"BooleanPredicate": {
"description": ""
+ },
+ "GeoJSONGeofencePredicate": {
+ "label": "",
+ "description": ""
}
}
},
diff --git a/ui/app/shared/locales/en/or.json b/ui/app/shared/locales/en/or.json
index b8c0518ba..851d134df 100644
--- a/ui/app/shared/locales/en/or.json
+++ b/ui/app/shared/locales/en/or.json
@@ -76,6 +76,8 @@
"outsideRadius": "Outside circle",
"withinRectangle": "Inside rectangle",
"outsideRectangle": "Outside rectangle",
+ "insideArea": "Inside area",
+ "outsideArea": "Outside area",
"indexContains": "Array index contains",
"notIndexContains": "Array index does not contain",
"lengthEquals": "Array length equals",
@@ -1051,6 +1053,10 @@
},
"BooleanPredicate": {
"description": "Predicate for boolean values; will evaluate the value as a boolean and match against this predicates value, any value that is not a boolean will not match"
+ },
+ "GeoJSONGeofencePredicate": {
+ "label": "GeoJSON Geofence",
+ "description": "Predicate for GeoJSON point values; will return true if the point is within the specified GeoJSON geometry (Polygon, MultiPolygon, or Feature/FeatureCollection containing such geometries) unless negated."
}
}
},
diff --git a/ui/app/shared/locales/es/or.json b/ui/app/shared/locales/es/or.json
index 8ab97d0ef..124e104a4 100644
--- a/ui/app/shared/locales/es/or.json
+++ b/ui/app/shared/locales/es/or.json
@@ -502,6 +502,10 @@
},
"BooleanPredicate": {
"description": ""
+ },
+ "GeoJSONGeofencePredicate": {
+ "label": "",
+ "description": ""
}
}
},
diff --git a/ui/app/shared/locales/fr/or.json b/ui/app/shared/locales/fr/or.json
index 1da122328..ea1b71cb7 100644
--- a/ui/app/shared/locales/fr/or.json
+++ b/ui/app/shared/locales/fr/or.json
@@ -505,6 +505,10 @@
},
"BooleanPredicate": {
"description": ""
+ },
+ "GeoJSONGeofencePredicate": {
+ "label": "",
+ "description": ""
}
}
},
diff --git a/ui/app/shared/locales/it/or.json b/ui/app/shared/locales/it/or.json
index 6e624c719..9d9493183 100644
--- a/ui/app/shared/locales/it/or.json
+++ b/ui/app/shared/locales/it/or.json
@@ -499,6 +499,10 @@
},
"BooleanPredicate": {
"description": ""
+ },
+ "GeoJSONGeofencePredicate": {
+ "label": "",
+ "description": ""
}
}
},
diff --git a/ui/app/shared/locales/nl/or.json b/ui/app/shared/locales/nl/or.json
index a943ededf..724207ccd 100644
--- a/ui/app/shared/locales/nl/or.json
+++ b/ui/app/shared/locales/nl/or.json
@@ -1048,6 +1048,10 @@
},
"BooleanPredicate": {
"description": "Predicaat voor boolean waarden; evalueert de waarde als een boolean en vergelijkt deze met de waarde van dit predicaat. Elke waarde die geen boolean is, komt niet overeen."
+ },
+ "GeoJSONGeofencePredicate": {
+ "label": "",
+ "description": ""
}
}
},
diff --git a/ui/app/shared/locales/pt/or.json b/ui/app/shared/locales/pt/or.json
index 5a7dd1985..a1559a9d3 100644
--- a/ui/app/shared/locales/pt/or.json
+++ b/ui/app/shared/locales/pt/or.json
@@ -500,6 +500,10 @@
},
"BooleanPredicate": {
"description": ""
+ },
+ "GeoJSONGeofencePredicate": {
+ "label": "",
+ "description": ""
}
}
},
diff --git a/ui/app/shared/locales/ro/or.json b/ui/app/shared/locales/ro/or.json
index 0fa66c1b9..c1b870c01 100644
--- a/ui/app/shared/locales/ro/or.json
+++ b/ui/app/shared/locales/ro/or.json
@@ -738,6 +738,10 @@
},
"BooleanPredicate": {
"description": ""
+ },
+ "GeoJSONGeofencePredicate": {
+ "label": "",
+ "description": ""
}
}
},
diff --git a/ui/app/shared/locales/uk/or.json b/ui/app/shared/locales/uk/or.json
index 510d5bd67..8eeb72e5b 100644
--- a/ui/app/shared/locales/uk/or.json
+++ b/ui/app/shared/locales/uk/or.json
@@ -780,6 +780,10 @@
},
"BooleanPredicate": {
"description": ""
+ },
+ "GeoJSONGeofencePredicate": {
+ "label": "",
+ "description": ""
}
}
},
diff --git a/ui/component/or-rules/src/index.ts b/ui/component/or-rules/src/index.ts
index fbffa524c..1ebf4dee7 100644
--- a/ui/component/or-rules/src/index.ts
+++ b/ui/component/or-rules/src/index.ts
@@ -117,7 +117,9 @@ export enum AssetQueryOperator {
OUTSIDE_RADIUS = "outsideRadius",
WITHIN_RECTANGLE = "withinRectangle",
OUTSIDE_RECTANGLE = "outsideRectangle",
- NOT_UPDATED_FOR = "notUpdatedFor"
+ NOT_UPDATED_FOR = "notUpdatedFor",
+ INSIDE_AREA = "insideArea",
+ OUTSIDE_AREA = "outsideArea"
}
export interface AllowedActionTargetTypes {
diff --git a/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts b/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts
index f0dbd32b6..c3be8c42a 100644
--- a/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts
+++ b/ui/component/or-rules/src/json-viewer/or-rule-asset-query.ts
@@ -145,6 +145,8 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
AssetQueryOperator.OUTSIDE_RADIUS,
AssetQueryOperator.WITHIN_RECTANGLE,
AssetQueryOperator.OUTSIDE_RECTANGLE,
+ AssetQueryOperator.INSIDE_AREA,
+ AssetQueryOperator.OUTSIDE_AREA,
AssetQueryOperator.VALUE_EMPTY,
AssetQueryOperator.VALUE_NOT_EMPTY,
AssetQueryOperator.NOT_UPDATED_FOR
@@ -304,6 +306,17 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
return html`<or-rule-radial-modal .query="${this.query}" .assetDescriptor="${assetDescriptor}" .attributePredicate="${attributePredicate}"></or-rule-radial-modal>`;
case "rect":
return html `<span>NOT IMPLEMENTED</span>`;
+ case "geojson":
+ const geoJsonConfig = valuePredicate.predicateType === "geojson" && (valuePredicate as any).geoJSON
+ ? (() => { try { return { source: JSON.parse((valuePredicate as any).geoJSON), layers: [] }; } catch { return undefined; } })()
+ : undefined;
+ return html`
+ <or-conf-map-geojson .geoJson="${geoJsonConfig}" @update="${(e: CustomEvent) => {
+ const cfg = e.detail.value; // GeoJsonConfig {source, layers}
+ const src = cfg && cfg.source ? JSON.stringify(cfg.source) : "";
+ this.setValuePredicateProperty(valuePredicate, "geoJSON", src)
+ }}"></or-conf-map-geojson>
+ `;
case "value-empty":
return ``;
case "array":
@@ -626,6 +639,8 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
return valuePredicate.negated ? AssetQueryOperator.OUTSIDE_RADIUS : AssetQueryOperator.WITHIN_RADIUS;
case "rect":
return valuePredicate.negated ? AssetQueryOperator.OUTSIDE_RECTANGLE : AssetQueryOperator.WITHIN_RECTANGLE;
+ case "geojson":
+ return valuePredicate.negated ? AssetQueryOperator.OUTSIDE_AREA : AssetQueryOperator.INSIDE_AREA;
case "array":
if (valuePredicate.value && valuePredicate.index) {
return valuePredicate.negated ? AssetQueryOperator.NOT_INDEX_CONTAINS : AssetQueryOperator.INDEX_CONTAINS;
@@ -744,6 +759,14 @@ export class OrRuleAssetQuery extends translate(i18next)(LitElement) {
lngMax: 0.1
};
break;
+ case AssetQueryOperator.INSIDE_AREA:
+ case AssetQueryOperator.OUTSIDE_AREA:
+ predicate = {
+ predicateType: "geojson",
+ negated: value === AssetQueryOperator.OUTSIDE_AREA,
+ geoJSON: ""
+ };
+ break;
// boolean
case AssetQueryOperator.IS_TRUE:
diff --git a/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts b/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts
index 3d16956a5..9cfe0b8db 100644
--- a/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts
+++ b/ui/component/or-rules/src/json-viewer/or-rule-json-viewer.ts
@@ -12,7 +12,7 @@ import {
Asset,
AssetQuery,
AssetQueryOperator as AQO,
- AssetTypeInfo,
+ AssetTypeInfo, GeoJSONFeatureCollection, GeoJSONGeometry,
JsonRule,
JsonRulesetDefinition,
LogicGroup,
@@ -446,6 +446,8 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implements
return valuePredicate.radius !== undefined && valuePredicate.lat !== undefined && valuePredicate.lng !== undefined;
case "rect":
return valuePredicate.lngMax !== undefined && valuePredicate.latMax !== undefined && valuePredicate.lngMin !== undefined && valuePredicate.latMin !== undefined;
+ case "geojson":
+ return valuePredicate.geoJSON !== undefined && this._validateGeoJSON(JSON.parse(valuePredicate.geoJSON) as GeoJSONFeatureCollection);
case "array":
return (valuePredicate.index && !valuePredicate.value) || valuePredicate.value || valuePredicate.lengthEquals || valuePredicate.lengthLessThan || valuePredicate.lengthGreaterThan;
case "value-empty":
@@ -454,4 +456,38 @@ export class OrRuleJsonViewer extends translate(i18next)(LitElement) implements
return false;
}
}
+ protected _validateGeoJSON(geoJSON: any): boolean {
+
+ if (!geoJSON) return false;
+
+ const validGeometryTypes = ["Polygon", "MultiPolygon"];
+
+ // Bit of a recursive function to validate geometry types
+ const isValidGeometry = (geom: any): boolean => {
+ if (!geom || !geom.type) return false;
+
+ if (validGeometryTypes.includes(geom.type)) return true;
+
+ if (geom.type === "GeometryCollection") {
+ if (!Array.isArray(geom.geometries)) return false;
+ return geom.geometries.every((g: any) => isValidGeometry(g));
+ }
+
+ return false;
+ };
+
+ // FeatureCollection
+ if (geoJSON.type === "FeatureCollection") {
+ if (!Array.isArray(geoJSON.features)) return false;
+ return geoJSON.features.every((f: any) => isValidGeometry(f.geometry));
+ }
+
+ // Feature
+ if (geoJSON.type === "Feature") {
+ return isValidGeometry(geoJSON.geometry);
+ }
+
+ // Raw geometry (Polygon, MultiPolygon, GeometryCollection)
+ return isValidGeometry(geoJSON);
+ }
}