示例#1
0
  public void testCropRectangle() throws Exception {
    final Envelope rasterEnvelope = geoRasterSrc.getMetadata().getEnvelope();
    geoRasterSrc.save(tmpData + "1.tif");
    final int buffer = (int) (rasterEnvelope.getWidth() / 2.3);
    final Rectangle2D cropRectangle =
        new Rectangle2D.Double(
            rasterEnvelope.getMinX() + buffer,
            rasterEnvelope.getMinY() + buffer,
            rasterEnvelope.getWidth() - 2 * buffer,
            rasterEnvelope.getHeight() - 2 * buffer);
    geoRasterDst = geoRasterSrc.doOperation(new Crop(cropRectangle));
    geoRasterDst.save(tmpData + "2.tif");

    assertTrue(geoRasterDst.getWidth() > 0);
    assertTrue(geoRasterDst.getHeight() > 0);

    final ImagePlus srcImagePlus = geoRasterSrc.getImagePlus();
    final ImagePlus dstImagePlus = geoRasterDst.getImagePlus();
    RasterMetadata dstMetadata = geoRasterDst.getMetadata();
    RasterMetadata srcMetadata = geoRasterSrc.getMetadata();
    assertTrue(dstMetadata.getEnvelope().getMinX() < cropRectangle.getMinX());
    assertTrue(dstMetadata.getEnvelope().getMinY() < cropRectangle.getMinY());
    assertTrue(dstMetadata.getEnvelope().getMaxX() > cropRectangle.getMaxX());
    assertTrue(dstMetadata.getEnvelope().getMaxY() > cropRectangle.getMaxY());
    assertTrue(dstMetadata.getEnvelope().getWidth() < srcMetadata.getEnvelope().getWidth());
    checkCrop(geoRasterDst.getMetadata().getEnvelope(), srcImagePlus, dstImagePlus);
  }
 private Envelope getMetaTileEnvelope(
     GetMapRequest request, Point tileCoords, Point metaTileCoords) {
   Envelope bbox = request.getBbox();
   double minx = bbox.getMinX() + (metaTileCoords.x - tileCoords.x) * bbox.getWidth();
   double miny = bbox.getMinY() + (metaTileCoords.y - tileCoords.y) * bbox.getHeight();
   double maxx = minx + bbox.getWidth() * 3;
   double maxy = miny + bbox.getHeight() * 3;
   return new Envelope(minx, maxx, miny, maxy);
 }
  /**
   * Given an envelope and origin, find the tile coordinate (row,col)
   *
   * @param env
   * @param origin
   * @return
   */
  Point getTileCoordinates(Envelope env, Point2D origin) {
    // this was using the low left corner and Math.round, but turned
    // out to be fragile when fairly zoomed in. Using the tile center
    // and then flooring the division seems to work much more reliably.
    double centerx = env.getMinX() + env.getWidth() / 2;
    double centery = env.getMinY() + env.getHeight() / 2;
    int x = (int) Math.floor((centerx - origin.getX()) / env.getWidth());
    int y = (int) Math.floor((centery - origin.getY()) / env.getWidth());

    return new Point(x, y);
  }
