Search in sources :

Example 1 with GridCoverage2DReader

use of org.geotools.coverage.grid.io.GridCoverage2DReader in project r5 by conveyal.

the class DataSourcePreviewGenerator method wgsPreviewGeometries.

/**
 * As a simplification when generating previews for some kinds of DataSources, return JTS Geometries rather than
 * complete GeoTools features. These Geometries will be converted to features for serialization to GeoJSON.
 * The userData on the first geometry in the list will determine the attribute schema. This userData must be null
 * or a Map<String, Object>. The user data on all subsequent features must have the same fields and types.
 * All geometries in the list must be of the same type. They must all be in longitude-first WGS84, as JTS
 * geometries do not have rich CRS data associated with them and cannot be automatically reprojected by GeoTools
 * when it writes GeoJSON.
 * @return wgs84 geometries with a map of attributes in userData, which can be converted to GeoTools features.
 */
private List<Geometry> wgsPreviewGeometries(DataSource dataSource) {
    if (dataSource.fileFormat == FileStorageFormat.GEOTIFF) {
        try {
            // FIXME this duplicates a lot of code in RasterDataSourceSampler, raster reading should be factored out.
            // This is crazy verbose considering that we're taking an Envelope with CRS from a GeoTools object
            // and have the final objective of turning it into a GeoTools feature, but we're passing through JTS
            // where we lose the CRS information.
            File localRasterFile = fileStorage.getFile(dataSource.fileStorageKey());
            AbstractGridFormat format = GridFormatFinder.findFormat(localRasterFile);
            // Only relevant for certain files with WGS CRS?
            Hints hints = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE);
            GridCoverage2DReader coverageReader = format.getReader(localRasterFile, hints);
            GridCoverage2D coverage = coverageReader.read(null);
            // Set CRS transform from WGS84 to coverage, if any.
            CoordinateReferenceSystem crs = coverage.getCoordinateReferenceSystem2D();
            MathTransform coverageToWgs = CRS.findMathTransform(crs, DefaultGeographicCRS.WGS84);
            Polygon projectedPolygon = JTS.toPolygon(coverage.getEnvelope2D());
            Geometry wgsGeometry = JTS.transform(projectedPolygon, coverageToWgs);
            wgsGeometry.setUserData(Map.of("name", dataSource.name));
            return List.of(wgsGeometry);
        } catch (Exception e) {
            throw new RuntimeException("Exception reading raster:", e);
        }
    }
    return defaultWgsPreviewGeometries(dataSource);
}
Also used : Geometry(org.locationtech.jts.geom.Geometry) GridCoverage2D(org.geotools.coverage.grid.GridCoverage2D) Hints(org.geotools.util.factory.Hints) MathTransform(org.opengis.referencing.operation.MathTransform) AbstractGridFormat(org.geotools.coverage.grid.io.AbstractGridFormat) GridCoverage2DReader(org.geotools.coverage.grid.io.GridCoverage2DReader) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) Polygon(org.locationtech.jts.geom.Polygon) File(java.io.File)

Example 2 with GridCoverage2DReader

use of org.geotools.coverage.grid.io.GridCoverage2DReader in project polymap4-core by Polymap4.

the class GridServiceInfo method of.

public static GridServiceInfo of(IMetadata metadata, Map<String, String> params) throws Exception {
    String url = params.get(IMetadataResourceResolver.CONNECTION_PARAM_URL);
    GridCoverage2DReader grid = GridCoverageReaderFactory.open(FileUtils.toFile(new URL(url)));
    return new GridServiceInfo(metadata, grid);
}
Also used : AbstractGridCoverage2DReader(org.geotools.coverage.grid.io.AbstractGridCoverage2DReader) GridCoverage2DReader(org.geotools.coverage.grid.io.GridCoverage2DReader) URL(java.net.URL)

Example 3 with GridCoverage2DReader

use of org.geotools.coverage.grid.io.GridCoverage2DReader in project structr by structr.

