@Test public void NetCDFProjectedEnvelopeTest() throws NoSuchAuthorityCodeException, FactoryException, IOException, ParseException { File mosaic = new File(TestData.file(this, "."), "NetCDFProjection"); if (mosaic.exists()) { FileUtils.deleteDirectory(mosaic); } assertTrue(mosaic.mkdirs()); File file = TestData.file(this, "wind.nc"); FileUtils.copyFileToDirectory(file, mosaic); file = new File(mosaic, "wind.nc"); // Get format final NetCDFReader reader = new NetCDFReader(file, null); try { String[] names = reader.getGridCoverageNames(); String coverageName = names[0]; // subsetting the envelope final ParameterValue<GridGeometry2D> gg = AbstractGridFormat.READ_GRIDGEOMETRY2D.createValue(); final GeneralEnvelope originalEnvelope = reader.getOriginalEnvelope(coverageName); final CoordinateReferenceSystem epsg3857 = CRS.decode("EPSG:3857", true); final GeneralEnvelope projectedEnvelope = CRS.transform(originalEnvelope, epsg3857); gg.setValue( new GridGeometry2D(new GridEnvelope2D(new Rectangle(0, 0, 30, 30)), projectedEnvelope)); GeneralParameterValue[] values = new GeneralParameterValue[] {gg}; GridCoverage2D coverage = reader.read(coverageName, values); // reader doesn't perform reprojection. It simply transforms reprojected envelope // to native envelope so BBOX and CRS should be wgs84 CoordinateReferenceSystem coverageCRS = coverage.getCoordinateReferenceSystem(); final int code = CRS.lookupEpsgCode(coverageCRS, false); assertEquals(4326, code); Extent extent = coverageCRS.getDomainOfValidity(); Collection<? extends GeographicExtent> geoElements = extent.getGeographicElements(); GeographicExtent geographicExtent = geoElements.iterator().next(); GeographicBoundingBoxImpl impl = (GeographicBoundingBoxImpl) geographicExtent; // Getting the coverage Envelope for coordinates check Envelope coverageEnvelope = coverage.getEnvelope(); assertTrue(impl.getEastBoundLongitude() >= coverageEnvelope.getMaximum(0)); assertTrue(impl.getWestBoundLongitude() <= coverageEnvelope.getMinimum(0)); assertTrue(impl.getNorthBoundLatitude() >= coverageEnvelope.getMaximum(1)); assertTrue(impl.getSouthBoundLatitude() <= coverageEnvelope.getMinimum(1)); } catch (Throwable t) { throw new RuntimeException(t); } finally { if (reader != null) { try { reader.dispose(); } catch (Throwable t) { // Does nothing } } } }
/** Visit all files to keep only XML files. */ @Override protected void visit() { final ParameterValue<URL> paramUrl = (ParameterValue<URL>) getSourceConfiguration(getSource()).parameter(URL.getName().getCode()); if (paramUrl == null || paramUrl.getValue() == null) { getLogger().log(Level.WARNING, "Provided File path is not defined."); return; } final URL urlPath = paramUrl.getValue(); try { path = new File(urlPath.toURI()); } catch (URISyntaxException e) { getLogger().log(Level.INFO, "Fails to convert path url to file."); path = new File(urlPath.getPath()); } List<File> candidates = new ArrayList<>(); if (path.isDirectory()) { candidates.addAll( FileUtilities.scanDirectory( path, new FileFilter() { @Override public boolean accept(File pathname) { final String fullName = pathname.getName(); final int idx = fullName.lastIndexOf('.'); final String extension = fullName.substring(idx + 1); return extension.equalsIgnoreCase("xml"); } })); } else { candidates.add(path); } index = new HashMap<>(); for (final File candidate : candidates) { try { final MapContext mapContext = MapContextIO.readMapContextFile(candidate, "", "", styleBusiness); if (mapContext != null) { final GenericName name = NamesExt.create(mapContext.getName()); index.put(name, candidate); } } catch (JAXBException e) { getLogger() .log( Level.WARNING, "Candidate MapContext file can't be read : " + candidate.getAbsolutePath(), e); } } super.visit(); }
@Override public WebMapTileClient open(ParameterValueGroup params) throws DataStoreException { ensureCanProcess(params); final WebMapTileClient server = new WebMapTileClient(params); try { final ParameterValue val = params.parameter(NIO_QUERIES.getName().getCode()); boolean useNIO = Boolean.TRUE.equals(val.getValue()); server.setUserProperty(CachedPyramidSet.PROPERTY_NIO, useNIO); } catch (ParameterNotFoundException ex) { } return server; }
/** * Returns the parameters for this math transform. * * @return The parameters for this math transform. */ @Override public ParameterValueGroup getParameterValues() { final ParameterValue<Integer> dim = new Parameter<Integer>(Provider.DIM); dim.setValue(getSourceDimensions()); return new ParameterGroup( getParameterDescriptors(), new ParameterValue[] { dim, new FloatParameter(Provider.DX, dx), new FloatParameter(Provider.DY, dy), new FloatParameter(Provider.DZ, dz), new FloatParameter(Provider.SRC_SEMI_MAJOR, a), new FloatParameter(Provider.SRC_SEMI_MINOR, b), new FloatParameter(Provider.TGT_SEMI_MAJOR, a + da), new FloatParameter(Provider.TGT_SEMI_MINOR, b + db) }); }
private GridCoverage2D readCoverage() throws NoSuchAuthorityCodeException, FactoryException, IOException { final AbstractGridFormat format = TestUtils.getFormat(testMosaicUrl); final ImageMosaicReader reader = TestUtils.getReader(testMosaicUrl, format); // activate footprint management GeneralParameterValue[] params = new GeneralParameterValue[2]; ParameterValue<String> footprintManagement = ImageMosaicFormat.FOOTPRINT_BEHAVIOR.createValue(); footprintManagement.setValue(FootprintBehavior.Cut.name()); params[0] = footprintManagement; // this prevents us from having problems with link to files still open. ParameterValue<Boolean> jaiImageRead = ImageMosaicFormat.USE_JAI_IMAGEREAD.createValue(); jaiImageRead.setValue(false); params[1] = jaiImageRead; GridCoverage2D coverage = reader.read(params); reader.dispose(); assertNotNull(coverage); return coverage; }
@Test public void testAreaOutside() throws Exception { // copy the footprints mosaic over FileUtils.copyDirectory(footprintsSource, testMosaic); Properties p = new Properties(); p.put(MultiLevelROIProviderFactory.INSET_PROPERTY, "0.1"); saveFootprintProperties(p); final AbstractGridFormat format = TestUtils.getFormat(testMosaicUrl); final ImageMosaicReader reader = TestUtils.getReader(testMosaicUrl, format); // activate footprint management GeneralParameterValue[] params = new GeneralParameterValue[3]; ParameterValue<String> footprintManagement = ImageMosaicFormat.FOOTPRINT_BEHAVIOR.createValue(); footprintManagement.setValue(FootprintBehavior.None.name()); params[0] = footprintManagement; // this prevents us from having problems with link to files still open. ParameterValue<Boolean> jaiImageRead = ImageMosaicFormat.USE_JAI_IMAGEREAD.createValue(); jaiImageRead.setValue(false); params[1] = jaiImageRead; // limit yourself to reading just a bit of it final ParameterValue<GridGeometry2D> gg = AbstractGridFormat.READ_GRIDGEOMETRY2D.createValue(); final Dimension dim = new Dimension(); dim.setSize(4, 4); final Rectangle rasterArea = ((GridEnvelope2D) reader.getOriginalGridRange()); rasterArea.setSize(dim); final GridEnvelope2D range = new GridEnvelope2D(rasterArea); gg.setValue( new GridGeometry2D( range, PixelInCell.CELL_CENTER, reader.getOriginalGridToWorld(PixelInCell.CELL_CENTER), reader.getCoordinateReferenceSystem(), null)); params[2] = gg; GridCoverage2D coverage = reader.read(params); reader.dispose(); assertNotNull(coverage); }
/** * Applies a crop operation to a coverage. * * @see * org.geotools.coverage.processing.AbstractOperation#doOperation(org.opengis.parameter.ParameterValueGroup, * org.geotools.factory.Hints) */ @SuppressWarnings("unchecked") public Coverage doOperation(ParameterValueGroup parameters, Hints hints) { final Geometry cropRoi; // extracted from parameters GeneralEnvelope cropEnvelope = null; // extracted from parameters final GridCoverage2D source; // extracted from parameters final double roiTolerance = parameters.parameter(Crop.PARAMNAME_ROITOLERANCE).doubleValue(); final boolean forceMosaic = parameters.parameter(Crop.PARAMNAME_FORCEMOSAIC).booleanValue(); // ///////////////////////////////////////////////////////////////////// // // Assigning and checking input parameters // // /////////////////////////////////////////////////////////////////// // source coverage final ParameterValue sourceParameter = parameters.parameter("Source"); if (sourceParameter == null || !(sourceParameter.getValue() instanceof GridCoverage2D)) { throw new CannotCropException( Errors.format(ErrorKeys.NULL_PARAMETER_$2, "Source", GridCoverage2D.class.toString())); } source = (GridCoverage2D) sourceParameter.getValue(); // Check Envelope and ROI existence - we need at least one of them final ParameterValue envelopeParameter = parameters.parameter(PARAMNAME_ENVELOPE); final ParameterValue roiParameter = parameters.parameter(PARAMNAME_ROI); if ((envelopeParameter == null || envelopeParameter.getValue() == null) && (roiParameter == null || roiParameter.getValue() == null)) throw new CannotCropException( Errors.format( ErrorKeys.NULL_PARAMETER_$2, PARAMNAME_ENVELOPE, GeneralEnvelope.class.toString())); Object envelope = envelopeParameter.getValue(); if (envelope != null) { if (envelope instanceof GeneralEnvelope) { cropEnvelope = (GeneralEnvelope) envelope; } else if (envelope instanceof Envelope) { cropEnvelope = new GeneralEnvelope((Envelope) envelope); } } // may be null // Check crop ROI try { cropRoi = IntersectUtils.unrollGeometries( (Geometry) roiParameter.getValue()); // may throw if format not correct } catch (IllegalArgumentException ex) { throw new CannotCropException( Errors.format(ErrorKeys.ILLEGAL_ARGUMENT_$2, PARAMNAME_ROI, ex.getMessage()), ex); } // Setting a GeneralEnvelope from ROI if needed if (cropRoi != null && cropEnvelope == null) { Envelope e2d = JTS.getEnvelope2D(cropRoi.getEnvelopeInternal(), source.getCoordinateReferenceSystem()); cropEnvelope = new GeneralEnvelope(e2d); } // ///////////////////////////////////////////////////////////////////// // // Initialization // // We take the crop envelope and the source envelope then we check their // crs and we also check if they ever overlap. // // ///////////////////////////////////////////////////////////////////// // envelope of the source coverage final Envelope2D sourceEnvelope = source.getEnvelope2D(); // crop envelope Envelope2D destinationEnvelope = new Envelope2D(cropEnvelope); CoordinateReferenceSystem sourceCRS = sourceEnvelope.getCoordinateReferenceSystem(); CoordinateReferenceSystem destinationCRS = destinationEnvelope.getCoordinateReferenceSystem(); if (destinationCRS == null) { // Do not change the user provided object - clone it first. final Envelope2D ge = new Envelope2D(destinationEnvelope); destinationCRS = source.getCoordinateReferenceSystem2D(); ge.setCoordinateReferenceSystem(destinationCRS); destinationEnvelope = ge; } // // // // Source and destination crs must be equals // // // if (!CRS.equalsIgnoreMetadata(sourceCRS, destinationCRS)) { throw new CannotCropException( Errors.format( ErrorKeys.MISMATCHED_ENVELOPE_CRS_$2, sourceCRS.getName().getCode(), destinationCRS.getName().getCode())); } if (cropRoi != null) { // TODO: check ROI SRID } // // // // Check the intersection and, if needed, do the crop operation. // // // final GeneralEnvelope intersectionEnvelope = new GeneralEnvelope((Envelope) destinationEnvelope); intersectionEnvelope.setCoordinateReferenceSystem(source.getCoordinateReferenceSystem()); // intersect the envelopes intersectionEnvelope.intersect(sourceEnvelope); if (intersectionEnvelope.isEmpty()) throw new CannotCropException(Errors.format(ErrorKeys.CANT_CROP)); // intersect the ROI with the intersection envelope and throw an error if they do not intersect if (cropRoi != null) { final Geometry jis = JTS.toGeometry( (com.vividsolutions.jts.geom.Envelope) new ReferencedEnvelope(intersectionEnvelope)); if (!IntersectUtils.intersects(cropRoi, jis)) throw new CannotCropException(Errors.format(ErrorKeys.CANT_CROP)); } // // // // Get the grid-to-world transform by keeping into account translation // of grid geometry constructor for respecting OGC PIXEL-IS-CENTER // ImageDatum assumption. // // // final AffineTransform sourceCornerGridToWorld = (AffineTransform) ((GridGeometry2D) source.getGridGeometry()).getGridToCRS(PixelInCell.CELL_CORNER); // // // // I set the tolerance as half the scale factor of the grid-to-world // transform. This should more or less means in most cases "don't bother // to crop if the new envelope is as close to the old one that we go // deep under pixel size." // // // final double tolerance = XAffineTransform.getScale(sourceCornerGridToWorld); if (cropRoi != null || !intersectionEnvelope.equals(sourceEnvelope, tolerance / 2.0, false)) { cropEnvelope = intersectionEnvelope.clone(); return buildResult( cropEnvelope, cropRoi, roiTolerance, forceMosaic, (hints instanceof Hints) ? (Hints) hints : new Hints(hints), source, sourceCornerGridToWorld); } else { // // // // Note that in case we don't crop at all, WE DO NOT UPDATE the // envelope. If we did we might end up doing multiple successive // crop without actually cropping the image but, still, we would // shrink the envelope each time. Just think about having a loop // that crops recursively the same coverage specifying each time an // envelope whose URC is only a a scale quarter close to the LLC of // the old one. We would never crop the raster but we would modify // the grid-to-world transform each time. // // // return source; } }
/** * This method reads in the TIFF image, constructs an appropriate CRS, determines the math * transform from raster to the CRS model, and constructs a GridCoverage. * * @param params currently ignored, potentially may be used for hints. * @return grid coverage represented by the image * @throws IOException on any IO related troubles */ public GridCoverage2D read(GeneralParameterValue[] params) throws IOException { GeneralEnvelope requestedEnvelope = null; Rectangle dim = null; Color inputTransparentColor = null; OverviewPolicy overviewPolicy = null; int[] suggestedTileSize = null; if (params != null) { // // Checking params // if (params != null) { for (int i = 0; i < params.length; i++) { final ParameterValue param = (ParameterValue) params[i]; final ReferenceIdentifier name = param.getDescriptor().getName(); if (name.equals(AbstractGridFormat.READ_GRIDGEOMETRY2D.getName())) { final GridGeometry2D gg = (GridGeometry2D) param.getValue(); requestedEnvelope = new GeneralEnvelope((Envelope) gg.getEnvelope2D()); dim = gg.getGridRange2D().getBounds(); continue; } if (name.equals(AbstractGridFormat.OVERVIEW_POLICY.getName())) { overviewPolicy = (OverviewPolicy) param.getValue(); continue; } if (name.equals(AbstractGridFormat.INPUT_TRANSPARENT_COLOR.getName())) { inputTransparentColor = (Color) param.getValue(); continue; } if (name.equals(AbstractGridFormat.SUGGESTED_TILE_SIZE.getName())) { String suggestedTileSize_ = (String) param.getValue(); if (suggestedTileSize_ != null && suggestedTileSize_.length() > 0) { suggestedTileSize_ = suggestedTileSize_.trim(); int commaPosition = suggestedTileSize_.indexOf(","); if (commaPosition < 0) { int tileDim = Integer.parseInt(suggestedTileSize_); suggestedTileSize = new int[] {tileDim, tileDim}; } else { int tileW = Integer.parseInt(suggestedTileSize_.substring(0, commaPosition)); int tileH = Integer.parseInt(suggestedTileSize_.substring(commaPosition + 1)); suggestedTileSize = new int[] {tileW, tileH}; } } continue; } } } } // // set params // Integer imageChoice = new Integer(0); final ImageReadParam readP = new ImageReadParam(); try { imageChoice = setReadParams(overviewPolicy, readP, requestedEnvelope, dim); } catch (TransformException e) { new DataSourceException(e); } // // IMAGE READ OPERATION // Hints newHints = null; if (suggestedTileSize != null) { newHints = hints.clone(); final ImageLayout layout = new ImageLayout(); layout.setTileGridXOffset(0); layout.setTileGridYOffset(0); layout.setTileHeight(suggestedTileSize[1]); layout.setTileWidth(suggestedTileSize[0]); newHints.add(new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout)); } final ParameterBlock pbjRead = new ParameterBlock(); if (extOvrImgChoice >= 0 && imageChoice >= extOvrImgChoice) { pbjRead.add( ovrInStreamSPI.createInputStreamInstance( ovrSource, ImageIO.getUseCache(), ImageIO.getCacheDirectory())); pbjRead.add(imageChoice - extOvrImgChoice); } else { pbjRead.add( inStreamSPI != null ? inStreamSPI.createInputStreamInstance( source, ImageIO.getUseCache(), ImageIO.getCacheDirectory()) : ImageIO.createImageInputStream(source)); pbjRead.add(imageChoice); } pbjRead.add(Boolean.FALSE); pbjRead.add(Boolean.FALSE); pbjRead.add(Boolean.FALSE); pbjRead.add(null); pbjRead.add(null); pbjRead.add(readP); pbjRead.add(READER_SPI.createReaderInstance()); RenderedOp coverageRaster = JAI.create("ImageRead", pbjRead, newHints != null ? (RenderingHints) newHints : null); // // MASKING INPUT COLOR as indicated // if (inputTransparentColor != null) { coverageRaster = new ImageWorker(coverageRaster) .setRenderingHints(newHints) .makeColorTransparent(inputTransparentColor) .getRenderedOperation(); } AffineTransform rasterToModel = getRescaledRasterToModel(coverageRaster); try { return createCoverage(coverageRaster, ProjectiveTransform.create(rasterToModel)); } catch (Exception e) { // dispose and close file ImageUtilities.disposePlanarImageChain(coverageRaster); // rethrow if (e instanceof DataSourceException) { throw (DataSourceException) e; } throw new DataSourceException(e); } }
/** * Complex test for Postgis indexing on db. * * @throws Exception */ @Test public void testPostgisIndexing() throws Exception { final File workDir = new File(TestData.file(this, "."), "watertemp4"); assertTrue(workDir.mkdir()); FileUtils.copyFile(TestData.file(this, "watertemp.zip"), new File(workDir, "watertemp.zip")); TestData.unzipFile(this, "watertemp4/watertemp.zip"); final URL timeElevURL = TestData.url(this, "watertemp4"); // place datastore.properties file in the dir for the indexing FileWriter out = null; try { out = new FileWriter(new File(TestData.file(this, "."), "/watertemp4/datastore.properties")); final Set<Object> keyset = fixture.keySet(); for (Object key : keyset) { final String key_ = (String) key; final String value = fixture.getProperty(key_); out.write(key_.replace(" ", "\\ ") + "=" + value.replace(" ", "\\ ") + "\n"); } out.flush(); } finally { if (out != null) { IOUtils.closeQuietly(out); } } // now start the test final AbstractGridFormat format = TestUtils.getFormat(timeElevURL); assertNotNull(format); ImageMosaicReader reader = TestUtils.getReader(timeElevURL, format); assertNotNull(reader); final String[] metadataNames = reader.getMetadataNames(); assertNotNull(metadataNames); assertEquals(metadataNames.length, 10); assertEquals("true", reader.getMetadataValue("HAS_TIME_DOMAIN")); final String timeMetadata = reader.getMetadataValue("TIME_DOMAIN"); assertNotNull(timeMetadata); assertEquals(2, timeMetadata.split(",").length); assertEquals(timeMetadata.split(",")[0], reader.getMetadataValue("TIME_DOMAIN_MINIMUM")); assertEquals(timeMetadata.split(",")[1], reader.getMetadataValue("TIME_DOMAIN_MAXIMUM")); assertEquals("true", reader.getMetadataValue("HAS_ELEVATION_DOMAIN")); final String elevationMetadata = reader.getMetadataValue("ELEVATION_DOMAIN"); assertNotNull(elevationMetadata); assertEquals(2, elevationMetadata.split(",").length); assertEquals( Double.parseDouble(elevationMetadata.split(",")[0]), Double.parseDouble(reader.getMetadataValue("ELEVATION_DOMAIN_MINIMUM")), 1E-6); assertEquals( Double.parseDouble(elevationMetadata.split(",")[1]), Double.parseDouble(reader.getMetadataValue("ELEVATION_DOMAIN_MAXIMUM")), 1E-6); // limit yourself to reading just a bit of it final ParameterValue<GridGeometry2D> gg = AbstractGridFormat.READ_GRIDGEOMETRY2D.createValue(); final GeneralEnvelope envelope = reader.getOriginalEnvelope(); final Dimension dim = new Dimension(); dim.setSize( reader.getOriginalGridRange().getSpan(0) / 2.0, reader.getOriginalGridRange().getSpan(1) / 2.0); final Rectangle rasterArea = ((GridEnvelope2D) reader.getOriginalGridRange()); rasterArea.setSize(dim); final GridEnvelope2D range = new GridEnvelope2D(rasterArea); gg.setValue(new GridGeometry2D(range, envelope)); // use imageio with defined tiles final ParameterValue<List> time = ImageMosaicFormat.TIME.createValue(); final List<Date> timeValues = new ArrayList<Date>(); final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss'Z'"); sdf.setTimeZone(TimeZone.getTimeZone("GMT+0")); Date date = sdf.parse("2008-10-31T00:00:00.000Z"); timeValues.add(date); time.setValue(timeValues); final ParameterValue<double[]> bkg = ImageMosaicFormat.BACKGROUND_VALUES.createValue(); bkg.setValue(new double[] {-9999.0}); final ParameterValue<Boolean> direct = ImageMosaicFormat.USE_JAI_IMAGEREAD.createValue(); direct.setValue(false); final ParameterValue<List> elevation = ImageMosaicFormat.ELEVATION.createValue(); elevation.setValue(Arrays.asList(100.0)); // Test the output coverage TestUtils.checkCoverage( reader, new GeneralParameterValue[] {gg, time, bkg, elevation, direct}, "Time-Elevation Test"); reader = TestUtils.getReader(timeElevURL, format); elevation.setValue(Arrays.asList(NumberRange.create(0.0, 10.0))); // Test the output coverage TestUtils.checkCoverage( reader, new GeneralParameterValue[] {gg, time, bkg, elevation, direct}, "Time-Elevation Test"); }
@SuppressWarnings({"rawtypes", "unchecked"}) @Test @Ignore public void IASI() throws Exception { final URL testURL = TestData.url(this, "IASI_C_EUMP_20121120062959_31590_eps_o_l2.nc"); final Hints hints = new Hints(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, CRS.decode("EPSG:4326", true)); // Get format final AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder.findFormat(testURL, hints); final NetCDFReader reader = (NetCDFReader) format.getReader(testURL, hints); assertNotNull(format); assertNotNull(reader); try { String[] names = reader.getGridCoverageNames(); assertNotNull(names); assertEquals(names.length, 20); // surface_emissivity final String coverageName = "surface_emissivity"; final String[] metadataNames = reader.getMetadataNames(coverageName); assertNotNull(metadataNames); assertEquals(14, metadataNames.length); // Parsing metadata values assertEquals("false", reader.getMetadataValue(coverageName, "HAS_TIME_DOMAIN")); assertEquals("false", reader.getMetadataValue(coverageName, "HAS_ELEVATION_DOMAIN")); assertEquals("true", reader.getMetadataValue(coverageName, "HAS_NEW_DOMAIN")); // additional domains final String newDomain = reader.getMetadataValue(coverageName, "NEW_DOMAIN"); assertNotNull(metadataNames); final String[] newDomainValues = newDomain.split(","); assertNotNull(newDomainValues); assertEquals(12, newDomainValues.length); assertEquals(13.063399669990758, Double.valueOf(newDomainValues[11]), 1E-6); assertEquals(3.6231999084702693, Double.valueOf(newDomainValues[0]), 1E-6); // subsetting the envelope final ParameterValue<GridGeometry2D> gg = AbstractGridFormat.READ_GRIDGEOMETRY2D.createValue(); final GeneralEnvelope originalEnvelope = reader.getOriginalEnvelope(coverageName); final GeneralEnvelope reducedEnvelope = new GeneralEnvelope( new double[] { originalEnvelope.getLowerCorner().getOrdinate(0), originalEnvelope.getLowerCorner().getOrdinate(1) }, new double[] { originalEnvelope.getMedian().getOrdinate(0), originalEnvelope.getMedian().getOrdinate(1) }); reducedEnvelope.setCoordinateReferenceSystem( reader.getCoordinateReferenceSystem(coverageName)); // Selecting bigger gridRange for a zoomed result final Dimension dim = new Dimension(); GridEnvelope gridRange = reader.getOriginalGridRange(coverageName); dim.setSize(gridRange.getSpan(0) * 4.0, gridRange.getSpan(1) * 2.0); final Rectangle rasterArea = ((GridEnvelope2D) gridRange); rasterArea.setSize(dim); final GridEnvelope2D range = new GridEnvelope2D(rasterArea); gg.setValue(new GridGeometry2D(range, reducedEnvelope)); // specify additional Dimensions Set<ParameterDescriptor<List>> params = reader.getDynamicParameters(coverageName); ParameterValue<List> new_ = null; for (ParameterDescriptor param : params) { if (param.getName().getCode().equalsIgnoreCase("NEW")) { new_ = param.createValue(); new_.setValue( new ArrayList() { { add(Double.valueOf(newDomainValues[11])); } }); } } GeneralParameterValue[] values = new GeneralParameterValue[] {gg, new_}; GridCoverage2D coverage = reader.read(coverageName, values); assertNotNull(coverage); if (TestData.isInteractiveTest()) { coverage.show(); } else { PlanarImage.wrapRenderedImage(coverage.getRenderedImage()).getTiles(); } } finally { if (reader != null) { try { reader.dispose(); } catch (Throwable t) { // Does nothing } } } }
@Test public void NetCDFTestAscatL1() throws NoSuchAuthorityCodeException, FactoryException, IOException, ParseException { File mosaic = new File(TestData.file(this, "."), "NetCDFTestAscatL1"); if (mosaic.exists()) { FileUtils.deleteDirectory(mosaic); } assertTrue(mosaic.mkdirs()); File file = TestData.file(this, "ascatl1.nc"); FileUtils.copyFileToDirectory(file, mosaic); file = new File(mosaic, "ascatl1.nc"); final Hints hints = new Hints(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, CRS.decode("EPSG:4326", true)); hints.add(new Hints(Utils.EXCLUDE_MOSAIC, true)); // Get format final AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder.findFormat(file.toURI().toURL(), hints); final NetCDFReader reader = (NetCDFReader) format.getReader(file.toURI().toURL(), hints); assertNotNull(format); try { String[] names = reader.getGridCoverageNames(); names = new String[] {names[1]}; for (String coverageName : names) { final String[] metadataNames = reader.getMetadataNames(coverageName); assertNotNull(metadataNames); assertEquals(17, metadataNames.length); // Parsing metadata values assertEquals("false", reader.getMetadataValue(coverageName, "HAS_TIME_DOMAIN")); assertEquals("false", reader.getMetadataValue(coverageName, "HAS_ELEVATION_DOMAIN")); assertEquals("true", reader.getMetadataValue(coverageName, "HAS_NUMSIGMA_DOMAIN")); final String sigmaMetadata = reader.getMetadataValue(coverageName, "NUMSIGMA_DOMAIN"); assertNotNull(sigmaMetadata); assertEquals("0,1,2", sigmaMetadata); assertEquals(3, sigmaMetadata.split(",").length); // subsetting the envelope final ParameterValue<GridGeometry2D> gg = AbstractGridFormat.READ_GRIDGEOMETRY2D.createValue(); final GeneralEnvelope originalEnvelope = reader.getOriginalEnvelope(coverageName); final GeneralEnvelope reducedEnvelope = new GeneralEnvelope( new double[] { originalEnvelope.getLowerCorner().getOrdinate(0), originalEnvelope.getLowerCorner().getOrdinate(1) }, new double[] { originalEnvelope.getMedian().getOrdinate(0), originalEnvelope.getMedian().getOrdinate(1) }); reducedEnvelope.setCoordinateReferenceSystem( reader.getCoordinateReferenceSystem(coverageName)); // Selecting bigger gridRange for a zoomed result final Dimension dim = new Dimension(); GridEnvelope gridRange = reader.getOriginalGridRange(coverageName); dim.setSize(gridRange.getSpan(0) * 4.0, gridRange.getSpan(1) * 2.0); final Rectangle rasterArea = ((GridEnvelope2D) gridRange); rasterArea.setSize(dim); final GridEnvelope2D range = new GridEnvelope2D(rasterArea); gg.setValue(new GridGeometry2D(range, reducedEnvelope)); ParameterValue<List<String>> sigmaValue = null; final String selectedSigma = "1"; Set<ParameterDescriptor<List>> params = reader.getDynamicParameters(coverageName); for (ParameterDescriptor param : params) { if (param.getName().getCode().equalsIgnoreCase("NUMSIGMA")) { sigmaValue = param.createValue(); sigmaValue.setValue( new ArrayList<String>() { { add(selectedSigma); } }); } } GeneralParameterValue[] values = new GeneralParameterValue[] {gg, sigmaValue}; GridCoverage2D coverage = reader.read(coverageName, values); assertNotNull(coverage); if (TestData.isInteractiveTest()) { coverage.show(); } else { PlanarImage.wrapRenderedImage(coverage.getRenderedImage()).getTiles(); } } } catch (Throwable t) { throw new RuntimeException(t); } finally { if (reader != null) { try { reader.dispose(); } catch (Throwable t) { // Does nothing } } } }
@Test public void NetCDFTestOn4DcoveragesWithImposedSchemas() throws NoSuchAuthorityCodeException, FactoryException, IOException, ParseException { File mosaic = new File(TestData.file(this, "."), "NetCDFTestOn4DcoveragesWithImposedSchemas"); if (mosaic.exists()) { FileUtils.deleteDirectory(mosaic); } assertTrue(mosaic.mkdirs()); File file = TestData.file(this, "O3NO2-noZ.nc"); File auxFile = TestData.file(this, "O3NO2-noZ.xml"); FileUtils.copyFileToDirectory(file, mosaic); FileUtils.copyFileToDirectory(auxFile, mosaic); file = new File(mosaic, "O3NO2-noZ.nc"); final Hints hints = new Hints(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, CRS.decode("EPSG:4326", true)); hints.put( Utils.AUXILIARY_FILES_PATH, new File(mosaic, "O3NO2-noZ.xml").getAbsolutePath()); // impose def // Get format final AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder.findFormat(file.toURI().toURL(), hints); final NetCDFReader reader = (NetCDFReader) format.getReader(file.toURI().toURL(), hints); assertNotNull(format); try { String[] names = reader.getGridCoverageNames(); for (String coverageName : names) { final String[] metadataNames = reader.getMetadataNames(coverageName); assertNotNull(metadataNames); assertEquals(metadataNames.length, 12); // Parsing metadata values assertEquals("true", reader.getMetadataValue(coverageName, "HAS_TIME_DOMAIN")); final String timeMetadata = reader.getMetadataValue(coverageName, "TIME_DOMAIN"); assertEquals( "2012-04-01T00:00:00.000Z/2012-04-01T00:00:00.000Z,2012-04-01T01:00:00.000Z/2012-04-01T01:00:00.000Z", timeMetadata); assertNotNull(timeMetadata); assertEquals( "2012-04-01T00:00:00.000Z", reader.getMetadataValue(coverageName, "TIME_DOMAIN_MINIMUM")); assertEquals( "2012-04-01T01:00:00.000Z", reader.getMetadataValue(coverageName, "TIME_DOMAIN_MAXIMUM")); if (coverageName.equalsIgnoreCase("O3")) { assertEquals("true", reader.getMetadataValue(coverageName, "HAS_ELEVATION_DOMAIN")); final String elevationMetadata = reader.getMetadataValue(coverageName, "ELEVATION_DOMAIN"); assertNotNull(elevationMetadata); assertEquals("10.0/10.0,450.0/450.0", elevationMetadata); assertEquals(2, elevationMetadata.split(",").length); assertEquals("10.0", reader.getMetadataValue(coverageName, "ELEVATION_DOMAIN_MINIMUM")); assertEquals("450.0", reader.getMetadataValue(coverageName, "ELEVATION_DOMAIN_MAXIMUM")); } else { // Note that This sample doesn't have elevation for NO2 assertEquals("false", reader.getMetadataValue(coverageName, "HAS_ELEVATION_DOMAIN")); final String elevationMetadata = reader.getMetadataValue(coverageName, "ELEVATION_DOMAIN"); assertNull(elevationMetadata); } // subsetting the envelope final ParameterValue<GridGeometry2D> gg = AbstractGridFormat.READ_GRIDGEOMETRY2D.createValue(); final GeneralEnvelope originalEnvelope = reader.getOriginalEnvelope(coverageName); final GeneralEnvelope reducedEnvelope = new GeneralEnvelope( new double[] { originalEnvelope.getLowerCorner().getOrdinate(0), originalEnvelope.getLowerCorner().getOrdinate(1) }, new double[] { originalEnvelope.getMedian().getOrdinate(0), originalEnvelope.getMedian().getOrdinate(1) }); reducedEnvelope.setCoordinateReferenceSystem( reader.getCoordinateReferenceSystem(coverageName)); // Selecting bigger gridRange for a zoomed result final Dimension dim = new Dimension(); GridEnvelope gridRange = reader.getOriginalGridRange(coverageName); dim.setSize(gridRange.getSpan(0) * 4.0, gridRange.getSpan(1) * 2.0); final Rectangle rasterArea = ((GridEnvelope2D) gridRange); rasterArea.setSize(dim); final GridEnvelope2D range = new GridEnvelope2D(rasterArea); gg.setValue(new GridGeometry2D(range, reducedEnvelope)); final ParameterValue<List> time = ImageMosaicFormat.TIME.createValue(); final SimpleDateFormat formatD = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); formatD.setTimeZone(TimeZone.getTimeZone("GMT")); final Date timeD = formatD.parse("2012-04-01T00:00:00.000Z"); time.setValue( new ArrayList() { { add(timeD); } }); final ParameterValue<List> elevation = ImageMosaicFormat.ELEVATION.createValue(); elevation.setValue( new ArrayList() { { add(450d); // Elevation } }); GeneralParameterValue[] values = coverageName.equalsIgnoreCase("O3") ? new GeneralParameterValue[] {gg, time, elevation} : new GeneralParameterValue[] {gg, time}; GridCoverage2D coverage = reader.read(coverageName, values); assertNotNull(coverage); if (TestData.isInteractiveTest()) { coverage.show(); } else { PlanarImage.wrapRenderedImage(coverage.getRenderedImage()).getTiles(); } } } catch (Throwable t) { throw new RuntimeException(t); } finally { if (reader != null) { try { reader.dispose(); } catch (Throwable t) { // Does nothing } } } }
@Test public void NetCDFTestOnFilter() throws NoSuchAuthorityCodeException, FactoryException, IOException, ParseException { File mosaic = new File(TestData.file(this, "."), "NetCDFTestOnFilter"); if (mosaic.exists()) { FileUtils.deleteDirectory(mosaic); } assertTrue(mosaic.mkdirs()); File file = TestData.file(this, "O3-NO2.nc"); FileUtils.copyFileToDirectory(file, mosaic); file = new File(mosaic, "O3-NO2.nc"); final Hints hints = new Hints(Hints.DEFAULT_COORDINATE_REFERENCE_SYSTEM, CRS.decode("EPSG:4326", true)); // Get format final AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder.findFormat(file.toURI().toURL(), hints); final NetCDFReader reader = (NetCDFReader) format.getReader(file.toURI().toURL(), hints); assertNotNull(format); try { String[] names = reader.getGridCoverageNames(); names = new String[] {names[1]}; for (String coverageName : names) { final String[] metadataNames = reader.getMetadataNames(coverageName); assertNotNull(metadataNames); assertEquals(12, metadataNames.length); // Parsing metadata values assertEquals("true", reader.getMetadataValue(coverageName, "HAS_TIME_DOMAIN")); final String timeMetadata = reader.getMetadataValue(coverageName, "TIME_DOMAIN"); assertEquals( "2012-04-01T00:00:00.000Z/2012-04-01T00:00:00.000Z,2012-04-01T01:00:00.000Z/2012-04-01T01:00:00.000Z", timeMetadata); assertNotNull(timeMetadata); assertEquals( "2012-04-01T00:00:00.000Z", reader.getMetadataValue(coverageName, "TIME_DOMAIN_MINIMUM")); assertEquals( "2012-04-01T01:00:00.000Z", reader.getMetadataValue(coverageName, "TIME_DOMAIN_MAXIMUM")); assertEquals("true", reader.getMetadataValue(coverageName, "HAS_ELEVATION_DOMAIN")); final String elevationMetadata = reader.getMetadataValue(coverageName, "ELEVATION_DOMAIN"); assertNotNull(elevationMetadata); assertEquals("10.0/10.0,450.0/450.0", elevationMetadata); assertEquals(2, elevationMetadata.split(",").length); assertEquals("10.0", reader.getMetadataValue(coverageName, "ELEVATION_DOMAIN_MINIMUM")); assertEquals("450.0", reader.getMetadataValue(coverageName, "ELEVATION_DOMAIN_MAXIMUM")); // subsetting the envelope final ParameterValue<GridGeometry2D> gg = AbstractGridFormat.READ_GRIDGEOMETRY2D.createValue(); final GeneralEnvelope originalEnvelope = reader.getOriginalEnvelope(coverageName); final GeneralEnvelope reducedEnvelope = new GeneralEnvelope( new double[] { originalEnvelope.getLowerCorner().getOrdinate(0), originalEnvelope.getLowerCorner().getOrdinate(1) }, new double[] { originalEnvelope.getMedian().getOrdinate(0), originalEnvelope.getMedian().getOrdinate(1) }); reducedEnvelope.setCoordinateReferenceSystem( reader.getCoordinateReferenceSystem(coverageName)); // Selecting bigger gridRange for a zoomed result final Dimension dim = new Dimension(); GridEnvelope gridRange = reader.getOriginalGridRange(coverageName); dim.setSize(gridRange.getSpan(0) * 4.0, gridRange.getSpan(1) * 2.0); final Rectangle rasterArea = ((GridEnvelope2D) gridRange); rasterArea.setSize(dim); final GridEnvelope2D range = new GridEnvelope2D(rasterArea); gg.setValue(new GridGeometry2D(range, reducedEnvelope)); final ParameterValue<Filter> filterParam = NetCDFFormat.FILTER.createValue(); FilterFactory2 FF = FeatureUtilities.DEFAULT_FILTER_FACTORY; Filter filter = FF.equals(FF.property("z"), FF.literal(450.0)); filterParam.setValue(filter); GeneralParameterValue[] values = new GeneralParameterValue[] {filterParam}; GridCoverage2D coverage = reader.read(coverageName, values); assertNotNull(coverage); if (TestData.isInteractiveTest()) { coverage.show(); } else { PlanarImage.wrapRenderedImage(coverage.getRenderedImage()).getTiles(); } } } catch (Throwable t) { throw new RuntimeException(t); } finally { if (reader != null) { try { reader.dispose(); } catch (Throwable t) { // Does nothing } } } }
@Test public void testInsetsMargin() throws Exception { // copy the footprints mosaic over FileUtils.copyDirectory(footprintsSource, testMosaic); Properties p = new Properties(); p.put(MultiLevelROIProviderFactory.INSET_PROPERTY, "0.1"); p.put(MultiLevelROIProviderFactory.INSET_TYPE_PROPERTY, "border"); saveFootprintProperties(p); GridCoverage2D coverage = readCoverage(); // RenderedImageBrowser.showChain(coverage.getRenderedImage()); // System.in.read(); // // check the footprints have been applied by pocking the output image byte[] pixel = new byte[3]; // Close to San Marino, black if we have the insets coverage.evaluate(new DirectPosition2D(12.54, 44.03), pixel); assertEquals(0, pixel[0]); assertEquals(0, pixel[1]); assertEquals(0, pixel[2]); // Inner BORDER should not get black with border insets coverage.evaluate(new DirectPosition2D(11.52, 44.57), pixel); assertTrue(pixel[0] + pixel[1] + pixel[2] > 0); // Golfo di La Spezia, should be black coverage.evaluate(new DirectPosition2D(9.12, 44.25), pixel); assertEquals(0, pixel[0]); assertEquals(0, pixel[1]); assertEquals(0, pixel[2]); // Sardinia, not black coverage.evaluate(new DirectPosition2D(9, 40), pixel); assertTrue(pixel[0] + pixel[1] + pixel[2] > 0); // Piedmont, not black coverage.evaluate(new DirectPosition2D(8, 45), pixel); assertTrue(pixel[0] + pixel[1] + pixel[2] > 0); disposeCoverage(coverage); final ImageMosaicReader reader = TestUtils.getReader(testMosaicUrl, new ImageMosaicFormat()); // activate footprint management GeneralParameterValue[] params = new GeneralParameterValue[3]; ParameterValue<String> footprintManagement = ImageMosaicFormat.FOOTPRINT_BEHAVIOR.createValue(); footprintManagement.setValue(FootprintBehavior.Transparent.name()); params[0] = footprintManagement; // this prevents us from having problems with link to files still open. ParameterValue<Boolean> jaiImageRead = ImageMosaicFormat.USE_JAI_IMAGEREAD.createValue(); jaiImageRead.setValue(false); params[1] = jaiImageRead; // GridGeometry, small aread at the upper right corner final GridEnvelope2D ge2D = new GridEnvelope2D( reader.getOriginalGridRange().getHigh(0) - 3, reader.getOriginalGridRange().getLow(1), 3, 3); final GridGeometry2D gg2D = new GridGeometry2D( ge2D, reader.getOriginalGridToWorld(PixelInCell.CELL_CENTER), reader.getCoordinateReferenceSystem()); ParameterValue<GridGeometry2D> gg2DParam = ImageMosaicFormat.READ_GRIDGEOMETRY2D.createValue(); gg2DParam.setValue(gg2D); params[2] = gg2DParam; coverage = reader.read(params); MathTransform tr = reader.getOriginalGridToWorld(PixelInCell.CELL_CORNER); reader.dispose(); assertNotNull(coverage); // check the footprints have been applied by pocking the output image pixel = new byte[4]; // Close to San Marino, black if we have the insets coverage.evaluate( tr.transform( new DirectPosition2D( coverage.getRenderedImage().getMinX(), coverage.getRenderedImage().getMinY()), null), pixel); // RenderedImageBrowser.showChain(coverage.getRenderedImage()); assertEquals(0, pixel[0]); assertEquals(0, pixel[1]); assertEquals(0, pixel[2]); assertEquals(0, pixel[3]); disposeCoverage(coverage); }
private ArcSDEGridCoverage2DReaderJAI.ReadParameters parseReadParams( final GeneralParameterValue[] params) throws IllegalArgumentException { if (params == null) { throw new IllegalArgumentException("No GeneralParameterValue given to read operation"); } GeneralEnvelope reqEnvelope = null; GridEnvelope dim = null; OverviewPolicy overviewPolicy = null; // ///////////////////////////////////////////////////////////////////// // // Checking params // // ///////////////////////////////////////////////////////////////////// for (int i = 0; i < params.length; i++) { final ParameterValue<?> param = (ParameterValue<?>) params[i]; final String name = param.getDescriptor().getName().getCode(); if (name.equals(AbstractGridFormat.READ_GRIDGEOMETRY2D.getName().toString())) { final GridGeometry2D gg = (GridGeometry2D) param.getValue(); reqEnvelope = new GeneralEnvelope((Envelope) gg.getEnvelope2D()); final GeneralEnvelope coverageEnvelope = getOriginalEnvelope(); CoordinateReferenceSystem nativeCrs = coverageEnvelope.getCoordinateReferenceSystem(); CoordinateReferenceSystem requestCrs = reqEnvelope.getCoordinateReferenceSystem(); if (!CRS.equalsIgnoreMetadata(nativeCrs, requestCrs)) { LOGGER.fine( "Request CRS and native CRS differ, " + "reprojecting request envelope to native CRS"); ReferencedEnvelope nativeCrsEnv; nativeCrsEnv = toNativeCrs(reqEnvelope, nativeCrs); reqEnvelope = new GeneralEnvelope(nativeCrsEnv); } dim = gg.getGridRange2D(); continue; } if (name.equals(AbstractGridFormat.OVERVIEW_POLICY.getName().toString())) { overviewPolicy = (OverviewPolicy) param.getValue(); continue; } } if (reqEnvelope == null && dim == null) { reqEnvelope = getOriginalEnvelope(); dim = getOriginalGridRange(); } if (reqEnvelope == null) { reqEnvelope = getOriginalEnvelope(); } if (dim == null) { final GeneralEnvelope adjustedGRange; try { MathTransform gridToWorld = getOriginalGridToWorld(PixelInCell.CELL_CENTER); MathTransform worldToGrid = gridToWorld.inverse(); adjustedGRange = CRS.transform(worldToGrid, reqEnvelope); } catch (Exception e) { throw new RuntimeException(e); } int xmin = (int) Math.floor(adjustedGRange.getMinimum(0)); int ymin = (int) Math.floor(adjustedGRange.getMinimum(1)); int xmax = (int) Math.ceil(adjustedGRange.getMaximum(0)); int ymax = (int) Math.ceil(adjustedGRange.getMaximum(1)); dim = new GridEnvelope2D(xmin, ymin, xmax - xmin, ymax - ymin); } if (!reqEnvelope.intersects(getOriginalEnvelope(), true)) { throw new IllegalArgumentException( "The requested extend does not overlap the coverage extent: " + getOriginalEnvelope()); } if (dim.getSpan(0) <= 0 || dim.getSpan(1) <= 0) { throw new IllegalArgumentException("The requested coverage dimension can't be null: " + dim); } if (overviewPolicy == null) { overviewPolicy = OverviewPolicy.NEAREST; LOGGER.finer("No overview policy requested, defaulting to " + overviewPolicy); } LOGGER.fine("Overview policy is " + overviewPolicy); ArcSDEGridCoverage2DReaderJAI.ReadParameters parsedParams = new ArcSDEGridCoverage2DReaderJAI.ReadParameters(); parsedParams.requestedEnvelope = reqEnvelope; parsedParams.dim = dim; parsedParams.overviewPolicy = overviewPolicy; return parsedParams; }
public ProjectionHandler getHandler( ReferencedEnvelope renderingEnvelope, CoordinateReferenceSystem sourceCrs, boolean wrap, int maxWraps) throws FactoryException { MapProjection mapProjection = CRS.getMapProjection(renderingEnvelope.getCoordinateReferenceSystem()); if (renderingEnvelope != null && mapProjection instanceof PolarStereographic) { boolean north; // variant B uses standard_parallel ParameterValue<?> stdParallel = null; try { stdParallel = mapProjection .getParameterValues() .parameter(AbstractProvider.STANDARD_PARALLEL_1.getName().getCode()); } catch (ParameterNotFoundException e) { // ignore } if (stdParallel != null) { north = stdParallel.doubleValue() > 0; } else { // variant A uses latitude of origin ParameterValue<?> latOrigin = null; try { latOrigin = mapProjection .getParameterValues() .parameter(AbstractProvider.LATITUDE_OF_ORIGIN.getName().getCode()); } catch (ParameterNotFoundException e) { // ignore } if (latOrigin != null) { north = latOrigin.doubleValue() > 0; } else { return null; } } ReferencedEnvelope validArea; if (north) { validArea = new ReferencedEnvelope( -Double.MAX_VALUE, Double.MAX_VALUE, -0, 90, DefaultGeographicCRS.WGS84); } else { validArea = new ReferencedEnvelope( -Double.MAX_VALUE, Double.MAX_VALUE, -90, 0, DefaultGeographicCRS.WGS84); } return new ProjectionHandler(sourceCrs, validArea, renderingEnvelope) { @Override public List<ReferencedEnvelope> getQueryEnvelopes() throws TransformException, FactoryException { // check if we are crossing the antimeridian and are fully below the pole, // in this case we'd end up reading the full globe when we'd have to just // read two portions near the dateline if (renderingEnvelope.getMaxY() < 0 && renderingEnvelope.getMinX() < 0 && renderingEnvelope.getMaxX() > 0) { ReferencedEnvelope e1 = new ReferencedEnvelope( renderingEnvelope.getMinX(), -1e-6, renderingEnvelope.getMinY(), renderingEnvelope.getMaxY(), renderingEnvelope.getCoordinateReferenceSystem()); ReferencedEnvelope e2 = new ReferencedEnvelope( 1e-6, renderingEnvelope.getMaxX(), renderingEnvelope.getMinY(), renderingEnvelope.getMaxY(), renderingEnvelope.getCoordinateReferenceSystem()); List<ReferencedEnvelope> envelopes = new ArrayList<ReferencedEnvelope>(); envelopes.add(e1); envelopes.add(e2); reprojectEnvelopes(sourceCRS, envelopes); return envelopes; } else { return super.getQueryEnvelopes(); } } }; } return null; }
/** * Returns the read parameters for the specified layer, merging some well known request parameters * into the read parameters if possible * * @param request * @param mapLayerInfo * @param layerFilter * @param reader * @return */ public GeneralParameterValue[] getWMSReadParameters( final GetMapRequest request, final MapLayerInfo mapLayerInfo, final Filter layerFilter, final List<Object> times, final List<Object> elevations, final GridCoverage2DReader reader, boolean readGeom) throws IOException { // setup the scene final ParameterValueGroup readParametersDescriptor = reader.getFormat().getReadParameters(); CoverageInfo coverage = mapLayerInfo.getCoverage(); MetadataMap metadata = coverage.getMetadata(); GeneralParameterValue[] readParameters = CoverageUtils.getParameters(readParametersDescriptor, coverage.getParameters(), readGeom); ReaderDimensionsAccessor dimensions = new ReaderDimensionsAccessor(reader); // pass down time final DimensionInfo timeInfo = metadata.get(ResourceInfo.TIME, DimensionInfo.class); // add the descriptors for custom dimensions final List<GeneralParameterDescriptor> parameterDescriptors = new ArrayList<GeneralParameterDescriptor>( readParametersDescriptor.getDescriptor().descriptors()); Set<ParameterDescriptor<List>> dynamicParameters = reader.getDynamicParameters(); parameterDescriptors.addAll(dynamicParameters); if (timeInfo != null && timeInfo.isEnabled()) { // handle "default" List<Object> fixedTimes = new ArrayList<Object>(times); for (int i = 0; i < fixedTimes.size(); i++) { if (fixedTimes.get(i) == null) { fixedTimes.set(i, getDefaultTime(coverage)); } } // pass down the parameters readParameters = CoverageUtils.mergeParameter( parameterDescriptors, readParameters, fixedTimes, "TIME", "Time"); } // pass down elevation final DimensionInfo elevationInfo = metadata.get(ResourceInfo.ELEVATION, DimensionInfo.class); if (elevationInfo != null && elevationInfo.isEnabled()) { // handle "default" List<Object> fixedElevations = new ArrayList<Object>(elevations); for (int i = 0; i < fixedElevations.size(); i++) { if (fixedElevations.get(i) == null) { fixedElevations.set(i, getDefaultElevation(coverage)); } } readParameters = CoverageUtils.mergeParameter( parameterDescriptors, readParameters, fixedElevations, "ELEVATION", "Elevation"); } if (layerFilter != null && readParameters != null) { // test for default [empty is replaced with INCLUDE filter] ]filter for (int i = 0; i < readParameters.length; i++) { GeneralParameterValue param = readParameters[i]; GeneralParameterDescriptor pd = param.getDescriptor(); if (pd.getName().getCode().equalsIgnoreCase("FILTER")) { final ParameterValue pv = (ParameterValue) pd.createValue(); // if something different from the default INCLUDE filter is specified if (layerFilter != Filter.INCLUDE) { // override the default filter pv.setValue(layerFilter); readParameters[i] = pv; } break; } } } // custom dimensions List<String> customDomains = new ArrayList(dimensions.getCustomDomains()); for (String domain : new ArrayList<String>(customDomains)) { List<String> values = request.getCustomDimension(domain); if (values != null) { readParameters = CoverageUtils.mergeParameter(parameterDescriptors, readParameters, values, domain); customDomains.remove(domain); } } // see if we have any custom domain for which we have to set the default value if (!customDomains.isEmpty()) { for (String name : customDomains) { final DimensionInfo customInfo = metadata.get(ResourceInfo.CUSTOM_DIMENSION_PREFIX + name, DimensionInfo.class); if (customInfo != null && customInfo.isEnabled()) { final ArrayList<String> val = new ArrayList<String>(1); val.add(getDefaultCustomDimensionValue(name, coverage, String.class)); readParameters = CoverageUtils.mergeParameter(parameterDescriptors, readParameters, val, name); } } } return readParameters; }