示例#4
0
  /** @throws RuntimeException */
  private void calculateAffineTransform() {
    if (extent == null) {
      return;
    } else if (image == null || getWidth() == 0 || getHeight() == 0) {
      return;
    }

    if (adjustExtent) {
      double escalaX = getWidth() / extent.getWidth();
      double escalaY = getHeight() / extent.getHeight();

      double xCenter = extent.getMinX() + extent.getWidth() / 2.0;
      double yCenter = extent.getMinY() + extent.getHeight() / 2.0;
      adjustedExtent = new Envelope();

      double scale;
      if (escalaX < escalaY) {
        scale = escalaX;
        double newHeight = getHeight() / scale;
        double newX = xCenter - (extent.getWidth() / 2.0);
        double newY = yCenter - (newHeight / 2.0);
        adjustedExtent = new Envelope(newX, newX + extent.getWidth(), newY, newY + newHeight);
      } else {
        scale = escalaY;
        double newWidth = getWidth() / scale;
        double newX = xCenter - (newWidth / 2.0);
        double newY = yCenter - (extent.getHeight() / 2.0);
        adjustedExtent = new Envelope(newX, newX + newWidth, newY, newY + extent.getHeight());
      }

      trans.setToIdentity();
      trans.concatenate(AffineTransform.getScaleInstance(scale, -scale));
      trans.concatenate(
          AffineTransform.getTranslateInstance(
              -adjustedExtent.getMinX(), -adjustedExtent.getMinY() - adjustedExtent.getHeight()));
    } else {
      adjustedExtent = new Envelope(extent);
      trans.setToIdentity();
      double scaleX = getWidth() / extent.getWidth();
      double scaleY = getHeight() / extent.getHeight();

      /** Map Y axis grows downward but CRS grows upward => -1 */
      trans.concatenate(AffineTransform.getScaleInstance(scaleX, -scaleY));
      trans.concatenate(
          AffineTransform.getTranslateInstance(
              -extent.getMinX(), -extent.getMinY() - extent.getHeight()));
    }
    try {
      transInv = trans.createInverse();
    } catch (NoninvertibleTransformException ex) {
      transInv = null;
      throw new RuntimeException(ex);
    }
  }
  /**
   * This adjusts the bounds by zooming out 2%, but also ensuring that the maximum bounds do not
   * exceed the world bounding box
   *
   * <p>This only applies if the SRS is EPSG:4326 or EPSG:900913
   *
   * @param reqSRS the SRS
   * @param bbox the current bounding box
   * @return the adjusted bounding box
   */
  private static Envelope adjustBounds(String reqSRS, Envelope bbox) {
    if (reqSRS.equalsIgnoreCase("EPSG:4326")) {
      bbox.expandBy(bbox.getWidth() / 100, bbox.getHeight() / 100);
      Envelope maxEnv = new Envelope(-180.0, -90.0, 180.0, 90.0);
      return bbox.intersection(maxEnv);

    } else if (reqSRS.equalsIgnoreCase("EPSG:900913")) {
      bbox.expandBy(bbox.getWidth() / 100, bbox.getHeight() / 100);
      Envelope maxEnv = new Envelope(-20037508.33, -20037508.33, 20037508.33, 20037508.33);
      return bbox.intersection(maxEnv);
    }
    return bbox;
  }
