public static void createGeom(List<Node> nodes) {
    StringBuilder wkt = new StringBuilder();
    for (Node node : nodes) wkt.append(node.lng + " " + node.lat + ", ");
    wkt.delete(wkt.length() - 2, wkt.length());

    wkt.insert(0, "POLYGON((");
    wkt.append("))");

    WKTReader wktreader = new WKTReader();
    Geometry geom = null;
    try {
      geom = wktreader.read(wkt.toString());
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    Polygon pol = (Polygon) geom;

    if (!pol.isValid()) {
      Geometry repaired = pol.buffer(0.0D);
      log.info("Invalid polygon detected. Is fixed? " + repaired.isValid());
      wkt = new StringBuilder(repaired.toText());
    }

    try {
      System.out.println(pol.contains(wktreader.read("POINT(82 25)")));
    } catch (ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  /**
   * @param dataStore
   * @param damageArea
   * @param target
   * @return
   * @throws IOException
   * @throws SQLException
   */
  public static Map<Integer, Double> calculateDamageValues(
      JDBCDataStore dataStore, Geometry damageArea, int target) throws IOException, SQLException {
    String wkt = damageArea.toText();
    DefaultTransaction transaction = new DefaultTransaction();
    Connection conn = null;
    Map<Integer, Double> damageValues = new HashMap<Integer, Double>();
    try {
      conn = dataStore.getConnection(transaction);

      if (FormulaUtils.isSimpleTarget(target)) {
        if (FormulaUtils.checkTarget(target, FormulaUtils.humanTargetsList)) {
          addDamageValuesByField(damageValues, conn, target + "", wkt);
        } else {
          addDamageValuesByArea(damageValues, conn, target + "", wkt);
        }

      } else if (FormulaUtils.isAllHumanTargets(target)) {
        addDamageValuesByField(damageValues, conn, FormulaUtils.humanTargetsList, wkt);
      } else if (FormulaUtils.isAllNotHumanTargets(target)) {
        addDamageValuesByArea(damageValues, conn, FormulaUtils.notHumanTargetsList, wkt);
      } else {
        addDamageValuesByField(damageValues, conn, FormulaUtils.humanTargetsList, wkt);
        addDamageValuesByArea(damageValues, conn, FormulaUtils.notHumanTargetsList, wkt);
      }

      return damageValues;
    } catch (SQLException e) {
      throw new ProcessException(e);
    } finally {
      transaction.close();
      if (conn != null) {
        conn.close();
      }
    }
  }
  /**
   * Analyze the feature list, and for those features that can suffer split operation, they'll be
   * split.
   *
   * @return The builder instance.
   * @throws SplitFeatureBuilderFailException if the operation fail
   * @throws CannotSplitException if the split line cannot divide the feature's geometry
   */
  public SplitFeatureBuilder buildSplit()
      throws SplitFeatureBuilderFailException, CannotSplitException {

    try {
      this.splitResultList = new LinkedList<SimpleFeature>();
      boolean existSplit = false;
      for (SimpleFeature feature : this.featureList) {

        Geometry geomToSplit = (Geometry) feature.getDefaultGeometry();
        assert geomToSplit.isValid() : "No Valid Geometry: " + geomToSplit.toText(); // $NON-NLS-1$
        CoordinateReferenceSystem featureCrs =
            feature.getFeatureType().getCoordinateReferenceSystem();
        geomToSplit = GeoToolsUtils.reproject(geomToSplit, featureCrs, this.desiredCRS);

        if (canSplit(geomToSplit)) {
          existSplit = true;
          this.featuresThatSufferedSplit.add(feature);

          List<Geometry> splitGeometriesResult = split(geomToSplit);
          this.splitResultList.addAll(createSplitFeatures(splitGeometriesResult, feature));
        }
      }
      if (!existSplit) {
        throw new CannotSplitException("The split line cannot split any features"); // $NON-NLS-1$
      }
    } catch (OperationNotFoundException e) {
      throw makeFailException(e);
    } catch (TransformException e) {
      throw makeFailException(e);
    }
    return this;
  }
  private void validate(final Geometry geom, final List<ValidationResult> validationErrors) {

    if (geom.isEmpty()) {
      return;
    }

    if (geom instanceof GeometryCollection) {
      final GeometryCollection gc = (GeometryCollection) geom;
      for (int numGeom = 0; numGeom < gc.getNumGeometries(); numGeom++) {
        validate(gc.getGeometryN(numGeom), validationErrors);
      }
    }

    final ValidationResult result = new ValidationResult();
    result.setWkt(geom.toText());
    final List<String> messages = new ArrayList<String>();

    if (!geom.isValid()) {
      messages.add("Error en topología básica");
    }

    if (!geom.isSimple()) {
      messages.add("No es una geometría simple");
    }

    if (repeatedPointTester.hasRepeatedPoint(geom)) {
      messages.add("Se encuentran vértices repetidos");
    }

    if (geom instanceof Polygon) {
      final Polygon polygon = (Polygon) geom;
      if (CGAlgorithms.isCCW(polygon.getExteriorRing().getCoordinates())) {
        messages.add("Error en orientación del polígono");
      } else {

        for (int numRing = 0; numRing < polygon.getNumInteriorRing(); numRing++) {
          if (!CGAlgorithms.isCCW(polygon.getInteriorRingN(numRing).getCoordinates())) {
            messages.add("Error en orientación del polígono en anillos interiores");
            break;
          }
        }
      }

      if (!validateMinPolygonArea(geom)) {
        messages.add("Error en validación mínima de area de un polígono");
      }
    }

    if (!validateMinSegmentLength(geom)) {
      messages.add("Error en validación mínima de longitud de segmento");
    }

    if (!messages.isEmpty()) {
      result.setMessages(messages);
      validationErrors.add(result);
    }
  }
 @Test
 public void testProyeccion() {
   GeometryFactory factory = new GeometryFactory();
   final String sourceSRID = "EPSG:4326";
   final String targetSRID = "EPSG:3395";
   Geometry geom = factory.createPoint(new Coordinate(42.349167d, 3.684722d));
   geom = MessageProcessor.transform(geom, sourceSRID, targetSRID);
   assertEquals(geom.toText(), "POINT (410181.3767547725 5184634.982024495)");
 }
  @Override
  public void serialize(Geometry value, JsonGenerator jgen, SerializerProvider provider)
      throws IOException {
    if (value == null) {
      provider.defaultSerializeNull(jgen);
      return;
    }

    // Todo support at least GeoJSON and WKT
    provider.defaultSerializeValue(value.toText(), jgen);
  }
  public Geometry createHullFromGeometry(
      Geometry clusterGeometry, Collection<Coordinate> additionalPoints, boolean fast) {

    if (additionalPoints.isEmpty()) return clusterGeometry;
    final Set<Coordinate> batchCoords = new HashSet<Coordinate>();

    for (final Coordinate coordinate : clusterGeometry.getCoordinates()) {
      batchCoords.add(coordinate);
    }
    for (final Coordinate coordinate : additionalPoints) {
      batchCoords.add(coordinate);
    }

    final Coordinate[] actualCoords = batchCoords.toArray(new Coordinate[batchCoords.size()]);

    if (batchCoords.size() == 2) {
      return clusterGeometry.getFactory().createLineString(actualCoords);
    }

    final ConvexHull convexHull = new ConvexHull(actualCoords, clusterGeometry.getFactory());

    final Geometry convexHullGeo = convexHull.getConvexHull();

    try {
      // does this shape benefit from concave hulling?
      // it cannot be a line string
      if (batchCoords.size() > 5 && convexHullGeo.getArea() > 0.0) {
        final Geometry concaveHull =
            fast
                ? concaveHull(convexHullGeo, batchCoords)
                : this.concaveHullParkOhMethod(convexHullGeo, batchCoords);
        if (!concaveHull.isSimple()) {
          LOGGER.warn("Produced non simple hull", concaveHull.toText());
          return convexHullGeo;
        }
        return concaveHull;
      } else {
        return convexHullGeo;
      }
    } catch (final Exception ex) {

      /*
       * Geometry[] points = new Geometry[actualCoords.length + 1]; for
       * (int i = 0; i < actualCoords.length; i++) points[i] =
       * hull.getFactory().createPoint( actualCoords[i]);
       * points[points.length - 1] = hull; try { ShapefileTool.writeShape(
       * "test_perf_xh", new File( "./targettest_perf_xh"), points); }
       * catch (IOException e) { e.printStackTrace(); }
       */
      LOGGER.error("Failed to compute hull", ex);

      return convexHullGeo;
    }
  }
  @Override
  public void encodeGeometryValue(Geometry value, int srid, StringBuffer sql) throws IOException {
    if (value == null || value.isEmpty()) {
      sql.append("NULL");
    } else {
      if (value instanceof LinearRing) {
        // postgis does not handle linear rings, convert to just a line string
        value = value.getFactory().createLineString(((LinearRing) value).getCoordinateSequence());
      }

      sql.append("ST_GeomFromText('" + value.toText() + "', " + srid + ")");
    }
  }
  /**
   * Build the graph using the given polygon and the split line.
   *
   * @return this builder
   */
  public SplitGraphBuilder build() {

    // after normalize() we know the shell is oriented CW and the holes CCW
    this.polygon.normalize();

    this.usefulSplitLineBuilder.build(this.polygon);
    Geometry utilSplitLine = this.usefulSplitLineBuilder.getResultSplitLine();
    AdaptedPolygon adaptedPolygon = this.usefulSplitLineBuilder.getAdaptedPolygon();

    LOGGER.fine("Adapted Polygon: " + adaptedPolygon.asPolygon().toText()); // $NON-NLS-1$
    LOGGER.fine("Util split line: " + utilSplitLine.toText()); // $NON-NLS-1$

    buildGraph(utilSplitLine, adaptedPolygon.asPolygon());

    return this;
  }
    // ~ Methods  ------------------------------------------------------------
    @Override
    protected Set<CidsBean> doInBackground() throws Exception {
      final FlurstueckSchluesselCustomBean currentKey =
          LagisBroker.getInstance().getCurrentFlurstueckSchluessel();
      if (currentKey != null) {
        Geometry flurstueckGeom = LagisBroker.getInstance().getInstance().getCurrentWFSGeometry();
        if (flurstueckGeom != null) {
          log.info(
              "Crossover: Geometrie zum bestimmen der Kassenzeichen (vor Transformation): "
                  + flurstueckGeom
                  + ",SRS"
                  + flurstueckGeom.getSRID());
          flurstueckGeom =
              CrsTransformer.transformToGivenCrs(flurstueckGeom, "EPSG:31466"); // Hardcoded FTW
          log.info(
              "Crossover: Geometrie zum bestimmen der Kassenzeichen: "
                  + flurstueckGeom
                  + ",SRS"
                  + flurstueckGeom.getSRID());

          //                    final KassenzeichenFacadeRemote verdisServer =
          // LagisBroker.getInstance().getVerdisServer();

          final String query =
              "SELECT 11, k.id\n"
                  + "FROM  kassenzeichen k, geom\n"
                  + "WHERE k.geometrie = geom.id\n"
                  + "AND not isEmpty(geom.geo_field)\n"
                  + "AND intersects(geom.geo_field,st_buffer(st_buffer(geometryfromtext('"
                  + flurstueckGeom.toText()
                  + "',31466), "
                  + LagisBroker.getInstance().getKassenzeichenBuffer()
                  + "), 0))";

          if (log.isDebugEnabled()) {
            log.debug(query);
          }

          if (isCancelled()) {
            return null;
          }

          final MetaObject[] result =
              CidsBroker.getInstance().getMetaObject(query, "VERDIS_GRUNDIS");
          final HashSet<CidsBean> kassenzeichen =
              new HashSet<CidsBean>((result == null) ? 0 : result.length);

          if (result != null) {
            for (int i = 0; i < result.length; i++) {
              kassenzeichen.add(result[i].getBean());
            }
          }

          //                        kassenzeichen =
          // verdisServer.getIntersectingKassenzeichen(flurstueckGeom,
          //                                LagisBroker.getInstance().getKassenzeichenBuffer());

          if ((kassenzeichen != null) && (kassenzeichen.size() > 0)) {
            if (log.isDebugEnabled()) {
              log.debug("Crossover: Anzahl Kassenzeichen: " + kassenzeichen.size());
            }
          } else {
            log.info("Crossover:Keine geschnittenen Kassenzeichen gefunden."); // ToDo Meldung an
            // benutzer
          }
          return kassenzeichen;
        } else { // ToDo user message !
          lblMessage.setText(
              "<html>Keine Flurstücksgeometrie vorhanden,<br/>bestimmen der Kasssenzeichen nicht möglich.</html>");
          log.warn("Crossover: Keine Geometrie vorhanden zum bestimmen der Kassenzeichen");
        }
      } else {
        // ToDo user message !
        lblMessage.setText(
            "<html>Bitte wählen Sie ein Flurstück aus,<br/>damit Kassenzeichen bestimmt werden können.</html > ");
        log.warn("Crossover: Kein  Flurstück ausgewählt kann Lagis Kassenzeichen nicht bestimmen");
      }
      return null;
    }
  /**
   * Add a feature with layer name (typically feature type name), some attributes and a Geometry.
   * The Geometry must be in "pixel" space 0,0 lower left and 256,256 upper right.
   *
   * <p>For optimization, geometries will be clipped, geometries will simplified and features with
   * geometries outside of the tile will be skipped.
   *
   * @param layerName
   * @param attributes
   * @param geometry
   */
  public void addFeature(String layerName, Map<String, ?> attributes, Geometry geometry) {

    // split up MultiPolygon and GeometryCollection (without subclasses)
    if (geometry instanceof MultiPolygon || geometry.getClass().equals(GeometryCollection.class)) {
      splitAndAddFeatures(layerName, attributes, (GeometryCollection) geometry);
      return;
    }

    // skip small Polygon/LineString.
    if (geometry instanceof Polygon && geometry.getArea() < 1.0d) {
      return;
    }
    if (geometry instanceof LineString && geometry.getLength() < 1.0d) {
      return;
    }

    // clip geometry. polygons right outside. other geometries at tile
    // border.
    try {
      if (geometry instanceof Polygon) {
        Geometry original = geometry;
        geometry = polygonClipGeometry.intersection(original);

        // some times a intersection is returned as an empty geometry.
        // going via wkt fixes the problem.
        if (geometry.isEmpty() && original.intersects(polygonClipGeometry)) {
          Geometry originalViaWkt = new WKTReader().read(original.toText());
          geometry = polygonClipGeometry.intersection(originalViaWkt);
        }

      } else {
        geometry = clipGeometry.intersection(geometry);
      }
    } catch (TopologyException e) {
      // could not intersect. original geometry will be used instead.
    } catch (ParseException e1) {
      // could not encode/decode WKT. original geometry will be used instead.
    }

    // if clipping result in MultiPolygon, then split once more
    if (geometry instanceof MultiPolygon) {
      splitAndAddFeatures(layerName, attributes, (GeometryCollection) geometry);
      return;
    }

    // no need to add empty geometry
    if (geometry.isEmpty()) {
      return;
    }

    Layer layer = layers.get(layerName);
    if (layer == null) {
      layer = new Layer();
      layers.put(layerName, layer);
    }

    Feature feature = new Feature();
    feature.geometry = geometry;

    for (Map.Entry<String, ?> e : attributes.entrySet()) {
      // skip attribute without value
      if (e.getValue() == null) {
        continue;
      }
      feature.tags.add(layer.key(e.getKey()));
      feature.tags.add(layer.value(e.getValue()));
    }

    layer.features.add(feature);
  }
Exemple #12
0
 public void runTest() throws ParseException {
   failed = false;
   isRun = true;
   initGeometry();
   if (expectedIM != null) {
     IntersectionMatrix im = null;
     if (geom[0] != null && geom[1] != null) {
       im = relate(geom[0], geom[1]);
     }
     if (im != null) {
       String msg = " expected " + expectedIM + ", found " + im.toString();
       assertTrue(im.matches(expectedIM), msg);
     }
   }
   if (expectedBoundary != null) {
     Geometry result = geom[0].getBoundary();
     assertEqualsExact(
         expectedBoundary,
         result,
         " expected boundary " + expectedBoundary.toText() + " , found " + result.toText());
   }
   if (expectedConvexHull != null) {
     Geometry result = geom[0].convexHull();
     assertEqualsExact(
         expectedConvexHull,
         result,
         " expected convex hull " + expectedConvexHull.toText() + " , found " + result.toText());
   }
   if (expectedIntersection != null) {
     Geometry result = geom[0].intersection(geom[1]);
     assertEqualsExact(
         expectedIntersection,
         result,
         " expected intersection "
             + expectedIntersection.toText()
             + " , found "
             + result.toText());
   }
   if (expectedUnion != null) {
     Geometry result = geom[0].union(geom[1]);
     assertEqualsExact(
         expectedUnion,
         result,
         " expected union " + expectedUnion.toText() + " , found " + result.toText());
   }
   if (expectedDifference != null) {
     Geometry result = geom[0].difference(geom[1]);
     assertEqualsExact(
         expectedDifference,
         result,
         " expected difference " + expectedDifference.toText() + " , found " + result.toText());
   }
   if (expectedSymDifference != null) {
     Geometry result = geom[0].symDifference(geom[1]);
     assertEqualsExact(
         expectedSymDifference,
         result,
         " expected sym difference "
             + expectedSymDifference.toText()
             + " , found "
             + result.toText());
   }
 }
 /**
  * Construct a geometry from the WKT representation of a geometry
  *
  * @param geom the constructor for the geometry.
  */
 public String db2Geom(Geometry geom) {
   String geomType = geom.getGeometryType();
   String g1 = geom.toText();
   String g2 = "db2gse.ST_" + geomType + "('" + g1 + "'," + getSRID() + ")";
   return g2;
 }