public int countImagesInSector(Sector sector, int levelNumber) {
    if (sector == null) {
      String msg = Logging.getMessage("nullValue.SectorIsNull");
      Logging.logger().severe(msg);
      throw new IllegalArgumentException(msg);
    }

    Level targetLevel = this.levels.getLastLevel();
    if (levelNumber >= 0) {
      for (int i = levelNumber; i < this.getLevels().getLastLevel().getLevelNumber(); i++) {
        if (this.levels.isLevelEmpty(i)) continue;

        targetLevel = this.levels.getLevel(i);
        break;
      }
    }

    // Collect all the tiles intersecting the input sector.
    LatLon delta = targetLevel.getTileDelta();
    Angle latOrigin = this.levels.getTileOrigin().getLatitude();
    Angle lonOrigin = this.levels.getTileOrigin().getLongitude();
    final int nwRow = Tile.computeRow(delta.getLatitude(), sector.getMaxLatitude(), latOrigin);
    final int nwCol = Tile.computeColumn(delta.getLongitude(), sector.getMinLongitude(), lonOrigin);
    final int seRow = Tile.computeRow(delta.getLatitude(), sector.getMinLatitude(), latOrigin);
    final int seCol = Tile.computeColumn(delta.getLongitude(), sector.getMaxLongitude(), lonOrigin);

    int numRows = nwRow - seRow + 1;
    int numCols = seCol - nwCol + 1;

    return numRows * numCols;
  }
  protected BufferedImage getImage(Object imageSource) {
    if (imageSource instanceof String) {
      String path = (String) imageSource;

      Object streamOrException = WWIO.getFileOrResourceAsStream(path, this.getClass());
      if (streamOrException == null || streamOrException instanceof Exception) {
        Logging.logger()
            .log(
                java.util.logging.Level.SEVERE,
                "generic.ExceptionAttemptingToReadImageFile",
                streamOrException != null ? streamOrException : path);
        return null;
      }

      try {
        return ImageIO.read((InputStream) streamOrException);
      } catch (Exception e) {
        Logging.logger()
            .log(
                java.util.logging.Level.SEVERE, "generic.ExceptionAttemptingToReadImageFile", path);
        return null;
      }
    } else if (imageSource instanceof BufferedImage) {
      return (BufferedImage) imageSource;
    }

    return null;
  }
  public GeotiffWriter(File file) throws IOException {
    if (null == file) {
      String msg = Logging.getMessage("nullValue.FileIsNull");
      Logging.logger().severe(msg);
      throw new IllegalArgumentException(msg);
    }

    commonInitializer(file);
  }
  public GeotiffWriter(String filename) throws IOException {
    if (null == filename || 0 == filename.trim().length()) {
      String msg = Logging.getMessage("generic.FileNameIsMissing");
      Logging.logger().severe(msg);
      throw new IllegalArgumentException(msg);
    }

    // the initializer does the validity checking...
    commonInitializer(new File(filename));
  }
  private void commonInitializer(File file) throws IOException {
    File parent = file.getParentFile();
    if (parent == null) parent = new File(System.getProperty("user.dir"));
    if (!parent.canWrite()) {
      String msg = Logging.getMessage("generic.FolderNoWritePermission", parent.getAbsolutePath());
      Logging.logger().severe(msg);
      throw new IllegalArgumentException(msg);
    }

    this.targetFile = new RandomAccessFile(file, "rw");
    this.theChannel = this.targetFile.getChannel();
  }
  protected static AVList wmsGetParamsFromCapsDoc(Capabilities caps, AVList params) {
    if (caps == null) {
      String message = Logging.getMessage("nullValue.WMSCapabilities");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    if (params == null) {
      String message = Logging.getMessage("nullValue.LayerConfigParams");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    try {
      DataConfigurationUtils.getWMSLayerParams(caps, formatOrderPreference, params);
    } catch (IllegalArgumentException e) {
      String message = Logging.getMessage("WMS.MissingLayerParameters");
      Logging.logger().log(java.util.logging.Level.SEVERE, message, e);
      throw new IllegalArgumentException(message, e);
    } catch (WWRuntimeException e) {
      String message = Logging.getMessage("WMS.MissingCapabilityValues");
      Logging.logger().log(java.util.logging.Level.SEVERE, message, e);
      throw new IllegalArgumentException(message, e);
    }

    setFallbacks(params);

    // Setup WMS URL builder.
    params.setValue(AVKey.WMS_VERSION, caps.getVersion());
    params.setValue(AVKey.TILE_URL_BUILDER, new URLBuilder(params));
    // Setup default WMS tiled image layer behaviors.
    params.setValue(AVKey.USE_TRANSPARENT_TEXTURES, true);

    return params;
  }
Exemplo n.º 7
0
  public void drawOnTo(DataRaster canvas) {
    if (canvas == null) {
      String message = Logging.getMessage("nullValue.DestinationIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }
    if (!(canvas instanceof BufferedImageRaster)) {
      String message = Logging.getMessage("DataRaster.IncompatibleRaster", canvas);
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    this.doDrawOnTo((BufferedImageRaster) canvas);
  }
  public WMSTiledImageLayer(String stateInXml) {
    this(wmsRestorableStateToParams(stateInXml));

    RestorableSupport rs;
    try {
      rs = RestorableSupport.parse(stateInXml);
    } catch (Exception e) {
      // Parsing the document specified by stateInXml failed.
      String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml);
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message, e);
    }

    this.doRestoreState(rs, null);
  }
Exemplo n.º 9
0
  public BufferedImageRaster(
      Sector sector, java.awt.image.BufferedImage bufferedImage, AVList list) {
    super(
        (null != bufferedImage) ? bufferedImage.getWidth() : 0,
        (null != bufferedImage) ? bufferedImage.getHeight() : 0,
        sector,
        list);

    if (bufferedImage == null) {
      String message = Logging.getMessage("nullValue.ImageIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    this.bufferedImage = bufferedImage;
  }
  public MercatorTiledImageLayer(LevelSet levelSet) {
    if (levelSet == null) {
      String message = Logging.getMessage("nullValue.LevelSetIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    this.levels =
        new LevelSet(levelSet); // the caller's levelSet may change internally, so we copy it.

    this.createTopLevelTiles();

    this.setPickEnabled(
        false); // textures are assumed to be terrain unless specifically indicated otherwise.
    this.tileCountName = this.getName() + " Tiles";
  }
  protected static AVList wmsGetParamsFromDocument(Element domElement, AVList params) {
    if (domElement == null) {
      String message = Logging.getMessage("nullValue.DocumentIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    if (params == null) params = new AVListImpl();

    LayerConfiguration.getWMSTiledImageLayerParams(domElement, params);
    BasicTiledImageLayer.getParamsFromDocument(domElement, params);

    params.setValue(AVKey.TILE_URL_BUILDER, new URLBuilder(params));

    return params;
  }
Exemplo n.º 12
0
  public BufferedImageRaster(int width, int height, int transparency, Sector sector) {
    super(width, height, sector);

    if (width < 1) {
      String message = Logging.getMessage("generic.InvalidWidth", width);
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }
    if (height < 1) {
      String message = Logging.getMessage("generic.InvalidHeight", height);
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    this.bufferedImage = ImageUtil.createCompatibleImage(width, height, transparency);
  }
  public boolean isLayerInView(DrawContext dc) {
    if (dc == null) {
      String message = Logging.getMessage("nullValue.DrawContextIsNull");
      Logging.logger().severe(message);
      throw new IllegalStateException(message);
    }

    if (dc.getView() == null) {
      String message = Logging.getMessage("layers.AbstractLayer.NoViewSpecifiedInDrawingContext");
      Logging.logger().severe(message);
      throw new IllegalStateException(message);
    }

    return !(dc.getVisibleSector() != null
        && !this.levels.getSector().intersects(dc.getVisibleSector()));
  }
  @Override
  public BufferedImage composeImageForSector(
      Sector sector,
      int canvasWidth,
      int canvasHeight,
      double aspectRatio,
      int levelNumber,
      String mimeType,
      boolean abortOnError,
      BufferedImage image,
      int timeout)
      throws Exception {
    if (sector == null) {
      String message = Logging.getMessage("nullValue.SectorIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    ComposeImageTile tile =
        new ComposeImageTile(
            sector, mimeType, this.getLevels().getLastLevel(), canvasWidth, canvasHeight);
    try {
      if (image == null)
        image = new BufferedImage(canvasWidth, canvasHeight, BufferedImage.TYPE_INT_RGB);

      downloadImage(tile, mimeType, timeout);
      Thread.sleep(1); // generates InterruptedException if thread has been interupted

      BufferedImage tileImage = ImageIO.read(tile.getFile());
      Thread.sleep(1); // generates InterruptedException if thread has been interupted

      ImageUtil.mergeImage(sector, tile.getSector(), aspectRatio, tileImage, image);
      Thread.sleep(1); // generates InterruptedException if thread has been interupted

      this.firePropertyChange(AVKey.PROGRESS, 0d, 1d);
    } catch (InterruptedIOException e) {
      throw e;
    } catch (Exception e) {
      if (abortOnError) throw e;

      String message = Logging.getMessage("generic.ExceptionWhileRequestingImage", tile.getPath());
      Logging.logger().log(java.util.logging.Level.WARNING, message, e);
    }

    return image;
  }
  private MercatorTextureTile[][] getTilesInSector(Sector sector, int levelNumber) {
    if (sector == null) {
      String msg = Logging.getMessage("nullValue.SectorIsNull");
      Logging.logger().severe(msg);
      throw new IllegalArgumentException(msg);
    }

    Level targetLevel = this.levels.getLastLevel();
    if (levelNumber >= 0) {
      for (int i = levelNumber; i < this.getLevels().getLastLevel().getLevelNumber(); i++) {
        if (this.levels.isLevelEmpty(i)) continue;

        targetLevel = this.levels.getLevel(i);
        break;
      }
    }

    // Collect all the tiles intersecting the input sector.
    LatLon delta = targetLevel.getTileDelta();
    Angle latOrigin = this.levels.getTileOrigin().getLatitude();
    Angle lonOrigin = this.levels.getTileOrigin().getLongitude();
    final int nwRow = Tile.computeRow(delta.getLatitude(), sector.getMaxLatitude(), latOrigin);
    final int nwCol = Tile.computeColumn(delta.getLongitude(), sector.getMinLongitude(), lonOrigin);
    final int seRow = Tile.computeRow(delta.getLatitude(), sector.getMinLatitude(), latOrigin);
    final int seCol = Tile.computeColumn(delta.getLongitude(), sector.getMaxLongitude(), lonOrigin);

    int numRows = nwRow - seRow + 1;
    int numCols = seCol - nwCol + 1;
    MercatorTextureTile[][] sectorTiles = new MercatorTextureTile[numRows][numCols];

    for (int row = nwRow; row >= seRow; row--) {
      for (int col = nwCol; col <= seCol; col++) {
        TileKey key =
            new TileKey(targetLevel.getLevelNumber(), row, col, targetLevel.getCacheName());
        Sector tileSector = this.levels.computeSectorForKey(key);
        MercatorSector mSector = MercatorSector.fromSector(tileSector); // TODO: check
        sectorTiles[nwRow - row][col - nwCol] =
            new MercatorTextureTile(mSector, targetLevel, row, col);
      }
    }

    return sectorTiles;
  }
Exemplo n.º 16
0
  public void fill(java.awt.Color color) {
    if (color == null) {
      String message = Logging.getMessage("nullValue.ColorIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    java.awt.Graphics2D g2d = this.getGraphics();

    // Keep track of the previous color.
    java.awt.Color prevColor = g2d.getColor();
    try {
      // Fill the raster with the specified color.
      g2d.setColor(color);
      g2d.fillRect(0, 0, this.getWidth(), this.getHeight());
    } finally {
      // Restore the previous color.
      g2d.setColor(prevColor);
    }
  }
  protected static AVList wmsRestorableStateToParams(String stateInXml) {
    if (stateInXml == null) {
      String message = Logging.getMessage("nullValue.StringIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    RestorableSupport rs;
    try {
      rs = RestorableSupport.parse(stateInXml);
    } catch (Exception e) {
      // Parsing the document specified by stateInXml failed.
      String message = Logging.getMessage("generic.ExceptionAttemptingToParseStateXml", stateInXml);
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message, e);
    }

    AVList params = new AVListImpl();
    wmsRestoreStateToParams(rs, null, params);
    return params;
  }
Exemplo n.º 18
0
  public void write(DataRaster raster) throws IOException, IllegalArgumentException {
    if (null == raster) {
      String msg = Logging.getMessage("nullValue.RasterIsNull");
      Logging.logger().finest(msg);
      throw new IllegalArgumentException(msg);
    }

    if (!(raster.getWidth() > 0)) {
      String msg = Logging.getMessage("generic.InvalidWidth", raster.getWidth());
      Logging.logger().finest(msg);
      throw new IllegalArgumentException(msg);
    }

    if (!(raster.getHeight() > 0)) {
      String msg = Logging.getMessage("generic.InvalidHeight", raster.getHeight());
      Logging.logger().finest(msg);
      throw new IllegalArgumentException(msg);
    }

    if (raster instanceof BufferedImageRaster) {
      this.write(((BufferedImageRaster) raster).getBufferedImage(), raster);
    } else if (raster instanceof BufferWrapperRaster) {
      this.writeRaster((BufferWrapperRaster) raster);
    }
  }
  public int computeLevelForResolution(Sector sector, Globe globe, double resolution) {
    if (sector == null) {
      String message = Logging.getMessage("nullValue.SectorIsNull");
      Logging.logger().severe(message);
      throw new IllegalStateException(message);
    }

    if (globe == null) {
      String message = Logging.getMessage("nullValue.GlobeIsNull");
      Logging.logger().severe(message);
      throw new IllegalStateException(message);
    }

    double texelSize = 0;
    Level targetLevel = this.levels.getLastLevel();
    for (int i = 0; i < this.getLevels().getLastLevel().getLevelNumber(); i++) {
      if (this.levels.isLevelEmpty(i)) continue;

      texelSize = this.levels.getLevel(i).getTexelSize();
      if (texelSize > resolution) continue;

      targetLevel = this.levels.getLevel(i);
      break;
    }

    Logging.logger()
        .info(
            Logging.getMessage(
                "layers.TiledImageLayer.LevelSelection", targetLevel.getLevelNumber(), texelSize));
    return targetLevel.getLevelNumber();
  }
Exemplo n.º 20
0
 private byte[] getBytes(short[] array) {
   try {
     ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
     DataOutputStream datastream = new DataOutputStream(bytestream);
     for (short n : array) {
       datastream.writeShort(n);
     }
     datastream.flush();
     return bytestream.toByteArray();
   } catch (IOException ioe) {
     Logging.logger().finest(ioe.getMessage());
   }
   return null;
 }
Exemplo n.º 21
0
  public static DataRaster wrap(BufferedImage image, AVList params) {
    if (null == image) {
      String message = Logging.getMessage("nullValue.ImageIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    if (null == params) {
      String msg = Logging.getMessage("nullValue.AVListIsNull");
      Logging.logger().finest(msg);
      throw new IllegalArgumentException(msg);
    }

    if (params.hasKey(AVKey.WIDTH)) {
      int width = (Integer) params.getValue(AVKey.WIDTH);
      if (width != image.getWidth()) {
        String msg =
            Logging.getMessage("generic.InvalidWidth", "" + width + "!=" + image.getWidth());
        Logging.logger().finest(msg);
        throw new IllegalArgumentException(msg);
      }
    } else {
      params.setValue(AVKey.WIDTH, image.getWidth());
    }

    if (params.hasKey(AVKey.HEIGHT)) {
      int height = (Integer) params.getValue(AVKey.HEIGHT);
      if (height != image.getHeight()) {
        String msg =
            Logging.getMessage("generic.InvalidHeight", "" + height + "!=" + image.getHeight());
        Logging.logger().finest(msg);
        throw new IllegalArgumentException(msg);
      }
    } else {
      params.setValue(AVKey.HEIGHT, image.getHeight());
    }

    Sector sector = null;
    if (params.hasKey(AVKey.SECTOR)) {
      Object o = params.getValue(AVKey.SECTOR);
      if (o instanceof Sector) {
        sector = (Sector) o;
      }
    }

    return new BufferedImageRaster(sector, image, params);
  }
  private BufferedImage requestImage(MercatorTextureTile tile, String mimeType)
      throws URISyntaxException {
    String pathBase = tile.getPath().substring(0, tile.getPath().lastIndexOf("."));
    String suffix = WWIO.makeSuffixForMimeType(mimeType);
    String path = pathBase + suffix;
    URL url = WorldWind.getDataFileStore().findFile(path, false);

    if (url == null) // image is not local
    return null;

    if (WWIO.isFileOutOfDate(url, tile.getLevel().getExpiryTime())) {
      // The file has expired. Delete it.
      WorldWind.getDataFileStore().removeFile(url);
      String message = Logging.getMessage("generic.DataFileExpired", url);
      Logging.logger().fine(message);
    } else {
      try {
        File imageFile = new File(url.toURI());
        BufferedImage image = ImageIO.read(imageFile);
        if (image == null) {
          String message = Logging.getMessage("generic.ImageReadFailed", imageFile);
          throw new RuntimeException(message);
        }

        this.levels.unmarkResourceAbsent(tile);
        return image;
      } catch (IOException e) {
        // Assume that something's wrong with the file and delete it.
        gov.nasa.worldwind.WorldWind.getDataFileStore().removeFile(url);
        this.levels.markResourceAbsent(tile);
        String message = Logging.getMessage("generic.DeletedCorruptDataFile", url);
        Logging.logger().info(message);
      }
    }

    return null;
  }
  private BufferedImage getImage(MercatorTextureTile tile, String mimeType) throws Exception {
    // Read the image from disk.
    BufferedImage image = this.requestImage(tile, mimeType);
    if (image != null) return image;

    // Retrieve it from the net since it's not on disk.
    this.downloadImage(tile, mimeType);

    // Try to read from disk again after retrieving it from the net.
    image = this.requestImage(tile, mimeType);
    if (image == null) {
      String message =
          Logging.getMessage("layers.TiledImageLayer.ImageUnavailable", tile.getPath());
      throw new RuntimeException(message);
    }

    return image;
  }
  private void downloadImage(final MercatorTextureTile tile, String mimeType) throws Exception {
    //        System.out.println(tile.getPath());
    final URL resourceURL = tile.getResourceURL(mimeType);
    Retriever retriever;

    String protocol = resourceURL.getProtocol();

    if ("http".equalsIgnoreCase(protocol)) {
      retriever = new HTTPRetriever(resourceURL, new HttpRetrievalPostProcessor(tile));
    } else {
      String message =
          Logging.getMessage("layers.TextureLayer.UnknownRetrievalProtocol", resourceURL);
      throw new RuntimeException(message);
    }

    retriever.setConnectTimeout(10000);
    retriever.setReadTimeout(20000);
    retriever.call();
  }
Exemplo n.º 25
0
  protected void validateParameters(AVList list, int srcWidth, int srcHeight)
      throws IllegalArgumentException {
    if (null == list || 0 == list.getValues().size()) {
      String reason = Logging.getMessage("nullValue.AVListIsNull");
      String msg = Logging.getMessage("GeotiffWriter.GeoKeysMissing", reason);
      Logging.logger().finest(msg);
      throw new IllegalArgumentException(msg);
    }

    if (!(srcWidth > 0 && srcHeight > 0)) {
      String msg = Logging.getMessage("generic.InvalidImageSize", srcWidth, srcHeight);
      Logging.logger().finest(msg);
      throw new IllegalArgumentException(msg);
    }

    if (list.hasKey(AVKey.WIDTH)) {
      int width = (Integer) list.getValue(AVKey.WIDTH);
      if (width != srcWidth) {
        String msg = Logging.getMessage("GeotiffWriter.ImageWidthMismatch", width, srcWidth);
        Logging.logger().severe(msg);
        throw new IllegalArgumentException(msg);
      }
    } else list.setValue(AVKey.WIDTH, srcWidth);

    if (list.hasKey(AVKey.HEIGHT)) {
      int height = (Integer) list.getValue(AVKey.HEIGHT);
      if (height != srcHeight) {
        String msg = Logging.getMessage("GeotiffWriter.ImageHeightMismatch", height, srcHeight);
        Logging.logger().severe(msg);
        throw new IllegalArgumentException(msg);
      }
    } else list.setValue(AVKey.HEIGHT, srcHeight);

    Sector sector = null;

    if (list.hasKey(AVKey.SECTOR)) sector = (Sector) list.getValue(AVKey.SECTOR);

    if (null == sector) {
      String msg = Logging.getMessage("GeotiffWriter.NoSectorSpecified");
      Logging.logger().severe(msg);
      throw new IllegalArgumentException(msg);
    }

    if (!list.hasKey(AVKey.COORDINATE_SYSTEM)) {
      String msg = Logging.getMessage("GeotiffWriter.GeoKeysMissing", AVKey.COORDINATE_SYSTEM);
      Logging.logger().finest(msg);
      //            throw new IllegalArgumentException(msg);

      // assume Geodetic Coordinate System
      list.setValue(AVKey.COORDINATE_SYSTEM, AVKey.COORDINATE_SYSTEM_GEOGRAPHIC);
    }

    if (!list.hasKey(AVKey.PROJECTION_EPSG_CODE)) {
      if (isGeographic(list)) {
        // assume WGS84
        list.setValue(AVKey.PROJECTION_EPSG_CODE, GeoTiff.GCS.WGS_84);
      } else {
        String msg = Logging.getMessage("GeotiffWriter.GeoKeysMissing", AVKey.PROJECTION_EPSG_CODE);
        Logging.logger().finest(msg);
        throw new IllegalArgumentException(msg);
      }
    }

    // if PIXEL_WIDTH is specified, we are not overriding it because UTM images
    // will have different pixel size
    if (!list.hasKey(AVKey.PIXEL_WIDTH)) {
      if (isGeographic(list)) {
        double pixelWidth = sector.getDeltaLonDegrees() / (double) srcWidth;
        list.setValue(AVKey.PIXEL_WIDTH, pixelWidth);
      } else {
        String msg = Logging.getMessage("GeotiffWriter.GeoKeysMissing", AVKey.PIXEL_WIDTH);
        Logging.logger().finest(msg);
        throw new IllegalArgumentException(msg);
      }
    }

    // if PIXEL_HEIGHT is specified, we are not overriding it
    // because UTM images will have different pixel size
    if (!list.hasKey(AVKey.PIXEL_HEIGHT)) {
      if (isGeographic(list)) {
        double pixelHeight = sector.getDeltaLatDegrees() / (double) srcHeight;
        list.setValue(AVKey.PIXEL_HEIGHT, pixelHeight);
      } else {
        String msg = Logging.getMessage("GeotiffWriter.GeoKeysMissing", AVKey.PIXEL_HEIGHT);
        Logging.logger().finest(msg);
        throw new IllegalArgumentException(msg);
      }
    }

    if (!list.hasKey(AVKey.PIXEL_FORMAT)) {
      String msg = Logging.getMessage("GeotiffWriter.GeoKeysMissing", AVKey.PIXEL_FORMAT);
      Logging.logger().finest(msg);
      throw new IllegalArgumentException(msg);
    } else {
      String pixelFormat = list.getStringValue(AVKey.PIXEL_FORMAT);
      if (!AVKey.ELEVATION.equals(pixelFormat) && !AVKey.IMAGE.equals(pixelFormat)) {
        String msg =
            Logging.getMessage("Geotiff.UnknownGeoKeyValue", pixelFormat, AVKey.PIXEL_FORMAT);
        Logging.logger().severe(msg);
        throw new IllegalArgumentException(msg);
      }
    }

    // validate elevation parameters
    if (AVKey.ELEVATION.equals(list.getValue(AVKey.PIXEL_FORMAT))) {
      if (!list.hasKey(AVKey.DATA_TYPE)) {
        String msg = Logging.getMessage("GeotiffWriter.GeoKeysMissing", AVKey.DATA_TYPE);
        Logging.logger().finest(msg);
        throw new IllegalArgumentException(msg);
      }

      String type = list.getStringValue(AVKey.DATA_TYPE);
      if (!AVKey.FLOAT32.equals(type) && !AVKey.INT16.equals(type)) {
        String msg = Logging.getMessage("Geotiff.UnknownGeoKeyValue", type, AVKey.DATA_TYPE);
        Logging.logger().severe(msg);
        throw new IllegalArgumentException(msg);
      }
    }

    if (!list.hasKey(AVKey.ORIGIN)) {
      // set UpperLeft corner as the origin, if not specified
      LatLon origin = new LatLon(sector.getMaxLatitude(), sector.getMinLongitude());
      list.setValue(AVKey.ORIGIN, origin);
    }

    if (list.hasKey(AVKey.BYTE_ORDER)
        && !AVKey.BIG_ENDIAN.equals(list.getStringValue(AVKey.BYTE_ORDER))) {
      String msg =
          Logging.getMessage(
              "generic.UnrecognizedByteOrder", list.getStringValue(AVKey.BYTE_ORDER));
      Logging.logger().severe(msg);
      throw new IllegalArgumentException(msg);
    }

    if (!list.hasKey(AVKey.DATE_TIME)) {
      // add NUL (\0) termination as required by TIFF v6 spec (20 bytes length)
      String timestamp = String.format("%1$tY:%1$tm:%1$td %tT\0", Calendar.getInstance());
      list.setValue(AVKey.DATE_TIME, timestamp);
    }

    if (!list.hasKey(AVKey.VERSION)) {
      list.setValue(AVKey.VERSION, Version.getVersion());
    }
  }
Exemplo n.º 26
0
  protected void doDrawOnTo(BufferedImageRaster canvas) {
    Sector sector = this.getSector();
    if (null == sector) {
      String message = Logging.getMessage("nullValue.SectorIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    if (!sector.intersects(canvas.getSector())) {
      return;
    }

    java.awt.Graphics2D g2d = null;
    java.awt.Shape prevClip = null;
    java.awt.Composite prevComposite = null;
    java.lang.Object prevInterpolation = null, prevAntialiasing = null;

    try {
      int canvasWidth = canvas.getWidth();
      int canvasHeight = canvas.getHeight();

      // Apply the transform that correctly maps the image onto the canvas.
      java.awt.geom.AffineTransform transform =
          this.computeSourceToDestTransform(
              this.getWidth(),
              this.getHeight(),
              this.getSector(),
              canvasWidth,
              canvasHeight,
              canvas.getSector());

      AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
      Rectangle2D rect = op.getBounds2D(this.getBufferedImage());

      int clipWidth =
          (int) Math.ceil((rect.getMaxX() >= canvasWidth) ? canvasWidth : rect.getMaxX());
      int clipHeight =
          (int) Math.ceil((rect.getMaxY() >= canvasHeight) ? canvasHeight : rect.getMaxY());

      if (clipWidth <= 0 || clipHeight <= 0) {
        return;
      }

      g2d = canvas.getGraphics();

      prevClip = g2d.getClip();
      prevComposite = g2d.getComposite();
      prevInterpolation = g2d.getRenderingHint(RenderingHints.KEY_INTERPOLATION);
      prevAntialiasing = g2d.getRenderingHint(RenderingHints.KEY_ANTIALIASING);

      // Set the alpha composite for appropriate alpha blending.
      g2d.setComposite(java.awt.AlphaComposite.SrcOver);
      g2d.setRenderingHint(
          RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

      g2d.drawImage(this.getBufferedImage(), transform, null);
    }
    //        catch (java.awt.image.ImagingOpException ioe)
    //        {
    //            // If we catch a ImagingOpException, then the transformed image has a width or
    // height of 0.
    //            // This indicates that there is no intersection between the source image and the
    // canvas,
    //            // or the intersection is smaller than one pixel.
    //        }
    //        catch (java.awt.image.RasterFormatException rfe)
    //        {
    //            // If we catch a RasterFormatException, then the transformed image has a width or
    // height of 0.
    //            // This indicates that there is no intersection between the source image and the
    // canvas,
    //            // or the intersection is smaller than one pixel.
    //        }
    catch (Throwable t) {
      String reason = WWUtil.extractExceptionReason(t);
      Logging.logger().log(java.util.logging.Level.SEVERE, reason, t);
    } finally {
      // Restore the previous clip, composite, and transform.
      try {
        if (null != g2d) {
          if (null != prevClip) g2d.setClip(prevClip);

          if (null != prevComposite) g2d.setComposite(prevComposite);

          if (null != prevInterpolation)
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, prevInterpolation);

          if (null != prevAntialiasing)
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, prevAntialiasing);
        }
      } catch (Throwable t) {
        Logging.logger().log(java.util.logging.Level.FINEST, WWUtil.extractExceptionReason(t), t);
      }
    }
  }
  public BufferedImage composeImageForSector(
      Sector sector,
      int imageWidth,
      int imageHeight,
      int levelNumber,
      String mimeType,
      boolean abortOnError,
      BufferedImage image) {
    if (sector == null) {
      String message = Logging.getMessage("nullValue.SectorIsNull");
      Logging.logger().severe(message);
      throw new IllegalStateException(message);
    }

    if (levelNumber < 0) {
      levelNumber = this.levels.getLastLevel().getLevelNumber();
    } else if (levelNumber > this.levels.getLastLevel().getLevelNumber()) {
      Logging.logger()
          .warning(
              Logging.getMessage(
                  "generic.LevelRequestedGreaterThanMaxLevel",
                  levelNumber,
                  this.levels.getLastLevel().getLevelNumber()));
      levelNumber = this.levels.getLastLevel().getLevelNumber();
    }

    MercatorTextureTile[][] tiles = this.getTilesInSector(sector, levelNumber);

    if (tiles.length == 0 || tiles[0].length == 0) {
      Logging.logger().severe(Logging.getMessage("layers.TiledImageLayer.NoImagesAvailable"));
      return null;
    }

    if (image == null)
      image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);

    Graphics2D g = image.createGraphics();

    for (MercatorTextureTile[] row : tiles) {
      for (MercatorTextureTile tile : row) {
        if (tile == null) continue;

        BufferedImage tileImage;
        try {
          tileImage = this.getImage(tile, mimeType);

          double sh =
              ((double) imageHeight / (double) tileImage.getHeight())
                  * (tile.getSector().getDeltaLat().divide(sector.getDeltaLat()));
          double sw =
              ((double) imageWidth / (double) tileImage.getWidth())
                  * (tile.getSector().getDeltaLon().divide(sector.getDeltaLon()));

          double dh =
              imageHeight
                  * (-tile.getSector().getMaxLatitude().subtract(sector.getMaxLatitude()).degrees
                      / sector.getDeltaLat().degrees);
          double dw =
              imageWidth
                  * (tile.getSector().getMinLongitude().subtract(sector.getMinLongitude()).degrees
                      / sector.getDeltaLon().degrees);

          AffineTransform txf = g.getTransform();
          g.translate(dw, dh);
          g.scale(sw, sh);
          g.drawImage(tileImage, 0, 0, null);
          g.setTransform(txf);
        } catch (Exception e) {
          if (abortOnError) throw new RuntimeException(e);

          String message =
              Logging.getMessage("generic.ExceptionWhileRequestingImage", tile.getPath());
          Logging.logger().log(java.util.logging.Level.WARNING, message, e);
        }
      }
    }

    return image;
  }
Exemplo n.º 28
0
  public static DataRaster wrapAsGeoreferencedRaster(BufferedImage image, AVList params) {
    if (null == image) {
      String message = Logging.getMessage("nullValue.ImageIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    if (null == params) {
      String msg = Logging.getMessage("nullValue.AVListIsNull");
      Logging.logger().finest(msg);
      throw new IllegalArgumentException(msg);
    }

    if (params.hasKey(AVKey.WIDTH)) {
      int width = (Integer) params.getValue(AVKey.WIDTH);
      if (width != image.getWidth()) {
        String msg =
            Logging.getMessage("generic.InvalidWidth", "" + width + "!=" + image.getWidth());
        Logging.logger().finest(msg);
        throw new IllegalArgumentException(msg);
      }
    }

    if (params.hasKey(AVKey.HEIGHT)) {
      int height = (Integer) params.getValue(AVKey.HEIGHT);
      if (height != image.getHeight()) {
        String msg =
            Logging.getMessage("generic.InvalidHeight", "" + height + "!=" + image.getHeight());
        Logging.logger().finest(msg);
        throw new IllegalArgumentException(msg);
      }
    }

    if (!params.hasKey(AVKey.SECTOR)) {
      String msg = Logging.getMessage("generic.MissingRequiredParameter", AVKey.SECTOR);
      Logging.logger().finest(msg);
      throw new IllegalArgumentException(msg);
    }

    Sector sector = (Sector) params.getValue(AVKey.SECTOR);
    if (null == sector) {
      String msg = Logging.getMessage("nullValue.SectorIsNull");
      Logging.logger().severe(msg);
      throw new IllegalArgumentException(msg);
    }

    if (!params.hasKey(AVKey.COORDINATE_SYSTEM)) {
      // assume Geodetic Coordinate System
      params.setValue(AVKey.COORDINATE_SYSTEM, AVKey.COORDINATE_SYSTEM_GEOGRAPHIC);
    }

    String cs = params.getStringValue(AVKey.COORDINATE_SYSTEM);
    if (!params.hasKey(AVKey.PROJECTION_EPSG_CODE)) {
      if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) {
        // assume WGS84
        params.setValue(AVKey.PROJECTION_EPSG_CODE, GeoTiff.GCS.WGS_84);
      } else {
        String msg =
            Logging.getMessage("generic.MissingRequiredParameter", AVKey.PROJECTION_EPSG_CODE);
        Logging.logger().finest(msg);
        throw new IllegalArgumentException(msg);
      }
    }

    // if PIXEL_WIDTH is specified, we are not overriding it because UTM images
    // will have different pixel size
    if (!params.hasKey(AVKey.PIXEL_WIDTH)) {
      if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) {
        double pixelWidth = sector.getDeltaLonDegrees() / (double) image.getWidth();
        params.setValue(AVKey.PIXEL_WIDTH, pixelWidth);
      } else {
        String msg = Logging.getMessage("generic.MissingRequiredParameter", AVKey.PIXEL_WIDTH);
        Logging.logger().finest(msg);
        throw new IllegalArgumentException(msg);
      }
    }

    // if PIXEL_HEIGHT is specified, we are not overriding it
    // because UTM images will have different pixel size
    if (!params.hasKey(AVKey.PIXEL_HEIGHT)) {
      if (AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) {
        double pixelHeight = sector.getDeltaLatDegrees() / (double) image.getHeight();
        params.setValue(AVKey.PIXEL_HEIGHT, pixelHeight);
      } else {
        String msg = Logging.getMessage("generic.MissingRequiredParameter", AVKey.PIXEL_HEIGHT);
        Logging.logger().finest(msg);
        throw new IllegalArgumentException(msg);
      }
    }

    if (!params.hasKey(AVKey.PIXEL_FORMAT)) {
      params.setValue(AVKey.PIXEL_FORMAT, AVKey.IMAGE);
    } else if (!AVKey.IMAGE.equals(params.getStringValue(AVKey.PIXEL_FORMAT))) {
      String msg =
          Logging.getMessage(
              "generic.UnknownValueForKey",
              params.getStringValue(AVKey.PIXEL_FORMAT),
              AVKey.PIXEL_FORMAT);
      Logging.logger().severe(msg);
      throw new IllegalArgumentException(msg);
    }

    if (!params.hasKey(AVKey.ORIGIN) && AVKey.COORDINATE_SYSTEM_GEOGRAPHIC.equals(cs)) {
      // set UpperLeft corner as the origin, if not specified
      LatLon origin = new LatLon(sector.getMaxLatitude(), sector.getMinLongitude());
      params.setValue(AVKey.ORIGIN, origin);
    }

    if (!params.hasKey(AVKey.DATE_TIME)) {
      // add NUL (\0) termination as required by TIFF v6 spec (20 bytes length)
      String timestamp = String.format("%1$tY:%1$tm:%1$td %tT\0", Calendar.getInstance());
      params.setValue(AVKey.DATE_TIME, timestamp);
    }

    if (!params.hasKey(AVKey.VERSION)) {
      params.setValue(AVKey.VERSION, Version.getVersion());
    }

    boolean hasAlpha = (null != image.getColorModel() && image.getColorModel().hasAlpha());
    params.setValue(AVKey.RASTER_HAS_ALPHA, hasAlpha);

    return new BufferedImageRaster(sector, image, params);
  }
    public ImageFormatter serviceRequest(IMapRequest req) throws IOException, WMSServiceException {
      ImageFormatter formatter = null;
      try {
        Sector reqExtent =
            (SingleFileLayer.this.isElevation)
                ? req.getExtentForElevationRequest()
                : req.getExtent();

        if (null == this.intersects(reqExtent, SingleFileLayer.this.getBBox())) {
          String msg =
              Logging.getMessage(
                  "WMS.Layer.OutOfCoverage",
                  reqExtent.toString(),
                  SingleFileLayer.this.getBBox().toString());
          Logging.logger().severe(msg);
          throw new WMSServiceException(msg);
        }

        if (req.getHeight() <= 0 || req.getWidth() <= 0) {
          String msg =
              Logging.getMessage("generic.InvalidImageSize", req.getWidth(), req.getHeight());
          Logging.logger().severe(msg);
          throw new WMSServiceException(msg);
        }

        DataRaster[] rasters = SingleFileLayer.this.rasters;
        if (null == rasters || 0 == rasters.length) {
          String msg = Logging.getMessage("nullValue.RasterIsNull");
          Logging.logger().severe(msg);
          throw new WMSServiceException(msg);
        }

        double missingDataReplacement = (double) SingleFileLayer.this.nodataReplacement;
        try {
          String s = req.getBGColor();
          if (null != s) {
            missingDataReplacement = Double.parseDouble(s);
          }
        } catch (Exception e) {
          missingDataReplacement = (double) SingleFileLayer.this.nodataReplacement;
        }

        DataRaster raster = rasters[0];
        if (raster instanceof BufferedImageRaster) {
          BufferedImageRaster reqRaster =
              new BufferedImageRaster(
                  req.getWidth(), req.getHeight(), Transparency.TRANSLUCENT, reqExtent);

          raster.drawOnTo(reqRaster);

          BufferedImage img = reqRaster.getBufferedImage();
          this.makeNoDataTransparent(
              img, SingleFileLayer.this.nodataSignal, (short) missingDataReplacement);

          formatter = new BufferedImageFormatter(img);
        } else if (raster instanceof ByteBufferRaster) {
          AVList reqParams = new AVListImpl();

          reqParams.setValue(AVKey.WIDTH, req.getWidth());
          reqParams.setValue(AVKey.HEIGHT, req.getHeight());
          reqParams.setValue(AVKey.SECTOR, reqExtent);
          reqParams.setValue(
              AVKey.BYTE_ORDER, AVKey.LITTLE_ENDIAN); // by default BIL is LITTLE ENDIAN
          reqParams.setValue(AVKey.PIXEL_FORMAT, AVKey.ELEVATION);

          String reqFormat = req.getFormat();
          if (null != reqFormat && reqFormat.endsWith("32")) {
            reqParams.setValue(AVKey.DATA_TYPE, AVKey.FLOAT32);
          } else {
            reqParams.setValue(AVKey.DATA_TYPE, AVKey.INT16);
          }
          reqParams.setValue(AVKey.MISSING_DATA_REPLACEMENT, missingDataReplacement);

          ByteBufferRaster reqRaster =
              new ByteBufferRaster(req.getWidth(), req.getHeight(), reqExtent, reqParams);

          raster.drawOnTo(reqRaster);

          if (SingleFileLayer.this.convertFeetToMeters) {
            this.convertFeetToMeters(reqRaster);
          }

          formatter = new DataRasterFormatter(reqRaster);
        } else {
          String msg =
              Logging.getMessage(
                  "generic.UnrecognizedImageSourceType", raster.getClass().getName());
          Logging.logger().severe(msg);
          throw new WMSServiceException(msg);
        }
      } catch (WMSServiceException wmsse) {
        throw wmsse;
      } catch (Exception ex) {
        Logging.logger()
            .log(
                java.util.logging.Level.SEVERE,
                SingleFileLayer.this.getThreadId() + ex.getMessage(),
                ex);
        // throw new WMSServiceException( s );
      } finally {
      }

      return formatter;
    }
  public boolean initialize(MapSource mapSource) throws IOException, WMSServiceException {
    if (null == mapSource) {
      String msg = Logging.getMessage("nullValue.MapSourceIsNull");
      Logging.logger().severe(msg);
      throw new WMSServiceException(msg);
    }

    this.mapSource = mapSource;

    this.params = mapSource.getParameters();
    if (null == params) {
      String msg = Logging.getMessage("nullValue.AVListIsNull");
      Logging.logger().severe(msg);
      throw new WMSServiceException(msg);
    }

    if (!params.hasKey(AVKey.FILE_NAME)) {
      String msg = Logging.getMessage("nullValue.ParamsIsNull");
      Logging.logger().severe(msg);
      throw new WMSServiceException(msg);
    }

    this.sourceFile = new File(params.getStringValue(AVKey.FILE_NAME));
    if (!this.sourceFile.exists()) {
      String msg = Logging.getMessage("generic.FileNotFound", this.sourceFile.getAbsolutePath());
      Logging.logger().severe(msg);
      throw new FileNotFoundException(msg);
    }

    AVList fileParams = this.params.copy();

    try {
      this.readerFactory =
          (DataRasterReaderFactory)
              WorldWind.createConfigurationComponent(AVKey.DATA_RASTER_READER_FACTORY_CLASS_NAME);
    } catch (Exception e) {
      this.readerFactory = new BasicDataRasterReaderFactory();
    }
    DataRasterReader reader =
        this.readerFactory.findReaderFor(this.sourceFile, fileParams, readers);
    if (reader == null) {
      String msg = Logging.getMessage("nullValue.ReaderIsNull", this.sourceFile);
      Logging.logger().severe(msg);
      throw new WMSServiceException(msg);
    }

    reader.readMetadata(this.sourceFile, fileParams);

    this.params.setValues(fileParams);

    if (!this.params.hasKey(AVKey.SECTOR)) {
      String msg = Logging.getMessage("nullValue.SectorIsNull");
      Logging.logger().severe(msg);
      throw new WMSServiceException(msg);
    }
    this.BBOX = (Sector) this.params.getValue(AVKey.SECTOR);

    if (0d == this.BBOX.getDeltaLatDegrees() || 0d == this.BBOX.getDeltaLonDegrees()) {
      String msg = Logging.getMessage("generic.SectorSizeInvalid");
      Logging.logger().severe(msg);
      throw new WMSServiceException(msg);
    }

    int height = 0;
    if (!this.params.hasKey(AVKey.HEIGHT)) {
      String msg = Logging.getMessage("generic.InvalidHeight", 0);
      Logging.logger().severe(msg);
      throw new WMSServiceException(msg);
    } else {
      Object o = this.params.getValue(AVKey.HEIGHT);
      double d = Double.parseDouble("" + o);
      height = (int) d;
    }

    if (!this.params.hasKey(AVKey.WIDTH)) {
      String msg = Logging.getMessage("generic.InvalidWidth", 0);
      Logging.logger().severe(msg);
      throw new WMSServiceException(msg);
    }

    this.isElevation =
        (this.params.hasKey(AVKey.PIXEL_FORMAT)
            && AVKey.ELEVATION.equals(this.params.getValue(AVKey.PIXEL_FORMAT)));

    if (this.params.hasKey(AVKey.MISSING_DATA_SIGNAL)) {
      try {
        Object o = this.params.getValue(AVKey.MISSING_DATA_SIGNAL);
        double d = Double.parseDouble("" + o);
        this.nodataSignal = (short) d;
      } catch (Exception e) {
        this.nodataSignal = (this.isElevation) ? Short.MIN_VALUE : 0;
      }
    } else {
      this.nodataSignal = (this.isElevation) ? Short.MIN_VALUE : 0;
    }

    if (this.params.hasKey(AVKey.MISSING_DATA_REPLACEMENT)) {
      try {
        Object o = this.params.getValue(AVKey.MISSING_DATA_REPLACEMENT);
        double d = Double.parseDouble("" + o);
        this.nodataReplacement = (short) d;
      } catch (Exception e) {
        Logging.logger().finest(e.getMessage());
        this.nodataReplacement = (this.isElevation) ? Short.MIN_VALUE : 0;
      }
    } else {
      this.nodataReplacement = (this.isElevation) ? Short.MIN_VALUE : 0;
    }

    if (this.isElevation) {
      if (this.params.hasKey(AVKey.ELEVATION_UNIT)) {
        try {
          String unit = this.params.getStringValue(AVKey.ELEVATION_UNIT);
          this.convertFeetToMeters = "feet".equalsIgnoreCase(unit);
        } catch (Exception e) {
          Logging.logger().finest(e.getMessage());
        }
      }
    }

    // if PIXEL_HEIGHT is specified, we are not overriding it
    // because UTM images will have different pixel size
    if (!this.params.hasKey(AVKey.PIXEL_HEIGHT)) {
      this.pixelHeight = this.BBOX.getDeltaLatDegrees() / (double) height;
    } else {
      try {
        Object o = this.params.getValue(AVKey.PIXEL_HEIGHT);
        this.pixelHeight = Double.parseDouble("" + o);
      } catch (Exception e) {
        Logging.logger().finest(e.getMessage());
      }
    }

    this.rasters = reader.read(this.sourceFile, this.params);

    if (null == this.rasters || 0 == this.rasters.length) {
      String msg = Logging.getMessage("nullValue.RasterIsNull");
      Logging.logger().severe(msg);
      throw new WMSServiceException(msg);
    }

    return true;
  }