示例#6
0
 /**
  * Gets the scale denominator. If the scale is 1:1000 this method returns 1000. The scale is not
  * absolutely precise and errors of 2% have been measured.
  *
  * @return
  */
 public double getScaleDenominator() {
   if (adjustedExtent.isNull()) {
     return 0;
   } else {
     return adjustedExtent.getWidth() / getImageMeters();
   }
 }
  public static double diagonalSize(Envelope env) {
    if (env.isNull()) return 0.0;

    double width = env.getWidth();
    double hgt = env.getHeight();
    return Math.sqrt(width * width + hgt * hgt);
  }
 /**
  * Ajusta el tamaño de la ventana al envelope pasado como parámetro
  *
  * @param ctx
  * @param newWrapperEnvelope
  * @param viewport
  */
 public static void resizeViewToEnvelope(
     PlugInContext ctx, Envelope newWrapperEnvelope, IViewport viewport) {
   // ajustamos las proporciones de la ventana a las de la feature
   JInternalFrame activeInternalFrame = ctx.getActiveInternalFrame();
   Dimension dimView = ((Dimension) ctx.getLayerViewPanel()).getSize();
   Double widthView = dimView.getWidth();
   Double heightView = dimView.getHeight();
   int widthDiff = (int) (activeInternalFrame.getWidth() - widthView);
   int heightDiff = (int) (activeInternalFrame.getHeight() - heightView);
   Integer newWidth =
       (int)
           ((newWrapperEnvelope.getWidth() / viewport.getEnvelopeInModelCoordinates().getWidth())
               * widthView);
   Integer newHeight =
       (int)
           ((newWrapperEnvelope.getHeight() / viewport.getEnvelopeInModelCoordinates().getHeight())
               * heightView);
   Dimension newDimensionView = new Dimension(newWidth + widthDiff, newHeight + heightDiff);
   activeInternalFrame.setSize(newDimensionView);
   // zoom al envelope actual
   try {
     viewport.zoom(newWrapperEnvelope);
   } catch (NoninvertibleTransformException e) {
     log.warn("No se ha podido alcanzar el zoom " + newWrapperEnvelope);
   }
 }
  /**
   * Creates a elliptical arc, as a LineString.
   *
   * @return an elliptical arc
   */
  public LineString createArc(double startAng, double endAng) {
    Envelope env = dim.getEnvelope();
    double xRadius = env.getWidth() / 2.0;
    double yRadius = env.getHeight() / 2.0;

    double centreX = env.getMinX() + xRadius;
    double centreY = env.getMinY() + yRadius;

    double angSize = (endAng - startAng);
    if (angSize <= 0.0 || angSize > 2 * Math.PI) angSize = 2 * Math.PI;
    double angInc = angSize / nPts;

    Coordinate[] pts = new Coordinate[nPts];
    int iPt = 0;
    for (int i = 0; i < nPts; i++) {
      double ang = startAng + i * angInc;
      double x = xRadius * Math.cos(ang) + centreX;
      double y = yRadius * Math.sin(ang) + centreY;
      Coordinate pt = new Coordinate(x, y);
      geomFact.getPrecisionModel().makePrecise(pt);
      pts[iPt++] = pt;
    }
    LineString line = geomFact.createLineString(pts);
    return line;
  }
 private void addEnv(@Nullable Bounded node) {
   if (node == null) {
     return;
   }
   Envelope env = envBuff;
   env.setToNull();
   node.expand(env);
   if (env.isNull()) {
     return;
   }
   if (isPoint(env)) {
     points.add(env.getMinX(), env.getMinY());
   } else if (isOrthoLine(env)) {
     // handle the case where the envelope is given by an orthogonal line so we don't add a
     // zero area polygon
     double width = env.getWidth();
     GrowableCoordinateSequence cs = new GrowableCoordinateSequence();
     if (width == 0D) {
       cs.add(env.getMinX(), env.getMinY());
       cs.add(env.getMinX(), env.getMaxY());
     } else {
       cs.add(env.getMinX(), env.getMinY());
       cs.add(env.getMaxX(), env.getMinY());
     }
     nonPoints.add(GEOM_FACTORY.createLineString(cs));
   } else {
     nonPoints.add(JTS.toGeometry(env, GEOM_FACTORY));
   }
 }
 void matchAspect() {
   /* Basic sinusoidal projection of lat/lon data to square pixels */
   double yCenter = modelBounds.centre().y;
   float xScale = cos(radians((float) yCenter));
   double newX =
       modelBounds.getHeight() * (1 / xScale) * ((float) this.getWidth() / this.getHeight());
   modelBounds.expandBy((newX - modelBounds.getWidth()) / 2f, 0);
 }
示例#12
0
 /** Compute the parameters need to create each cells */
 private void initParameters() {
   this.minX = envelope.getMinX();
   this.minY = envelope.getMinY();
   double cellWidth = envelope.getWidth();
   double cellHeight = envelope.getHeight();
   this.maxI = (int) Math.ceil(cellWidth / deltaX);
   this.maxJ = (int) Math.ceil(cellHeight / deltaY);
 }
示例#13
0
 public void testProducedRasterEnvelope() throws Exception {
   DataSource ds = dsf.getDataSource("raster");
   ds.open();
   SpatialDataSourceDecorator sds = new SpatialDataSourceDecorator(ds);
   Envelope env = sds.getFullExtent();
   assertTrue(env.getWidth() > 0);
   assertTrue(env.getHeight() > 0);
   ds.close();
 }
  protected Shape getShape() {
    if (zoomBoxEnd == null) return null;

    Envelope envModel = getEnvelope();

    Point2D base = toView(new Coordinate(envModel.getMinX(), envModel.getMaxY()));
    double width = toView(envModel.getWidth());
    double height = toView(envModel.getHeight());
    return new Rectangle2D.Double(base.getX(), base.getY(), width, height);
  }
