/** Include the provided envelope, expanding as necessary. */
  @Override
  public void expandToInclude(Envelope other) {
    if (other instanceof BoundingBox) {
      if (other.isNull()) {
        return;
      }

      BoundingBox bbox = (BoundingBox) other;
      ensureCompatibleReferenceSystem(bbox);

      expandToInclude(bbox.getLowerCorner());
      expandToInclude(bbox.getUpperCorner());
    } else {
      super.expandToInclude(other);
    }
  }
  /** @see org.geotools.data.FeatureStore#setFeatures(org.geotools.data.FeatureReader) */
  public void setFeatures(FeatureReader<SimpleFeatureType, SimpleFeature> reader)
      throws IOException {
    WFSTransactionState ts = null;

    if (trans == Transaction.AUTO_COMMIT) {
      ts = new WFSTransactionState(ds);
    } else {
      ts = (WFSTransactionState) trans.getState(ds);
    }

    ts.addAction(
        getSchema().getTypeName(), new DeleteAction(getSchema().getTypeName(), Filter.INCLUDE));

    ReferencedEnvelope bounds = null;
    while (reader.hasNext()) {

      try {
        SimpleFeature f = reader.next();
        List<AttributeDescriptor> atrs = f.getFeatureType().getAttributeDescriptors();
        for (int i = 0; i < atrs.size(); i++) {
          if (atrs.get(i) instanceof GeometryDescriptor) {
            Geometry g = (Geometry) f.getAttribute(i);
            CoordinateReferenceSystem cs =
                ((GeometryDescriptor) atrs.get(i)).getCoordinateReferenceSystem();
            if (cs != null && !cs.getIdentifiers().isEmpty())
              g.setUserData(cs.getIdentifiers().iterator().next().toString());
            if (g == null) continue;
            if (bounds == null) {
              bounds = new ReferencedEnvelope(g.getEnvelopeInternal(), cs);
            } else {
              bounds.expandToInclude(g.getEnvelopeInternal());
            }
          }
        }
        ts.addAction(getSchema().getTypeName(), new InsertAction(f));
      } catch (NoSuchElementException e) {
        WFS_1_0_0_DataStore.LOGGER.warning(e.toString());
      } catch (IllegalAttributeException e) {
        WFS_1_0_0_DataStore.LOGGER.warning(e.toString());
      }
    }

    // Fire a notification.
    // JE
    if (bounds == null) {
      // if bounds are null then send an envelope to say that features were added but
      // at an unknown location.
      bounds = new ReferencedEnvelope(getSchema().getCoordinateReferenceSystem());
      ((WFS_1_0_0_DataStore) getDataStore())
          .listenerManager.fireFeaturesRemoved(
              getSchema().getTypeName(), getTransaction(), bounds, false);
    } else {
      ((WFS_1_0_0_DataStore) getDataStore())
          .listenerManager.fireFeaturesRemoved(
              getSchema().getTypeName(), getTransaction(), bounds, false);
    }
    if (trans == Transaction.AUTO_COMMIT) {
      ts.commit();
    }
  }
 @Override
 public BoundingBox getBounds() {
   // Calculate bounds?
   //
   if (bounds == null) {
     //
     // Initialize bounds
     //
     bounds = new ReferencedEnvelope(getFeatureType().getCoordinateReferenceSystem());
     //
     // Loop over all geometries
     //
     for (EFeatureGeometry<Geometry> it : eInternal.getGeometryList(Geometry.class)) {
       if (!it.isEmpty()) {
         Geometry g = it.getValue();
         if (bounds.isNull()) {
           bounds.init(g.getEnvelopeInternal());
         } else {
           bounds.expandToInclude(g.getEnvelopeInternal());
         }
       }
     }
   }
   return bounds;
 }
  /**
   * @see org.geotools.data.FeatureStore#modifyFeatures(org.geotools.feature.AttributeType[],
   *     java.lang.Object[], org.geotools.filter.Filter)
   */
  public void modifyFeatures(Name[] names, Object[] value, Filter filter2) throws IOException {
    Filter filter = ds.processFilter(filter2);
    WFSTransactionState ts = null;

    if (trans == Transaction.AUTO_COMMIT) {
      ts = new WFSTransactionState(ds);
    } else {
      ts = (WFSTransactionState) trans.getState(ds);
    }

    Map<String, Object> props = new HashMap<String, Object>();

    ReferencedEnvelope bounds = null;
    for (int i = 0; i < names.length; i++) {
      if (names[i] instanceof GeometryDescriptor) {
        Geometry g = (Geometry) value[i];
        CoordinateReferenceSystem cs =
            ((GeometryDescriptor) names[i]).getCoordinateReferenceSystem();

        if (cs != null && !cs.getIdentifiers().isEmpty())
          g.setUserData(cs.getIdentifiers().iterator().next().toString());
        g.setUserData(cs.getIdentifiers().iterator().next().toString());
        if (cs != null && !cs.getIdentifiers().isEmpty())
          g.setUserData(cs.getIdentifiers().iterator().next().toString());
        // set/expand the bounds that are being changed.
        if (g == null) continue;
        if (bounds == null) {
          bounds = new ReferencedEnvelope(g.getEnvelopeInternal(), cs);
        } else {
          bounds.expandToInclude(g.getEnvelopeInternal());
        }
      }
      props.put(names[i].getLocalPart(), value[i]);
    }

    ts.addAction(
        getSchema().getTypeName(), new UpdateAction(getSchema().getTypeName(), filter, props));

    // Fire a notification.
    // JE
    if (bounds == null) {
      // if bounds are null then send an envelope to say that features were modified but
      // at an unknown location.
      bounds = new ReferencedEnvelope(getSchema().getCoordinateReferenceSystem());
      ((WFS_1_0_0_DataStore) getDataStore())
          .listenerManager.fireFeaturesRemoved(
              getSchema().getTypeName(), getTransaction(), bounds, false);
    } else {
      ((WFS_1_0_0_DataStore) getDataStore())
          .listenerManager.fireFeaturesRemoved(
              getSchema().getTypeName(), getTransaction(), bounds, false);
    }

    if (trans == Transaction.AUTO_COMMIT) {
      ts.commit();
    }
  }
  public ReferencedEnvelope getBounds() {
    FeatureReader<SimpleFeatureType, SimpleFeature> reader = null;
    try {
      ReferencedEnvelope result = featureSource.getBounds(query);
      if (result != null) {
        return result;
      }

      // ops, we have to compute the results by hand. Let's load just the
      // geometry attributes though
      Query q = new Query(query);
      List<String> geometries = new ArrayList<String>();
      for (AttributeDescriptor ad : getSchema().getAttributeDescriptors()) {
        if (ad instanceof GeometryDescriptor) {
          geometries.add(ad.getLocalName());
        }
      }
      // no geometries, no bounds
      if (geometries.size() == 0) {
        return new ReferencedEnvelope();
      } else {
        q.setPropertyNames(geometries);
      }
      // grab the features and scan through them
      reader = featureSource.getReader(q);
      while (reader.hasNext()) {
        SimpleFeature f = reader.next();
        ReferencedEnvelope featureBounds = ReferencedEnvelope.reference(f.getBounds());
        if (result == null) {
          result = featureBounds;
        } else if (featureBounds != null) {
          result.expandToInclude(featureBounds);
        }
      }
      // return the results if we got any, or return an empty one otherwise
      if (result != null) {
        return result;
      } else {
        return new ReferencedEnvelope(getSchema().getCoordinateReferenceSystem());
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException ex) {
          // we tried...
        }
      }
    }
  }
 /**
  * Gets the extent of the cadastre objects that are related with the baUnitId
  *
  * @param baUnitId
  */
 private ReferencedEnvelope getExtentOfCadastreObjectsOfBaUnit(String baUnitId) {
   List<CadastreObjectTO> cadastreObjects =
       this.getPojoDataAccess().getCadastreService().getCadastreObjectsByBaUnit(baUnitId);
   ReferencedEnvelope envelope = null;
   for (CadastreObjectTO cadastreObject : cadastreObjects) {
     Geometry geom = GeometryUtility.getGeometryFromWkb(cadastreObject.getGeomPolygon());
     ReferencedEnvelope tmpEnvelope = JTS.toEnvelope(geom);
     if (envelope == null) {
       envelope = tmpEnvelope;
     } else {
       envelope.expandToInclude(tmpEnvelope);
     }
   }
   return envelope;
 }
  ReferencedEnvelope toEnvelope(String xml) throws Exception {
    Parser p = new Parser(new OWSConfiguration());
    Object parsed = p.parse(new ByteArrayInputStream(xml.getBytes()));
    assertTrue(parsed instanceof BoundingBoxType);
    BoundingBoxType box = (BoundingBoxType) parsed;

    ReferencedEnvelope re;
    if (box.getCrs() != null) {
      re = new ReferencedEnvelope(CRS.decode(box.getCrs()));
    } else {
      re = new ReferencedEnvelope();
    }

    re.expandToInclude((Double) box.getLowerCorner().get(0), (Double) box.getLowerCorner().get(1));
    re.expandToInclude((Double) box.getUpperCorner().get(0), (Double) box.getUpperCorner().get(1));
    return re;
  }
