Search in sources :

Example 1 with BinarySpatialOperator

use of org.opengis.filter.BinarySpatialOperator in project geotoolkit by Geomatys.

the class FeatureFilterSpatialTest method testSpatialFilter.

/**
 * Test that we get acces attributs without knowing the namespace
 */
@Test
public void testSpatialFilter() throws Exception {
    /**
     *******************************************************************************************
     *                                                                                           *
     *                            AggregateGeoFeature                                            *
     *                                                                                           *
     ********************************************************************************************
     */
    final GenericName description = NamesExt.create("http://www.opengis.net/gml", "description");
    final GenericName name = NamesExt.create("http://www.opengis.net/gml", "name");
    final GenericName multiPointProperty = NamesExt.create("http://cite.opengeospatial.org/gmlsf", "multiPointProperty");
    final GenericName multiCurveProperty = NamesExt.create("http://cite.opengeospatial.org/gmlsf", "multiCurveProperty");
    final GenericName multiSurfaceProperty = NamesExt.create("http://cite.opengeospatial.org/gmlsf", "multiSurfaceProperty");
    final GenericName doubleProperty = NamesExt.create("http://cite.opengeospatial.org/gmlsf", "doubleProperty");
    final GenericName intRangeProperty = NamesExt.create("http://cite.opengeospatial.org/gmlsf", "intRangeProperty");
    final GenericName strProperty = NamesExt.create("http://cite.opengeospatial.org/gmlsf", "strProperty");
    final GenericName featureCode = NamesExt.create("http://cite.opengeospatial.org/gmlsf", "featureCode");
    final GenericName id = NamesExt.create("http://cite.opengeospatial.org/gmlsf", "id");
    FeatureTypeBuilder sftb = new FeatureTypeBuilder();
    sftb.setName(NamesExt.create("http://cite.opengeospatial.org/gmlsf", "AggregateGeoFeature"));
    sftb.addAttribute(String.class).setName(description);
    sftb.addAttribute(String.class).setName(name);
    sftb.addAttribute(MultiPoint.class).setName(multiPointProperty).setCRS(CommonCRS.WGS84.geographic());
    sftb.addAttribute(MultiLineString.class).setName(multiCurveProperty).setCRS(CommonCRS.WGS84.geographic());
    sftb.addAttribute(MultiPolygon.class).setName(multiSurfaceProperty).setCRS(CommonCRS.WGS84.geographic());
    sftb.addAttribute(Double.class).setName(doubleProperty);
    sftb.addAttribute(String.class).setName(intRangeProperty);
    sftb.addAttribute(String.class).setName(strProperty);
    sftb.addAttribute(String.class).setName(featureCode);
    sftb.addAttribute(String.class).setName(id).addRole(AttributeRole.IDENTIFIER_COMPONENT);
    final FeatureType aggregateGeoFeatureType = sftb.build();
    /**
     *******************************************************************************************
     *                            AggregateGeoFeature 1                                          *
     ********************************************************************************************
     */
    final Feature aggregateGeoFeature1 = aggregateGeoFeatureType.newInstance();
    aggregateGeoFeature1.setPropertyValue(AttributeConvention.IDENTIFIER, "f005");
    aggregateGeoFeature1.setPropertyValue(description.toString(), "description-f005");
    aggregateGeoFeature1.setPropertyValue(name.toString(), "name-f005");
    GeometryFactory factory = org.geotoolkit.geometry.jts.JTS.getFactory();
    Point[] points = new Point[3];
    points[0] = factory.createPoint(new Coordinate(70.83, 29.86));
    points[1] = factory.createPoint(new Coordinate(68.87, 31.08));
    points[2] = factory.createPoint(new Coordinate(71.96, 32.19));
    aggregateGeoFeature1.setPropertyValue(multiPointProperty.toString(), factory.createMultiPoint(points));
    aggregateGeoFeature1.setPropertyValue(doubleProperty.toString(), 2012.78);
    aggregateGeoFeature1.setPropertyValue(strProperty.toString(), "Ma quande lingues coalesce...");
    aggregateGeoFeature1.setPropertyValue(featureCode.toString(), "BK030");
    aggregateGeoFeature1.setPropertyValue(id.toString(), "f005");
    /**
     *******************************************************************************************
     *                                                                                           *
     *                            EntitéGénérique                                                *
     *                                                                                           *
     ********************************************************************************************
     */
    final GenericName attributGeometrie = NamesExt.create("http://cite.opengeospatial.org/gmlsf", "attribut.Géométrie");
    final GenericName boolProperty = NamesExt.create("http://cite.opengeospatial.org/gmlsf", "boolProperty");
    final GenericName str4Property = NamesExt.create("http://cite.opengeospatial.org/gmlsf", "str4Property");
    final GenericName featureRef = NamesExt.create("http://cite.opengeospatial.org/gmlsf", "featureRef");
    sftb = new FeatureTypeBuilder();
    sftb.setName(NamesExt.create("http://cite.opengeospatial.org/gmlsf", "EntitéGénérique"));
    sftb.addAttribute(String.class).setName(description);
    sftb.addAttribute(String.class).setName(name);
    sftb.addAttribute(Geometry.class).setName(attributGeometrie).setCRS(CommonCRS.WGS84.geographic());
    sftb.addAttribute(Boolean.class).setName(boolProperty);
    sftb.addAttribute(String.class).setName(str4Property);
    sftb.addAttribute(String.class).setName(featureRef);
    sftb.addAttribute(String.class).setName(id).addRole(AttributeRole.IDENTIFIER_COMPONENT);
    final FeatureType entiteGeneriqueType = sftb.build();
    /**
     *******************************************************************************************
     *                            EntitéGénérique 1                                              *
     ********************************************************************************************
     */
    final Feature entiteGenerique1 = entiteGeneriqueType.newInstance();
    entiteGenerique1.setPropertyValue(description.toString(), "description-f004");
    entiteGenerique1.setPropertyValue(name.toString(), "name-f004");
    Coordinate[] exteriorCoord = new Coordinate[5];
    exteriorCoord[0] = new Coordinate(60.5, 0);
    exteriorCoord[1] = new Coordinate(64, 0);
    exteriorCoord[2] = new Coordinate(64, 6.25);
    exteriorCoord[3] = new Coordinate(60.5, 6.25);
    exteriorCoord[4] = new Coordinate(60.5, 0);
    LinearRing exterior = factory.createLinearRing(exteriorCoord);
    Coordinate[] interiorCoord = new Coordinate[4];
    interiorCoord[0] = new Coordinate(61.5, 2);
    interiorCoord[1] = new Coordinate(62.5, 2);
    interiorCoord[2] = new Coordinate(62, 4);
    interiorCoord[3] = new Coordinate(61.5, 2);
    LinearRing interior = factory.createLinearRing(interiorCoord);
    LinearRing[] interiors = new LinearRing[1];
    interiors[0] = interior;
    entiteGenerique1.setPropertyValue(attributGeometrie.toString(), factory.createPolygon(exterior, interiors));
    entiteGenerique1.setPropertyValue(boolProperty.toString(), false);
    entiteGenerique1.setPropertyValue(str4Property.toString(), "abc3");
    entiteGenerique1.setPropertyValue(featureRef.toString(), "name-f003");
    entiteGenerique1.setPropertyValue(id.toString(), "f004");
    /**
     *******************************************************************************************
     *                            EntitéGénérique 2                                              *
     ********************************************************************************************
     */
    final Feature entiteGenerique2 = entiteGeneriqueType.newInstance();
    entiteGenerique2.setPropertyValue(description.toString(), "description-f007");
    entiteGenerique2.setPropertyValue(name.toString(), "name-f007");
    Coordinate[] exteriorCoord2 = new Coordinate[6];
    exteriorCoord2[0] = new Coordinate(35, 15);
    exteriorCoord2[1] = new Coordinate(40, 16);
    exteriorCoord2[2] = new Coordinate(39, 20);
    exteriorCoord2[3] = new Coordinate(37, 22.5);
    exteriorCoord2[4] = new Coordinate(36, 18);
    exteriorCoord2[5] = new Coordinate(35, 15);
    LinearRing exterior2 = factory.createLinearRing(exteriorCoord);
    Coordinate[] interiorCoord2 = new Coordinate[7];
    interiorCoord2[0] = new Coordinate(37.1, 17.5);
    interiorCoord2[1] = new Coordinate(37.2, 17.6);
    interiorCoord2[2] = new Coordinate(37.3, 17.7);
    interiorCoord2[3] = new Coordinate(37.4, 17.8);
    interiorCoord2[4] = new Coordinate(37.5, 17.9);
    interiorCoord2[5] = new Coordinate(37, 17.9);
    interiorCoord2[6] = new Coordinate(37.1, 17.5);
    LinearRing interior2 = factory.createLinearRing(interiorCoord);
    LinearRing[] interiors2 = new LinearRing[1];
    interiors2[0] = interior;
    entiteGenerique2.setPropertyValue(attributGeometrie.toString(), factory.createPolygon(exterior2, interiors2));
    entiteGenerique2.setPropertyValue(boolProperty.toString(), false);
    entiteGenerique2.setPropertyValue(str4Property.toString(), "def4");
    entiteGenerique2.setPropertyValue(id.toString(), "f007");
    /**
     *******************************************************************************************
     *                            EntitéGénérique 3                                              *
     ********************************************************************************************
     */
    final Feature entiteGenerique3 = entiteGeneriqueType.newInstance();
    entiteGenerique3.setPropertyValue(description.toString(), "description-f017");
    entiteGenerique3.setPropertyValue(name.toString(), "name-f017");
    Coordinate[] lineCoord = new Coordinate[5];
    lineCoord[0] = new Coordinate(50.174, 4.899);
    lineCoord[1] = new Coordinate(52.652, 5.466);
    lineCoord[2] = new Coordinate(53.891, 6.899);
    lineCoord[3] = new Coordinate(54.382, 7.780);
    lineCoord[4] = new Coordinate(54.982, 8.879);
    entiteGenerique3.setPropertyValue(attributGeometrie.toString(), factory.createLineString(lineCoord));
    entiteGenerique3.setPropertyValue(boolProperty.toString(), false);
    entiteGenerique3.setPropertyValue(str4Property.toString(), "qrst");
    entiteGenerique3.setPropertyValue(featureRef.toString(), "name-f015");
    entiteGenerique3.setPropertyValue(id.toString(), "f017");
    /*
         * Filter equals on aggregateGeoFeature1
         */
    CoordinateReferenceSystem crs = CommonCRS.WGS84.geographic();
    JTSMultiPoint multiPoint = new JTSMultiPoint();
    multiPoint.getElements().add(new JTSPoint(new GeneralDirectPosition(70.83, 29.86), crs));
    multiPoint.getElements().add(new JTSPoint(new GeneralDirectPosition(68.87, 31.08), crs));
    multiPoint.getElements().add(new JTSPoint(new GeneralDirectPosition(71.96, 32.19), crs));
    BinarySpatialOperator equalsfilter = FF.equals(FF.property("{http://cite.opengeospatial.org/gmlsf}multiPointProperty"), FF.literal(multiPoint));
    boolean match = equalsfilter.test(aggregateGeoFeature1);
    assertTrue(match);
    /*
         * Filter intersects on entitiGenerique*
         */
    multiPoint = new JTSMultiPoint();
    multiPoint.getElements().add(new JTSPoint(new GeneralDirectPosition(38.83, 16.22), crs));
    multiPoint.getElements().add(new JTSPoint(new GeneralDirectPosition(62.07, 2.48), crs));
    BinarySpatialOperator intfilter = FF.intersects(FF.property("{http://cite.opengeospatial.org/gmlsf}attribut.Géométrie"), FF.literal(multiPoint));
    match = intfilter.test(entiteGenerique1);
    assertFalse(match);
    match = intfilter.test(entiteGenerique2);
    assertFalse(match);
    match = intfilter.test(entiteGenerique3);
    assertFalse(match);
}
Also used : FeatureTypeBuilder(org.apache.sis.feature.builder.FeatureTypeBuilder) FeatureType(org.opengis.feature.FeatureType) GeneralDirectPosition(org.apache.sis.geometry.GeneralDirectPosition) GeometryFactory(org.locationtech.jts.geom.GeometryFactory) JTSMultiPoint(org.geotoolkit.geometry.isoonjts.spatialschema.geometry.aggregate.JTSMultiPoint) JTSPoint(org.geotoolkit.geometry.isoonjts.spatialschema.geometry.primitive.JTSPoint) MultiLineString(org.locationtech.jts.geom.MultiLineString) Point(org.locationtech.jts.geom.Point) JTSPoint(org.geotoolkit.geometry.isoonjts.spatialschema.geometry.primitive.JTSPoint) MultiPoint(org.locationtech.jts.geom.MultiPoint) JTSMultiPoint(org.geotoolkit.geometry.isoonjts.spatialschema.geometry.aggregate.JTSMultiPoint) Feature(org.opengis.feature.Feature) GenericName(org.opengis.util.GenericName) Coordinate(org.locationtech.jts.geom.Coordinate) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) LinearRing(org.locationtech.jts.geom.LinearRing) BinarySpatialOperator(org.opengis.filter.BinarySpatialOperator) Test(org.junit.Test)

