Search in sources :

Example 76 with CoordinateReferenceSystem

use of org.opengis.referencing.crs.CoordinateReferenceSystem in project georocket by georocket.

the class XMLBoundingBoxIndexer method handleSrsName.

/**
 * Parse and decode a CRS string
 * @param srsName the CRS string (may be null)
 */
private void handleSrsName(String srsName) {
    if (srsName == null || srsName.isEmpty()) {
        return;
    }
    if (crsStr != null && crsStr.equals(srsName)) {
        // same string, no need to parse
        return;
    }
    try {
        CoordinateReferenceSystem crs;
        // decode string
        if (CompoundCRSDecoder.isCompound(srsName)) {
            crs = CompoundCRSDecoder.decode(srsName);
        } else {
            crs = CRS.decode(srsName);
        }
        // only keep horizontal CRS
        CoordinateReferenceSystem hcrs = CRS.getHorizontalCRS(crs);
        if (hcrs != null) {
            crs = hcrs;
        }
        // find transformation to WGS84
        MathTransform transform = CRS.findMathTransform(crs, WGS84, true);
        boolean flippedCRS = isFlippedCRS(crs);
        this.crsStr = srsName;
        this.crs = crs;
        this.transform = transform;
        this.flippedCRS = flippedCRS;
    } catch (FactoryException e) {
    // unknown CRS or no transformation available
    }
}
Also used : MathTransform(org.opengis.referencing.operation.MathTransform) FactoryException(org.opengis.referencing.FactoryException) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem)

Example 77 with CoordinateReferenceSystem

use of org.opengis.referencing.crs.CoordinateReferenceSystem in project polymap4-core by Polymap4.

the class SimpleWmsServer method doGet.

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    log.debug("Request: " + request.getQueryString());
    try {
        final Map<String, String> kvp = parseKvpSet(request.getQueryString());
        sessionContext.execute(() -> {
            // LAYERS
            final String layer = kvp.get("LAYERS");
            assert !layer.contains(INNER_DELIMETER);
            final String style = kvp.get("STYLES");
            assert style == null || !style.contains(INNER_DELIMETER);
            log.info("layers=" + layer + ", style=" + style);
            // WIDTH/HEIGHT
            int width = Integer.parseInt(kvp.get("WIDTH"));
            int height = Integer.parseInt(kvp.get("HEIGHT"));
            // BBOX
            ReferencedEnvelope bbox = parseBBox(kvp.get("BBOX"));
            String srsCode = kvp.get("SRS");
            CoordinateReferenceSystem crs = CRS.decode(srsCode);
            bbox = new ReferencedEnvelope(bbox, crs);
            // FORMAT
            String format = kvp.get("FORMAT");
            format = format != null ? format : "image/png";
            log.debug("    --layers= " + layer);
            log.debug("    --imageSize= " + width + "x" + height);
            log.debug("    --bbox= " + bbox);
            crs = bbox.getCoordinateReferenceSystem();
            log.debug("    --CRS= " + bbox.getCoordinateReferenceSystem().getName());
            // find/create pipeline
            final Pipeline pipeline = pipelines.get(layer, key -> createPipeline(key));
            long modifiedSince = request.getDateHeader("If-Modified-Since");
            final ProcessorRequest pr = new GetMapRequest(Collections.singletonList(layer), Collections.singletonList(style), srsCode, bbox, format, width, height, modifiedSince);
            // process
            Lazy<ServletOutputStream> out = new PlainLazyInit(() -> {
                try {
                    return response.getOutputStream();
                } catch (Exception e) {
                    log.warn("Pipeline exception: " + e, e);
                    response.setStatus(502);
                    return null;
                }
            });
            try {
                createPipelineExecutor().execute(pipeline, pr, new ResponseHandler() {

                    @Override
                    public void handle(ProcessorResponse pipeResponse) throws Exception {
                        if (pipeResponse == EncodedImageResponse.NOT_MODIFIED) {
                            response.setStatus(304);
                        } else {
                            long lastModified = ((EncodedImageResponse) pipeResponse).getLastModified();
                            // allow the browser to use a cached tile for max-age without a request
                            if (lastModified > 0) {
                                long maxAge = ((EncodedImageResponse) pipeResponse).getExpires() - System.currentTimeMillis() / 1000;
                                response.setDateHeader("Last-Modified", lastModified);
                                response.setHeader("Cache-Control", "public,must-revalidate");
                            } else // disable browser cache if there is no internal Cache for this layer
                            {
                                response.setHeader("Cache-Control", "no-cache,no-store,must-revalidate");
                                response.setDateHeader("Expires", 0);
                                response.setHeader("Pragma", "no-cache");
                            }
                            byte[] chunk = ((EncodedImageResponse) pipeResponse).getChunk();
                            int len = ((EncodedImageResponse) pipeResponse).getChunkSize();
                            out.get().write(chunk, 0, len);
                        }
                    }
                });
            } catch (Throwable e) {
                log.warn("Pipeline exception: " + e, e);
                response.setStatus(502);
            }
            return null;
        });
    } catch (IOException e) {
        // assuming that this is an EOF exception
        log.info("Exception: " + e);
    } catch (Exception e) {
        log.warn(e.toString(), e);
    } finally {
    // XXX do I have to close out?
    // out.close();
    }
}
Also used : ProcessorResponse(org.polymap.core.data.pipeline.ProcessorResponse) ResponseHandler(org.polymap.core.data.pipeline.ResponseHandler) ServletOutputStream(javax.servlet.ServletOutputStream) IOException(java.io.IOException) PlainLazyInit(org.polymap.core.runtime.PlainLazyInit) FactoryException(org.opengis.referencing.FactoryException) ServletException(javax.servlet.ServletException) NoSuchAuthorityCodeException(org.opengis.referencing.NoSuchAuthorityCodeException) ServiceException(org.osgi.framework.ServiceException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Pipeline(org.polymap.core.data.pipeline.Pipeline) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) EncodedImageResponse(org.polymap.core.data.image.EncodedImageResponse) ProcessorRequest(org.polymap.core.data.pipeline.ProcessorRequest) GetMapRequest(org.polymap.core.data.image.GetMapRequest) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem)