示例#15
0
  /**
   * @param li ImageLevelInfo object
   * @param con JDBC Connection
   * @return the resolution for li, based on a random chosen tile
   * @throws SQLException
   * @throws IOException
   */
  protected double[] getPixelResolution(ImageLevelInfo li, Connection con)
      throws SQLException, IOException {
    double[] result = null;
    String statementString = getRandomTileStatement(li);
    PreparedStatement s = con.prepareStatement(statementString);
    ResultSet r = s.executeQuery();

    while (r.next()) {
      byte[] tileBytes = getTileBytes(r);

      if (tileBytes == null) {
        continue;
      }

      BufferedImage buffImage = null;
      li.setCanImageIOReadFromInputStream(true);
      try {
        buffImage = ImageIO.read(new ByteArrayInputStream(tileBytes));
      } catch (IOException e) {
      }

      if (buffImage == null) {
        if (LOGGER.isLoggable(Level.WARNING)) {
          LOGGER.warning(
              "Image IO cannot read from ByteInputStream,use less efficient jai methods");
        }
        li.setCanImageIOReadFromInputStream(false);
        SeekableStream stream = new ByteArraySeekableStream(tileBytes);
        String decoderName = null;

        for (String dn : ImageCodec.getDecoderNames(stream)) {
          decoderName = dn;
          break;
        }

        ImageDecoder decoder = ImageCodec.createImageDecoder(decoderName, stream, null);
        PlanarImage img = PlanarImage.wrapRenderedImage(decoder.decodeAsRenderedImage());
        buffImage = img.getAsBufferedImage();
      }

      Envelope env = getEnvelopeFromResultSet(r);

      result =
          new double[] {
            env.getWidth() / buffImage.getWidth(), env.getHeight() / buffImage.getHeight()
          };

      break;
    }

    r.close();
    s.close();

    return result;
  }
 public void highlightVertex(Vertex v) {
   Coordinate c = v.getCoordinate();
   double xd = 0, yd = 0;
   while (!modelBounds.contains(c)) {
     xd = modelBounds.getWidth() / 100;
     yd = modelBounds.getHeight() / 100;
     modelBounds.expandBy(xd, yd);
   }
   modelBounds.expandBy(xd, yd);
   highlightedVertex = v;
   drawLevel = DRAW_ALL;
 }
 /*
  * Zoom in/out. Translate the viewing window such that the place under the mouse pointer is a fixed point. If p is null, zoom around the center of
  * the viewport.
  */
 void zoom(double f, Point p) {
   double ex = modelBounds.getWidth() * f;
   double ey = modelBounds.getHeight() * f;
   modelBounds.expandBy(ex / 2, ey / 2);
   if (p != null) {
     // Note: Graphics Y coordinates increase down the screen, hence the opposite signs.
     double tx = ex * -((p.getX() / this.width) - 0.5);
     double ty = ey * +((p.getY() / this.height) - 0.5);
     modelBounds.translate(tx, ty);
   }
   // update the display
   drawLevel = DRAW_PARTIAL;
 }
示例#18
0
  public static int findZoomLevel(Envelope extent) {
    double resolution = Math.max(extent.getWidth() / 256d, extent.getHeight() / 256d);

    int i;

    for (i = 1; i < TILE_RESOLUTIONS.length; i++) {
      if (resolution > TILE_RESOLUTIONS[i]) {
        i--;
        break;
      }
    }

    return i;
  }
  /**
   * Determines the dimensions of the image to request, usually 1:1 to display, but sometimes more
   * (too fuzzy) or less (image too large) when reprojecting.
   *
   * @param maxDimensions TODO
   * @param viewport
   * @param request
   * @param context
   * @return
   * @throws RenderException
   */
  public static Dimension calculateImageDimensions(
      Dimension displaySize, Dimension maxDimensions, Envelope viewport, Envelope request)
      throws RenderException {
    double xScale = request.getWidth() / viewport.getWidth();
    double yScale = request.getHeight() / viewport.getHeight();
    // TODO: adjust height and width when we are reprojecting to make things less fuzzy

    int width = (int) (xScale * displaySize.getWidth());
    int height = (int) (yScale * displaySize.getHeight());

    // ensure we don't exceed the dimensions the server will allow
    int maxWidth = (int) maxDimensions.getWidth();
    if ((maxWidth > 0) && (width > maxWidth)) {
      width = maxWidth;
    }
    int maxHeight = (int) maxDimensions.getHeight();
    if ((maxHeight > 0) && (height > maxHeight)) {
      height = maxHeight;
    }

    WMSPlugin.trace(
        "WMS request image dimensions: " + width + ", " + height); // $NON-NLS-1$ //$NON-NLS-2$
    return new Dimension(width, height);
  }
