/**
   * Unzips the sole entry in the specified zip file, and saves it in a temporary directory, and
   * returns a File to the temporary location.
   *
   * @param path the path to the source file.
   * @param suffix the suffix to give the temp file.
   * @return a {@link File} for the temp file.
   * @throws IllegalArgumentException if the <code>path</code> is <code>null</code> or empty.
   */
  public static File unzipAndSaveToTempFile(String path, String suffix) {
    if (WWUtil.isEmpty(path)) {
      String message = Logging.getMessage("nullValue.PathIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    InputStream stream = null;

    try {
      stream = WWIO.openStream(path);

      ByteBuffer buffer = WWIO.readStreamToBuffer(stream);
      File file = WWIO.saveBufferToTempFile(buffer, WWIO.getFilename(path));

      buffer = WWIO.readZipEntryToBuffer(file, null);
      return WWIO.saveBufferToTempFile(buffer, suffix);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      WWIO.closeStream(stream, path);
    }

    return null;
  }
Example #2
0
 public static void main(String[] args) {
   try {
     AppFrame frame = new AppFrame();
     frame.setTitle(APP_NAME);
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.setVisible(true);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  public static VirtualEarthTile[] createTiles(
      Sector bbox /*int wwLevel, int wwRow, int wwCol*/, VirtualEarthLayer layer)
      throws WWRuntimeException {
    if (null == bbox) {
      String message = Logging.getMessage("nullValue.SectorIsNull");
      Logging.logger().severe(message);
      throw new WWRuntimeException(message);
    }

    if (null == layer) {
      String message = Logging.getMessage("nullValue.LayerIsNull");
      Logging.logger().severe(message);
      throw new WWRuntimeException(message);
    }

    int level = getZoomLevelByTrueViewRange(bbox.getDeltaLatDegrees());

    Point startPixel =
        LatLongToPixelXY(bbox.getMaxLatitude().degrees, bbox.getMinLongitude().degrees, level);
    Point endPixel =
        LatLongToPixelXY(bbox.getMinLatitude().degrees, bbox.getMaxLongitude().degrees, level);

    Point startTile = PixelXYToTileXY(startPixel.x, startPixel.y);
    Point endTile = PixelXYToTileXY(endPixel.x, endPixel.y);

    ArrayList<VirtualEarthTile> tileList = new ArrayList<VirtualEarthTile>();

    for (int y = startTile.y; y <= endTile.y; y++) {
      for (int x = startTile.x; x <= endTile.x; x++) {
        try {
          int ulPixelX = x * VE_MAX_TILE_SIZE;
          int ulPixelY = y * VE_MAX_TILE_SIZE;
          LatLon ul = PixelXYToLatLong(ulPixelX, ulPixelY, level);

          int lrPixelX = ulPixelX + VE_MAX_TILE_SIZE;
          int lrPixelY = ulPixelY + VE_MAX_TILE_SIZE;
          LatLon lr = PixelXYToLatLong(lrPixelX, lrPixelY, level);

          Sector tileSector = Sector.boundingSector(ul, lr);

          tileList.add(new VirtualEarthTile(x, y, level, layer, tileSector));
        } catch (Exception ex) {
          Logging.logger().log(Level.SEVERE, ex.getMessage(), ex);
        }
      }
    }

    VirtualEarthTile[] tiles = new VirtualEarthTile[tileList.size()];
    return tileList.toArray(tiles);
  }
Example #4
0
  public void openLink(String link) {
    if (WWUtil.isEmpty(link)) return;

    try {
      try {
        // See if the link is a URL, and invoke the browser if it is
        URL url = new URL(link.replace(" ", "%20"));
        Desktop.getDesktop().browse(url.toURI());
        return;
      } catch (MalformedURLException ignored) { // just means that the link is not a URL
      }

      // It's not a URL, so see if it's a file and invoke the desktop to open it if it is.
      File file = new File(link);
      if (file.exists()) {
        Desktop.getDesktop().open(new File(link));
        return;
      }

      String message = "Cannot open resource. It's not a valid file or URL.";
      Util.getLogger().log(Level.SEVERE, message);
      this.showErrorDialog(null, "No Reconocido V\u00ednculo", message);
    } catch (UnsupportedOperationException e) {
      String message =
          "Unable to open resource.\n"
              + link
              + (e.getMessage() != null ? "\n" + e.getMessage() : "");
      Util.getLogger().log(Level.SEVERE, message, e);
      this.showErrorDialog(e, "Error Opening Resource", message);
    } catch (IOException e) {
      String message =
          "I/O error while opening resource.\n"
              + link
              + (e.getMessage() != null ? ".\n" + e.getMessage() : "");
      Util.getLogger().log(Level.SEVERE, message, e);
      this.showErrorDialog(e, "I/O Error", message);
    } catch (Exception e) {
      String message =
          "Error attempting to open resource.\n"
              + link
              + (e.getMessage() != null ? "\n" + e.getMessage() : "");
      Util.getLogger().log(Level.SEVERE, message);
      this.showMessageDialog(message, "Error Opening Resource", JOptionPane.ERROR_MESSAGE);
    }
  }
  private BufferWrapperRaster readTileRaster(MeshTile tile) {
    File file = new File(this.dataDescriptor.getFileStoreLocation(), tile.getPath());
    if (!file.exists()) return null;

    DataSource source = new BasicDataSource(file);
    source.setValue(AVKey.SECTOR, tile.getSector());

    BILRasterReader reader = new BILRasterReader();
    DataRaster[] rasters;
    try {
      rasters = reader.read(source);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }

    return (BufferWrapperRaster) rasters[0];
  }
    protected void loadAirspacesFromPath(String path, Collection<Airspace> airspaces) {
      File file = ExampleUtil.saveResourceToTempFile(path, ".zip");
      if (file == null) return;

      try {
        ZipFile zipFile = new ZipFile(file);

        ZipEntry entry = null;
        for (Enumeration<? extends ZipEntry> e = zipFile.entries();
            e.hasMoreElements();
            entry = e.nextElement()) {
          if (entry == null) continue;

          String name = WWIO.getFilename(entry.getName());

          if (!(name.startsWith("gov.nasa.worldwind.render.airspaces") && name.endsWith(".xml")))
            continue;

          String[] tokens = name.split("-");

          try {
            Class c = Class.forName(tokens[0]);
            Airspace airspace = (Airspace) c.newInstance();
            BufferedReader input =
                new BufferedReader(new InputStreamReader(zipFile.getInputStream(entry)));
            String s = input.readLine();
            airspace.restoreState(s);
            airspaces.add(airspace);

            if (tokens.length >= 2) {
              airspace.setValue(AVKey.DISPLAY_NAME, tokens[1]);
            }
          } catch (Exception ex) {
            ex.printStackTrace();
          }
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    public AppFrame() {
      super(true, true, false);

      try {
        // Create the Quad from a Sector
        Globe globe = this.getWwd().getModel().getGlobe();
        double radius = globe.getRadiusAt(sector.getCentroid());
        double quadWidth = sector.getDeltaLonRadians() * radius;
        double quadHeight = sector.getDeltaLatRadians() * radius;
        final SurfaceQuad quad =
            new SurfaceQuad(sector.getCentroid(), quadWidth, quadHeight, Angle.ZERO);

        // Create the layer to hold it
        final RenderableLayer layer = new RenderableLayer();
        layer.setName("Rotating Sector");
        layer.addRenderable(quad);

        // Add the layer to the model and update the ApplicationTemplate's layer manager
        insertBeforeCompass(this.getWwd(), layer);
        this.getLayerPanel().update(this.getWwd());

        // Rotate the quad continuously
        Timer timer =
            new Timer(
                50,
                new ActionListener() {
                  public void actionPerformed(ActionEvent actionEvent) {
                    // Increment the current heading if the layer is visible
                    if (layer.isEnabled()) {
                      quad.setHeading(
                          Angle.fromDegrees((quad.getHeading().getDegrees() + 1) % 360));
                      getWwd().redraw();
                    }
                  }
                });
        timer.start();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
Example #8
0
  @SuppressWarnings({"StringConcatenationInsideStringBufferAppend"})
  private static String formatMessage(Exception e, Object message, Object[] args) {
    StringBuilder sb = new StringBuilder();

    if (message != null) sb.append(message.toString());

    if (e != null) sb.append((sb.length() > 0 ? "\n" : "") + e.toString());

    for (Object o : args) {
      if (o != null) sb.append((sb.length() > 0 ? "\n" : "") + o.toString());
    }

    return sb.toString();
  }
    protected void importImagery() {
      try {
        // Read the data and save it in a temp file.
        File sourceFile = ExampleUtil.saveResourceToTempFile(IMAGE_PATH, ".tif");

        // Create a raster reader to read this type of file. The reader is created from the
        // currently
        // configured factory. The factory class is specified in the Configuration, and a different
        // one can be
        // specified there.
        DataRasterReaderFactory readerFactory =
            (DataRasterReaderFactory)
                WorldWind.createConfigurationComponent(AVKey.DATA_RASTER_READER_FACTORY_CLASS_NAME);
        DataRasterReader reader = readerFactory.findReaderFor(sourceFile, null);

        // Before reading the raster, verify that the file contains imagery.
        AVList metadata = reader.readMetadata(sourceFile, null);
        if (metadata == null || !AVKey.IMAGE.equals(metadata.getStringValue(AVKey.PIXEL_FORMAT)))
          throw new Exception("Not an image file.");

        // Read the file into the raster. read() returns potentially several rasters if there are
        // multiple
        // files, but in this case there is only one so just use the first element of the returned
        // array.
        DataRaster[] rasters = reader.read(sourceFile, null);
        if (rasters == null || rasters.length == 0)
          throw new Exception("Can't read the image file.");

        DataRaster raster = rasters[0];

        // Determine the sector covered by the image. This information is in the GeoTIFF file or
        // auxiliary
        // files associated with the image file.
        final Sector sector = (Sector) raster.getValue(AVKey.SECTOR);
        if (sector == null) throw new Exception("No location specified with image.");

        // Request a sub-raster that contains the whole image. This step is necessary because only
        // sub-rasters
        // are reprojected (if necessary); primary rasters are not.
        int width = raster.getWidth();
        int height = raster.getHeight();

        // getSubRaster() returns a sub-raster of the size specified by width and height for the
        // area indicated
        // by a sector. The width, height and sector need not be the full width, height and sector
        // of the data,
        // but we use the full values of those here because we know the full size isn't huge. If it
        // were huge
        // it would be best to get only sub-regions as needed or install it as a tiled image layer
        // rather than
        // merely import it.
        DataRaster subRaster = raster.getSubRaster(width, height, sector, null);

        // Tne primary raster can be disposed now that we have a sub-raster. Disposal won't affect
        // the
        // sub-raster.
        raster.dispose();

        // Verify that the sub-raster can create a BufferedImage, then create one.
        if (!(subRaster instanceof BufferedImageRaster))
          throw new Exception("Cannot get BufferedImage.");
        BufferedImage image = ((BufferedImageRaster) subRaster).getBufferedImage();

        // The sub-raster can now be disposed. Disposal won't affect the BufferedImage.
        subRaster.dispose();

        // Create a SurfaceImage to display the image over the specified sector.
        final SurfaceImage si1 = new SurfaceImage(image, sector);

        // On the event-dispatch thread, add the imported data as an SurfaceImageLayer.
        SwingUtilities.invokeLater(
            new Runnable() {
              public void run() {
                // Add the SurfaceImage to a layer.
                SurfaceImageLayer layer = new SurfaceImageLayer();
                layer.setName("Imported Surface Image");
                layer.setPickEnabled(false);
                layer.addRenderable(si1);

                // Add the layer to the model and update the application's layer panel.
                insertBeforeCompass(AppFrame.this.getWwd(), layer);
                AppFrame.this.getLayerPanel().update(AppFrame.this.getWwd());

                // Set the view to look at the imported image.
                ExampleUtil.goTo(getWwd(), sector);
              }
            });
      } catch (Exception e) {
        e.printStackTrace();
      }
    }