Example 2 with BinarySpatialOperator

use of org.opengis.filter.BinarySpatialOperator in project geotoolkit by Geomatys.

the class LuceneOGCWeight method scorer.

@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
    // final SortedDocValues values = context.reader().getSortedDocValues(IDENTIFIER_FIELD_NAME);
    final LeafReader reader = context.reader();
    boolean treeSearch = false;
    boolean reverse = false;
    boolean distanceFilter = false;
    final Set<String> treeMatching = new HashSet<>();
    if (tree != null) {
        /*
             * For distance buffer filter no envelope only mode
             */
        List<Expression<Object, ?>> expressions = filter.getExpressions();
        Expression e2 = (expressions.size() >= 2) ? expressions.get(1) : null;
        if (filter instanceof DistanceOperator) {
            distanceFilter = true;
            reverse = filter.getOperatorType() == DistanceOperatorName.BEYOND;
            final DistanceOperator sp = (DistanceOperator) filter;
            if (e2 instanceof Literal) {
                try {
                    final Literal lit = (Literal) e2;
                    Quantity distance = sp.getDistance();
                    final GeneralEnvelope bound = getExtendedReprojectedEnvelope(lit.getValue(), tree.getCrs(), distance.getUnit().toString(), distance.getValue().doubleValue());
                    final int[] resultID = tree.searchID(bound);
                    Arrays.sort(resultID);
                    treeMatching.clear();
                    TreeElementMapper<NamedEnvelope> tem = tree.getTreeElementMapper();
                    for (int id : resultID) {
                        final NamedEnvelope env = tem.getObjectFromTreeIdentifier(id);
                        if (env != null) {
                            treeMatching.add(env.getId());
                        }
                    }
                    treeSearch = true;
                } catch (FactoryException ex) {
                    throw new IOException(ex);
                } catch (StoreIndexException ex) {
                    Throwable cause = ex.getCause();
                    if (cause instanceof IOException) {
                        throw (IOException) cause;
                    } else {
                        throw new IOException(ex);
                    }
                }
            } else {
                LOGGER.log(Level.WARNING, "Not a literal for spatial filter:{0}", e2);
            }
        } else if (filter instanceof BinarySpatialOperator) {
            final BinarySpatialOperator sp = (BinarySpatialOperator) filter;
            if (e2 instanceof Literal) {
                final Literal lit = (Literal) e2;
                final Envelope boundFilter = getReprojectedEnvelope(lit.getValue(), tree.getCrs());
                try {
                    if (filterType == SpatialFilterType.CROSSES || !envelopeOnly) {
                        if (filterType == SpatialFilterType.DISJOINT) {
                            reverse = true;
                        }
                        final int[] resultID = tree.searchID(boundFilter);
                        Arrays.sort(resultID);
                        final TreeElementMapper<NamedEnvelope> tem = tree.getTreeElementMapper();
                        treeMatching.clear();
                        for (int id : resultID) {
                            final NamedEnvelope env = tem.getObjectFromTreeIdentifier(id);
                            if (env != null) {
                                treeMatching.add(env.getId());
                            }
                        }
                        treeSearch = true;
                        envelopeOnly = false;
                    } else {
                        final int[] resultID = TreeX.search(tree, boundFilter, filterType);
                        Arrays.sort(resultID);
                        final TreeElementMapper<NamedEnvelope> tem = tree.getTreeElementMapper();
                        treeMatching.clear();
                        for (int id : resultID) {
                            final NamedEnvelope env = tem.getObjectFromTreeIdentifier(id);
                            if (env != null) {
                                treeMatching.add(env.getId());
                            }
                        }
                        treeSearch = true;
                    }
                } catch (StoreIndexException ex) {
                    Throwable cause = ex.getCause();
                    if (cause instanceof IOException) {
                        throw (IOException) cause;
                    } else {
                        throw new IOException(ex);
                    }
                }
            } else {
                LOGGER.log(Level.WARNING, "Not a literal for spatial filter:{0}", e2);
            }
        } else {
            LOGGER.log(Level.WARNING, "not a spatial operator:{0}", filter.getClass().getName());
        }
    } else {
        LOGGER.finer("Null R-tree in spatial search");
    }
    final BitSet set = new FixedBitSet(reader.maxDoc());
    Bits b = reader.getLiveDocs();
    if (b == null) {
        b = new Bits.MatchAllBits(reader.maxDoc());
    }
    for (int i = 0; i < b.length(); i++) {
        if (b.get(i)) {
            final int docId = i;
            final Document doc = reader.document(docId, ID_FIELDS);
            final String id = doc.get(IDENTIFIER_FIELD_NAME);
            final boolean match = treeMatching.contains(id);
            if (treeSearch && reverse && !match) {
                set.set(docId);
            } else if (!treeSearch || match) {
                if (envelopeOnly && !distanceFilter) {
                    set.set(docId);
                } else {
                    final Document geoDoc = reader.document(docId, GEOMETRY_FIELDS);
                    if (filter.test(geoDoc)) {
                        set.set(docId);
                    }
                }
            }
        }
    }
    return new ConstantScoreScorer(this, boost, scoreMode, new BitSetIterator(set, 5));
}
Also used : NamedEnvelope(org.geotoolkit.index.tree.manager.NamedEnvelope) FactoryException(org.opengis.util.FactoryException) Envelope(org.opengis.geometry.Envelope) GeneralEnvelope(org.apache.sis.geometry.GeneralEnvelope) LuceneUtils.getReprojectedEnvelope(org.geotoolkit.lucene.LuceneUtils.getReprojectedEnvelope) LuceneUtils.getExtendedReprojectedEnvelope(org.geotoolkit.lucene.LuceneUtils.getExtendedReprojectedEnvelope) NamedEnvelope(org.geotoolkit.index.tree.manager.NamedEnvelope) Document(org.apache.lucene.document.Document) ConstantScoreScorer(org.apache.lucene.search.ConstantScoreScorer) FixedBitSet(org.apache.lucene.util.FixedBitSet) Literal(org.opengis.filter.Literal) HashSet(java.util.HashSet) BinarySpatialOperator(org.opengis.filter.BinarySpatialOperator) StoreIndexException(org.geotoolkit.index.tree.StoreIndexException) BitSetIterator(org.apache.lucene.util.BitSetIterator) LeafReader(org.apache.lucene.index.LeafReader) DistanceOperator(org.opengis.filter.DistanceOperator) FixedBitSet(org.apache.lucene.util.FixedBitSet) BitSet(org.apache.lucene.util.BitSet) Quantity(javax.measure.Quantity) IOException(java.io.IOException) Expression(org.opengis.filter.Expression) TreeElementMapper(org.geotoolkit.index.tree.TreeElementMapper) Bits(org.apache.lucene.util.Bits) GeneralEnvelope(org.apache.sis.geometry.GeneralEnvelope)

