Search in sources :

Example 21 with WKTReader

use of com.vividsolutions.jts.io.WKTReader in project spatial-portal by AtlasOfLivingAustralia.

the class AreaUploadShapefileWizardController method loadOnMap.

private void loadOnMap(Set<FeatureId> ids, String filename) {
    try {
        final FilterFactory ff = CommonFactoryFinder.getFilterFactory(GeoTools.getDefaultHints());
        Filter filter = ff.id(ids);
        // set up the math transform used to process the data
        SimpleFeatureType schema = features.getSchema();
        CoordinateReferenceSystem dataCRS = schema.getCoordinateReferenceSystem();
        CoordinateReferenceSystem wgsCRS = DefaultGeographicCRS.WGS84;
        // allow for some error due to different datums
        boolean lenient = true;
        if (dataCRS == null) {
            // attempt to parse prj
            try {
                File prjFile = new File(filename.substring(0, filename.length() - 3) + "prj");
                if (prjFile.exists()) {
                    String prj = FileUtils.readFileToString(prjFile);
                    if (prj.equals("PROJCS[\"WGS_1984_Web_Mercator_Auxiliary_Sphere\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Mercator_Auxiliary_Sphere\"],PARAMETER[\"False_Easting\",0.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",0.0],PARAMETER[\"Standard_Parallel_1\",0.0],PARAMETER[\"Auxiliary_Sphere_Type\",0.0],UNIT[\"Meter\",1.0]]")) {
                        // support for arcgis online default shp exports
                        dataCRS = CRS.decode("EPSG:3857");
                    } else {
                        dataCRS = CRS.parseWKT(FileUtils.readFileToString(prjFile));
                    }
                }
            } catch (Exception e) {
                LOGGER.error("failed to read prj for " + filename);
            }
            if (dataCRS == null) {
                dataCRS = DefaultGeographicCRS.WGS84;
            }
        }
        MathTransform transform = CRS.findMathTransform(dataCRS, wgsCRS, lenient);
        SimpleFeatureCollection sff = source.getFeatures(filter);
        SimpleFeatureIterator fif = sff.features();
        StringBuilder sb = new StringBuilder();
        StringBuilder sbGeometryCollection = new StringBuilder();
        boolean isGeometryCollection = false;
        List<Geometry> geoms = new ArrayList<Geometry>();
        while (fif.hasNext()) {
            SimpleFeature f = fif.next();
            LOGGER.debug("Selected Feature: " + f.getID() + " -> " + f.getAttribute("ECOREGION"));
            Geometry geom = (Geometry) f.getDefaultGeometry();
            geom = JTS.transform(geom, transform);
            String wktString = geom.toText();
            wktString = wktString.replaceAll(", ", ",");
            boolean valid = true;
            boolean multipolygon = false;
            boolean polygon = false;
            boolean geometrycollection = false;
            if (wktString.startsWith(StringConstants.MULTIPOLYGON + " ")) {
                wktString = wktString.substring((StringConstants.MULTIPOLYGON + " ").length(), wktString.length() - 1);
                multipolygon = true;
            } else if (wktString.startsWith(StringConstants.POLYGON + " ")) {
                wktString = wktString.substring((StringConstants.POLYGON + " ").length());
                polygon = true;
            } else if (wktString.startsWith(StringConstants.GEOMETRYCOLLECTION + " (")) {
                wktString = wktString.substring((StringConstants.GEOMETRYCOLLECTION + " (").length(), wktString.length() - 1);
                geometrycollection = true;
                isGeometryCollection = true;
            } else {
                valid = false;
            }
            if (valid) {
                if (sb.length() > 0) {
                    sb.append(",");
                    sbGeometryCollection.append(",");
                }
                sb.append(wktString);
                if (multipolygon) {
                    sbGeometryCollection.append(StringConstants.MULTIPOLYGON).append("(").append(wktString.replace("(((", "(("));
                    if (!wktString.endsWith(")))")) {
                        sbGeometryCollection.append(")");
                    }
                } else if (polygon) {
                    sbGeometryCollection.append(StringConstants.POLYGON).append(wktString);
                } else if (geometrycollection) {
                    sbGeometryCollection.append(wktString);
                }
            }
        }
        String wkt;
        if (!isGeometryCollection) {
            if (!sb.toString().contains(")))")) {
                sb.append(")");
            }
            wkt = StringConstants.MULTIPOLYGON + "(" + sb.toString().replace("(((", "((");
        } else {
            sbGeometryCollection.append(")");
            wkt = StringConstants.GEOMETRYCOLLECTION + "(" + sbGeometryCollection.toString();
            getMapComposer().showMessage("Shape is invalid: " + "GEOMETRYCOLLECTION not supported.");
        }
        GeometryFactory gf = new GeometryFactory();
        gf.createGeometryCollection(GeometryFactory.toGeometryArray(geoms));
        String msg = "";
        boolean invalid = false;
        try {
            WKTReader wktReader = new WKTReader();
            com.vividsolutions.jts.geom.Geometry g = wktReader.read(wkt);
            // NC 20130319: Ensure that the WKT is valid according to the WKT standards.
            IsValidOp op = new IsValidOp(g);
            if (!op.isValid()) {
                // this will fix some issues
                g = g.buffer(0);
                op = new IsValidOp(g);
            }
            if (!op.isValid()) {
                invalid = true;
                LOGGER.warn(CommonData.lang(StringConstants.ERROR_WKT_INVALID) + " " + op.getValidationError().getMessage());
                msg = op.getValidationError().getMessage();
            // TODO Fix invalid WKT text using https://github.com/tudelft-gist/prepair maybe???
            } else if (g.isRectangle()) {
                // NC 20130319: When the shape is a rectangle ensure that the points a specified in the correct order.
                // get the new WKT for the rectangle will possibly need to change the order.
                com.vividsolutions.jts.geom.Envelope envelope = g.getEnvelopeInternal();
                String wkt2 = StringConstants.POLYGON + "((" + envelope.getMinX() + " " + envelope.getMinY() + "," + envelope.getMaxX() + " " + envelope.getMinY() + "," + envelope.getMaxX() + " " + envelope.getMaxY() + "," + envelope.getMinX() + " " + envelope.getMaxY() + "," + envelope.getMinX() + " " + envelope.getMinY() + "))";
                if (!wkt.equals(wkt2)) {
                    LOGGER.debug("NEW WKT for Rectangle: " + wkt);
                    msg = CommonData.lang("error_wkt_anticlockwise");
                    invalid = true;
                }
            }
            if (!invalid) {
                invalid = !op.isValid();
            }
        } catch (ParseException parseException) {
            LOGGER.error("error testing validity of uploaded shape file wkt", parseException);
        }
        if (invalid) {
            getMapComposer().showMessage(CommonData.lang(StringConstants.ERROR_WKT_INVALID) + " " + msg);
        } else {
            MapLayer mapLayer = getMapComposer().addWKTLayer(wkt, layername, layername);
            UserDataDTO ud = new UserDataDTO(layername);
            ud.setFilename(media.getName());
            ud.setUploadedTimeInMs(System.currentTimeMillis());
            ud.setType("shapefile");
            String metadata = "";
            metadata += "User uploaded Shapefile \n";
            metadata += "Name: " + ud.getName() + " <br />\n";
            metadata += "Filename: " + ud.getFilename() + " <br />\n";
            metadata += "Date: " + ud.getDisplayTime() + " <br />\n";
            metadata += "Selected polygons (fid): <br />\n";
            metadata += "<ul>";
            metadata += "</ul>";
            mapLayer.getMapLayerMetadata().setMoreInfo(metadata);
            getMapComposer().replaceWKTwithWMS(mapLayer);
        }
    } catch (IOException e) {
        LOGGER.debug("IO Error retrieving geometry", e);
    } catch (Exception e) {
        LOGGER.debug("Generic Error retrieving geometry", e);
    }
}
Also used : GeometryFactory(com.vividsolutions.jts.geom.GeometryFactory) MathTransform(org.opengis.referencing.operation.MathTransform) MapLayer(au.org.emii.portal.menu.MapLayer) WKTReader(com.vividsolutions.jts.io.WKTReader) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) FilterFactory(org.opengis.filter.FilterFactory) SimpleFeatureIterator(org.geotools.data.simple.SimpleFeatureIterator) Geometry(com.vividsolutions.jts.geom.Geometry) UserDataDTO(au.org.ala.spatial.dto.UserDataDTO) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) IOException(java.io.IOException) ParseException(com.vividsolutions.jts.io.ParseException) IOException(java.io.IOException) SimpleFeature(org.opengis.feature.simple.SimpleFeature) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) Geometry(com.vividsolutions.jts.geom.Geometry) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) Filter(org.opengis.filter.Filter) IsValidOp(com.vividsolutions.jts.operation.valid.IsValidOp) ParseException(com.vividsolutions.jts.io.ParseException) File(java.io.File)

