Search in sources :

Example 6 with Hints

use of org.geotools.util.factory.Hints in project geo-platform by geosdi.

the class GPPublisherBasicServiceImpl method getCRSFromGeotiff.

private Integer getCRSFromGeotiff(File file) {
    Integer code = null;
    try {
        GeoTiffReader geotiffReader = new GeoTiffReader(file, new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, TRUE));
        GridCoverage2D coverage = (GridCoverage2D) geotiffReader.read(null);
        CoordinateReferenceSystem crs = coverage.getCoordinateReferenceSystem2D();
        code = CRS.lookupEpsgCode(crs, TRUE);
    } catch (DataSourceException ex) {
        logger.error("Errore retrieving the crs: " + ex);
    } catch (IOException ioe) {
        logger.error("Errore retrieving the crs: " + ioe);
    } catch (FactoryException ioe) {
        logger.error("Errore retrieving the crs: " + ioe);
    }
    return code;
}
Also used : GridCoverage2D(org.geotools.coverage.grid.GridCoverage2D) Hints(org.geotools.util.factory.Hints) DataSourceException(org.geotools.data.DataSourceException) FactoryException(org.opengis.referencing.FactoryException) GeoTiffReader(org.geotools.gce.geotiff.GeoTiffReader) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) IOException(java.io.IOException)

Example 7 with Hints

use of org.geotools.util.factory.Hints 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)

Example 8 with Hints

use of org.geotools.util.factory.Hints in project OpenTripPlanner by opentripplanner.

the class GeotiffGridCoverageFactoryImpl method getUninterpolatedGridCoverage.

/**
 * Lazy-creates a GridCoverage2D instance by loading the specific elevation file into memory. During a refactor in
 * the year 2020, the code at one point was written such that each coverage instance was created and wrapped in the
 * Interpolator2D interpolator for each thread to use. However, benchmarking showed that this caused longer run
 * times which is likely due to too much memory competing for a slot in the processor cache.
 */
public GridCoverage2D getUninterpolatedGridCoverage() {
    if (coverage == null) {
        try {
            // There is a serious standardization failure around the axis order of WGS84. See issue #1930.
            // GeoTools assumes strict EPSG axis order of (latitude, longitude) unless told otherwise.
            // Both NED and SRTM data use the longitude-first axis order, so OTP makes grid coverages
            // for unprojected DEMs assuming coordinates are in (longitude, latitude) order.
            Hints forceLongLat = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE);
            GeoTiffFormat format = new GeoTiffFormat();
            GeoTiffReader reader = format.getReader(getSource(), forceLongLat);
            coverage = reader.read(null);
            LOG.debug("Elevation model CRS is: {}", coverage.getCoordinateReferenceSystem2D());
        } catch (IOException e) {
            throw new RuntimeException("Error getting coverage automatically. ", e);
        }
    }
    return coverage;
}
Also used : Hints(org.geotools.util.factory.Hints) GeoTiffFormat(org.geotools.gce.geotiff.GeoTiffFormat) GeoTiffReader(org.geotools.gce.geotiff.GeoTiffReader) IOException(java.io.IOException)

Example 9 with Hints

use of org.geotools.util.factory.Hints in project hortonmachine by TheHortonMachine.

the class OmsRasterReader method process.