Example 3 with BinarySpatialOperator

use of org.opengis.filter.BinarySpatialOperator in project geotoolkit by Geomatys.

the class OGC110Test method testFilterSpatialOverlaps.

@Test
public void testFilterSpatialOverlaps() throws JAXBException, NoSuchAuthorityCodeException, FactoryException {
    final Unmarshaller UNMARSHALLER = POOL.acquireUnmarshaller();
    final Marshaller MARSHALLER = POOL.acquireMarshaller();
    // Read test
    Object obj = UNMARSHALLER.unmarshal(FILE_FIL_SPA_OVERLAPS2);
    assertNotNull(obj);
    JAXBElement<? extends FilterType> jaxfilter = (JAXBElement<? extends FilterType>) obj;
    assertNotNull(jaxfilter);
    Filter filter = TRANSFORMER_GT.visitFilter(jaxfilter.getValue());
    assertNotNull(filter);
    BinarySpatialOperator prop = (BinarySpatialOperator) filter;
    BinarySpatialOperator subfilter = (BinarySpatialOperator) prop;
    ValueReference left = (ValueReference) subfilter.getOperand1();
    Literal right = (Literal) subfilter.getOperand2();
    assertEquals(left.getXPath(), valueStr);
    assertEquals(right.apply(null).toString().trim(), "LINESTRING (46.652 10.466, 47.114 11.021, 46.114 12.114, 45.725 12.523)");
    POOL.recycle(MARSHALLER);
    POOL.recycle(UNMARSHALLER);
// write test - not yet
// FilterType ft = TRANSFORMER_OGC.apply(filter);
// assertNotNull(ft.getSpatialOps());
// 
// SpatialOpsType cot = ft.getSpatialOps().getValue();
// assertEquals( ft.getLogicOps().getName().getLocalPart(), SEJAXBStatics.FILTER_SPATIAL_OVERLAPS);
// OverlapsType pibt = (OverlapsType) cot;
// 
// BinarySpatialOperator leftoptype = (BinarySpatialOperator) pibt.getComparisonOps().getValue();
// 
// PropertyNameType lf = (PropertyNameType) leftoptype.getExpression().get(0).getValue();
// LiteralType rg = (LiteralType) leftoptype.getExpression().get(1).getValue();
// 
// assertEquals(lf.getContent(), valueStr);
// assertEquals(rg.getContent().get(0).toString().trim(), valueFStr );
// 
// MARSHALLER.marshal(ft.getLogicOps(), TEST_FILE_FIL_SPA_OVERLAPS2);
}
Also used : Marshaller(javax.xml.bind.Marshaller) FilterType(org.geotoolkit.ogc.xml.v110.FilterType) Filter(org.opengis.filter.Filter) Literal(org.opengis.filter.Literal) JAXBElement(javax.xml.bind.JAXBElement) Unmarshaller(javax.xml.bind.Unmarshaller) BinarySpatialOperator(org.opengis.filter.BinarySpatialOperator) ValueReference(org.opengis.filter.ValueReference) Test(org.junit.Test)

Example 4 with BinarySpatialOperator

use of org.opengis.filter.BinarySpatialOperator in project geotoolkit by Geomatys.

the class FilterToOGC110Converter method visit.