Example 22 with WKTReader

use of com.vividsolutions.jts.io.WKTReader in project alliance by codice.

the class CatalogRolloverActionTest method testLocationUnion.

@Test
public void testLocationUnion() throws RolloverActionException, SourceUnavailableException, IngestException, ParseException {
    String parentWkt = "POLYGON (( 0 0, 1 0, 1 1, 0 1, 0 0 ))";
    when(createdParentMetacard.getLocation()).thenReturn(parentWkt);
    catalogRolloverAction.doAction(tempFile);
    ArgumentCaptor<Attribute> attributeCaptor = ArgumentCaptor.forClass(Attribute.class);
    verify(createdParentMetacard, atLeastOnce()).setAttribute(attributeCaptor.capture());
    List<Attribute> geoAttributeList = attributeCaptor.getAllValues().stream().filter(attr -> attr.getName().equals(Metacard.GEOGRAPHY)).collect(Collectors.toList());
    assertThat(geoAttributeList, hasSize(1));
    WKTReader wktReader = new WKTReader();
    WKTWriter wktWriter = new WKTWriter();
    String unionWkt = wktWriter.write(wktReader.read(childWkt).union(wktReader.read(parentWkt)).norm());
    String actualWkt = (String) geoAttributeList.get(0).getValue();
    assertThat(wktWriter.write(wktReader.read(actualWkt).norm()), is(unionWkt));
}
Also used : Arrays(java.util.Arrays) CreateRequest(ddf.catalog.operation.CreateRequest) GeometryOperatorList(org.codice.alliance.libs.klv.GeometryOperatorList) CreateStorageRequest(ddf.catalog.content.operation.CreateStorageRequest) Date(java.util.Date) Assert.assertThat(org.junit.Assert.assertThat) TemporalEndMetacardUpdater(org.codice.alliance.video.stream.mpegts.metacard.TemporalEndMetacardUpdater) AttributeNameConstants(org.codice.alliance.libs.klv.AttributeNameConstants) WKTWriter(com.vividsolutions.jts.io.WKTWriter) UdpStreamProcessor(org.codice.alliance.video.stream.mpegts.netty.UdpStreamProcessor) URI(java.net.URI) ModifiedDateMetacardUpdater(org.codice.alliance.video.stream.mpegts.metacard.ModifiedDateMetacardUpdater) GeometryOperator(org.codice.alliance.libs.klv.GeometryOperator) ParseException(com.vividsolutions.jts.io.ParseException) AttributeDescriptor(ddf.catalog.data.AttributeDescriptor) FrameCenterMetacardUpdater(org.codice.alliance.video.stream.mpegts.metacard.FrameCenterMetacardUpdater) StreamProcessor(org.codice.alliance.video.stream.mpegts.netty.StreamProcessor) Mockito.atLeastOnce(org.mockito.Mockito.atLeastOnce) WKTReader(com.vividsolutions.jts.io.WKTReader) Collectors(java.util.stream.Collectors) MetacardType(ddf.catalog.data.MetacardType) Matchers.any(org.mockito.Matchers.any) List(java.util.List) Attribute(ddf.catalog.data.Attribute) SimpleSubject(org.codice.alliance.video.stream.mpegts.SimpleSubject) Optional(java.util.Optional) Matchers.is(org.hamcrest.Matchers.is) Context(org.codice.alliance.video.stream.mpegts.Context) UpdateResponse(ddf.catalog.operation.UpdateResponse) SimplifyGeometryFunction(org.codice.alliance.libs.klv.SimplifyGeometryFunction) Mockito.mock(org.mockito.Mockito.mock) SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) CatalogFramework(ddf.catalog.CatalogFramework) AttributeImpl(ddf.catalog.data.impl.AttributeImpl) Update(ddf.catalog.operation.Update) TemporalStartMetacardUpdater(org.codice.alliance.video.stream.mpegts.metacard.TemporalStartMetacardUpdater) ArgumentCaptor(org.mockito.ArgumentCaptor) CreateResponse(ddf.catalog.operation.CreateResponse) LocationMetacardUpdater(org.codice.alliance.video.stream.mpegts.metacard.LocationMetacardUpdater) Metacard(ddf.catalog.data.Metacard) UpdateRequest(ddf.catalog.operation.UpdateRequest) FilenameGenerator(org.codice.alliance.video.stream.mpegts.filename.FilenameGenerator) Matchers.hasSize(org.hamcrest.Matchers.hasSize) NormalizeGeometry(org.codice.alliance.libs.klv.NormalizeGeometry) ListMetacardUpdater(org.codice.alliance.video.stream.mpegts.metacard.ListMetacardUpdater) Before(org.junit.Before) Security(org.codice.ddf.security.common.Security) IngestException(ddf.catalog.source.IngestException) Mockito.times(org.mockito.Mockito.times) Subject(ddf.security.Subject) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) File(java.io.File) Mockito.verify(org.mockito.Mockito.verify) Collections(java.util.Collections) UuidGenerator(org.codice.ddf.platform.util.uuidgenerator.UuidGenerator) WKTWriter(com.vividsolutions.jts.io.WKTWriter) Attribute(ddf.catalog.data.Attribute) WKTReader(com.vividsolutions.jts.io.WKTReader) Test(org.junit.Test)