the class AbstractGeoserverFunction method getWCSCoverage.

protected GridCoverage2D getWCSCoverage(final String baseUrl, final String coverageId, final Geometry subset) throws FrameworkException {
    try {
        final Map<String, Object> coverageDescription = getWCSCoverageDescription(baseUrl, coverageId);
        final int statusCode = get(coverageDescription, "status", 500);
        if (statusCode == 200) {
            final File tmpFile = File.createTempFile("structr", ".tiff");
            final URL url = getWCSCoverageUrl(baseUrl, coverageId, subset, get(coverageDescription, "axisLabels", "X Y"));
            try {
                HttpHelper.streamURLToFile(url.toString(), tmpFile);
                final AbstractGridFormat format = GridFormatFinder.findFormat(tmpFile);
                final GridCoverage2DReader reader = format.getReader(tmpFile, new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE));
                return (GridCoverage2D) reader.read(null);
            } finally {
                // remove tmp file after fetching the data
                tmpFile.delete();
            }
        } else {
            throw new FrameworkException(statusCode, get(coverageDescription, "message", "Error"));
        }
    } catch (Throwable t) {
        throw new FrameworkException(GEOSERVER_ERROR_STATUS, t.getMessage());
    }
}
Also used : GridCoverage2D(org.geotools.coverage.grid.GridCoverage2D) Hints(org.geotools.factory.Hints) FrameworkException(org.structr.common.error.FrameworkException) AbstractGridFormat(org.geotools.coverage.grid.io.AbstractGridFormat) GridCoverage2DReader(org.geotools.coverage.grid.io.GridCoverage2DReader) JSONObject(org.json.JSONObject) File(java.io.File) URL(java.net.URL)

Example 4 with GridCoverage2DReader

use of org.geotools.coverage.grid.io.GridCoverage2DReader in project geowave by locationtech.

the class GeoToolsRasterDataStoreIngestPlugin method toGeoWaveData.