示例#20
0
 /**
  * @param geom
  * @param seq
  */
 private boolean decimateOnEnvelope(Geometry geom, LiteCoordinateSequence seq) {
   Envelope env = geom.getEnvelopeInternal();
   if (env.getWidth() <= spanx && env.getHeight() <= spany) {
     double[] coords = seq.getArray();
     int dim = seq.getDimension();
     double[] newcoords = new double[dim * 2];
     for (int i = 0; i < dim; i++) {
       newcoords[i] = coords[i];
       newcoords[dim + i] = coords[coords.length - dim + i];
     }
     seq.setArray(coords);
     return true;
   }
   return false;
 }
  /**
   * Given a tiled request, builds a key that can be used to access the cache looking for a specific
   * meta-tile, and also as a synchronization tool to avoid multiple requests to trigger parallel
   * computation of the same meta-tile
   *
   * @param request
   * @return
   */
  public MetaTileKey getMetaTileKey(GetMapRequest request) {
    String mapDefinition = buildMapDefinition(request.getHttpServletRequest());
    Envelope bbox = request.getBbox();
    Point2D origin = request.getTilesOrigin();
    MapKey mapKey =
        new MapKey(mapDefinition, normalize(bbox.getWidth() / request.getWidth()), origin);
    Point tileCoords = getTileCoordinates(bbox, origin);
    Point metaTileCoords = getMetaTileCoordinates(tileCoords);
    Envelope metaTileEnvelope = getMetaTileEnvelope(request, tileCoords, metaTileCoords);
    MetaTileKey key = new MetaTileKey(mapKey, metaTileCoords, metaTileEnvelope);

    // since this will be used for thread synchronization, we have to make
    // sure two thread asking for the same meta tile will get the same key
    // object
    return (MetaTileKey) metaTileKeys.unique(key);
  }
示例#22
0
  public void testCropAll() throws Exception {
    final Envelope rasterEnvelope = geoRasterSrc.getMetadata().getEnvelope();
    final Rectangle2D cropRectangle =
        new Rectangle2D.Double(
            rasterEnvelope.getMinX(),
            rasterEnvelope.getMinY(),
            rasterEnvelope.getWidth(),
            rasterEnvelope.getHeight());
    geoRasterDst = geoRasterSrc.doOperation(new Crop(cropRectangle));

    assertTrue(geoRasterDst.getWidth() > 0);
    assertTrue(geoRasterDst.getHeight() > 0);

    RasterMetadata dstMetadata = geoRasterDst.getMetadata();
    RasterMetadata srcMetadata = geoRasterSrc.getMetadata();
    assertTrue(dstMetadata.equals(srcMetadata));
  }
  private void displayCopiedFeatures(Envelope env) {
    if (!getMap().getViewportModel().getBounds().intersects(env) && !env.isNull()
        || tooSmallOnScreen(env)) {

      double d = env.getHeight() / 2;
      double e = env.getWidth() / 2;

      ViewportModel viewportModel = getMap().getViewportModelInternal();
      viewportModel.eSetDeliver(false);
      try {
        viewportModel.setBounds(
            env.getMinX() - e, env.getMaxX() + e,
            env.getMinY() - d, env.getMaxY() + d);
      } finally {
        viewportModel.eSetDeliver(true);
      }
    }
  }
示例#24
0
 public void fit() throws Exception {
   MapContent generalMapContext = getGeneralMapContext();
   Dimension size = getSize();
   Envelope projectedBounds = generalMapContext.getMaxBounds();
   double destWidth = projectedBounds.getWidth();
   double destHeight = projectedBounds.getHeight();
   Coordinate centre = projectedBounds.centre();
   Point2D.Double screenLT = awtScreen2Cartesian(new Point(0, 0));
   Point2D.Double screenBR = awtScreen2Cartesian(new Point(size.width, size.height));
   double srcWidth = screenBR.x - screenLT.x;
   double srcHeight = screenBR.y - screenLT.y;
   double sx = srcWidth / destWidth;
   double sy = srcHeight / destHeight;
   double coef = Math.min(sx, sy);
   coef = snapScale(coef);
   scaleView(coef, coef, false);
   Point2D.Double projectedScreenCenter = screen2Cartesian(new Point(0, 0));
   translateView(projectedScreenCenter.x - centre.x, projectedScreenCenter.y - centre.y, true);
   repaint();
 }
 public void mouseDragged(MouseEvent e) {
   Point c = e.getPoint();
   if (startDrag == null) {
     startDrag = c;
     dragX = c.x;
     dragY = c.y;
   }
   double dx = dragX - c.x;
   double dy = c.y - dragY;
   if (ctrlPressed || mouseButton == RIGHT) {
     zoom(dy * 0.01, startDrag);
   } else {
     double tx = modelBounds.getWidth() * dx / getWidth();
     double ty = modelBounds.getHeight() * dy / getHeight();
     modelBounds.translate(tx, ty);
   }
   dragX = c.x;
   dragY = c.y;
   drawLevel = DRAW_PARTIAL;
 }