Example 23 with WKTReader

use of com.vividsolutions.jts.io.WKTReader in project alliance by codice.

the class FrameCenterUpdateFieldTest method testThatGeoOperatorIsCalled.

@Test
public void testThatGeoOperatorIsCalled() throws ParseException {
    String wktChild1 = "LINESTRING (30 10, 10 30, 40 40)";
    GeometryOperator geometryOperator = mock(GeometryOperator.class);
    Geometry geometry = new WKTReader().read("LINESTRING (0 0, 1 1)");
    Context context = mock(Context.class);
    GeometryOperator.Context geometryOperatorContext = new GeometryOperator.Context();
    geometryOperatorContext.setSubsampleCount(FrameCenterUpdateField.MAX_SIZE * 2);
    when(context.getGeometryOperatorContext()).thenReturn(geometryOperatorContext);
    when(geometryOperator.apply(any(), any())).thenReturn(geometry);
    Metacard parentMetacard = mock(Metacard.class);
    Metacard childMetacard1 = mock(Metacard.class);
    when(childMetacard1.getAttribute(AttributeNameConstants.FRAME_CENTER)).thenReturn(new AttributeImpl(AttributeNameConstants.FRAME_CENTER, wktChild1));
    FrameCenterUpdateField frameCenterUpdateField = new FrameCenterUpdateField(geometryOperator, new GeometryFactory());
    frameCenterUpdateField.updateField(parentMetacard, Collections.singletonList(childMetacard1), context);
    verify(geometryOperator, never()).apply(any(), any());
    frameCenterUpdateField.end(parentMetacard, context);
    verify(geometryOperator, times(1)).apply(any(), any());
    assertThat(geometryOperatorContext.getSubsampleCount(), is(FrameCenterUpdateField.MAX_SIZE * 2));
}
Also used : Geometry(com.vividsolutions.jts.geom.Geometry) Context(org.codice.alliance.video.stream.mpegts.Context) Metacard(ddf.catalog.data.Metacard) GeometryFactory(com.vividsolutions.jts.geom.GeometryFactory) GeometryOperator(org.codice.alliance.libs.klv.GeometryOperator) AttributeImpl(ddf.catalog.data.impl.AttributeImpl) WKTReader(com.vividsolutions.jts.io.WKTReader) Test(org.junit.Test)

