Package org.geotools.coverage.grid.io

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


                collection = identifyVectorLayer(filters, x, y, buffer, viewParam,
                        requestedCRS, width, height, bbox, ff, results, i, layer, rules, maxFeatures);

            } else if (layer.getType() == MapLayerInfo.TYPE_RASTER) {
                final CoverageInfo cinfo = requestedLayers.get(i).getCoverage();
                final AbstractGridCoverage2DReader reader = (AbstractGridCoverage2DReader) cinfo
                        .getGridCoverageReader(new NullProgressListener(),
                                GeoTools.getDefaultHints());
               
               
                // get the original grid geometry
                final GridGeometry2D coverageGeometry = (GridGeometry2D) cinfo.getGrid();
                // set the requested position in model space for this request
                final Coordinate middle = pixelToWorld(x, y, bbox, width, height);
                DirectPosition position = new DirectPosition2D(requestedCRS, middle.x, middle.y);

                // change from request crs to coverage crs in order to compute a minimal request
                // area,
                // TODO this code need to be made much more robust
                if (requestedCRS != null) {

                    final CoordinateReferenceSystem targetCRS = coverageGeometry
                            .getCoordinateReferenceSystem();
                    final TransformedDirectPosition arbitraryToInternal = new TransformedDirectPosition(
                            requestedCRS, targetCRS, new Hints(Hints.LENIENT_DATUM_SHIFT,
                                    Boolean.TRUE));
                    try {
                        arbitraryToInternal.transform(position);
                    } catch (TransformException exception) {
                        throw new CannotEvaluateException("Unable to answer the geatfeatureinfo",
                                exception);
                    }
                    position = arbitraryToInternal;
                }
                // check that the provided point is inside the bbox for this coverage
                if (!reader.getOriginalEnvelope().contains(position)) {
                    continue;
                }

                // read from the request
                GeneralParameterValue[] parameters = wms.getWMSReadParameters(request.getGetMapRequest(),
View Full Code Here


        File info = new File(coverageDir, "info.xml");
        info.createNewFile();
       
        // let's grab the necessary metadata
        AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder.findFormat(coverageFile);
        AbstractGridCoverage2DReader reader = (AbstractGridCoverage2DReader) format.getReader(coverageFile);
        if (reader == null) {
            throw new RuntimeException("No reader for " + coverageFile.getCanonicalPath() + " with format " + format.getName());
        }
        // basic info
        FileWriter writer = new FileWriter(info);
        writer.write("<coverage format=\"" + coverage + "\">\n");
        writer.write("<name>" + coverage + "</name>\n");
        writer.write("<label>" + coverage + "</label>\n");
        writer.write("<description>" + coverage + " description</description>\n");
        writer.write("<metadataLink about = \"http://www.remotesensing.org:16080/websites/geotiff/geotiff.html\" metadataType = \"other\" />");
        writer.write("<keywords>WCS," + coverage + " </keywords>\n");
        if(styleName == null)
            styleName = "raster";
        writer.write("<styles default=\"" + styleName + "\"/>\n");
       
        // envelope
        CoordinateReferenceSystem crs = reader.getCrs();
        GeneralEnvelope envelope = reader.getOriginalEnvelope();
        GeneralEnvelope wgs84envelope = CoverageStoreUtils.getWGS84LonLatEnvelope(envelope);
        final String nativeCrsName = CRS.lookupIdentifier(crs, false);
        writer.write("<envelope crs=\"" + crs.toString().replaceAll("\"", "'") + "\" srsName=\"" + nativeCrsName + "\">\n");
        writer.write("<pos>" + wgs84envelope.getMinimum(0) + " " + wgs84envelope.getMinimum(1) + "</pos>\n");
        writer.write("<pos>" + wgs84envelope.getMaximum(0) + " " + wgs84envelope.getMaximum(1) + "</pos>\n");
        writer.write("</envelope>\n");
       
        /**
         * Now reading a fake small GridCoverage just to retrieve meta information:
         * - calculating a new envelope which is 1/20 of the original one
         * - reading the GridCoverage subset
         */

        final ParameterValueGroup readParams = reader.getFormat().getReadParameters();
        final Map parameters = CoverageUtils.getParametersKVP(readParams);
        double[] minCP = envelope.getLowerCorner().getCoordinates();
        double[] maxCP = new double[] {
                minCP[0] + (envelope.getLength(0) / 20.0),
                minCP[1] + (envelope.getLength(1) / 20.0)
            };
        final GeneralEnvelope subEnvelope = new GeneralEnvelope(minCP, maxCP);
        subEnvelope.setCoordinateReferenceSystem(reader.getCrs());

        parameters.put(AbstractGridFormat.READ_GRIDGEOMETRY2D.getName().toString(),
            new GridGeometry2D(reader.getOriginalGridRange(), subEnvelope));
        GridCoverage2D gc = (GridCoverage2D) reader.read(CoverageUtils.getParameters(readParams, parameters,
                    true));
       
        // grid geometry
        final GridGeometry geometry = gc.getGridGeometry();
        final int dimensions = geometry.getGridRange().getDimension();
View Full Code Here

        //
        // Get a reader
        //
        final Feature feature = mapContext.getLayer(0).getFeatureSource().getFeatures().features().next();
        final AbstractGridCoverage2DReader reader = (AbstractGridCoverage2DReader) feature.getProperty("grid").getValue();
        final Object params = feature.getProperty("params").getValue();

        // if there is a output tile size hint, use it, otherwise use the output size itself
        final int tileSizeX;
        final int tileSizeY;
        if (mapContext.getTileSize() != -1) {
            tileSizeX = tileSizeY = mapContext.getTileSize();
        } else {
            tileSizeX = mapContext.getMapWidth();
            tileSizeY = mapContext.getMapHeight();
        }
       
        //
        // dimensions
        //
        final int mapWidth = mapContext.getMapWidth();
        final int mapHeight= mapContext.getMapHeight();
        final ReferencedEnvelope mapEnvelope = mapContext.getAreaOfInterest();
        final CoordinateReferenceSystem mapCRS=mapContext.getCoordinateReferenceSystem();       
        final Rectangle mapRasterArea = new Rectangle(0, 0, mapWidth,mapHeight);
        final AffineTransform worldToScreen = RendererUtilities.worldToScreenTransform(mapEnvelope, mapRasterArea);       
        

        //
        // Check transparency and bg color
        //
        final boolean transparent = mapContext.isTransparent() && isTransparencySupported();
        Color bgColor = mapContext.getBgColor();
        // set transparency
        if (transparent) {
            bgColor = new Color(bgColor.getRed(), bgColor.getGreen(), bgColor.getBlue(), 0);
        } else {
            bgColor = new Color(bgColor.getRed(), bgColor.getGreen(), bgColor.getBlue(), 255);
        }
 
        //
        // grab the interpolation
        //
        Interpolation interpolation = Interpolation.getInstance(Interpolation.INTERP_NEAREST);
        if (wms != null) {
            if (WMSInterpolation.Nearest.equals(wms.getInterpolation())) {
                interpolation = Interpolation.getInstance(Interpolation.INTERP_NEAREST);
            } else if (WMSInterpolation.Bilinear.equals(wms.getInterpolation())) {
                interpolation = Interpolation.getInstance(Interpolation.INTERP_BILINEAR);
            } else if (WMSInterpolation.Bicubic.equals(wms.getInterpolation())) {
                interpolation = Interpolation.getInstance(Interpolation.INTERP_BICUBIC);
            }
        }

        //
        // read best available coverage and render it
        //       
        final CoordinateReferenceSystem coverageCRS= reader.getCrs();
        final GridGeometry2D readGG;
        final ReferencedEnvelope bufferedEnvelope;
        final Rectangle bufferedTargetArea;
        final boolean equalsMetadata=CRS.equalsIgnoreMetadata(mapCRS, coverageCRS);
        boolean sameCRS;
View Full Code Here

       
        MockHttpServletResponse response = postAsServletResponse("wcs", xml);
        assertEquals("image/tiff;subtype=\"geotiff\"", response.getContentType());
       
        GeoTiffFormat format = new GeoTiffFormat();
        AbstractGridCoverage2DReader reader = format.getReader(getBinaryInputStream(response));
       
        assertEquals(CRS.decode("EPSG:3857"), reader.getOriginalEnvelope().getCoordinateReferenceSystem());
    }
View Full Code Here

                if (csinfo == null)
                    throw new RuntimeException(
                            "Unable to acquire coverage store resource for layer: "
                                    + layer.getName());

                AbstractGridCoverage2DReader reader = null;
                try {
                    reader = (AbstractGridCoverage2DReader) catalog.getResourcePool()
                            .getGridCoverageReader(csinfo, GeoTools.getDefaultHints());
                } catch (Throwable t) {
                    LOGGER.severe("Unable to acquire a reader for this coverage with format: "
                            + csinfo.getFormat().getName());
                }

                if (reader == null)
                    throw new RuntimeException(
                            "Unable to acquire a reader for this coverage with format: "
                                    + csinfo.getFormat().getName());

                final String[] metadataNames = reader.getMetadataNames();

                if (metadataNames != null && metadataNames.length > 0) {
                    // TIME DIMENSION
                    timeMetadata = reader.getMetadataValue("TIME_DOMAIN");

                    if (timeMetadata != null) {
                        AttributesImpl timeDim = new AttributesImpl();
                        timeDim.addAttribute("", "name", "name", "", "time");
                        timeDim.addAttribute("", "units", "units", "", "ISO8601");
                        element("Dimension", null, timeDim);
                    }

                    // ELEVATION DIMENSION
                    elevationMetadata = reader.getMetadataValue("ELEVATION_DOMAIN");

                    if (elevationMetadata != null) {
                        AttributesImpl elevDim = new AttributesImpl();
                        elevDim.addAttribute("", "name", "name", "", "elevation");
                        elevDim.addAttribute("", "units", "units", "", "EPSG:5030");
View Full Code Here

        super(delegate);
        this.policy = policy;
    }

    public AbstractGridCoverage2DReader getReader(Object source, Hints hints) {
        AbstractGridCoverage2DReader reader = delegate.getReader(source, hints);
        if (reader == null) {
            return reader;
        } else {
            return (AbstractGridCoverage2DReader) SecuredObjects.secure(reader, policy);
        }
View Full Code Here

            return (AbstractGridCoverage2DReader) SecuredObjects.secure(reader, policy);
        }
    }

    public AbstractGridCoverage2DReader getReader(Object source) {
        AbstractGridCoverage2DReader reader = delegate.getReader(source);
        if (reader == null) {
            return reader;
        } else {
            return (AbstractGridCoverage2DReader) SecuredObjects.secure(reader, policy);
        }
View Full Code Here

            return; // no symbolizers so return
        }

        LOGGER.finer("applying one symbolizer: " + symbolizers[0].toString());

        final AbstractGridCoverage2DReader gcReader =
            (AbstractGridCoverage2DReader) feature.getAttribute("grid");

        // TODO add read parameters feature.getAttribute("params")
        final String baseURL = mapContext.getRequest().getBaseUrl();
View Full Code Here

            //
            // GRAB A READER
            //
            // grab the reader using the default params
            final AbstractGridCoverage2DReader reader = (AbstractGridCoverage2DReader) meta
                    .getGridCoverageReader(null, WCSUtils.getReaderHints(wcs));
            if (reader == null) {
                // cannot instantiate a reader, we should return an empty array
                return coverageResults.toArray(new GridCoverage2D[] {});
            }

            // get native elements and then play with the the requested ones
            final GeneralEnvelope nativeEnvelope = reader.getOriginalEnvelope();
            final CoordinateReferenceSystem nativeCRS = nativeEnvelope
                    .getCoordinateReferenceSystem();

            // get requested crs
            String requestedCRS = null;
            if (outputCRS != null) {
                requestedCRS = outputCRS.getValue();
            }

            // Compute the target crs, the crs that the final coverage will be served into
            final CoordinateReferenceSystem targetCRS;
            if (requestedCRS == null) {
                targetCRS = reader.getOriginalEnvelope().getCoordinateReferenceSystem();
                requestedCRS = CRS.lookupIdentifier(targetCRS, true);
            } else {
                // FORCE LON,LAT!!!!
                targetCRS = CRS.decode(requestedCRS, true);
            }
           
            //
            // PREPARE DESTINATION DIMENSIONS
            //
            final Rectangle destinationSize;
            final AffineTransform2D destinationG2W;
            final GridEnvelope limits = grid.getLimits();
            if (limits != null) {
                //
                // we have imposed limits from the request, we just use them as they are
                //
                final int[] lowers = limits.getLow().getCoordinateValues();
                destinationG2W = null;
                destinationSize = new Rectangle(lowers[0], lowers[1], limits.getSpan(0), limits
                        .getSpan(1));
            } else if (grid.getOffsetVector() != null && grid.getOffsetVector().size() > 0) {
                //
                // we have NO imposed limits from the request, we need to create a proper G2W with
                // the RESOLUTION we where given.
                // Notice that this is specific to WCS 1.0.0 since the request just allow us to
                // specify ResX and ResY
                //
                final VectorType offsetVector = (VectorType) grid.getOffsetVector().get(0);
                final List offsetValues = offsetVector.getValue();
                final double resX = (Double) offsetValues.get(0);
                final double resY = (Double) offsetValues.get(1);

                final DirectPositionType origin_ = grid.getOrigin().getPos();
                destinationSize = null;
                destinationG2W = new AffineTransform2D(resX, 0d, 0d, resY, (Double) origin_
                        .getValue().get(0), (Double) origin_.getValue().get(1));

            } else
                throw new WcsException("Invalid Grid value:" + grid.toString(),
                        InvalidParameterValue, null);

            //
            // ELEVATION SUPPORT VIA A SPECIFIC AXIS ELEVATION
            //

            double[] elevations = null;
            // extract elevation values
            List axisSubset = null;
            if (request.getRangeSubset() != null) {
                axisSubset = request.getRangeSubset().getAxisSubset();
                if (axisSubset.size() > 0) {
                    for (int a = 0; a < axisSubset.size(); a++) {
                        AxisSubsetType axis = (AxisSubsetType) axisSubset.get(a);

                        String axisName = axis.getName();
                        if (axisName.equalsIgnoreCase(WCSUtils.ELEVATION)) {
                            if (axis.getSingleValue().size() > 0) {
                                elevations = new double[axis.getSingleValue().size()];
                                for (int s = 0; s < axis.getSingleValue().size(); s++) {
                                    elevations[s] = Double.parseDouble(((TypedLiteralType) axis
                                            .getSingleValue().get(s)).getValue());
                                }
                            } else if (axis.getInterval().size() > 0) {
                                IntervalType interval = (IntervalType) axis.getInterval().get(0);
                                int min = Integer.parseInt(interval.getMin().getValue());
                                int max = Integer.parseInt(interval.getMax().getValue());
                                int res = (interval.getRes() != null ? Integer.parseInt(interval
                                        .getRes().getValue()) : 1);

                                elevations = new double[(int) (Math.floor(max - min) / res + 1)];
                                for (int b = 0; b < elevations.length; b++)
                                    elevations[b] = (min + b * res);
                            }
                        }
                    }
                }
            }
            // if(dimension==3&&elevationLevels>0)
            // {
            // // compute the elevation levels, we have elevationLevels values
            // elevations=new double[elevationLevels];
            //
            // elevations[0]=requestedEnvelope.getLowerCorner().getOrdinate(2); // TODO put the
            // extrema
            // elevations[elevationLevels-1]=requestedEnvelope.getUpperCorner().getOrdinate(2);
            // if(elevationLevels>2){
            // final int adjustedLevelsNum=elevationLevels-1;
            // double step = (elevations[elevationLevels-1]-elevations[0])/adjustedLevelsNum;
            // for(int i=1;i<adjustedLevelsNum;i++)
            // elevations[i]=elevations[i-1]+step;
            // }
            // }

            //
            // TIME
            //
            final List<Date> timeValues = new LinkedList<Date>();
            // sequence of timepositions
            if (temporalSubset != null && temporalSubset.getTimePosition() != null
                    && temporalSubset.getTimePosition().size() > 0) {
                final EList timePositionLists = temporalSubset.getTimePosition();
                for (Iterator it = timePositionLists.iterator(); it.hasNext();) {
                    TimePositionTypeImpl tp = (TimePositionTypeImpl) it.next();
                    timeValues.add((Date) tp.getValue());
                }
            }
            // else if (temporalSubset!=null&&temporalSubset.getTimePeriod() != null
            // &&temporalSubset.getTimePeriod().size() > 0) {
            // final EList timePeriodLists =temporalSubset.getTimePeriod();
            // for (Iterator it =domainSubset.getTemporalSubset().getTimePeriod().iterator();
            // it.hasNext(); ) {
            // TimePeriodType tp = (TimePeriodType) it.next();
            // Date beginning = (Date)tp.getBeginPosition().getValue();
            // Date ending = (Date)tp.getEndPosition().getValue();
            //                   
            // timeValues.add(beginning);
            // timeValues.add(ending);
            // }
            // }

            //
            // SETTING COVERAGE READING PARAMS
            //
            // get the group of parameters tha this reader supports
            final ParameterValueGroup readParametersDescriptor = reader.getFormat()
                    .getReadParameters();
            GeneralParameterValue[] readParameters = CoverageUtils.getParameters(
                    readParametersDescriptor, meta.getParameters());
            readParameters = (readParameters != null ? readParameters
                    : new GeneralParameterValue[0]);

            // read grid geometry
            final GridGeometry2D requestedGridGeometry;
            if (destinationSize != null)
                // we have been asked to support a specific raster size, we will se the grid2world
                // accordingly
                requestedGridGeometry = new GridGeometry2D(new GridEnvelope2D(destinationSize),
                        getHorizontalEnvelope(requestedEnvelope));
            else
                // we have been asked to support a specific g2w, we will set the raster size
                // accordingly
                requestedGridGeometry = new GridGeometry2D(PixelInCell.CELL_CENTER, destinationG2W,
                        getHorizontalEnvelope(requestedEnvelope), null);
            // NOTICE that we always have to respect the provided envelope
            final ParameterValue<GeneralGridGeometry> requestedGridGeometryParam = new DefaultParameterDescriptor<GeneralGridGeometry>(
                    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(WCSUtils.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 going to read too much data
            WCSUtils.checkInputLimits(wcs, meta, reader, requestedGridGeometry);

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

            // double check what we have loaded
View Full Code Here

TOP

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

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.