示例#26
0
 /**
  * Sets the extent of the transformation. This extent is not used directly to calculate the
  * transformation but is adjusted to obtain an extent with the same ratio than the image
  *
  * @param newExtent The new base extent.
  */
 public void setExtent(Envelope newExtent) {
   if ((newExtent != null) && ((newExtent.getWidth() == 0) || (newExtent.getHeight() == 0))) {
     newExtent.expandBy(10);
   }
   Envelope oldExtent = this.extent;
   boolean modified = true;
   /* Set extent when Envelope is modified */
   if (extent != null) {
     if (extent.equals(newExtent)) {
       modified = false;
     }
   }
   if (modified) {
     this.extent = newExtent;
     calculateAffineTransform();
     for (TransformListener listener : listeners) {
       listener.extentChanged(oldExtent, this);
     }
   }
 }
示例#27
0
  public void testCropPolygon() throws Exception {
    Envelope rasterEnvelope = geoRasterSrc.getMetadata().getEnvelope();
    final int bufferSize = (int) (rasterEnvelope.getWidth() / 2.3);
    rasterEnvelope =
        new Envelope(
            new Coordinate(
                rasterEnvelope.getMinX() + bufferSize, rasterEnvelope.getMinY() + bufferSize),
            new Coordinate(
                rasterEnvelope.getMaxX() - bufferSize, rasterEnvelope.getMaxY() - bufferSize));
    final LinearRing polygon = (LinearRing) EnvelopeUtil.toGeometry(rasterEnvelope);
    geoRasterSrc.save(tmpData + "1.tif");
    geoRasterDst = geoRasterSrc.doOperation(new Crop(polygon));
    geoRasterDst.save(tmpData + "2.png");

    assertTrue(geoRasterDst.getWidth() > 0);
    assertTrue(geoRasterDst.getHeight() > 0);

    final ImagePlus srcImagePlus = geoRasterSrc.getImagePlus();
    final ImagePlus dstImagePlus = geoRasterDst.getImagePlus();
    checkCrop(geoRasterDst.getMetadata().getEnvelope(), srcImagePlus, dstImagePlus);
  }
  /**
   * Creates a circular {@link Polygon}.
   *
   * @return a circle
   */
  public Polygon createCircle() {

    Envelope env = dim.getEnvelope();
    double xRadius = env.getWidth() / 2.0;
    double yRadius = env.getHeight() / 2.0;

    double centreX = env.getMinX() + xRadius;
    double centreY = env.getMinY() + yRadius;

    Coordinate[] pts = new Coordinate[nPts + 1];
    int iPt = 0;
    for (int i = 0; i < nPts; i++) {
      double ang = i * (2 * Math.PI / nPts);
      double x = xRadius * Math.cos(ang) + centreX;
      double y = yRadius * Math.sin(ang) + centreY;
      Coordinate pt = new Coordinate(x, y);
      pts[iPt++] = pt;
    }
    pts[iPt] = pts[0];

    LinearRing ring = geomFact.createLinearRing(pts);
    Polygon poly = geomFact.createPolygon(ring, null);
    return poly;
  }