Example 78 with CoordinateReferenceSystem

use of org.opengis.referencing.crs.CoordinateReferenceSystem in project polymap4-core by Polymap4.

the class RasterRenderProcessor method getBoundsRequest.

@Override
public void getBoundsRequest(GetBoundsRequest request, ProcessorContext context) throws Exception {
    GeneralEnvelope envelope = reader.getOriginalEnvelope();
    if (envelope != null) {
        context.sendResponse(new GetBoundsResponse(new ReferencedEnvelope(envelope)));
        return;
    }
    CoordinateReferenceSystem crs = reader.getCoordinateReferenceSystem();
    if (crs != null) {
        context.sendResponse(new GetBoundsResponse(new ReferencedEnvelope(crs)));
        return;
    }
    throw new IllegalStateException("No bounds founds.");
}
Also used : ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) GetBoundsResponse(org.polymap.core.data.feature.GetBoundsResponse) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) GeneralEnvelope(org.geotools.geometry.GeneralEnvelope)

Example 79 with CoordinateReferenceSystem

use of org.opengis.referencing.crs.CoordinateReferenceSystem in project polymap4-core by Polymap4.

the class WmsRenderProcessor method setBBox.

protected void setBBox(org.geotools.data.wms.request.GetMapRequest getMap, Envelope envelope) {
    // code is from AbstractGetMapRequest
    String version = getMap.getProperties().getProperty(Request.VERSION);
    boolean forceXY = version == null || !version.startsWith("1.3");
    String srsName = CRS.toSRS(envelope.getCoordinateReferenceSystem());
    CoordinateReferenceSystem crs = AbstractGetMapRequest.toServerCRS(srsName, forceXY);
    Envelope bbox = null;
    try {
        bbox = CRS.transform(envelope, crs);
    } catch (TransformException e) {
        bbox = envelope;
    }
    // FIXME
    String s = srsName.contains("31468") && version.startsWith("1.3") ? Joiner.on(',').join(bbox.getMinimum(1), bbox.getMinimum(0), bbox.getMaximum(1), bbox.getMaximum(0)) : Joiner.on(',').join(bbox.getMinimum(0), bbox.getMinimum(1), bbox.getMaximum(0), bbox.getMaximum(1));
    // log.info( "Requested BBOX: " + s );
    getMap.setBBox(s);
}
Also used : TransformException(org.opengis.referencing.operation.TransformException) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) Envelope(org.opengis.geometry.Envelope) CRSEnvelope(org.geotools.data.ows.CRSEnvelope)

