Exemplo n.º 1
0
  @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
        }
      }
    }
  }
  @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);
  }
Exemplo n.º 3
0
  @Test
  public void testCrs84wms13() throws Exception {
    // prepare the responses
    MockHttpClient client =
        new MockHttpClient() {

          public HTTPResponse get(URL url) throws IOException {
            if (url.getQuery().contains("GetCapabilities")) {
              URL caps130 = WMSCoverageReaderTest.class.getResource("caps130_crs84.xml");
              return new MockHttpResponse(caps130, "text/xml");
            } else if (url.getQuery().contains("GetMap") && url.getQuery().contains("world84")) {
              Map<String, String> params = parseParams(url.getQuery());
              assertEquals("1.3.0", params.get("VERSION"));
              assertEquals("CRS:84", params.get("CRS"));
              assertEquals("-180.0,-90.0,180.0,90.0", params.get("BBOX"));
              URL world = WMSCoverageReaderTest.class.getResource("world.png");
              return new MockHttpResponse(world, "image/png");
            } else {
              throw new IllegalArgumentException(
                  "Don't know how to handle a get request over " + url.toExternalForm());
            }
          }
        };
    WebMapServer server = new WebMapServer(new URL("http://geoserver.org/geoserver/wms"), client);
    WMSCoverageReader reader = new WMSCoverageReader(server, getLayer(server, "world84"));

    // setup the request and check it
    CoordinateReferenceSystem wgs84 = CRS.decode("EPSG:4326", true);
    ReferencedEnvelope worldEnvelope = new ReferencedEnvelope(-180, 180, -90, 90, wgs84);
    GridGeometry2D gg = new GridGeometry2D(new GridEnvelope2D(0, 0, 180, 90), worldEnvelope);
    final Parameter<GridGeometry2D> ggParam =
        (Parameter<GridGeometry2D>) AbstractGridFormat.READ_GRIDGEOMETRY2D.createValue();
    ggParam.setValue(gg);

    GridCoverage2D coverage = reader.read(new GeneralParameterValue[] {ggParam});
    assertTrue(CRS.equalsIgnoreMetadata(wgs84, coverage.getCoordinateReferenceSystem()));
    assertEquals(worldEnvelope, new ReferencedEnvelope(coverage.getEnvelope()));
  }
Exemplo n.º 4
0
  /**
   * 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");
  }
  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;
  }
Exemplo n.º 7
0
  @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
        }
      }
    }
  }
Exemplo n.º 8
0
  @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
        }
      }
    }
  }
Exemplo n.º 9
0
  @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
        }
      }
    }
  }
Exemplo n.º 10
0
  @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
        }
      }
    }
  }