@Override
public CloseableIterator<GeoWaveData<GridCoverage>> toGeoWaveData(final URL input, final String[] indexNames) {
    final AbstractGridFormat format = prioritizedFindFormat(input);
    if (format == null) {
        return new Wrapper<>(Collections.emptyIterator());
    }
    Hints hints = null;
    if ((optionProvider.getCrs() != null) && !optionProvider.getCrs().trim().isEmpty()) {
        try {
            final CoordinateReferenceSystem crs = CRS.decode(optionProvider.getCrs());
            if (crs != null) {
                hints = new Hints();
                hints.put(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, crs);
            }
        } catch (final Exception e) {
            LOGGER.warn("Unable to find coordinate reference system, continuing without hint", e);
        }
    }
    final GridCoverage2DReader reader = format.getReader(input, hints);
    if (reader == null) {
        LOGGER.error("Unable to get reader instance, getReader returned null");
        return new Wrapper<>(Collections.emptyIterator());
    }
    try {
        final GridCoverage2D coverage = reader.read(null);
        if (coverage != null) {
            final Map<String, String> metadata = new HashMap<>();
            final String coverageName = coverage.getName().toString();
            try {
                // wrapping with try-catch block because often the reader
                // does not support operations on coverage name
                // if not, we just don't have metadata, and continue
                final String[] mdNames = reader.getMetadataNames(coverageName);
                if ((mdNames != null) && (mdNames.length > 0)) {
                    for (final String mdName : mdNames) {
                        if (mdName != null) {
                            final String value = reader.getMetadataValue(coverageName, mdName);
                            if (value != null) {
                                metadata.put(mdName, value);
                            }
                        }
                    }
                }
            } catch (final Exception e) {
                LOGGER.debug("Unable to find metadata from coverage reader", e);
            }
            final List<GeoWaveData<GridCoverage>> coverages = new ArrayList<>();
            if (optionProvider.isSeparateBands() && (coverage.getNumSampleDimensions() > 1)) {
                final String baseName = optionProvider.getCoverageName() != null ? optionProvider.getCoverageName() : FilenameUtils.getName(input.getPath());
                final double[][] nodata = optionProvider.getNodata(coverage.getNumSampleDimensions());
                for (int b = 0; b < coverage.getNumSampleDimensions(); b++) {
                    final RasterDataAdapter adapter = new RasterDataAdapter(baseName + "_B" + b, metadata, (GridCoverage2D) RasterUtils.getCoverageOperations().selectSampleDimension(coverage, new int[] { b }), optionProvider.getTileSize(), optionProvider.isBuildPyramid(), optionProvider.isBuildHistogram(), new double[][] { nodata[b] });
                    coverages.add(new GeoWaveData<>(adapter, indexNames, coverage));
                }
            } else {
                final RasterDataAdapter adapter = new RasterDataAdapter(optionProvider.getCoverageName() != null ? optionProvider.getCoverageName() : input.getPath(), metadata, coverage, optionProvider.getTileSize(), optionProvider.isBuildPyramid(), optionProvider.isBuildHistogram(), optionProvider.getNodata(coverage.getNumSampleDimensions()));
                coverages.add(new GeoWaveData<>(adapter, indexNames, coverage));
            }
            return new Wrapper<GeoWaveData<GridCoverage>>(coverages.iterator()) {

                @Override
                public void close() {
                    try {
                        reader.dispose();
                    } catch (final IOException e) {
                        LOGGER.warn("unable to dispose of reader resources", e);
                    }
                }
            };
        } else {
            LOGGER.warn("Null grid coverage from file '" + input.getPath() + "' for discovered geotools format '" + format.getName() + "'");
        }
    } catch (final IOException e) {
        LOGGER.warn("Unable to read grid coverage of file '" + input.getPath() + "' for discovered geotools format '" + format.getName() + "'", e);
    }
    return new Wrapper<>(Collections.emptyIterator());
}
Also used : Wrapper(org.locationtech.geowave.core.store.CloseableIterator.Wrapper) GridCoverage2D(org.geotools.coverage.grid.GridCoverage2D) Hints(org.geotools.util.factory.Hints) HashMap(java.util.HashMap) GridCoverage2DReader(org.geotools.coverage.grid.io.GridCoverage2DReader) ArrayList(java.util.ArrayList) IOException(java.io.IOException) IOException(java.io.IOException) RasterDataAdapter(org.locationtech.geowave.adapter.raster.adapter.RasterDataAdapter) GridCoverage(org.opengis.coverage.grid.GridCoverage) GeoWaveData(org.locationtech.geowave.core.store.ingest.GeoWaveData) AbstractGridFormat(org.geotools.coverage.grid.io.AbstractGridFormat) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem)

Aggregations

GridCoverage2DReader (org.geotools.coverage.grid.io.GridCoverage2DReader)4 GridCoverage2D (org.geotools.coverage.grid.GridCoverage2D)3 AbstractGridFormat (org.geotools.coverage.grid.io.AbstractGridFormat)3 File (java.io.File)2 URL (java.net.URL)2 Hints (org.geotools.util.factory.Hints)2 CoordinateReferenceSystem (org.opengis.referencing.crs.CoordinateReferenceSystem)2 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 AbstractGridCoverage2DReader (org.geotools.coverage.grid.io.AbstractGridCoverage2DReader)1 Hints (org.geotools.factory.Hints)1 JSONObject (org.json.JSONObject)1 RasterDataAdapter (org.locationtech.geowave.adapter.raster.adapter.RasterDataAdapter)1 Wrapper (org.locationtech.geowave.core.store.CloseableIterator.Wrapper)1 GeoWaveData (org.locationtech.geowave.core.store.ingest.GeoWaveData)1 Geometry (org.locationtech.jts.geom.Geometry)1 Polygon (org.locationtech.jts.geom.Polygon)1 GridCoverage (org.opengis.coverage.grid.GridCoverage)1 MathTransform (org.opengis.referencing.operation.MathTransform)1