public JAXBElement<?> visit(final Filter filter) {
    if (filter.equals(Filter.include())) {
        return null;
    }
    if (filter.equals(Filter.exclude())) {
        return null;
    }
    final CodeList<?> type = filter.getOperatorType();
    if (filter instanceof BetweenComparisonOperator) {
        final BetweenComparisonOperator pib = (BetweenComparisonOperator) filter;
        final LowerBoundaryType lbt = ogc_factory.createLowerBoundaryType();
        lbt.setExpression(extract(pib.getLowerBoundary()));
        final UpperBoundaryType ubt = ogc_factory.createUpperBoundaryType();
        ubt.setExpression(extract(pib.getUpperBoundary()));
        final PropertyIsBetweenType bot = new PropertyIsBetweenType(extract(pib.getExpression()), lbt, ubt);
        return ogc_factory.createPropertyIsBetween(bot);
    } else if (type == ComparisonOperatorName.PROPERTY_IS_EQUAL_TO) {
        final BinaryComparisonOperator pit = (BinaryComparisonOperator) filter;
        final PropertyIsEqualToType bot = ogc_factory.createPropertyIsEqualToType();
        bot.getExpression().add(extract(pit.getOperand1()));
        bot.getExpression().add(extract(pit.getOperand2()));
        return ogc_factory.createPropertyIsEqualTo(bot);
    } else if (type == ComparisonOperatorName.PROPERTY_IS_GREATER_THAN) {
        final BinaryComparisonOperator pit = (BinaryComparisonOperator) filter;
        final PropertyIsGreaterThanType bot = ogc_factory.createPropertyIsGreaterThanType();
        bot.getExpression().add(extract(pit.getOperand1()));
        bot.getExpression().add(extract(pit.getOperand2()));
        return ogc_factory.createPropertyIsGreaterThan(bot);
    } else if (type == ComparisonOperatorName.PROPERTY_IS_GREATER_THAN_OR_EQUAL_TO) {
        final BinaryComparisonOperator pit = (BinaryComparisonOperator) filter;
        final PropertyIsGreaterThanOrEqualToType bot = ogc_factory.createPropertyIsGreaterThanOrEqualToType();
        bot.getExpression().add(extract(pit.getOperand1()));
        bot.getExpression().add(extract(pit.getOperand2()));
        return ogc_factory.createPropertyIsGreaterThanOrEqualTo(bot);
    } else if (type == ComparisonOperatorName.PROPERTY_IS_LESS_THAN) {
        final BinaryComparisonOperator pit = (BinaryComparisonOperator) filter;
        final PropertyIsLessThanType bot = ogc_factory.createPropertyIsLessThanType();
        bot.getExpression().add(extract(pit.getOperand1()));
        bot.getExpression().add(extract(pit.getOperand2()));
        return ogc_factory.createPropertyIsLessThan(bot);
    } else if (type == ComparisonOperatorName.PROPERTY_IS_LESS_THAN_OR_EQUAL_TO) {
        final BinaryComparisonOperator pit = (BinaryComparisonOperator) filter;
        final PropertyIsLessThanOrEqualToType bot = ogc_factory.createPropertyIsLessThanOrEqualToType();
        bot.getExpression().add(extract(pit.getOperand1()));
        bot.getExpression().add(extract(pit.getOperand2()));
        return ogc_factory.createPropertyIsLessThanOrEqualTo(bot);
    } else if (filter instanceof LikeOperator) {
        final LikeOperator pis = (LikeOperator) filter;
        final List<Expression> expressions = filter.getExpressions();
        final PropertyIsLikeType bot = ogc_factory.createPropertyIsLikeType();
        bot.setEscapeChar(String.valueOf(pis.getEscapeChar()));
        final LiteralType lt = ogc_factory.createLiteralType();
        lt.setContent(((Literal) expressions.get(1)).getValue());
        bot.setLiteral(lt.getStringValue());
        final Expression expression = expressions.get(0);
        if (!(expression instanceof ValueReference)) {
            throw new IllegalArgumentException("LikeOperator can support ValueReference only, but was a " + expression);
        }
        final PropertyNameType pnt = (PropertyNameType) extract(expression).getValue();
        bot.setPropertyName(pnt);
        bot.setSingleChar(String.valueOf(pis.getSingleChar()));
        bot.setWildCard(String.valueOf(pis.getWildCard()));
        return ogc_factory.createPropertyIsLike(bot);
    } else if (type == ComparisonOperatorName.PROPERTY_IS_NOT_EQUAL_TO) {
        final BinaryComparisonOperator pit = (BinaryComparisonOperator) filter;
        final PropertyIsNotEqualToType bot = ogc_factory.createPropertyIsNotEqualToType();
        bot.getExpression().add(extract(pit.getOperand1()));
        bot.getExpression().add(extract(pit.getOperand2()));
        return ogc_factory.createPropertyIsNotEqualTo(bot);
    } else if (filter instanceof NullOperator) {
        final NullOperator pis = (NullOperator) filter;
        final PropertyIsNullType bot = ogc_factory.createPropertyIsNullType();
        final Object obj = extract((Expression) pis.getExpressions().get(0)).getValue();
        bot.setPropertyName((PropertyNameType) obj);
        return ogc_factory.createPropertyIsNull(bot);
    } else if (type == LogicalOperatorName.AND) {
        final LogicalOperator and = (LogicalOperator) filter;
        final List<JAXBElement> children = new ArrayList<>();
        for (final Filter f : (List<Filter>) and.getOperands()) {
            final JAXBElement<? extends LogicOpsType> ele = (JAXBElement<? extends LogicOpsType>) visit(f);
            if (ele != null) {
                children.add(ele);
            }
        }
        return ogc_factory.createAnd(new AndType(children.toArray()));
    } else if (type == LogicalOperatorName.OR) {
        final LogicalOperator or = (LogicalOperator) filter;
        final List<JAXBElement> children = new ArrayList<>();
        for (final Filter f : (List<Filter>) or.getOperands()) {
            final JAXBElement<? extends LogicOpsType> ele = (JAXBElement<? extends LogicOpsType>) visit(f);
            if (ele != null) {
                children.add(ele);
            }
        }
        return ogc_factory.createOr(new OrType(children.toArray()));
    } else if (type == LogicalOperatorName.NOT) {
        final LogicalOperator not = (LogicalOperator) filter;
        JAXBElement<?> sf = visit((Filter) not.getOperands().get(0));
        return ogc_factory.createNot(new NotType(sf.getValue()));
    } else if (filter instanceof ResourceId) {
        throw new IllegalArgumentException("Not parsed yet : " + filter);
    } else if (type == SpatialOperatorName.BBOX) {
        final BBOX bbox = BBOX.wrap((BinarySpatialOperator) filter);
        final Expression left = bbox.getOperand1();
        final Expression right = bbox.getOperand2();
        final String property;
        final double minx;
        final double maxx;
        final double miny;
        final double maxy;
        String srs;
        if (left instanceof ValueReference) {
            property = ((ValueReference) left).getXPath();
            final Object objGeom = ((Literal) right).getValue();
            if (objGeom instanceof org.opengis.geometry.Envelope) {
                final org.opengis.geometry.Envelope env = (org.opengis.geometry.Envelope) objGeom;
                minx = env.getMinimum(0);
                maxx = env.getMaximum(0);
                miny = env.getMinimum(1);
                maxy = env.getMaximum(1);
                try {
                    srs = IdentifiedObjects.lookupURN(env.getCoordinateReferenceSystem(), null);
                    if (srs == null) {
                        srs = ReferencingUtilities.lookupIdentifier(env.getCoordinateReferenceSystem(), true);
                    }
                } catch (FactoryException ex) {
                    throw new IllegalArgumentException("invalid bbox element : " + filter + " " + ex.getMessage(), ex);
                }
            } else if (objGeom instanceof Geometry) {
                final Geometry geom = (Geometry) objGeom;
                final Envelope env = geom.getEnvelopeInternal();
                minx = env.getMinX();
                maxx = env.getMaxX();
                miny = env.getMinY();
                maxy = env.getMaxY();
                srs = SRIDGenerator.toSRS(geom.getSRID(), SRIDGenerator.Version.V1);
            } else {
                throw new IllegalArgumentException("invalide bbox element : " + filter);
            }
        } else if (right instanceof ValueReference) {
            property = ((ValueReference) right).getXPath();
            final Object objGeom = ((Literal) left).getValue();
            if (objGeom instanceof org.opengis.geometry.Envelope) {
                final org.opengis.geometry.Envelope env = (org.opengis.geometry.Envelope) objGeom;
                minx = env.getMinimum(0);
                maxx = env.getMaximum(0);
                miny = env.getMinimum(1);
                maxy = env.getMaximum(1);
                try {
                    srs = IdentifiedObjects.lookupURN(env.getCoordinateReferenceSystem(), null);
                } catch (FactoryException ex) {
                    throw new IllegalArgumentException("invalide bbox element : " + filter + " " + ex.getMessage(), ex);
                }
            } else if (objGeom instanceof Geometry) {
                final Geometry geom = (Geometry) objGeom;
                final Envelope env = geom.getEnvelopeInternal();
                minx = env.getMinX();
                maxx = env.getMaxX();
                miny = env.getMinY();
                maxy = env.getMaxY();
                srs = SRIDGenerator.toSRS(geom.getSRID(), SRIDGenerator.Version.V1);
            } else {
                throw new IllegalArgumentException("invalide bbox element : " + filter);
            }
        } else {
            throw new IllegalArgumentException("invalide bbox element : " + filter);
        }
        final BBOXType bbtype = new BBOXType(property, minx, miny, maxx, maxy, srs);
        return ogc_factory.createBBOX(bbtype);
    } else if (filter instanceof ResourceId) {
        // todo OGC filter can not handle ID when we are inside another filter type
        // so here we make a small tric to change an id filter in a serie of propertyequal filter
        // this is not really legal but we dont have the choice here
        // we should propose an evolution of ogc filter do consider id filter as a comparison filter
        final ValueReference n = FF.property(AttributeConvention.IDENTIFIER);
        String ident = ((ResourceId) filter).getIdentifier();
        return visit(FF.equal(n, FF.literal(ident)));
    } else if (filter instanceof SpatialOperator) {
        final BinarySpatialOperator spatialOp = (BinarySpatialOperator) filter;
        Expression exp1 = spatialOp.getOperand1();
        Expression exp2 = spatialOp.getOperand2();
        if (!(exp1 instanceof ValueReference)) {
            // flip order
            final Expression ex = exp1;
            exp1 = exp2;
            exp2 = ex;
        }
        if (!(exp1 instanceof ValueReference)) {
            throw new IllegalArgumentException("Filter can not be transformed in wml filter, " + "expression are not of the requiered type ");
        }
        final JAXBElement<PropertyNameType> pnt = (JAXBElement<PropertyNameType>) extract(exp1);
        final JAXBElement<EnvelopeType> jaxEnv;
        final JAXBElement<? extends AbstractGeometryType> jaxGeom;
        final Object geom = ((Literal) exp2).getValue();
        if (geom instanceof Geometry) {
            final Geometry jts = (Geometry) geom;
            final String srid = SRIDGenerator.toSRS(jts.getSRID(), SRIDGenerator.Version.V1);
            CoordinateReferenceSystem crs;
            try {
                crs = CRS.forCode(srid);
            } catch (Exception ex) {
                Logger.getLogger("org.geotoolkit.sld.xml").log(Level.WARNING, null, ex);
                crs = null;
            }
            final AbstractGeometryType gt = GMLUtilities.getGMLFromISO(JTSUtils.toISO(jts, crs));
            // TODO use gml method to return any JAXBElement
            if (gt instanceof PointType) {
                jaxGeom = gml_factory.createPoint((PointType) gt);
            } else if (gt instanceof CurveType) {
                jaxGeom = gml_factory.createCurve((CurveType) gt);
            } else if (gt instanceof LineStringType) {
                jaxGeom = gml_factory.createLineString((LineStringType) gt);
            } else if (gt instanceof PolygonType) {
                jaxGeom = gml_factory.createPolygon((PolygonType) gt);
            } else if (gt instanceof MultiPolygonType) {
                jaxGeom = gml_factory.createMultiPolygon((MultiPolygonType) gt);
            } else if (gt instanceof MultiLineStringType) {
                jaxGeom = gml_factory.createMultiLineString((MultiLineStringType) gt);
            } else if (gt instanceof MultiCurveType) {
                jaxGeom = gml_factory.createMultiLineString((MultiLineStringType) gt);
            } else if (gt instanceof MultiPointType) {
                jaxGeom = gml_factory.createMultiLineString((MultiLineStringType) gt);
            } else if (gt instanceof MultiGeometryType) {
                jaxGeom = gml_factory.createMultiGeometry((MultiGeometryType) gt);
            } else if (gt instanceof PolyhedralSurfaceType) {
                jaxGeom = gml_factory.createPolyhedralSurface((PolyhedralSurfaceType) gt);
            } else if (gt != null) {
                throw new IllegalArgumentException("unexpected Geometry type:" + gt.getClass().getName());
            } else {
                jaxGeom = null;
            }
            jaxEnv = null;
        } else if (geom instanceof org.opengis.geometry.Geometry) {
            final AbstractGeometryType gt = GMLUtilities.getGMLFromISO((org.opengis.geometry.Geometry) geom);
            // TODO use gml method to return any JAXBElement
            if (gt instanceof PointType) {
                jaxGeom = gml_factory.createPoint((PointType) gt);
            } else if (gt instanceof CurveType) {
                jaxGeom = gml_factory.createCurve((CurveType) gt);
            } else if (gt instanceof LineStringType) {
                jaxGeom = gml_factory.createLineString((LineStringType) gt);
            } else if (gt instanceof PolygonType) {
                jaxGeom = gml_factory.createPolygon((PolygonType) gt);
            } else if (gt instanceof MultiPolygonType) {
                jaxGeom = gml_factory.createMultiPolygon((MultiPolygonType) gt);
            } else if (gt instanceof MultiLineStringType) {
                jaxGeom = gml_factory.createMultiLineString((MultiLineStringType) gt);
            } else if (gt instanceof MultiCurveType) {
                jaxGeom = gml_factory.createMultiLineString((MultiLineStringType) gt);
            } else if (gt instanceof MultiPointType) {
                jaxGeom = gml_factory.createMultiLineString((MultiLineStringType) gt);
            } else if (gt instanceof MultiGeometryType) {
                jaxGeom = gml_factory.createMultiGeometry((MultiGeometryType) gt);
            } else if (gt instanceof PolyhedralSurfaceType) {
                jaxGeom = gml_factory.createPolyhedralSurface((PolyhedralSurfaceType) gt);
            } else if (gt != null) {
                throw new IllegalArgumentException("unexpected Geometry type:" + gt.getClass().getName());
            } else {
                jaxGeom = null;
            }
            jaxEnv = null;
        } else if (geom instanceof org.opengis.geometry.Envelope) {
            final org.opengis.geometry.Envelope genv = (org.opengis.geometry.Envelope) geom;
            EnvelopeType ee = gml_factory.createEnvelopeType();
            try {
                ee.setSrsName(IdentifiedObjects.lookupURN(genv.getCoordinateReferenceSystem(), null));
            } catch (FactoryException ex) {
                Logger.getLogger("org.geotoolkit.sld.xml").log(Level.WARNING, null, ex);
            }
            ee.setLowerCorner(new DirectPositionType(genv.getLowerCorner()));
            ee.setUpperCorner(new DirectPositionType(genv.getUpperCorner()));
            jaxGeom = null;
            jaxEnv = gml_factory.createEnvelope(ee);
        } else {
            throw new IllegalArgumentException("Type is not geometric or envelope.");
        }
        if (type == DistanceOperatorName.BEYOND) {
            final BeyondType jaxelement = ogc_factory.createBeyondType();
            jaxelement.setAbstractGeometry(jaxGeom);
            jaxelement.setPropertyName(pnt.getValue());
            return ogc_factory.createBeyond(jaxelement);
        } else if (type == SpatialOperatorName.CONTAINS) {
            final ContainsType jaxelement = ogc_factory.createContainsType();
            jaxelement.setAbstractGeometry(jaxGeom);
            jaxelement.setEnvelope(jaxEnv);
            jaxelement.setPropertyName(pnt);
            return ogc_factory.createContains(jaxelement);
        } else if (type == SpatialOperatorName.CROSSES) {
            final CrossesType jaxelement = ogc_factory.createCrossesType();
            jaxelement.setAbstractGeometry(jaxGeom);
            jaxelement.setEnvelope(jaxEnv);
            jaxelement.setPropertyName(pnt);
            return ogc_factory.createCrosses(jaxelement);
        } else if (type == DistanceOperatorName.WITHIN) {
            final DWithinType jaxelement = ogc_factory.createDWithinType();
            jaxelement.setAbstractGeometry(jaxGeom);
            jaxelement.setPropertyName(pnt.getValue());
            return ogc_factory.createDWithin(jaxelement);
        } else if (type == SpatialOperatorName.DISJOINT) {
            final DisjointType jaxelement = ogc_factory.createDisjointType();
            jaxelement.setAbstractGeometry(jaxGeom);
            jaxelement.setEnvelope(jaxEnv);
            jaxelement.setPropertyName(pnt);
            return ogc_factory.createDisjoint(jaxelement);
        } else if (type == SpatialOperatorName.EQUALS) {
            final EqualsType jaxelement = ogc_factory.createEqualsType();
            jaxelement.setAbstractGeometry(jaxGeom);
            jaxelement.setEnvelope(jaxEnv);
            jaxelement.setPropertyName(pnt);
            return ogc_factory.createEquals(jaxelement);
        } else if (type == SpatialOperatorName.INTERSECTS) {
            final IntersectsType jaxelement = ogc_factory.createIntersectsType();
            jaxelement.setAbstractGeometry(jaxGeom);
            jaxelement.setEnvelope(jaxEnv);
            jaxelement.setPropertyName(pnt);
            return ogc_factory.createIntersects(jaxelement);
        } else if (type == SpatialOperatorName.OVERLAPS) {
            final OverlapsType jaxelement = new OverlapsType();
            jaxelement.setAbstractGeometry(jaxGeom);
            jaxelement.setEnvelope(jaxEnv);
            jaxelement.setPropertyName(pnt);
            return ogc_factory.createOverlaps(jaxelement);
        } else if (type == SpatialOperatorName.TOUCHES) {
            final TouchesType jaxelement = ogc_factory.createTouchesType();
            jaxelement.setAbstractGeometry(jaxGeom);
            jaxelement.setEnvelope(jaxEnv);
            jaxelement.setPropertyName(pnt);
            return ogc_factory.createTouches(jaxelement);
        } else if (type == SpatialOperatorName.WITHIN) {
            final WithinType jaxelement = ogc_factory.createWithinType();
            jaxelement.setAbstractGeometry(jaxGeom);
            jaxelement.setEnvelope(jaxEnv);
            jaxelement.setPropertyName(pnt);
            return ogc_factory.createWithin(jaxelement);
        } else {
            throw new IllegalArgumentException("Unknowed filter element : " + filter + " class :" + filter.getClass());
        }
    } else {
        throw new IllegalArgumentException("Unknowed filter element : " + filter + " class :" + filter.getClass());
    }
}
Also used : OverlapsType(org.geotoolkit.ogc.xml.v110.OverlapsType) FactoryException(org.opengis.util.FactoryException) MultiCurveType(org.geotoolkit.gml.xml.v311.MultiCurveType) BeyondType(org.geotoolkit.ogc.xml.v110.BeyondType) ArrayList(java.util.ArrayList) MultiGeometryType(org.geotoolkit.gml.xml.v311.MultiGeometryType) CrossesType(org.geotoolkit.ogc.xml.v110.CrossesType) DWithinType(org.geotoolkit.ogc.xml.v110.DWithinType) NotType(org.geotoolkit.ogc.xml.v110.NotType) Literal(org.opengis.filter.Literal) DisjointType(org.geotoolkit.ogc.xml.v110.DisjointType) MultiLineStringType(org.geotoolkit.gml.xml.v311.MultiLineStringType) CodeList(org.opengis.util.CodeList) List(java.util.List) ArrayList(java.util.ArrayList) PropertyIsBetweenType(org.geotoolkit.ogc.xml.v110.PropertyIsBetweenType) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) BetweenComparisonOperator(org.opengis.filter.BetweenComparisonOperator) ValueReference(org.opengis.filter.ValueReference) PropertyNameType(org.geotoolkit.ogc.xml.v110.PropertyNameType) DWithinType(org.geotoolkit.ogc.xml.v110.DWithinType) WithinType(org.geotoolkit.ogc.xml.v110.WithinType) AbstractGeometryType(org.geotoolkit.gml.xml.v311.AbstractGeometryType) PropertyIsGreaterThanType(org.geotoolkit.ogc.xml.v110.PropertyIsGreaterThanType) LogicalOperator(org.opengis.filter.LogicalOperator) PolygonType(org.geotoolkit.gml.xml.v311.PolygonType) MultiPolygonType(org.geotoolkit.gml.xml.v311.MultiPolygonType) JAXBElement(javax.xml.bind.JAXBElement) IntersectsType(org.geotoolkit.ogc.xml.v110.IntersectsType) LineStringType(org.geotoolkit.gml.xml.v311.LineStringType) MultiLineStringType(org.geotoolkit.gml.xml.v311.MultiLineStringType) PropertyIsGreaterThanOrEqualToType(org.geotoolkit.ogc.xml.v110.PropertyIsGreaterThanOrEqualToType) MultiPointType(org.geotoolkit.gml.xml.v311.MultiPointType) LogicOpsType(org.geotoolkit.ogc.xml.v110.LogicOpsType) UpperBoundaryType(org.geotoolkit.ogc.xml.v110.UpperBoundaryType) PropertyIsNotEqualToType(org.geotoolkit.ogc.xml.v110.PropertyIsNotEqualToType) ContainsType(org.geotoolkit.ogc.xml.v110.ContainsType) BBOXType(org.geotoolkit.ogc.xml.v110.BBOXType) LikeOperator(org.opengis.filter.LikeOperator) BinaryComparisonOperator(org.opengis.filter.BinaryComparisonOperator) PolyhedralSurfaceType(org.geotoolkit.gml.xml.v311.PolyhedralSurfaceType) PropertyIsLikeType(org.geotoolkit.ogc.xml.v110.PropertyIsLikeType) PropertyIsLessThanType(org.geotoolkit.ogc.xml.v110.PropertyIsLessThanType) AndType(org.geotoolkit.ogc.xml.v110.AndType) DirectPositionType(org.geotoolkit.gml.xml.v311.DirectPositionType) CurveType(org.geotoolkit.gml.xml.v311.CurveType) MultiCurveType(org.geotoolkit.gml.xml.v311.MultiCurveType) PropertyIsLessThanOrEqualToType(org.geotoolkit.ogc.xml.v110.PropertyIsLessThanOrEqualToType) Envelope(org.locationtech.jts.geom.Envelope) PropertyIsNullType(org.geotoolkit.ogc.xml.v110.PropertyIsNullType) EqualsType(org.geotoolkit.ogc.xml.v110.EqualsType) BinarySpatialOperator(org.opengis.filter.BinarySpatialOperator) OrType(org.geotoolkit.ogc.xml.v110.OrType) EnvelopeType(org.geotoolkit.gml.xml.v311.EnvelopeType) MultiPolygonType(org.geotoolkit.gml.xml.v311.MultiPolygonType) LiteralType(org.geotoolkit.ogc.xml.v110.LiteralType) NullOperator(org.opengis.filter.NullOperator) FactoryException(org.opengis.util.FactoryException) Geometry(org.locationtech.jts.geom.Geometry) PropertyIsEqualToType(org.geotoolkit.ogc.xml.v110.PropertyIsEqualToType) Expression(org.opengis.filter.Expression) Filter(org.opengis.filter.Filter) ResourceId(org.opengis.filter.ResourceId) PointType(org.geotoolkit.gml.xml.v311.PointType) MultiPointType(org.geotoolkit.gml.xml.v311.MultiPointType) LowerBoundaryType(org.geotoolkit.ogc.xml.v110.LowerBoundaryType) BinarySpatialOperator(org.opengis.filter.BinarySpatialOperator) TouchesType(org.geotoolkit.ogc.xml.v110.TouchesType)