@Execute
public void process() throws Exception {
    if (!concatOr(outRaster == null, doReset)) {
        return;
    }
    if (hasBoundsRequest() && (!hasResolutionRequest() && !hasRowColsRequest())) {
        throw new RuntimeException("If bounds are requested, also a resolution or number of rows/cols has to be supplied.");
    }
    if (hasBoundsRequest()) {
        pBounds = new double[] { pNorth, pSouth, pWest, pEast };
    }
    if (hasResolutionRequest()) {
        pRes = new double[] { pXres, pYres };
    }
    if (hasRowColsRequest()) {
        pRowcol = new int[] { pRows, pCols };
    }
    File mapFile = new File(file);
    AbstractGridFormat format = GridFormatFinder.findFormat(mapFile);
    if (format != null && !(format instanceof GrassCoverageFormat)) {
        if (format instanceof UnknownFormat) {
            throw new ModelsIllegalargumentException("Unupported format for: " + mapFile, this.getClass().getSimpleName(), pm);
        } else {
            try {
                pm.beginTask("Reading coverage: " + mapFile.getName(), IHMProgressMonitor.UNKNOWN);
                AbstractGridCoverage2DReader rasterReader = format.getReader(mapFile, new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE));
                if (file.toLowerCase().endsWith(".nc")) {
                    // try to force netcdf reader even if not recognised
                    Class<?> ncfClass = Class.forName("org.geotools.coverage.io.netcdf.NetCDFReader");
                    Class<?>[] type = { Object.class, Hints.class };
                    Constructor<?> cons = ncfClass.getConstructor(type);
                    Object[] obj = { mapFile, null };
                    rasterReader = (AbstractGridCoverage2DReader) cons.newInstance(obj);
                }
                originalEnvelope = rasterReader.getOriginalEnvelope();
                if (!doEnvelope) {
                    outRaster = rasterReader.read(generalParameter);
                    resample();
                // checkNovalues();
                }
                boolean crsValid = CrsUtilities.isCrsValid(outRaster.getCoordinateReferenceSystem());
                if (!crsValid) {
                    pm.errorMessage("The read CRS doesn't seem to be valid. This could lead to unexpected results. Consider adding a .prj file with the proper CRS definition if none is present.");
                }
            } finally {
                pm.done();
            }
        }
    } else if (CoverageUtilities.isGrass(file)) {
        try {
            pm.beginTask("Reading coverage: " + mapFile.getName(), IHMProgressMonitor.UNKNOWN);
            readGrass(mapFile);
        } finally {
            pm.done();
        }
    } else {
        throw new ModelsIllegalargumentException("Can't recognize the data format for: " + mapFile, this.getClass().getSimpleName(), pm);
    }
}
Also used : UnknownFormat(org.geotools.coverage.grid.io.UnknownFormat) Hints(org.geotools.util.factory.Hints) AbstractGridCoverage2DReader(org.geotools.coverage.grid.io.AbstractGridCoverage2DReader) GrassCoverageFormat(org.geotools.gce.grassraster.format.GrassCoverageFormat) ModelsIllegalargumentException(org.hortonmachine.gears.libs.exceptions.ModelsIllegalargumentException) AbstractGridFormat(org.geotools.coverage.grid.io.AbstractGridFormat) File(java.io.File) Execute(oms3.annotations.Execute)

Example 10 with Hints

use of org.geotools.util.factory.Hints in project SOS by 52North.

the class GeometryHandler method init.

@Override
public void init() {
    boolean eastingFirstEpsgCode = true;
    try {
        eastingFirstEpsgCode = isEastingFirstEpsgCode(getStorageEPSG());
    } catch (Exception e) {
        LOGGER.error("The storage EPSG code '{}' is invalid. Easting first = true would be used!", getStorageEPSG());
    }
    Hints hints = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, eastingFirstEpsgCode);
    this.crsAuthority = ReferencingFactoryFinder.getCRSAuthorityFactory(this.authority, hints);
    supportedCRS.stream().forEach(crs -> {
        CrsRegistry.ifAbsentReturnProjected2D(Integer.parseInt(crs));
    });
}
Also used : Hints(org.geotools.util.factory.Hints) FactoryException(org.opengis.referencing.FactoryException) InvalidParameterValueException(org.n52.shetland.ogc.ows.exception.InvalidParameterValueException) CodedException(org.n52.shetland.ogc.ows.exception.CodedException) TransformException(org.opengis.referencing.operation.TransformException) MismatchedDimensionException(org.opengis.geometry.MismatchedDimensionException) NoApplicableCodeException(org.n52.shetland.ogc.ows.exception.NoApplicableCodeException)

Aggregations

Hints (org.geotools.util.factory.Hints)11 AbstractGridFormat (org.geotools.coverage.grid.io.AbstractGridFormat)5 CoordinateReferenceSystem (org.opengis.referencing.crs.CoordinateReferenceSystem)5 IOException (java.io.IOException)4 GridCoverage2D (org.geotools.coverage.grid.GridCoverage2D)4 File (java.io.File)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 FactoryException (org.opengis.referencing.FactoryException)3 GridCoverage2DReader (org.geotools.coverage.grid.io.GridCoverage2DReader)2 Query (org.geotools.data.Query)2 GeoTiffFormat (org.geotools.gce.geotiff.GeoTiffFormat)2 GeoTiffReader (org.geotools.gce.geotiff.GeoTiffReader)2 GridCoverage (org.opengis.coverage.grid.GridCoverage)2 MathTransform (org.opengis.referencing.operation.MathTransform)2 TransformException (org.opengis.referencing.operation.TransformException)2 HashSet (java.util.HashSet)1 TreeSet (java.util.TreeSet)1 Execute (oms3.annotations.Execute)1 GridSampleDimension (org.geotools.coverage.GridSampleDimension)1