Example 24 with WKTReader

use of com.vividsolutions.jts.io.WKTReader in project alliance by codice.

the class FrameCenterUpdateFieldTest method testThatSubsampleCountIsResetOnException.

@Test(expected = RuntimeException.class)
public void testThatSubsampleCountIsResetOnException() throws ParseException {
    String wktChild1 = "LINESTRING (30 10, 10 30, 40 40)";
    GeometryOperator geometryOperator = mock(GeometryOperator.class);
    Geometry geometry = new WKTReader().read("LINESTRING (0 0, 1 1)");
    Context context = mock(Context.class);
    GeometryOperator.Context geometryOperatorContext = new GeometryOperator.Context();
    geometryOperatorContext.setSubsampleCount(FrameCenterUpdateField.MAX_SIZE * 2);
    when(context.getGeometryOperatorContext()).thenReturn(geometryOperatorContext);
    when(geometryOperator.apply(any(), any())).thenThrow(RuntimeException.class);
    Metacard parentMetacard = mock(Metacard.class);
    Metacard childMetacard1 = mock(Metacard.class);
    when(childMetacard1.getAttribute(AttributeNameConstants.FRAME_CENTER)).thenReturn(new AttributeImpl(AttributeNameConstants.FRAME_CENTER, wktChild1));
    FrameCenterUpdateField frameCenterUpdateField = new FrameCenterUpdateField(geometryOperator, new GeometryFactory());
    frameCenterUpdateField.updateField(parentMetacard, Collections.singletonList(childMetacard1), context);
    verify(geometryOperator, never()).apply(any(), any());
    try {
        frameCenterUpdateField.end(parentMetacard, context);
        verify(geometryOperator, times(1)).apply(any(), any());
    } finally {
        assertThat(geometryOperatorContext.getSubsampleCount(), is(FrameCenterUpdateField.MAX_SIZE * 2));
    }
}
Also used : Geometry(com.vividsolutions.jts.geom.Geometry) Context(org.codice.alliance.video.stream.mpegts.Context) Metacard(ddf.catalog.data.Metacard) GeometryFactory(com.vividsolutions.jts.geom.GeometryFactory) GeometryOperator(org.codice.alliance.libs.klv.GeometryOperator) AttributeImpl(ddf.catalog.data.impl.AttributeImpl) WKTReader(com.vividsolutions.jts.io.WKTReader) Test(org.junit.Test)