Example #8
0
  @Override
  /**
   * Calculates the bounds of a specified query.
   *
   * @param query - the query to be applied.
   */
  protected ReferencedEnvelope getBoundsInternal(Query query) throws IOException {

    ReferencedEnvelope env = new ReferencedEnvelope(getSchema().getCoordinateReferenceSystem());
    if (lastQuery != query) filterFeatures(query);
    for (SimpleFeature feature : filteredFeatures) {

      Point p = (Point) feature.getDefaultGeometry();
      env.expandToInclude(p.getCoordinate());
    }

    return env;
  }
  public static ReferencedEnvelope getLayersBoundingBox(
      CoordinateReferenceSystem crs, List<Layer> layers, String version) {
    ReferencedEnvelope envelope = null;
    for (Layer layer : layers) {
      GeneralEnvelope temp = layer.getEnvelope(crs);
      if (temp != null) {
        ReferencedEnvelope jtsTemp = ReferencedEnvelope.reference(temp);
        //              if( version != null && version.startsWith("1.3")){
        //                  jtsTemp = swapAxis(jtsTemp);
        //              }
        if (envelope == null) {
          envelope = jtsTemp;
        } else {
          envelope.expandToInclude(jtsTemp);
        }
      }
    }

    return envelope;
  }
  private ReferencedEnvelope calcLayersBounds(
      Collection<ILayer> layers, CoordinateReferenceSystem crs, IProgressMonitor monitor)
      throws Exception {
    log.debug("### mapCRS: " + crs); // $NON-NLS-1$

    ReferencedEnvelope result = null; // new ReferencedEnvelope( crs );
    for (ILayer layer : layers) {
      try {
        IGeoResource res = layer.getGeoResource();
        if (res == null) {
          continue;
        }
        ReferencedEnvelope bbox =
            SetLayerBoundsOperation.obtainBoundsFromResources(layer, crs, monitor);
        if (!bbox.getCoordinateReferenceSystem().equals(crs)) {
          bbox = bbox.transform(crs, true);
        }
        log.debug("layer: " + layer + ", bbox= " + bbox); // $NON-NLS-1$ //$NON-NLS-2$

        if (result == null) {
          result = bbox;
        } else {
          result.expandToInclude(bbox);
        }
        log.debug("result: bbox=  " + result); // $NON-NLS-1$
      } catch (Exception e) {
        // XXX mark layers!?
        log.debug("", e); // $NON-NLS-1$
        log.warn(
            "skipping layer: " + layer.getLabel() + " (" + e.toString(),
            e); //$NON-NLS-1$ //$NON-NLS-2$
        layer.setLayerStatus(
            new LayerStatus(
                Status.WARNING,
                LayerStatus.UNSPECIFIED,
                Messages.get("LayerStatus_noCrs"),
                e)); //$NON-NLS-1$
      }
    }
    return result != null ? result : ReferencedEnvelope.EVERYTHING.transform(crs, true);
  }
  /** @param query */
  protected ReferencedEnvelope getBoundsInternal(Query query) {
    ReferencedEnvelope envelope =
        new ReferencedEnvelope(featureType.getCoordinateReferenceSystem());

    FeatureIterator<SimpleFeature> iterator = collection.features();
    try {
      if (iterator.hasNext()) {
        int count = 1;
        Filter filter = query.getFilter();

        while (iterator.hasNext() && (count < query.getMaxFeatures())) {
          SimpleFeature feature = iterator.next();
          if (filter.evaluate(feature)) {
            count++;
            envelope.expandToInclude(
                ((Geometry) feature.getDefaultGeometry()).getEnvelopeInternal());
          }
        }
      }
    } finally {
      iterator.close();
    }
    return envelope;
  }
 /**
  * Expand to include the provided DirectPosition
  *
  * @param pt
  */
 public void expandToInclude(DirectPosition pt) {
   Coordinate coordinate = new Coordinate(pt.getOrdinate(0), pt.getOrdinate(1));
   expandToInclude(coordinate);
 }
  public List<FeatureId> addFeatures(FeatureCollection<SimpleFeatureType, SimpleFeature> collection)
      throws IOException {
    WFSTransactionState ts = null;

    if (trans == Transaction.AUTO_COMMIT) {
      ts = new WFSTransactionState(ds);
    } else {
      ts = (WFSTransactionState) trans.getState(ds);
    }
    List<FeatureId> r = new LinkedList<FeatureId>();

    SimpleFeatureType schema = getSchema();

    LenientBuilder build = new LenientBuilder(schema);

    boolean isLenient = true;
    if (schema.getUserData().containsKey("lenient")) {
      isLenient = (Boolean) schema.getUserData().get("lenient");
    }

    if (isLenient) {
      build.setFeatureFactory(new LenientFeatureFactory());
    }

    List<AttributeDescriptor> atrs = schema.getAttributeDescriptors();
    FeatureIterator<SimpleFeature> iter = collection.features();
    try {
      ReferencedEnvelope bounds = null;

      while (iter.hasNext()) {
        try {
          SimpleFeature newFeature;
          try {
            SimpleFeature f = iter.next();

            String nextFid = ts.nextFid(schema.getTypeName());
            Object[] values = f.getAttributes().toArray();

            build.addAll(values);
            newFeature = build.buildFeature(nextFid);

            r.add(newFeature.getIdentifier());
          } catch (IllegalAttributeException e) {
            throw (IOException) new IOException(e.getLocalizedMessage());
          }

          for (int i = 0; i < atrs.size(); i++) {
            AttributeDescriptor att = atrs.get(i);
            if (att instanceof GeometryDescriptor) {
              Object geom = newFeature.getAttribute(i);
              if (geom instanceof Geometry) {
                Geometry g = (Geometry) geom;
                CoordinateReferenceSystem cs =
                    ((GeometryDescriptor) att).getCoordinateReferenceSystem();
                if (g == null) continue;
                if (cs != null && !cs.getIdentifiers().isEmpty())
                  g.setUserData(cs.getIdentifiers().iterator().next().toString());
                if (bounds == null) {
                  bounds =
                      new ReferencedEnvelope(
                          g.getEnvelopeInternal(), schema.getCoordinateReferenceSystem());
                } else {
                  bounds.expandToInclude(g.getEnvelopeInternal());
                }
              }
            }
          }
          ts.addAction(schema.getTypeName(), new InsertAction(newFeature));

        } catch (NoSuchElementException e) {
          WFS_1_0_0_DataStore.LOGGER.warning(e.toString());
          throw new IOException(e.toString());
        }
      }

      // Fire a notification.
      // JE
      if (bounds == null) {
        // if bounds are null then send an envelope to say that features were added but
        // at an unknown location.
        bounds = new ReferencedEnvelope(getSchema().getCoordinateReferenceSystem());
        ((WFS_1_0_0_DataStore) getDataStore())
            .listenerManager.fireFeaturesRemoved(
                schema.getTypeName(), getTransaction(), bounds, false);
      } else {
        ((WFS_1_0_0_DataStore) getDataStore())
            .listenerManager.fireFeaturesRemoved(
                schema.getTypeName(), getTransaction(), bounds, false);
      }

    } finally {
      iter.close();
    }
    if (trans == Transaction.AUTO_COMMIT) {
      ts.commit();

      String[] fids = ts.getFids(schema.getTypeName());
      int i = 0;
      for (String fid : fids) {
        FeatureId identifier = r.get(i);
        if (identifier instanceof FeatureIdImpl) {
          ((FeatureIdImpl) identifier).setID(fid);
        }
        i++;
      }
      return r;
    }
    return r;
  }
  @Execute
  public void process() throws Exception {
    checkNull(inPath, inServiceUrl, pEpsg, pMinzoom, pMaxzoom, pWest, pEast, pSouth, pNorth);

    CoordinateReferenceSystem boundsCrs = CRS.decode(pEpsg);
    CoordinateReferenceSystem mercatorCrs = CRS.decode(EPSG_MERCATOR);
    CoordinateReferenceSystem latLongCrs = CRS.decode(EPSG_LATLONG);

    ReferencedEnvelope inBounds = new ReferencedEnvelope(pWest, pEast, pSouth, pNorth, boundsCrs);

    MathTransform in2MercatorTransform = CRS.findMathTransform(boundsCrs, mercatorCrs);
    Envelope mercatorEnvelope = JTS.transform(inBounds, in2MercatorTransform);
    ReferencedEnvelope mercatorBounds = new ReferencedEnvelope(mercatorEnvelope, mercatorCrs);

    MathTransform transform = CRS.findMathTransform(boundsCrs, latLongCrs);
    Envelope latLongBounds = JTS.transform(inBounds, transform);
    Coordinate latLongCentre = latLongBounds.centre();

    File inFolder = new File(inPath);
    File baseFolder = new File(inFolder, pName);

    double w = latLongBounds.getMinX();
    double s = latLongBounds.getMinY();
    double e = latLongBounds.getMaxX();
    double n = latLongBounds.getMaxY();

    GlobalMercator mercator = new GlobalMercator();

    for (int z = pMinzoom; z <= pMaxzoom; z++) {

      // get ul and lr tile number in GOOGLE tiles
      int[] llTileXY = mercator.GoogleTile(s, w, z);
      int[] urTileXY = mercator.GoogleTile(n, e, z);

      int startXTile = Math.min(llTileXY[0], urTileXY[0]);
      int endXTile = Math.max(llTileXY[0], urTileXY[0]);
      int startYTile = Math.min(llTileXY[1], urTileXY[1]);
      int endYTile = Math.max(llTileXY[1], urTileXY[1]);

      int tileNum = 0;

      ReferencedEnvelope levelBounds = new ReferencedEnvelope();

      pm.beginTask("Generating tiles at zoom level: " + z, (endXTile - startXTile + 1));
      for (int i = startXTile; i <= endXTile; i++) {

        for (int j = startYTile; j <= endYTile; j++) {
          tileNum++;

          double[] bounds = mercator.TileLatLonBounds(i, j, z);
          double west = bounds[0];
          double south = bounds[1];
          double east = bounds[2];
          double north = bounds[3];

          ReferencedEnvelope tmpBounds =
              new ReferencedEnvelope(west, east, south, north, latLongCrs);
          levelBounds.expandToInclude(tmpBounds);

          if (!doDryrun) {
            int[] onlineTileNumbers = {i, j};
            int[] fileNameTileNumbers = {i, j};
            // switch( pType ) {
            // case 1:
            // need to convert in TMS format
            int[] tmsNUms = mercator.TMSTileFromGoogleTile(i, j, z);
            fileNameTileNumbers = tmsNUms;

            // break;
            // case 0:
            // default:
            // break;
            // }

            File imageFolder = new File(baseFolder, z + "/" + fileNameTileNumbers[0]);
            if (!imageFolder.exists()) {
              if (!imageFolder.mkdirs()) {
                throw new ModelsIOException("Unable to create folder:" + imageFolder, this);
              }
            }
            File imageFile = new File(imageFolder, fileNameTileNumbers[1] + ".png");
            if (imageFile.exists()) {
              continue;
            }

            String tmp = inServiceUrl.replaceFirst("ZZZ", String.valueOf(z));
            tmp = tmp.replaceFirst("XXX", String.valueOf(onlineTileNumbers[0]));
            tmp = tmp.replaceFirst("YYY", String.valueOf(onlineTileNumbers[1]));
            // System.out.println(tmp);

            URL url = new URL(tmp);
            InputStream imgStream = null;
            OutputStream out = null;
            try {
              imgStream = url.openStream();
              out = new FileOutputStream(imageFile);
              int read = 0;
              byte[] bytes = new byte[1024];
              while ((read = imgStream.read(bytes)) != -1) {
                out.write(bytes, 0, read);
              }
            } catch (Exception ex) {
              pm.errorMessage("Unable to get image: " + tmp);
            } finally {
              if (imgStream != null) imgStream.close();
              if (out != null) {
                out.flush();
                out.close();
              }
            }
          }
        }
        pm.worked(1);
      }
      pm.done();

      pm.message("Zoom level: " + z + " has " + tileNum + " tiles.");
      pm.message("Boundary covered at Zoom level: " + z + ": " + levelBounds);
      pm.message("Total boundary wanted: " + mercatorBounds);
    }

    StringBuilder properties = new StringBuilder();
    properties.append("url=").append(pName).append("/ZZZ/XXX/YYY.png\n");
    properties.append("minzoom=").append(pMinzoom).append("\n");
    properties.append("maxzoom=").append(pMaxzoom).append("\n");
    properties
        .append("center=")
        .append(latLongCentre.x)
        .append(" ")
        .append(latLongCentre.y)
        .append("\n");
    properties.append("type=tms").append("\n");

    File propFile = new File(inFolder, pName + ".mapurl");
    FileUtilities.writeFile(properties.toString(), propFile);
  }