Example 5 with BinarySpatialOperator

use of org.opengis.filter.BinarySpatialOperator in project geotoolkit by Geomatys.

the class FilterToOGC200Converter method visit.

public JAXBElement visit(Filter filter) {
    if (filter.equals(Filter.include()) || filter.equals(Filter.exclude())) {
        return null;
    }
    final CodeList<?> type = filter.getOperatorType();
    if (filter instanceof BetweenComparisonOperator) {
        final BetweenComparisonOperator pib = (BetweenComparisonOperator) filter;
        final LowerBoundaryType lbt = ogc_factory.createLowerBoundaryType();
        lbt.setExpression(extract(pib.getLowerBoundary()));
        final UpperBoundaryType ubt = ogc_factory.createUpperBoundaryType();
        ubt.setExpression(extract(pib.getUpperBoundary()));
        final PropertyIsBetweenType bot = new PropertyIsBetweenType();
        bot.setExpression(extract(pib.getExpression()));
        bot.setLowerBoundary(lbt);
        bot.setUpperBoundary(ubt);
        return ogc_factory.createPropertyIsBetween(bot);
    } else if (type == ComparisonOperatorName.PROPERTY_IS_EQUAL_TO) {
        final BinaryComparisonOperator pit = (BinaryComparisonOperator) filter;
        final PropertyIsEqualToType bot = new PropertyIsEqualToType();
        bot.getExpression().add(extract(pit.getOperand1()));
        bot.getExpression().add(extract(pit.getOperand2()));
        return ogc_factory.createPropertyIsEqualTo(bot);
    } else if (type == ComparisonOperatorName.PROPERTY_IS_GREATER_THAN) {
        final BinaryComparisonOperator pit = (BinaryComparisonOperator) filter;
        final PropertyIsGreaterThanType bot = new PropertyIsGreaterThanType();
        bot.getExpression().add(extract(pit.getOperand1()));
        bot.getExpression().add(extract(pit.getOperand2()));
        return ogc_factory.createPropertyIsGreaterThan(bot);
    } else if (type == ComparisonOperatorName.PROPERTY_IS_GREATER_THAN_OR_EQUAL_TO) {
        final BinaryComparisonOperator pit = (BinaryComparisonOperator) filter;
        final PropertyIsGreaterThanOrEqualToType bot = new PropertyIsGreaterThanOrEqualToType();
        bot.getExpression().add(extract(pit.getOperand1()));
        bot.getExpression().add(extract(pit.getOperand2()));
        return ogc_factory.createPropertyIsGreaterThanOrEqualTo(bot);
    } else if (type == ComparisonOperatorName.PROPERTY_IS_LESS_THAN) {
        final BinaryComparisonOperator pit = (BinaryComparisonOperator) filter;
        final PropertyIsLessThanType bot = new PropertyIsLessThanType();
        bot.getExpression().add(extract(pit.getOperand1()));
        bot.getExpression().add(extract(pit.getOperand2()));
        return ogc_factory.createPropertyIsLessThan(bot);
    } else if (type == ComparisonOperatorName.PROPERTY_IS_LESS_THAN_OR_EQUAL_TO) {
        final BinaryComparisonOperator pit = (BinaryComparisonOperator) filter;
        final PropertyIsLessThanOrEqualToType bot = new PropertyIsLessThanOrEqualToType();
        bot.getExpression().add(extract(pit.getOperand1()));
        bot.getExpression().add(extract(pit.getOperand2()));
        return ogc_factory.createPropertyIsLessThanOrEqualTo(bot);
    } else if (filter instanceof LikeOperator) {
        final LikeOperator pis = (LikeOperator) filter;
        final List<Expression> expressions = filter.getExpressions();
        final PropertyIsLikeType bot = ogc_factory.createPropertyIsLikeType();
        bot.setEscape(String.valueOf(pis.getEscapeChar()));
        final LiteralType lt = ogc_factory.createLiteralType();
        lt.setContent(((Literal) expressions.get(1)).getValue());
        bot.getElements().add(ogc_factory.createLiteral(lt));
        final Expression expression = expressions.get(0);
        if (!(expression instanceof ValueReference)) {
            throw new IllegalArgumentException("LikeOperator can support ValueReference only, but was a " + expression);
        }
        bot.getElements().add(0, extract(expression));
        bot.setSingleChar(String.valueOf(pis.getSingleChar()));
        bot.setWildCard(String.valueOf(pis.getWildCard()));
        return ogc_factory.createPropertyIsLike(bot);
    } else if (type == ComparisonOperatorName.PROPERTY_IS_NOT_EQUAL_TO) {
        final BinaryComparisonOperator pit = (BinaryComparisonOperator) filter;
        final PropertyIsNotEqualToType bot = new PropertyIsNotEqualToType();
        bot.getExpression().add(extract(pit.getOperand1()));
        bot.getExpression().add(extract(pit.getOperand2()));
        return ogc_factory.createPropertyIsNotEqualTo(bot);
    } else if (filter instanceof NullOperator) {
        final NullOperator pis = (NullOperator) filter;
        final PropertyIsNullType bot = ogc_factory.createPropertyIsNullType();
        bot.setExpression(extract((Expression) pis.getExpressions().get(0)));
        return ogc_factory.createPropertyIsNull(bot);
    } else if (type == LogicalOperatorName.AND) {
        final LogicalOperator and = (LogicalOperator) filter;
        final List<JAXBElement> lot = new ArrayList<>();
        for (final Filter f : (List<Filter>) and.getOperands()) {
            final JAXBElement<?> ele = visit(f);
            if (ele != null && ele.getValue() instanceof LogicOpsType) {
                lot.add(ele);
            }
        }
        return ogc_factory.createAnd(new AndType(lot.toArray()));
    } else if (type == LogicalOperatorName.OR) {
        final LogicalOperator or = (LogicalOperator) filter;
        final List<JAXBElement> lot = new ArrayList<>();
        for (final Filter f : (List<Filter>) or.getOperands()) {
            final JAXBElement subFilter = visit(f);
            if (subFilter != null) {
                lot.add(subFilter);
            }
        }
        return ogc_factory.createOr(new OrType(lot.toArray()));
    } else if (type == LogicalOperatorName.NOT) {
        final LogicalOperator not = (LogicalOperator) filter;
        final JAXBElement<?> sf = visit((Filter) not.getOperands().get(0));
        // should not happen
        return ogc_factory.createNot(new NotType(sf));
    } else if (filter instanceof ResourceId) {
        throw new IllegalArgumentException("Not parsed yet : " + filter);
    } else if (type == SpatialOperatorName.BBOX) {
        final BBOX bbox = BBOX.wrap((BinarySpatialOperator) filter);
        final Expression left = bbox.getOperand1();
        final Expression right = bbox.getOperand2();
        final String property;
        final double minx;
        final double maxx;
        final double miny;
        final double maxy;
        String srs;
        if (left instanceof ValueReference) {
            property = ((ValueReference) left).getXPath();
            final Object objGeom = ((Literal) right).getValue();
            if (objGeom instanceof org.opengis.geometry.Envelope) {
                final org.opengis.geometry.Envelope env = (org.opengis.geometry.Envelope) objGeom;
                minx = env.getMinimum(0);
                maxx = env.getMaximum(0);
                miny = env.getMinimum(1);
                maxy = env.getMaximum(1);
                try {
                    srs = IdentifiedObjects.lookupURN(env.getCoordinateReferenceSystem(), null);
                    if (srs == null) {
                        srs = ReferencingUtilities.lookupIdentifier(env.getCoordinateReferenceSystem(), true);
                    }
                } catch (FactoryException ex) {
                    throw new IllegalArgumentException("invalid bbox element : " + filter + " " + ex.getMessage(), ex);
                }
            } else if (objGeom instanceof Geometry) {
                final Geometry geom = (Geometry) objGeom;
                final Envelope env = geom.getEnvelopeInternal();
                minx = env.getMinX();
                maxx = env.getMaxX();
                miny = env.getMinY();
                maxy = env.getMaxY();
                srs = SRIDGenerator.toSRS(geom.getSRID(), SRIDGenerator.Version.V1);
            } else {
                throw new IllegalArgumentException("invalid bbox element : " + filter);
            }
        } else if (right instanceof ValueReference) {
            property = ((ValueReference) right).getXPath();
            final Object objGeom = ((Literal) left).getValue();
            if (objGeom instanceof org.opengis.geometry.Envelope) {
                final org.opengis.geometry.Envelope env = (org.opengis.geometry.Envelope) objGeom;
                minx = env.getMinimum(0);
                maxx = env.getMaximum(0);
                miny = env.getMinimum(1);
                maxy = env.getMaximum(1);
                try {
                    srs = IdentifiedObjects.lookupURN(env.getCoordinateReferenceSystem(), null);
                    if (srs == null) {
                        srs = ReferencingUtilities.lookupIdentifier(env.getCoordinateReferenceSystem(), true);
                    }
                } catch (FactoryException ex) {
                    throw new IllegalArgumentException("invalid bbox element : " + filter + " " + ex.getMessage(), ex);
                }
            } else if (objGeom instanceof Geometry) {
                final Geometry geom = (Geometry) objGeom;
                final Envelope env = geom.getEnvelopeInternal();
                minx = env.getMinX();
                maxx = env.getMaxX();
                miny = env.getMinY();
                maxy = env.getMaxY();
                srs = SRIDGenerator.toSRS(geom.getSRID(), SRIDGenerator.Version.V1);
            } else {
                throw new IllegalArgumentException("invalid bbox element : " + filter);
            }
        } else {
            throw new IllegalArgumentException("invalid bbox element : " + filter);
        }
        final BBOXType bbtype = new BBOXType(property, minx, miny, maxx, maxy, srs);
        return ogc_factory.createBBOX(bbtype);
    } else if (filter instanceof ResourceId) {
        final ValueReference n = FF.property(AttributeConvention.IDENTIFIER);
        ResourceId idFilter = (ResourceId) filter;
        final String id = idFilter.getIdentifier();
        final ResourceIdType rId = ogc_factory.createResourceIdType();
        rId.setRid(id);
        return ogc_factory.createResourceId(rId);
    } else if (filter instanceof BinarySpatialOperator) {
        final BinarySpatialOperator spatialOp = (BinarySpatialOperator) filter;
        Expression exp1 = spatialOp.getOperand1();
        Expression exp2 = spatialOp.getOperand2();
        if (!(exp1 instanceof ValueReference)) {
            // flip order
            final Expression ex = exp1;
            exp1 = exp2;
            exp2 = ex;
        }
        if (!(exp1 instanceof ValueReference)) {
            throw new IllegalArgumentException("Filter can not be transformed in xml filter, " + "expression are not of the required type ");
        } else if (!(exp2 instanceof Literal)) {
            throw new IllegalArgumentException("Spatial operator should use a literal object containing the filtering geometry.");
        }
        final JAXBElement pnt = extract(exp1);
        final String pName;
        if (pnt.getValue() instanceof String) {
            pName = (String) pnt.getValue();
        } else {
            throw new IllegalArgumentException("Property name cannot be cast to string.");
        }
        final JAXBElement<?> geometryExpression;
        final Object geom = ((Literal) exp2).getValue();
        if (geom instanceof Geometry) {
            final Geometry jts = (Geometry) geom;
            final String srid = SRIDGenerator.toSRS(jts.getSRID(), SRIDGenerator.Version.V1);
            CoordinateReferenceSystem crs;
            try {
                crs = CRS.forCode(srid);
            } catch (Exception ex) {
                Logger.getLogger("org.geotoolkit.sld.xml").log(Level.WARNING, null, ex);
                crs = null;
            }
            final AbstractGeometry gmlGeom;
            try {
                gmlGeom = JTStoGeometry.toGML("3.2.1", jts);
            } catch (FactoryException ex) {
                throw new IllegalArgumentException(ex);
            }
            // TODO use gml method to return any JAXBElement
            if (gmlGeom instanceof PointType) {
                geometryExpression = gml_factory.createPoint((PointType) gmlGeom);
            } else if (gmlGeom instanceof CurveType) {
                geometryExpression = gml_factory.createCurve((CurveType) gmlGeom);
            } else if (gmlGeom instanceof LineStringType) {
                geometryExpression = gml_factory.createLineString((LineStringType) gmlGeom);
            } else if (gmlGeom instanceof PolygonType) {
                geometryExpression = gml_factory.createPolygon((PolygonType) gmlGeom);
            } else if (gmlGeom instanceof MultiSurfaceType) {
                geometryExpression = gml_factory.createMultiSurface((MultiSurfaceType) gmlGeom);
            } else if (gmlGeom instanceof MultiCurveType) {
                geometryExpression = gml_factory.createMultiCurve((MultiCurveType) gmlGeom);
            } else if (gmlGeom instanceof MultiPointType) {
                geometryExpression = gml_factory.createMultiPoint((MultiPointType) gmlGeom);
            } else if (gmlGeom instanceof MultiGeometryType) {
                geometryExpression = gml_factory.createMultiGeometry((MultiGeometryType) gmlGeom);
            } else if (gmlGeom instanceof SurfaceType) {
                geometryExpression = gml_factory.createPolyhedralSurface((SurfaceType) gmlGeom);
            } else {
                throw new IllegalArgumentException("Unexpected Geometry type:" + gmlGeom.getClass().getName());
            }
        } else if (geom instanceof org.opengis.geometry.Geometry) {
            throw new UnsupportedOperationException("No valid ISO implementation avaiable for now.");
        } else if (geom instanceof org.opengis.geometry.Envelope) {
            final org.opengis.geometry.Envelope genv = (org.opengis.geometry.Envelope) geom;
            EnvelopeType ee = gml_factory.createEnvelopeType();
            ee.setSrsDimension(genv.getDimension());
            if (genv.getCoordinateReferenceSystem() != null) {
                String urn;
                try {
                    urn = IdentifiedObjects.lookupURN(genv.getCoordinateReferenceSystem(), null);
                } catch (FactoryException ex) {
                    Logger.getLogger("org.geotoolkit.sld.xml").log(Level.WARNING, null, ex);
                    urn = null;
                }
                if (urn == null) {
                    urn = IdentifiedObjects.getIdentifierOrName(genv.getCoordinateReferenceSystem());
                }
                if (urn != null) {
                    ee.setSrsName(urn);
                }
            }
            ee.setLowerCorner(new DirectPositionType(genv.getLowerCorner(), false));
            ee.setUpperCorner(new DirectPositionType(genv.getUpperCorner(), false));
            geometryExpression = gml_factory.createEnvelope(ee);
        } else {
            throw new IllegalArgumentException("Type is neither geometric nor envelope.");
        }
        if (type == DistanceOperatorName.BEYOND) {
            throw new UnsupportedOperationException();
        } else if (type == SpatialOperatorName.CONTAINS) {
            return ogc_factory.createContains(new ContainsType(pName, geometryExpression));
        } else if (type == SpatialOperatorName.CROSSES) {
            ogc_factory.createCrosses(new CrossesType(pName, geometryExpression));
        } else if (type == DistanceOperatorName.WITHIN) {
            Quantity q = ((DistanceOperator) filter).getDistance();
            return ogc_factory.createDWithin(new DWithinType(pName, geometryExpression, q.getValue().doubleValue(), q.getUnit().toString()));
        } else if (type == SpatialOperatorName.DISJOINT) {
            return ogc_factory.createDisjoint(new DisjointType(pName, geometryExpression));
        } else if (type == SpatialOperatorName.EQUALS) {
            return ogc_factory.createEquals(new EqualsType(pName, geometryExpression));
        } else if (type == SpatialOperatorName.INTERSECTS) {
            return ogc_factory.createIntersects(new IntersectsType(pName, geometryExpression));
        } else if (type == SpatialOperatorName.OVERLAPS) {
            return ogc_factory.createOverlaps(new OverlapsType(pName, geometryExpression));
        } else if (type == SpatialOperatorName.TOUCHES) {
            return ogc_factory.createTouches(new TouchesType(pName, geometryExpression));
        } else if (type == SpatialOperatorName.WITHIN) {
            return ogc_factory.createWithin(new WithinType(pName, geometryExpression));
        }
        throw new IllegalArgumentException("Unknown filter element : " + filter + " class :" + filter.getClass());
    }
    throw new IllegalArgumentException("Unknown filter element : " + filter + " class :" + filter.getClass());
}
Also used : OverlapsType(org.geotoolkit.ogc.xml.v200.OverlapsType) FactoryException(org.opengis.util.FactoryException) MultiCurveType(org.geotoolkit.gml.xml.v321.MultiCurveType) ArrayList(java.util.ArrayList) MultiGeometryType(org.geotoolkit.gml.xml.v321.MultiGeometryType) CrossesType(org.geotoolkit.ogc.xml.v200.CrossesType) DWithinType(org.geotoolkit.ogc.xml.v200.DWithinType) MultiSurfaceType(org.geotoolkit.gml.xml.v321.MultiSurfaceType) NotType(org.geotoolkit.ogc.xml.v200.NotType) Literal(org.opengis.filter.Literal) DisjointType(org.geotoolkit.ogc.xml.v200.DisjointType) CodeList(org.opengis.util.CodeList) List(java.util.List) ArrayList(java.util.ArrayList) PropertyIsBetweenType(org.geotoolkit.ogc.xml.v200.PropertyIsBetweenType) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) BetweenComparisonOperator(org.opengis.filter.BetweenComparisonOperator) ValueReference(org.opengis.filter.ValueReference) DWithinType(org.geotoolkit.ogc.xml.v200.DWithinType) WithinType(org.geotoolkit.ogc.xml.v200.WithinType) ResourceIdType(org.geotoolkit.ogc.xml.v200.ResourceIdType) PropertyIsGreaterThanType(org.geotoolkit.ogc.xml.v200.PropertyIsGreaterThanType) LogicalOperator(org.opengis.filter.LogicalOperator) PolygonType(org.geotoolkit.gml.xml.v321.PolygonType) JAXBElement(javax.xml.bind.JAXBElement) IntersectsType(org.geotoolkit.ogc.xml.v200.IntersectsType) LineStringType(org.geotoolkit.gml.xml.v321.LineStringType) MultiSurfaceType(org.geotoolkit.gml.xml.v321.MultiSurfaceType) SurfaceType(org.geotoolkit.gml.xml.v321.SurfaceType) PropertyIsGreaterThanOrEqualToType(org.geotoolkit.ogc.xml.v200.PropertyIsGreaterThanOrEqualToType) MultiPointType(org.geotoolkit.gml.xml.v321.MultiPointType) LogicOpsType(org.geotoolkit.ogc.xml.v200.LogicOpsType) UpperBoundaryType(org.geotoolkit.ogc.xml.v200.UpperBoundaryType) PropertyIsNotEqualToType(org.geotoolkit.ogc.xml.v200.PropertyIsNotEqualToType) ContainsType(org.geotoolkit.ogc.xml.v200.ContainsType) BBOXType(org.geotoolkit.ogc.xml.v200.BBOXType) LikeOperator(org.opengis.filter.LikeOperator) BinaryComparisonOperator(org.opengis.filter.BinaryComparisonOperator) PropertyIsLikeType(org.geotoolkit.ogc.xml.v200.PropertyIsLikeType) PropertyIsLessThanType(org.geotoolkit.ogc.xml.v200.PropertyIsLessThanType) AndType(org.geotoolkit.ogc.xml.v200.AndType) AbstractGeometry(org.geotoolkit.gml.xml.AbstractGeometry) DirectPositionType(org.geotoolkit.gml.xml.v321.DirectPositionType) CurveType(org.geotoolkit.gml.xml.v321.CurveType) MultiCurveType(org.geotoolkit.gml.xml.v321.MultiCurveType) PropertyIsLessThanOrEqualToType(org.geotoolkit.ogc.xml.v200.PropertyIsLessThanOrEqualToType) Envelope(org.locationtech.jts.geom.Envelope) PropertyIsNullType(org.geotoolkit.ogc.xml.v200.PropertyIsNullType) EqualsType(org.geotoolkit.ogc.xml.v200.EqualsType) BinarySpatialOperator(org.opengis.filter.BinarySpatialOperator) OrType(org.geotoolkit.ogc.xml.v200.OrType) EnvelopeType(org.geotoolkit.gml.xml.v321.EnvelopeType) DistanceOperator(org.opengis.filter.DistanceOperator) Quantity(javax.measure.Quantity) LiteralType(org.geotoolkit.ogc.xml.v200.LiteralType) NullOperator(org.opengis.filter.NullOperator) FactoryException(org.opengis.util.FactoryException) JTStoGeometry(org.geotoolkit.gml.JTStoGeometry) Geometry(org.locationtech.jts.geom.Geometry) AbstractGeometry(org.geotoolkit.gml.xml.AbstractGeometry) PropertyIsEqualToType(org.geotoolkit.ogc.xml.v200.PropertyIsEqualToType) Expression(org.opengis.filter.Expression) Filter(org.opengis.filter.Filter) ResourceId(org.opengis.filter.ResourceId) PointType(org.geotoolkit.gml.xml.v321.PointType) MultiPointType(org.geotoolkit.gml.xml.v321.MultiPointType) LowerBoundaryType(org.geotoolkit.ogc.xml.v200.LowerBoundaryType) TouchesType(org.geotoolkit.ogc.xml.v200.TouchesType)

Aggregations

BinarySpatialOperator (org.opengis.filter.BinarySpatialOperator)7 Literal (org.opengis.filter.Literal)6 Filter (org.opengis.filter.Filter)5 ValueReference (org.opengis.filter.ValueReference)5 JAXBElement (javax.xml.bind.JAXBElement)4 Test (org.junit.Test)4 CoordinateReferenceSystem (org.opengis.referencing.crs.CoordinateReferenceSystem)4 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Quantity (javax.measure.Quantity)2 Marshaller (javax.xml.bind.Marshaller)2 Unmarshaller (javax.xml.bind.Unmarshaller)2 BinaryComparisonOperator (org.opengis.filter.BinaryComparisonOperator)2 Expression (org.opengis.filter.Expression)2 LogicalOperator (org.opengis.filter.LogicalOperator)2 FactoryException (org.opengis.util.FactoryException)2 IOException (java.io.IOException)1 HashSet (java.util.HashSet)1 Document (org.apache.lucene.document.Document)1 LeafReader (org.apache.lucene.index.LeafReader)1