Example 25 with WKTReader

use of com.vividsolutions.jts.io.WKTReader in project alliance by codice.

the class LocationUpdateField method doUpdateField.

@Override
protected void doUpdateField(Metacard parent, List<Metacard> children, Context context) {
    WKTReader wktReader = new WKTReader();
    List<String> childLocations = extractChildLocations(children);
    List<Geometry> geometries = childLocations.stream().map(s -> GeometryUtility.wktToGeometry(s, wktReader)).filter(Optional::isPresent).map(Optional::get).map(geometry -> preUnionGeometryOperator.apply(geometry, context.getGeometryOperatorContext())).collect(Collectors.toList());
    if (intermediateGeometry != null) {
        geometries.add(intermediateGeometry);
    }
    geometries.stream().reduce(Geometry::union).ifPresent(geometry -> intermediateGeometry = geometry);
}
Also used : Geometry(com.vividsolutions.jts.geom.Geometry) StringUtils(org.apache.commons.lang.StringUtils) AttributeImpl(ddf.catalog.data.impl.AttributeImpl) WKTReader(com.vividsolutions.jts.io.WKTReader) Collectors(java.util.stream.Collectors) List(java.util.List) Metacard(ddf.catalog.data.Metacard) Geometry(com.vividsolutions.jts.geom.Geometry) WKTWriter(com.vividsolutions.jts.io.WKTWriter) Optional(java.util.Optional) GeometryUtility(org.codice.alliance.libs.klv.GeometryUtility) Context(org.codice.alliance.video.stream.mpegts.Context) GeometryOperator(org.codice.alliance.libs.klv.GeometryOperator) Core(ddf.catalog.data.types.Core) NotThreadSafe(javax.annotation.concurrent.NotThreadSafe) Optional(java.util.Optional) WKTReader(com.vividsolutions.jts.io.WKTReader)

Aggregations

WKTReader (com.vividsolutions.jts.io.WKTReader)71 Geometry (com.vividsolutions.jts.geom.Geometry)51 Test (org.junit.Test)28 ParseException (com.vividsolutions.jts.io.ParseException)23 WKTWriter (com.vividsolutions.jts.io.WKTWriter)9 Metacard (ddf.catalog.data.Metacard)9 Coordinate (com.vividsolutions.jts.geom.Coordinate)6 IsValidOp (com.vividsolutions.jts.operation.valid.IsValidOp)6 AttributeImpl (ddf.catalog.data.impl.AttributeImpl)6 GeometryOperator (org.codice.alliance.libs.klv.GeometryOperator)6 Context (org.codice.alliance.video.stream.mpegts.Context)6 MapLayer (au.org.emii.portal.menu.MapLayer)5 GeometryFactory (com.vividsolutions.jts.geom.GeometryFactory)4 Polygon (com.vividsolutions.jts.geom.Polygon)4 ArrayList (java.util.ArrayList)4 List (java.util.List)4 Optional (java.util.Optional)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 Before (org.junit.Before)3 Facet (au.org.ala.legend.Facet)2