Package org.geotools.coverage.grid.io

Examples of org.geotools.coverage.grid.io.GridCoverage2DReader


        final Rectangle queryRect = createQueryGridEnvelope(centrePos);
        if (queryRect.isEmpty()) {
            return false;
        }

        final GridCoverage2DReader reader = sourceRef.get();
        GeneralParameterValue parameter = new Parameter(
                AbstractGridFormat.READ_GRIDGEOMETRY2D,
                new GridGeometry2D(new GridEnvelope2D(queryRect),
                reader.getOriginalGridToWorld(PixelInCell.CELL_CENTER),
                reader.getCoordinateReferenceSystem()));
       
        try {
            cachedCoverage = (GridCoverage2D) reader.read(new GeneralParameterValue[]{parameter});
            return cachedCoverage != null;
           
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
View Full Code Here


            throw new RuntimeException(ex);
        }
    }

    private Rectangle createQueryGridEnvelope(DirectPosition pos) {
        final GridCoverage2DReader reader = sourceRef.get();
        try {
            MathTransform worldToGridTransform =
                    reader.getOriginalGridToWorld(PixelInCell.CELL_CORNER).inverse();

            DirectPosition midPos = worldToGridTransform.transform(pos, null);
            int x = (int) midPos.getOrdinate(0);
            int y = (int) midPos.getOrdinate(1);
            int halfWidth = CACHED_RASTER_WIDTH / 2;

            final Rectangle queryRect = new Rectangle(
                    x - halfWidth, y - halfWidth,
                    CACHED_RASTER_WIDTH, CACHED_RASTER_WIDTH);

            GridEnvelope gridEnv = reader.getOriginalGridRange();
                Rectangle rect = new Rectangle(
                        gridEnv.getLow(0), gridEnv.getLow(1),
                        gridEnv.getSpan(0), gridEnv.getSpan(1));

            XRectangle2D.intersect(queryRect, rect, queryRect);
View Full Code Here

    if (format == null) {
      String message = "Could not find a format for this coverage";
      fireException(message, 0, new IOException(message));
      return;
    }
    final GridCoverage2DReader inReader = (GridCoverage2DReader) format.getReader(inputLocation);
    if (inReader == null) {
      String message = "Unable to instantiate a reader for this coverage";
      fireException(message, 0, new IOException(message));
      return;
    }

    envelope = inReader.getOriginalEnvelope();
    try {
        inReader.dispose();
    } catch(IOException e) {
        LOGGER.log(Level.SEVERE, "Failure occurred while closing grid coverage reader", e);
    }

    // /////////////////////////////////////////////////////////////////////
View Full Code Here

          0,
          new IOException("Could not find a format for this coverage"));
      return;
    }
    // get a reader for this file
    final GridCoverage2DReader inReader =
      (GridCoverage2DReader) format.getReader(inputLocation, new Hints(Hints.OVERVIEW_POLICY, OverviewPolicy.IGNORE));
    if (inReader == null) {
      message = new StringBuilder(
          "Unable to instantiate a reader for this coverage");
      if (LOGGER.isLoggable(Level.WARNING))
        LOGGER.fine(message.toString());
      fireEvent(message.toString(), 0);
      return;
    }

    // /////////////////////////////////////////////////////////////////////
    //
    //
    // If everything went fine, let's proceed with tiling this coverage.
    //
    //
    // /////////////////////////////////////////////////////////////////////
    if (!outputLocation.exists())
      outputLocation.mkdir();

    // //
    //
    // getting source envelope and crs
    //
    // //
    final GeneralEnvelope envelope = inReader.getOriginalEnvelope();
    message = new StringBuilder("Original envelope is ").append(envelope
        .toString());
    if (LOGGER.isLoggable(Level.FINE))
      LOGGER.fine(message.toString());
    fireEvent(message.toString(), 0);

    // //
    //
    // getting source gridrange and checking tile dimensions to be not
    // bigger than the original coverage size
    //
    // //
    final GridEnvelope range = inReader.getOriginalGridRange();
    final int w = range.getSpan(0);
    final int h = range.getSpan(1);
    tileWidth = tileWidth > w ? w : tileWidth;
    tileHeight = tileHeight > h ? h : tileHeight;
    message = new StringBuilder("Original range is ").append(range.toString());
    if (LOGGER.isLoggable(Level.FINE))
      LOGGER.fine(message.toString());
    fireEvent(message.toString(), 0);
    message = new StringBuilder("New matrix dimension is (cols,rows)==(")
        .append(tileWidth).append(",").append(tileHeight).append(")");
    if (LOGGER.isLoggable(Level.FINE))
      LOGGER.fine(message.toString());
    fireEvent(message.toString(), 0);

    // //
    //
    // read the coverage
    //
    // //
    GridCoverage2D gc;
    try {
      gc = (GridCoverage2D) inReader.read(null);
    } catch (IOException e) {
      LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
      fireException(e);
      return;
View Full Code Here

      final File input,
      final ByteArrayId primaryIndexId,
      final String globalVisibility ) {

    final AbstractGridFormat format = GridFormatFinder.findFormat(input);
    final GridCoverage2DReader reader = format.getReader(input);

    try {
      final GridCoverage2D coverage = reader.read(null);
      if (coverage != null) {
        final Map<String, String> metadata = new HashMap<String, String>();
        final String coverageName = coverage.getName().toString();
        final String[] mdNames = reader.getMetadataNames(coverageName);
        if ((mdNames != null) && (mdNames.length > 0)) {
          for (final String mdName : mdNames) {
            metadata.put(
                mdName,
                reader.getMetadataValue(
                    coverageName,
                    mdName));
          }
        }
        final RasterDataAdapter adapter = new RasterDataAdapter(
            input.getName(),
            metadata,
            coverage);
        final List<GeoWaveData<GridCoverage>> coverages = new ArrayList<GeoWaveData<GridCoverage>>();
        coverages.add(new GeoWaveData<GridCoverage>(
            adapter,
            primaryIndexId,
            coverage));
        return new Wrapper(
            coverages.iterator()) {

          @Override
          public void close()
              throws IOException {
            reader.dispose();
          }
        };
      }
      else {
        LOGGER.warn("Null grid coverage from file '" + input.getAbsolutePath() + "' for discovered geotools format '" + format.getName() + "'");
View Full Code Here

                CoverageInfo ci = gc.coverage;
                String datasetId = codec.getDatasetName(ci);
                start("wcseo:DatasetSeriesDescription", atts("gml:id", datasetId));

                try {
                    GridCoverage2DReader reader = (GridCoverage2DReader) ci.getGridCoverageReader(
                            null, null);

                    // encode the bbox
                    encodeDatasetBounds(ci, reader);
View Full Code Here

                element(tx, "ows:UpperCorner", bbox.getMaxX() + " " + bbox.getMaxY(), null);
                tx.end("ows:WGS84BoundingBox");
                String datasetId = codec.getDatasetName(ci);
                element(tx, "wcseo:DatasetSeriesId", datasetId, null);

                GridCoverage2DReader reader = (GridCoverage2DReader) ci.getGridCoverageReader(null, null);

                WCSDimensionsHelper dimensionsHelper = new WCSDimensionsHelper(time, reader, null);
                tx.start("gml:TimePeriod", atts("gml:id", datasetId + "__timeperiod"));
                element(tx, "gml:beginPosition", dimensionsHelper.getBeginTime(), null);
                element(tx, "gml:endPosition", dimensionsHelper.getEndTime(), null);
View Full Code Here

        if (time == null) {
            LOGGER.log(Level.FINE, "We received a coverage info that has no " +
                "associated time, cannot add EO metadata to it: "+ ci.prefixedName());
            return;
        }
        GridCoverage2DReader reader = (GridCoverage2DReader) ci.getGridCoverageReader(null, null);
        String coverageId = NCNameResourceCodec.encode(ci);
        WCSDimensionsHelper dimensionHelper = new WCSDimensionsHelper(time, reader, coverageId);
        tx.start("wcseo:EOMetadata");
        tx.start("eop:EarthObservation", atts("gml:id", coverageId + "_metadata"));
       
        // phenomenon time
        tx.start("om:phenomenonTime");
        tx.start("gml:TimePeriod", atts("gml:id", coverageId + "_tp"));
        element(tx, "gml:beginPosition", dimensionHelper.getBeginTime(), null);
        element(tx, "gml:endPosition", dimensionHelper.getEndTime(), null);
        tx.end("gml:TimePeriod");
        tx.end("om:phenomenonTime");
       
        // resultTime
        tx.start("om:resultTime");
        tx.start("gml:TimeInstant", atts("gml:id", coverageId + "_rt"));
        element(tx, "gml:timePosition", dimensionHelper.getEndTime(), null);
        tx.end("gml:TimeInstant");
        tx.end("om:resultTime");
       
        // some empty elements...
        element(tx, "om:procedure", null, null);
        element(tx, "om:observedProperty", null, null);

        // the footprint
        GeneralEnvelope ge = reader.getOriginalEnvelope();
        CoordinateReferenceSystem crs = reader.getCoordinateReferenceSystem();
        String srsName = getSRSName(crs);
        final boolean axisSwap = CRS.getAxisOrder(crs).equals(AxisOrder.EAST_NORTH);
        double minx = ge.getLowerCorner().getOrdinate(axisSwap ? 1 : 0);
        double miny = ge.getLowerCorner().getOrdinate(axisSwap ? 0 : 1);
        double maxx = ge.getUpperCorner().getOrdinate(axisSwap ? 1 : 0);
View Full Code Here

            checkDomainSubset(meta, request.getDomainSubset(), wcs);
            checkRangeSubset(meta, request.getRangeSubset());
            checkOutput(meta, request.getOutput());

            // grab the format, the reader using the default params
            final GridCoverage2DReader reader = (GridCoverage2DReader) meta.getGridCoverageReader(
                    null, WCSUtils.getReaderHints(wcs));

            // handle spatial domain subset, if needed
            final GeneralEnvelope originalEnvelope = reader.getOriginalEnvelope();
            final BoundingBoxType bbox = request.getDomainSubset().getBoundingBox();
            final CoordinateReferenceSystem nativeCRS = originalEnvelope
                    .getCoordinateReferenceSystem();
            final GeneralEnvelope requestedEnvelopeInNativeCRS;
            final GeneralEnvelope requestedEnvelope;
            if (bbox != null) {
                // first off, parse the envelope corners
                double[] lowerCorner = new double[bbox.getLowerCorner().size()];
                double[] upperCorner = new double[bbox.getUpperCorner().size()];
                for (int i = 0; i < lowerCorner.length; i++) {
                    lowerCorner[i] = (Double) bbox.getLowerCorner().get(i);
                    upperCorner[i] = (Double) bbox.getUpperCorner().get(i);
                }
                requestedEnvelope = new GeneralEnvelope(lowerCorner, upperCorner);
                // grab the native crs
                // if no crs has beens specified, the native one is assumed
                if (bbox.getCrs() == null) {
                    requestedEnvelope.setCoordinateReferenceSystem(nativeCRS);
                    requestedEnvelopeInNativeCRS = requestedEnvelope;
                } else {
                    // otherwise we need to transform
                    final CoordinateReferenceSystem bboxCRS = CRS.decode(bbox.getCrs());
                    requestedEnvelope.setCoordinateReferenceSystem(bboxCRS);
                    if (!CRS.equalsIgnoreMetadata(bboxCRS, nativeCRS)) {
                        CoordinateOperationFactory of = CRS.getCoordinateOperationFactory(true);
                        CoordinateOperation co = of.createOperation(bboxCRS, nativeCRS);
                        requestedEnvelopeInNativeCRS = CRS.transform(co, requestedEnvelope);
                    } else {
                        requestedEnvelopeInNativeCRS = new GeneralEnvelope(requestedEnvelope);
                    }
                }
            } else {
                requestedEnvelopeInNativeCRS = reader.getOriginalEnvelope();
                requestedEnvelope = requestedEnvelopeInNativeCRS;
            }

            final GridCrsType gridCRS = request.getOutput().getGridCRS();

            // Compute the crs that the final coverage will be served into
            final CoordinateReferenceSystem targetCRS;
            if (gridCRS == null) {
                targetCRS = reader.getOriginalEnvelope().getCoordinateReferenceSystem();
            } else {
                targetCRS = CRS.decode(gridCRS.getGridBaseCRS());
            }

            //
            // Raster destination size
            //
            int elevationLevels = 0;
            double[] elevations = null;

            // grab the grid to world transformation
            MathTransform gridToCRS = reader.getOriginalGridToWorld(PixelInCell.CELL_CENTER);

            //
            // TIME Values
            //
            final List<Date> timeValues = new LinkedList<Date>();

            TimeSequenceType temporalSubset = request.getDomainSubset().getTemporalSubset();

            if (temporalSubset != null && temporalSubset.getTimePosition() != null
                    && temporalSubset.getTimePosition().size() > 0) {
                for (Iterator it = temporalSubset.getTimePosition().iterator(); it.hasNext();) {
                    Date tp = (Date) it.next();
                    timeValues.add(tp);
                }
            } else if (temporalSubset != null && temporalSubset.getTimePeriod() != null
                    && temporalSubset.getTimePeriod().size() > 0) {
                for (Iterator it = temporalSubset.getTimePeriod().iterator(); it.hasNext();) {
                    TimePeriodType tp = (TimePeriodType) it.next();
                    Date beginning = (Date) tp.getBeginPosition();
                    Date ending = (Date) tp.getEndPosition();

                    timeValues.add(beginning);
                    timeValues.add(ending);
                }
            }

            // now we have enough info to read the coverage, grab the parameters
            // and add the grid geometry info
            final GeneralEnvelope intersectionEnvelopeInSourceCRS = new GeneralEnvelope(
                    requestedEnvelopeInNativeCRS);
            intersectionEnvelopeInSourceCRS.intersect(originalEnvelope);

            final GridGeometry2D requestedGridGeometry = new GridGeometry2D(
                    PixelInCell.CELL_CENTER, gridToCRS, intersectionEnvelopeInSourceCRS, null);

            final ParameterValueGroup readParametersDescriptor = reader.getFormat()
                    .getReadParameters();
            GeneralParameterValue[] readParameters = CoverageUtils.getParameters(
                    readParametersDescriptor, meta.getParameters());
            readParameters = (readParameters != null ? readParameters
                    : new GeneralParameterValue[0]);

            //
            // Setting coverage reading params.
            //
            final ParameterValue requestedGridGeometryParam = new DefaultParameterDescriptor(
                    AbstractGridFormat.READ_GRIDGEOMETRY2D.getName().toString(),
                    GeneralGridGeometry.class, null, requestedGridGeometry).createValue();

            /*
             * Test if the parameter "TIME" is present in the WMS request, and by the way in the reading parameters. If it is the case, one can adds
             * it to the request. If an exception is thrown, we have nothing to do.
             */
            final List<GeneralParameterDescriptor> parameterDescriptors = readParametersDescriptor
                    .getDescriptor().descriptors();
            ParameterValue time = null;
            boolean hasTime = timeValues.size() > 0;
            ParameterValue elevation = null;
            boolean hasElevation = elevations != null && !Double.isNaN(elevations[0]);

            if (hasElevation || hasTime) {
                for (GeneralParameterDescriptor pd : parameterDescriptors) {

                    final String code = pd.getName().getCode();

                    //
                    // TIME
                    //
                    if (code.equalsIgnoreCase("TIME")) {
                        time = (ParameterValue) pd.createValue();
                        time.setValue(timeValues);
                    }

                    //
                    // ELEVATION
                    //
                    if (code.equalsIgnoreCase("ELEVATION")) {
                        elevation = (ParameterValue) pd.createValue();
                        elevation.setValue(elevations[0]);
                    }

                    // leave?
                    if ((hasElevation && elevation != null && hasTime && time != null)
                            || !hasElevation && hasTime && time != null || hasElevation
                            && elevation != null && !hasTime)
                        break;
                }
            }
            //
            // add read parameters
            //
            int addedParams = 1 + (hasTime ? 1 : 0) + (hasElevation ? 1 : 0);
            // add to the list
            GeneralParameterValue[] readParametersClone = new GeneralParameterValue[readParameters.length
                    + addedParams--];
            System.arraycopy(readParameters, 0, readParametersClone, 0, readParameters.length);
            readParametersClone[readParameters.length + addedParams--] = requestedGridGeometryParam;
            if (hasTime)
                readParametersClone[readParameters.length + addedParams--] = time;
            if (hasElevation)
                readParametersClone[readParameters.length + addedParams--] = elevation;
            readParameters = readParametersClone;

            // Check we're not being requested to read too much data from input (first check,
            // guesses the grid size using the information contained in CoverageInfo)
            WCSUtils.checkInputLimits(wcs, meta, reader, requestedGridGeometry);

            //
            // Check if we have a filter among the params
            //
            Filter filter = WCSUtils.getRequestFilter();
            if (filter != null) {
                readParameters = CoverageUtils.mergeParameter(parameterDescriptors, readParameters,
                        filter, "FILTER", "Filter");
            }

            //
            // make sure we work in streaming mode
            //
            // work in streaming fashion when JAI is involved
            readParameters = WCSUtils.replaceParameter(readParameters, Boolean.FALSE,
                    AbstractGridFormat.USE_JAI_IMAGEREAD);

            //
            // perform Read ...
            //
            coverage = (GridCoverage2D) reader.read(readParameters);
            if ((coverage == null) || !(coverage instanceof GridCoverage2D)) {
                throw new IOException("The requested coverage could not be found.");
            }

            // now that we have read the coverage double check the input size
View Full Code Here

     * @param info the {@link CoverageStoreInfo} instance used to look for {@link CoverageInfo} instances.
     * @return
     */
    public static GridCoverageReader wrap(GridCoverage2DReader delegate, String coverageName,
            CoverageStoreInfo info) {
        GridCoverage2DReader reader = delegate;
        if (coverageName != null) {
            reader = SingleGridCoverage2DReader.wrap(delegate, coverageName);
        }
        if (reader instanceof StructuredGridCoverage2DReader) {
            return new CoverageDimensionCustomizerStructuredReader((StructuredGridCoverage2DReader) reader, coverageName, info);
View Full Code Here

TOP

Related Classes of org.geotools.coverage.grid.io.GridCoverage2DReader

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.