示例#1
1
  protected Header readHeaderFromBuffer(ByteBuffer buffer) throws WWRuntimeException {
    // Read file code - first byte
    int fileCode = buffer.get();
    if (fileCode > 5) {
      String message = Logging.getMessage("SHP.NotADBaseFile", file.getPath());
      Logging.logger().log(java.util.logging.Level.SEVERE, message);
      throw new WWRuntimeException(message);
    }

    // Last update date
    int yy = 0xFF & buffer.get(); // unsigned
    int mm = buffer.get();
    int dd = buffer.get();

    // Number of records
    int numRecords = buffer.getInt();

    // Header struct length
    int headerLength = buffer.getShort();

    // Record length
    int recordLength = buffer.getShort();

    // Assemble header
    Header header = new Header();
    header.fileCode = fileCode;
    Calendar cal = Calendar.getInstance();
    cal.set(1900 + yy, mm - 1, dd);
    header.lastModificationDate = cal.getTime();
    header.numberOfRecords = numRecords;
    header.headerLength = headerLength;
    header.recordLength = recordLength;

    return header;
  }
  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;
  }
  /**
   * Causes resources used by the World Window to be freed. The World Window cannot be used once
   * this method is called. An OpenGL context for the window must be current.
   */
  public void shutdown() {
    WorldWind.getDataFileStore().removePropertyChangeListener(this);

    if (this.inputHandler != null) {
      this.inputHandler.dispose();
      this.inputHandler = new NoOpInputHandler();
    }

    // Clear the texture cache
    if (this.getGpuResourceCache() != null) this.getGpuResourceCache().clear();

    // Dispose all the layers //  TODO: Need per-window dispose for layers
    if (this.getModel() != null && this.getModel().getLayers() != null) {
      for (Layer layer : this.getModel().getLayers()) {
        try {
          layer.dispose();
        } catch (Exception e) {
          Logging.logger()
              .log(
                  java.util.logging.Level.SEVERE,
                  Logging.getMessage("WorldWindowGLCanvas.ExceptionWhileShuttingDownWorldWindow"),
                  e);
        }
      }
    }

    SceneController sc = this.getSceneController();
    if (sc != null) sc.dispose();
  }
  /**
   * @param url the "file:" URL of the file to remove from the file store. Only files in the
   *     writable World Wind disk cache or temp file directory are removed by this method.
   * @throws IllegalArgumentException if <code>url</code> is null
   */
  @SuppressWarnings({"ResultOfMethodCallIgnored"})
  public void removeFile(java.net.URL url) {
    if (url == null) {
      String msg = Logging.getMessage("nullValue.URLIsNull");
      Logging.logger().severe(msg);
      throw new IllegalArgumentException(msg);
    }

    try {
      java.io.File file = new java.io.File(url.toURI());

      // This block of code must be synchronized for proper operation. A thread may check that the
      // file exists,
      // and become immediately suspended. A second thread may then delete that file. When the first
      // thread
      // wakes up, file.delete() fails.
      synchronized (this.fileLock) {
        if (file.exists()) {
          // Don't remove files outside the cache or temp directory.
          String parent = file.getParent();
          if (!(parent.startsWith(this.getWriteLocation().getPath())
              || parent.startsWith(Configuration.getSystemTempDirectory()))) return;

          file.delete();
        }
      }
    } catch (java.net.URISyntaxException e) {
      Logging.logger()
          .log(
              Level.SEVERE,
              Logging.getMessage("FileStore.ExceptionRemovingFile", url.toString()),
              e);
    }
  }
  /**
   * {@inheritDoc}
   *
   * @param positions Control points. This graphic uses only two control point, which determine the
   *     midpoints of two opposite sides of the quad. See Fire Support Area (2.X.4.3.2.1.2) on pg.
   *     652 of MIL-STD-2525C for an example of how these points are interpreted.
   */
  public void setPositions(Iterable<? extends Position> positions) {
    if (positions == null) {
      String message = Logging.getMessage("nullValue.PositionsListIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    Iterator<? extends Position> iterator = positions.iterator();
    try {
      Position pos1 = iterator.next();
      Position pos2 = iterator.next();

      LatLon center = LatLon.interpolateGreatCircle(0.5, pos1, pos2);
      this.quad.setCenter(center);

      Angle heading = LatLon.greatCircleAzimuth(pos2, pos1);
      this.quad.setHeading(heading.subtract(Angle.POS90));

      this.positions = positions;
      this.shapeInvalid = true; // Need to recompute quad size
    } catch (NoSuchElementException e) {
      String message = Logging.getMessage("generic.InsufficientPositions");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }
  }
示例#6
0
  public boolean isAirspaceVisible(DrawContext dc) {
    if (dc == null) {
      String message = Logging.getMessage("nullValue.DrawContextIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    // If the parent Cake is not visible, then return false immediately without testing the child
    // layers.
    if (!super.isAirspaceVisible(dc)) return false;

    boolean visible = false;

    // The parent Cake is visible. Since the parent Cake's extent potentially contains volumes where
    // no child
    // geometry exists, test that at least one of the child layers are visible.
    for (Layer l : this.layers) {
      if (l.isAirspaceVisible(dc)) {
        visible = true;
        break;
      }
    }

    return visible;
  }
  /**
   * Create an screen image.
   *
   * @param tc the current {@link KMLTraversalContext}.
   * @param overlay the <i>Overlay</i> element containing.
   * @throws NullPointerException if the traversal context is null.
   * @throws IllegalArgumentException if the parent overlay or the traversal context is null.
   */
  public KMLSurfaceImageImpl(KMLTraversalContext tc, KMLGroundOverlay overlay) {
    this.parent = overlay;

    if (tc == null) {
      String msg = Logging.getMessage("nullValue.TraversalContextIsNull");
      Logging.logger().severe(msg);
      throw new IllegalArgumentException(msg);
    }

    if (overlay == null) {
      String msg = Logging.getMessage("nullValue.ParentIsNull");
      Logging.logger().severe(msg);
      throw new IllegalArgumentException(msg);
    }

    // Positions are specified either as a kml:LatLonBox or a gx:LatLonQuad
    KMLLatLonBox box = overlay.getLatLonBox();
    if (box != null) {
      Sector sector = KMLUtil.createSectorFromLatLonBox(box);
      this.initializeGeometry(sector);

      // TODO: rotation
    } else {
      GXLatLongQuad latLonQuad = overlay.getLatLonQuad();
      if (latLonQuad != null && latLonQuad.getCoordinates() != null) {
        this.initializeGeometry(latLonQuad.getCoordinates().list);
      }
    }

    this.setPickEnabled(false);
  }
  /**
   * @param placeNameServiceSet the set of PlaceNameService objects that PlaceNameLayer will render.
   * @throws IllegalArgumentException if {@link
   *     gov.nasa.worldwind.layers.placename.PlaceNameServiceSet} is null
   */
  public PlaceNameLayer(PlaceNameServiceSet placeNameServiceSet) {
    if (placeNameServiceSet == null) {
      String message = Logging.getMessage("nullValue.PlaceNameServiceSetIsNull");
      Logging.logger().fine(message);
      throw new IllegalArgumentException(message);
    }

    //
    this.placeNameServiceSet = placeNameServiceSet.deepCopy();
    for (int i = 0; i < this.placeNameServiceSet.getServiceCount(); i++) {
      // todo do this for long as well and pick min
      int calc1 =
          (int)
              (PlaceNameService.TILING_SECTOR.getDeltaLatDegrees()
                  / this.placeNameServiceSet
                      .getService(i)
                      .getTileDelta()
                      .getLatitude()
                      .getDegrees());
      int numLevels = (int) Math.log(calc1);
      navTiles.add(
          new NavigationTile(
              this.placeNameServiceSet.getService(i),
              PlaceNameService.TILING_SECTOR,
              numLevels,
              "top"));
    }

    if (!WorldWind.getMemoryCacheSet().containsCache(Tile.class.getName())) {
      long size = Configuration.getLongValue(AVKey.PLACENAME_LAYER_CACHE_SIZE, 2000000L);
      MemoryCache cache = new BasicMemoryCache((long) (0.85 * size), size);
      cache.setName("Placename Tiles");
      WorldWind.getMemoryCacheSet().addCache(Tile.class.getName(), cache);
    }
  }
  /**
   * 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;
  }
  protected String validateMetadata(Object source, AVList params) {
    StringBuilder sb = new StringBuilder();

    String message = super.validateMetadata(source, params);
    if (message != null) sb.append(message);

    Object o = (params != null) ? params.getValue(AVKey.BYTE_ORDER) : null;
    if (o == null || !(o instanceof String))
      sb.append(sb.length() > 0 ? ", " : "")
          .append(Logging.getMessage("WorldFile.NoByteOrderSpecified", source));

    o = (params != null) ? params.getValue(AVKey.PIXEL_FORMAT) : null;
    if (o == null) {
      sb.append(sb.length() > 0 ? ", " : "")
          .append(Logging.getMessage("WorldFile.NoPixelFormatSpecified", source));
    } else if (!AVKey.ELEVATION.equals(o)) {
      sb.append(sb.length() > 0 ? ", " : "")
          .append(Logging.getMessage("WorldFile.InvalidPixelFormat", source));
    }

    o = (params != null) ? params.getValue(AVKey.PIXEL_TYPE) : null;
    if (o == null) {
      o = (params != null) ? params.getValue(AVKey.DATA_TYPE) : null;
      if (o == null) {
        sb.append(sb.length() > 0 ? ", " : "")
            .append(Logging.getMessage("WorldFile.NoPixelTypeSpecified", source));
      }
    }

    if (sb.length() == 0) return null;

    return sb.toString();
  }
  private java.nio.ByteBuffer readElevations(Object source) throws java.io.IOException {
    if (!(source instanceof java.io.File) && !(source instanceof java.net.URL)) {
      String message = Logging.getMessage("DataRaster.CannotRead", source);
      Logging.logger().severe(message);
      throw new java.io.IOException(message);
    }

    if (source instanceof java.io.File) {
      java.io.File file = (java.io.File) source;

      // handle .bil.zip, .bil16.zip, and .bil32.gz files
      if (file.getName().toLowerCase().endsWith(".zip")) {
        return WWIO.readZipEntryToBuffer(file, null);
      }
      // handle bil.gz, bil16.gz, and bil32.gz files
      else if (file.getName().toLowerCase().endsWith(".gz")) {
        return WWIO.readGZipFileToBuffer(file);
      } else if (!this.isMapLargeFiles() || (this.getLargeFileThreshold() > file.length())) {
        return WWIO.readFileToBuffer(file);
      } else {
        return WWIO.mapFile(file);
      }
    } else // (source instanceof java.net.URL)
    {
      java.net.URL url = (java.net.URL) source;
      return WWIO.readURLContentToBuffer(url);
    }
  }
  /**
   * Appends elevation model parameters as elements to a specified context. If a parameter key
   * exists, that parameter is appended to the context. Supported key and element paths are:
   *
   * <table> <th><td>Key</td><td>Name</td><td>Type</td></th>
   * <tr><td>{@link AVKey#DISPLAY_NAME}</td><td>DisplayName</td><td>String</td></tr> <tr><td>{@link
   * AVKey#NETWORK_RETRIEVAL_ENABLED}</td><td>NetworkRetrievalEnabled</td><td>Boolean</td></tr> <tr><td>{@link
   * AVKey#MISSING_DATA_SIGNAL}</td><td>MissingData/@signal</td><td>Double</td></tr> <tr><td>{@link
   * AVKey#MISSING_DATA_REPLACEMENT}</td><td>MissingData/@replacement</td><td>Double</td></tr> <tr><td>{@link
   * AVKey#DETAIL_HINT}</td><td>DataDetailHint</td><td>Double</td></tr> </table>
   *
   * @param params the key-value pairs which define the elevation model parameters.
   * @param context the XML document root on which to append parameter elements.
   * @return a reference to context.
   * @throws IllegalArgumentException if either the parameters or the context are null.
   */
  public static Element createElevationModelElements(AVList params, Element context) {
    if (params == null) {
      String message = Logging.getMessage("nullValue.ParametersIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

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

    WWXML.checkAndAppendTextElement(params, AVKey.DISPLAY_NAME, context, "DisplayName");
    WWXML.checkAndAppendBooleanElement(
        params, AVKey.NETWORK_RETRIEVAL_ENABLED, context, "NetworkRetrievalEnabled");

    if (params.getValue(AVKey.MISSING_DATA_SIGNAL) != null
        || params.getValue(AVKey.MISSING_DATA_REPLACEMENT) != null) {
      Element el = WWXML.getElement(context, "MissingData", null);
      if (el == null) el = WWXML.appendElementPath(context, "MissingData");

      Double d = AVListImpl.getDoubleValue(params, AVKey.MISSING_DATA_SIGNAL);
      if (d != null) el.setAttribute("signal", Double.toString(d));

      d = AVListImpl.getDoubleValue(params, AVKey.MISSING_DATA_REPLACEMENT);
      if (d != null) el.setAttribute("replacement", Double.toString(d));
    }

    WWXML.checkAndAppendDoubleElement(params, AVKey.DETAIL_HINT, context, "DataDetailHint");

    return context;
  }
  /** {@inheritDoc} */
  public void dispose() {
    if (this.disposed) // Do not dispose the WebView multiple times
    return;

    try {
      // Remove the notification adapter
      if (webViewWindowPtr != 0 && observerPtr != 0)
        WindowsWebViewJNI.removeWindowUpdateObserver(webViewWindowPtr, observerPtr);
      // Free the native WebView object associated with this Java WebView object.
      if (webViewWindowPtr != 0) {
        WindowsWebViewJNI.releaseWebView(webViewWindowPtr);
        // Decrement the instance counter. Only do this if the webViewWindow pointer was non-zero,
        // indicating
        // that native resources were actually allocated.
        instances.decrementAndGet();
      }
      if (observerPtr != 0) WindowsWebViewJNI.releaseComObject(observerPtr);

      this.webViewWindowPtr = 0;
      this.observerPtr = 0;

      // Terminate the message loop thread if this is the last active instance.
      this.stopMessageLoopIfNoInstances();

      this.disposed = true;
    } catch (Exception e) {
      Logging.logger()
          .log(
              Level.SEVERE,
              Logging.getMessage("generic.ExceptionAttemptingToDisposeRenderable"),
              e);
    }
  }
示例#14
0
  /**
   * Construct a unit-length cube centered at a specified point.
   *
   * @param point the center of the cube.
   * @throws IllegalArgumentException if the point is null.
   */
  public Box(Vec4 point) {
    if (point == null) {
      String msg = Logging.getMessage("nullValue.PointIsNull");
      Logging.error(msg);
      throw new IllegalArgumentException(msg);
    }

    this.ru = new Vec4(1, 0, 0, 1);
    this.su = new Vec4(0, 1, 0, 1);
    this.tu = new Vec4(0, 0, 1, 1);

    this.r = this.ru;
    this.s = this.su;
    this.t = this.tu;

    this.rLength = 1;
    this.sLength = 1;
    this.tLength = 1;

    // Plane normals point outwards from the box.
    this.planes = new Plane[6];
    double d = 0.5 * point.getLength3();
    this.planes[0] = new Plane(-this.ru.x, -this.ru.y, -this.ru.z, -(d + 0.5));
    this.planes[1] = new Plane(+this.ru.x, +this.ru.y, +this.ru.z, -(d + 0.5));
    this.planes[2] = new Plane(-this.su.x, -this.su.y, -this.su.z, -(d + 0.5));
    this.planes[3] = new Plane(+this.su.x, +this.su.y, +this.su.z, -(d + 0.5));
    this.planes[4] = new Plane(-this.tu.x, -this.tu.y, -this.tu.z, -(d + 0.5));
    this.planes[5] = new Plane(+this.tu.x, +this.tu.y, +this.tu.z, -(d + 0.5));

    this.center = ru.add3(su).add3(tu).multiply3(0.5);

    Vec4 rHalf = r.multiply3(0.5);
    this.topCenter = this.center.add3(rHalf);
    this.bottomCenter = this.center.subtract3(rHalf);
  }
示例#15
0
  /**
   * Creates a frustum by extracting the six frustum planes from a projection matrix.
   *
   * @param matrix the projection matrix to extract the frustum planes from.
   * @return a frustum defined by the extracted planes.
   * @throws IllegalArgumentException if the projection matrix is null.
   */
  public Frustum setProjection(Matrix matrix) {
    //noinspection UnnecessaryLocalVariable
    Matrix m = matrix;
    if (m == null) {
      String msg = Logging.getMessage("nullValue.MatrixIsNull");
      Logging.error(msg);
      throw new IllegalArgumentException(msg);
    }

    // Extract the six clipping planes from the projection-matrix.
    this.left
        .set(m.m[12] + m.m[0], m.m[13] + m.m[1], m.m[14] + m.m[2], m.m[15] + m.m[3])
        .normalizeAndSet();
    this.right
        .set(m.m[12] - m.m[0], m.m[13] - m.m[1], m.m[14] - m.m[2], m.m[15] - m.m[3])
        .normalizeAndSet();
    this.bottom
        .set(m.m[12] + m.m[4], m.m[13] + m.m[5], m.m[14] + m.m[6], m.m[15] + m.m[7])
        .normalizeAndSet();
    this.top
        .set(m.m[12] - m.m[4], m.m[13] - m.m[5], m.m[14] - m.m[6], m.m[15] - m.m[7])
        .normalizeAndSet();
    this.near
        .set(m.m[12] + m.m[8], m.m[13] + m.m[9], m.m[14] + m.m[10], m.m[15] + m.m[11])
        .normalizeAndSet();
    this.far
        .set(m.m[12] - m.m[8], m.m[13] - m.m[9], m.m[14] - m.m[10], m.m[15] - m.m[11])
        .normalizeAndSet();

    return this;
  }
示例#16
0
  public void makeOrderedRenderable(DrawContext dc, AirspaceRenderer renderer) {
    if (dc == null) {
      String message = Logging.getMessage("nullValue.DrawContextIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

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

    for (Layer layer : this.layers) {
      if (!layer.isVisible()) continue;

      if (!layer.isAirspaceVisible(dc)) continue;

      // The layer is responsible for applying its own attributes, so we override its attributes
      // with our own just
      // before rendering.
      layer.setAttributes(this.getAttributes());

      // Create an ordered renderable that draws each layer, but specifies this Cake as the picked
      // object.
      OrderedRenderable or =
          renderer.createOrderedRenderable(dc, layer, layer.computeEyeDistance(dc), this);
      dc.addOrderedRenderable(or);
    }
  }
  /**
   * Resolves a reference to a local element identified by address and identifier, where {@code
   * linkBase} identifies a document, including the current document, and {@code linkRef} is the id
   * of the desired element.
   *
   * <p>If {@code linkBase} refers to a local COLLADA file and {@code linkRef} is non-null, the
   * return value is the element identified by {@code linkRef}. If {@code linkRef} is null, the
   * return value is a parsed {@link ColladaRoot} for the COLLADA file identified by {@code
   * linkBase}. Otherwise, {@code linkBase} is returned.
   *
   * @param linkBase the address of the document containing the requested element.
   * @param linkRef the element's identifier.
   * @return the requested element, or null if the element is not found.
   * @throws IllegalArgumentException if the address is null.
   */
  protected Object resolveLocalReference(String linkBase, String linkRef) {
    if (linkBase == null) {
      String message = Logging.getMessage("nullValue.DocumentSourceIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    try {
      File file = new File(linkBase);

      if (!file.exists()) return null;

      // Determine whether the file is a COLLADA document. If not, just return the file path.
      if (!WWIO.isContentType(file, ColladaConstants.COLLADA_MIME_TYPE))
        return file.toURI().toString();

      // Attempt to open and parse the COLLADA file.
      ColladaRoot refRoot = ColladaRoot.createAndParse(file);
      // An exception is thrown if parsing fails, so no need to check for null.

      // Add the parsed file to the session cache so it doesn't have to be parsed again.
      WorldWind.getSessionCache().put(linkBase, refRoot);

      // Now check the newly opened COLLADA file for the referenced item, if a reference was
      // specified.
      if (linkRef != null) return refRoot.getItemByID(linkRef);
      else return refRoot;
    } catch (Exception e) {
      String message =
          Logging.getMessage("generic.UnableToResolveReference", linkBase + "/" + linkRef);
      Logging.logger().warning(message);
      return null;
    }
  }
  public ViewControlsSelectListener(
      WorldWindow wwd, ViewControlsLayer layer, JFrame appFrame, GlobalSettings globalSettings) {
    this.globalSettings = globalSettings;
    this.appFrame = appFrame;
    if (wwd == null) {
      String msg = Logging.getMessage("nullValue.WorldWindow");
      Logging.logger().severe(msg);
      throw new IllegalArgumentException(msg);
    }
    if (layer == null) {
      String msg = Logging.getMessage("nullValue.LayerIsNull");
      Logging.logger().severe(msg);
      throw new IllegalArgumentException(msg);
    }

    this.wwd = wwd;
    this.viewControlsLayer = layer;

    // Setup repeat timer
    this.repeatTimer =
        new Timer(
            DEFAULT_TIMER_DELAY,
            new ActionListener() {
              public void actionPerformed(ActionEvent event) {
                if (pressedControl != null) updateView(pressedControl, pressedControlType);
              }
            });
    this.repeatTimer.start();
  }
  protected boolean loadTile(Tile tile, java.net.URL url) {
    if (WWIO.isFileOutOfDate(url, this.placeNameServiceSet.getExpiryTime())) {
      // The file has expired. Delete it then request download of newer.
      this.getDataFileStore().removeFile(url);
      String message = Logging.getMessage("generic.DataFileExpired", url);
      Logging.logger().fine(message);
      return false;
    }

    PlaceNameChunk tileData;
    synchronized (this.fileLock) {
      tileData = readTileData(tile, url);
    }

    if (tileData == null) {
      // Assume that something's wrong with the file and delete it.
      this.getDataFileStore().removeFile(url);
      tile.getPlaceNameService()
          .markResourceAbsent(tile.getPlaceNameService().getTileNumber(tile.row, tile.column));
      String message = Logging.getMessage("generic.DeletedCorruptDataFile", url);
      Logging.logger().fine(message);
      return false;
    }

    tile.setDataChunk(tileData);
    WorldWind.getMemoryCache(Tile.class.getName()).add(tile.getFileCachePath(), tile);
    return true;
  }
    @Override
    public int compareTo(RetrievalTask that) {
      if (that == null) {
        String msg = Logging.getMessage("nullValue.RetrieverIsNull");
        Logging.logger().fine(msg);
        throw new IllegalArgumentException(msg);
      }

      if (this.priority > 0
          && that.priority > 0) // only secondary priority used if either is negative
      {
        // Requests submitted within different time-granularity periods are ordered exclusive of
        // their
        // client-specified priority.
        long now = System.currentTimeMillis();
        long thisElapsedTime = now - this.retriever.getSubmitTime();
        long thatElapsedTime = now - that.retriever.getSubmitTime();
        if (((thisElapsedTime - thatElapsedTime) / DEFAULT_TIME_PRIORITY_GRANULARITY) != 0)
          return thisElapsedTime < thatElapsedTime ? -1 : 1;
      }

      // The client-pecified priority is compared for requests submitted within the same granularity
      // period.
      return this.priority == that.priority ? 0 : this.priority < that.priority ? -1 : 1;
    }
  /**
   * Causes the View attached to the specified WorldWindow to animate to the specified sector. The
   * View starts animating at its current location and stops when the sector fills the window.
   *
   * @param wwd the WorldWindow who's View animates.
   * @param sector the sector to go to.
   * @throws IllegalArgumentException if either the <code>wwd</code> or the <code>sector</code> are
   *     <code>null</code>.
   */
  public static void goTo(WorldWindow wwd, Sector sector) {
    if (wwd == null) {
      String message = Logging.getMessage("nullValue.WorldWindow");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

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

    // Create a bounding box for the specified sector in order to estimate its size in model
    // coordinates.
    Box extent =
        Sector.computeBoundingBox(
            wwd.getModel().getGlobe(), wwd.getSceneController().getVerticalExaggeration(), sector);

    // Estimate the distance between the center position and the eye position that is necessary to
    // cause the sector to
    // fill a viewport with the specified field of view. Note that we change the distance between
    // the center and eye
    // position here, and leave the field of view constant.
    Angle fov = wwd.getView().getFieldOfView();
    double zoom = extent.getRadius() / fov.cosHalfAngle() / fov.tanHalfAngle();

    // Configure OrbitView to look at the center of the sector from our estimated distance. This
    // causes OrbitView to
    // animate to the specified position over several seconds. To affect this change immediately use
    // the following:
    // ((OrbitView) wwd.getView()).setCenterPosition(new Position(sector.getCentroid(), 0d));
    // ((OrbitView) wwd.getView()).setZoom(zoom);
    wwd.getView().goTo(new Position(sector.getCentroid(), 0d), zoom);
  }
  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;
  }
示例#23
0
  /**
   * {@inheritDoc}
   *
   * @param positions Control points that orient the graphic. Must provide at least three points.
   */
  public void setPositions(Iterable<? extends Position> positions) {
    if (positions == null) {
      String message = Logging.getMessage("nullValue.PositionsListIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    try {
      Iterator<? extends Position> iterator = positions.iterator();
      this.position1 = iterator.next();
      this.position2 = iterator.next();
      this.position3 = iterator.next();
    } catch (NoSuchElementException e) {
      String message = Logging.getMessage("generic.InsufficientPositions");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    this.paths = null; // Need to recompute path for the new control points
    this.arrowHead1 = null;
    this.arrowHead2 = null;

    if (this.symbol != null) {
      this.symbol.setPosition(this.position1);
    }
  }
  @Override
  protected Layer doCreateFromCapabilities(OGCCapabilities caps, AVList params) {
    String serviceName = caps.getServiceInformation().getServiceName();
    if (serviceName == null
        || !(serviceName.equalsIgnoreCase(OGCConstants.WMS_SERVICE_NAME)
            || serviceName.equalsIgnoreCase("WMS"))) {
      String message =
          Logging.getMessage("WMS.NotWMSService", serviceName != null ? serviceName : "null");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

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

    if (params.getStringValue(AVKey.LAYER_NAMES) == null) {
      // Use the first named layer since no other guidance given
      List<WMSLayerCapabilities> namedLayers = ((WMSCapabilities) caps).getNamedLayers();

      if (namedLayers == null || namedLayers.size() == 0 || namedLayers.get(0) == null) {
        String message = Logging.getMessage("WMS.NoLayersFound");
        Logging.logger().severe(message);
        throw new IllegalStateException(message);
      }

      params.setValue(AVKey.LAYER_NAMES, namedLayers.get(0).getName());
    }

    return new WMSTiledImageLayer((WMSCapabilities) caps, params);
  }
示例#25
0
  protected ByteBuffer doRead(URLConnection connection) throws Exception {
    if (connection == null) {
      String msg = Logging.getMessage("nullValue.ConnectionIsNull");
      Logging.logger().severe(msg);
      throw new IllegalArgumentException(msg);
    }

    JarURLConnection htpc = (JarURLConnection) connection;
    this.responseCode = htpc.getContentLength() >= 0 ? HttpURLConnection.HTTP_OK : -1;
    this.responseMessage = this.responseCode >= 0 ? "OK" : "FAILED";

    String contentType = connection.getContentType();
    Logging.logger()
        .log(
            Level.FINE,
            "HTTPRetriever.ResponseInfo",
            new Object[] {
              this.responseCode,
              connection.getContentLength(),
              contentType != null ? contentType : "content type not returned",
              connection.getURL()
            });

    if (this.responseCode == HttpURLConnection.HTTP_OK) // intentionally re-using HTTP constant
    return super.doRead(connection);

    return null;
  }
示例#26
0
  protected void initializeTexture(DrawContext dc) {
    Texture iconTexture = dc.getTextureCache().getTexture(this.getIconFilePath());
    if (iconTexture != null) return;

    try {
      InputStream iconStream = this.getClass().getResourceAsStream("/" + this.getIconFilePath());
      if (iconStream == null) {
        File iconFile = new File(this.iconFilePath);
        if (iconFile.exists()) {
          iconStream = new FileInputStream(iconFile);
        }
      }

      iconTexture = TextureIO.newTexture(iconStream, false, null);
      iconTexture.bind();
      this.iconWidth = iconTexture.getWidth();
      this.iconHeight = iconTexture.getHeight();
      dc.getTextureCache().put(this.getIconFilePath(), iconTexture);
    } catch (IOException e) {
      String msg = Logging.getMessage("layers.IOExceptionDuringInitialization");
      Logging.logger().severe(msg);
      throw new WWRuntimeException(msg, e);
    }

    GL gl = dc.getGL();
    gl.glTexParameteri(
        GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR); // _MIPMAP_LINEAR);
    gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);
    gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE);
    gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE);
    // Enable texture anisotropy, improves "tilted" world map quality.
    int[] maxAnisotropy = new int[1];
    gl.glGetIntegerv(GL.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy, 0);
    gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy[0]);
  }
示例#27
0
  public static String getFeatureTypeName(String tableName) {
    if (tableName == null) {
      String message = Logging.getMessage("nullValue.StringIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    String suffix = WWIO.getSuffix(tableName);
    if (suffix == null) return null;

    suffix = "." + suffix;

    if (suffix.equalsIgnoreCase(VPFConstants.POINT_FEATURE_TABLE))
      return VPFConstants.POINT_FEATURE_TYPE;
    else if (suffix.equalsIgnoreCase(VPFConstants.LINE_FEATURE_TABLE))
      return VPFConstants.LINE_FEATURE_TYPE;
    else if (suffix.equalsIgnoreCase(VPFConstants.AREA_FEATURE_TABLE))
      return VPFConstants.AREA_FEATURE_TYPE;
    else if (suffix.equalsIgnoreCase(VPFConstants.TEXT_FEATURE_TABLE))
      return VPFConstants.TEXT_FEATURE_TYPE;
    else if (suffix.equalsIgnoreCase(VPFConstants.COMPLEX_FEATURE_TABLE))
      return VPFConstants.COMPLEX_FEATURE_TYPE;

    return null;
  }
  @Override
  public boolean accept(File pathname) {
    String filename = null;
    if (null != pathname
        && pathname.isFile()
        && null != (filename = pathname.getName())
        && (filename.endsWith(".tiff")
            || filename.endsWith(".tif")
            || filename.endsWith(".gtif")
            || filename.endsWith(".gtiff"))) {
      try {
        GDALUtils gdal = GDALUtils.getGDAL();
        AVList params = gdal.info(this.mapSource.getName(), pathname);

        if (null != params
            && params.hasKey(AVKey.SECTOR)
            && params.hasKey(AVKey.WIDTH)
            && params.hasKey(AVKey.HEIGHT)
            && params.hasKey(AVKey.LAYER_NAME)) {
          params.setValue(AVKey.SERVICE_NAME, SingleFileImageLayer.class);

          AVListMapSource ms = new AVListMapSource(this.mapSource, params);

          this.mapSource.addChild(ms);

          //                    WMSServer.getMapSourceRegistry().add( ms );

          Logging.logger().finest("Added --> " + pathname.getAbsolutePath());
        }
      } catch (Exception ex) {
        Logging.logger().log(java.util.logging.Level.SEVERE, ex.getMessage(), ex);
      }
    }
    return false;
  }
  protected void readFromBuffer(DBaseFile dbaseFile, ByteBuffer buffer) {
    buffer.order(ByteOrder.LITTLE_ENDIAN);

    int pos = buffer.position();

    byte[] bytes = new byte[FIELD_NAME_LENGTH];
    int numRead = dbaseFile.readZeroTerminatedString(buffer, bytes, FIELD_NAME_LENGTH);
    this.name = dbaseFile.decodeString(bytes, numRead);

    char type = (char) buffer.get();
    this.type = getFieldType(type);
    if (this.type == null) {
      String message = Logging.getMessage("SHP.UnsupportedDBaseFieldType", type);
      Logging.logger().log(java.util.logging.Level.SEVERE, message);
      throw new WWRuntimeException(message);
    }

    // Skip four bytes
    buffer.getInt();

    this.length = 0xff & buffer.get(); // unsigned
    this.decimals = 0xff & buffer.get();

    buffer.position(pos + DBaseFile.FIELD_DESCRIPTOR_LENGTH); // move to next field
  }
  /**
   * @param fileName the name to give the newly created file
   * @return a handle to the newly created file if it could be created and added to the file store,
   *     otherwise null
   * @throws IllegalArgumentException if <code>fileName</code> is null
   */
  public java.io.File newFile(String fileName) {
    if (fileName == null) {
      String message = Logging.getMessage("nullValue.FilePathIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    if (this.writeLocation != null) {
      String fullPath = makeAbsolutePath(this.writeLocation.getFile(), fileName);
      java.io.File file = new java.io.File(fullPath);
      boolean canCreateFile = false;

      // This block of code must be synchronized for proper operation. A thread may check that
      // file.getParentFile() does not exist, and become immediately suspended. A second thread may
      // then create
      // the parent and ancestor directories. When the first thread wakes up,
      // file.getParentFile().mkdirs()
      // fails, resulting in an erroneous log message: The log reports that the file cannot be
      // created.
      synchronized (this.fileLock) {
        if (file.getParentFile().exists()) canCreateFile = true;
        else if (file.getParentFile().mkdirs()) canCreateFile = true;
      }

      if (canCreateFile) return file;
      else {
        String msg = Logging.getMessage("generic.CannotCreateFile", fullPath);
        Logging.logger().severe(msg);
      }
    }

    return null;
  }