Example 80 with CoordinateReferenceSystem

use of org.opengis.referencing.crs.CoordinateReferenceSystem in project OpenTripPlanner by opentripplanner.

the class RasterPopulation method createIndividuals0.

/**
 * Shared internal createIndividuals method allowing synthetic subclass to reuse projection code
 */
protected void createIndividuals0() {
    MathTransform tr;
    try {
        final CoordinateReferenceSystem WGS84 = CRS.decode("EPSG:4326", true);
        tr = CRS.findMathTransform(coverageCRS, WGS84);
    } catch (Exception e) {
        LOG.error("error creating CRS transform.", e);
        return;
    }
    // grid coordinate object to be reused for reading each cell in the raster
    GridCoordinates2D coord = new GridCoordinates2D();
    // evaluating a raster returns an array of results, in this case 1D
    int[] val = new int[1];
    for (int row = 0; row < rows; row++) {
        for (int col = 0; col < cols; col++) {
            coord.x = col;
            coord.y = row;
            try {
                // find coordinates for current raster cell in raster CRS
                DirectPosition sourcePos = gridGeometry.gridToWorld(coord);
                // TODO: we are performing 2 transforms here, it would probably be more efficient to compose
                // the grid-to-crs and crs-to-WGS84 transforms into grid-to-WGS84.
                // cf. MathTransformFactory and CoordinateOperationFactory
                // convert coordinates in raster CRS to WGS84
                DirectPosition targetPos = tr.transform(sourcePos, null);
                double lon = targetPos.getOrdinate(0);
                double lat = targetPos.getOrdinate(1);
                // evaluate using grid coordinates, which should be more efficient than using world coordinates
                if (coverage != null)
                    coverage.evaluate(coord, val);
                // add this grid cell to the population
                String label = row + "_" + col;
                Individual individual = new Individual(label, lon, lat, val[band]);
                this.addIndividual(individual);
            } catch (Exception e) {
                LOG.error("error creating individuals for raster", e);
                return;
            }
        }
    }
}
Also used : DirectPosition(org.opengis.geometry.DirectPosition) MathTransform(org.opengis.referencing.operation.MathTransform) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem)

Aggregations

CoordinateReferenceSystem (org.opengis.referencing.crs.CoordinateReferenceSystem)210 Test (org.junit.Test)80 MathTransform (org.opengis.referencing.operation.MathTransform)32 FactoryException (org.opengis.referencing.FactoryException)25 CoordinateOperation (org.opengis.referencing.operation.CoordinateOperation)24 ReferencedEnvelope (org.geotools.geometry.jts.ReferencedEnvelope)23 Geometry (com.vividsolutions.jts.geom.Geometry)21 TransformException (org.opengis.referencing.operation.TransformException)21 DependsOnMethod (org.apache.sis.test.DependsOnMethod)19 CoordinateSystem (org.opengis.referencing.cs.CoordinateSystem)13 Geometry (org.locationtech.jts.geom.Geometry)11 FactoryException (org.opengis.util.FactoryException)11 SimpleFeature (org.opengis.feature.simple.SimpleFeature)9 DirectPosition (org.opengis.geometry.DirectPosition)9 GeographicCRS (org.opengis.referencing.crs.GeographicCRS)9 VerticalCRS (org.opengis.referencing.crs.VerticalCRS)9 CoordinateSystemAxis (org.opengis.referencing.cs.CoordinateSystemAxis)9 ArrayList (java.util.ArrayList)8 GeometryType (org.opengis.feature.type.GeometryType)8 RevFeatureType (org.locationtech.geogig.api.RevFeatureType)7