示例#29
0
  public static Envelope expandToTile(Envelope extent) {
    double resolution = Math.max(extent.getWidth() / 256d, extent.getHeight() / 256d);

    int i = findZoomLevel(extent);

    while (i > 0) {
      resolution = TILE_RESOLUTIONS[i];

      double tilelon = resolution * 256;
      double tilelat = resolution * 256;

      double lon0 = extent.getMinX() - WORLD_BOUNDS_WGS84.getMinX();
      double lon1 = extent.getMaxX() - WORLD_BOUNDS_WGS84.getMinX();

      int col0 = (int) Math.floor(lon0 / tilelon);
      int col1 = (int) Math.floor((lon1 / tilelon) - 1E-9);

      double lat0 = extent.getMinY() - WORLD_BOUNDS_WGS84.getMinY();
      double lat1 = extent.getMaxY() - WORLD_BOUNDS_WGS84.getMinY();

      int row0 = (int) Math.floor(lat0 / tilelat);
      int row1 = (int) Math.floor((lat1 / tilelat) - 1E-9);

      if ((col0 == col1) && (row0 == row1)) {
        double tileoffsetlon = WORLD_BOUNDS_WGS84.getMinX() + (col0 * tilelon);
        double tileoffsetlat = WORLD_BOUNDS_WGS84.getMinY() + (row0 * tilelat);

        return new Envelope(
            tileoffsetlon, tileoffsetlon + tilelon, tileoffsetlat, tileoffsetlat + tilelat);
      } else {
        i--;
      }
    }

    return WORLD_BOUNDS_WGS84;
  }
示例#30
0
  /*
   * (non-Javadoc)
   *
   * @see org.geotools.gce.imagemosaic.jdbc.JDBCAccess#startTileDecoders(java.awt.Rectangle,
   *      org.geotools.geometry.GeneralEnvelope,
   *      org.geotools.gce.imagemosaic.jdbc.ImageLevelInfo,
   *      java.util.concurrent.LinkedBlockingQueue)
   */
  public void startTileDecoders(
      Rectangle pixelDimension,
      GeneralEnvelope requestEnvelope,
      ImageLevelInfo levelInfo,
      LinkedBlockingQueue<TileQueueElement> tileQueue,
      GridCoverageFactory coverageFactory)
      throws IOException {
    Date start = new Date();
    Connection con = null;
    List<ImageDecoderThread> threads = new ArrayList<ImageDecoderThread>();
    ExecutorService pool = getExecutorServivicePool();

    String statementString = getGridSelectStatement(levelInfo);

    try {
      con = dataSource.getConnection();

      PreparedStatement s = con.prepareStatement(statementString);
      setGridSelectParams(s, requestEnvelope, levelInfo);

      ResultSet r = s.executeQuery();

      while (r.next()) {
        byte[] tileBytes = getTileBytes(r);
        Envelope env = getEnvelopeFromResultSet(r);
        String location = r.getString(config.getKeyAttributeNameInSpatialTable());

        Rectangle2D tmp =
            new Rectangle2D.Double(env.getMinX(), env.getMinY(), env.getWidth(), env.getHeight());
        GeneralEnvelope tileGeneralEnvelope = new GeneralEnvelope(tmp);
        tileGeneralEnvelope.setCoordinateReferenceSystem(
            requestEnvelope.getCoordinateReferenceSystem());

        ImageDecoderThread thread =
            new ImageDecoderThread(
                tileBytes,
                location,
                tileGeneralEnvelope,
                pixelDimension,
                requestEnvelope,
                levelInfo,
                tileQueue,
                config);
        //				thread.start();
        threads.add(thread);
        pool.execute(thread);
      }

      ;
      r.close();
      s.close();

      // if (con.getAutoCommit() == false) {
      // con.commit();
      // }

      con.close();
    } catch (SQLException e) {
      try {
        // if (con.getAutoCommit() == false) {
        // con.rollback();
        // }

        con.close();
      } catch (SQLException e1) {
      }

      LOGGER.log(Level.SEVERE, e.getMessage(), e);
      throw new IOException(e);
    }

    if (LOGGER.isLoggable(Level.INFO))
      LOGGER.info(
          "Getting "
              + threads.size()
              + " Tiles needs "
              + ((new Date()).getTime() - start.getTime())
              + " millisecs");

    // wait for all threads dto finish and write end marker
    pool.shutdown();
    try {
      pool.awaitTermination(3600, TimeUnit.SECONDS); // wait for one hour
    } catch (InterruptedException e) {
      throw new RuntimeException(e.getLocalizedMessage());
    }

    //		for (AbstractThread thread : threads) {
    //			try {
    //				thread.join();
    //			} catch (InterruptedException e) {
    //				throw new RuntimeException(e.getLocalizedMessage());
    //			}
    //		}

    tileQueue.add(TileQueueElement.ENDELEMENT);

    if (LOGGER.isLoggable(Level.INFO))
      LOGGER.info(
          "Getting and decoding  "
              + threads.size()
              + " Tiles needs "
              + ((new Date()).getTime() - start.getTime())
              + " millisecs");
  }