/**
   * Handles the feature creation/update/deletion strategy. You may want to override this in a
   * subclass to handle workflow.
   *
   * @param feature the feature that is about to be split
   * @param geoms new geometries that are the result of splitting
   * @param filter filter to get at feature
   * @param localStore the store we're working against
   * @param localStrategy the strategy in use
   * @return A list of FeatureIds is returned, one for each feature in the order created. However,
   *     these might not be assigned until after a commit has been performed.
   * @throws Exception if an error occurs modifying the data source, converting the geometry or an
   *     illegal argument was given
   */
  protected List<FeatureId> handleStrategy(
      SimpleFeature feature,
      List<? extends Geometry> geoms,
      Filter filter,
      SimpleFeatureStore localStore,
      String localStrategy)
      throws Exception {

    List<SimpleFeature> newFeats = new ArrayList();
    GeometryTypeConverterFactory cf = new GeometryTypeConverterFactory();
    Converter c =
        cf.createConverter(
            Geometry.class,
            localStore.getSchema().getGeometryDescriptor().getType().getBinding(),
            null);
    GeometryType type = localStore.getSchema().getGeometryDescriptor().getType();
    String geomAttribute = localStore.getSchema().getGeometryDescriptor().getLocalName();
    boolean firstFeature = true;
    for (Geometry newGeom : geoms) {
      if (firstFeature) {
        if (localStrategy.equalsIgnoreCase("replace")) {
          // use first/largest geom to update existing feature geom
          feature.setAttribute(geomAttribute, c.convert(newGeom, type.getBinding()));
          feature = this.handleExtraData(feature);
          Object[] attributevalues =
              feature.getAttributes().toArray(new Object[feature.getAttributeCount()]);
          AttributeDescriptor[] attributes =
              feature
                  .getFeatureType()
                  .getAttributeDescriptors()
                  .toArray(new AttributeDescriptor[feature.getAttributeCount()]);
          localStore.modifyFeatures(attributes, attributevalues, filter);
          firstFeature = false;
          continue;
        } else if (localStrategy.equalsIgnoreCase("add")) {
          // delete the source feature, new ones will be created
          localStore.removeFeatures(filter);
          firstFeature = false;
        } else {
          throw new IllegalArgumentException(
              "Unknown strategy '" + localStrategy + "', cannot split");
        }
      }
      // create + add new features
      SimpleFeature newFeat =
          DataUtilities.createFeature(
              feature.getType(), DataUtilities.encodeFeature(feature, false));
      newFeat.setAttribute(geomAttribute, c.convert(newGeom, type.getBinding()));
      newFeats.add(newFeat);
    }
    newFeats = this.handleExtraData(newFeats);
    return localStore.addFeatures(DataUtilities.collection(newFeats));
  }
Exemplo n.º 2
0
  public static <T extends FeatureType, F extends org.opengis.feature.Feature> void featuresToJson(
      FeatureCollection<T, F> collection, JSONBuilder json, boolean returnGeometry)
      throws IOException {
    FeatureIterator<F> iterator = collection.features();

    T schema = collection.getSchema();
    json.object().key("objectIdFieldName").value("objectid").key("globalIdFieldName").value("");

    if (returnGeometry) {
      GeometryDescriptor geometryDescriptor = schema.getGeometryDescriptor();
      if (geometryDescriptor == null)
        throw new RuntimeException(
            "No geometry descriptor for type " + schema + "; " + schema.getDescriptors());
      GeometryType geometryType = geometryDescriptor.getType();
      if (geometryType == null) throw new RuntimeException("No geometry type for type " + schema);
      Class<?> binding = geometryType.getBinding();
      if (binding == null) throw new RuntimeException("No binding for geometry type " + schema);
      GeometryTypeEnum geometryTypeEnum = GeometryTypeEnum.forJTSClass(binding);
      json.key("geometryType").value(geometryTypeEnum.getGeometryType());
    }

    if (schema.getCoordinateReferenceSystem() != null) {
      try {
        SpatialReference sr = SpatialReferences.fromCRS(schema.getCoordinateReferenceSystem());
        json.key("spatialReference");
        SpatialReferenceEncoder.toJson(sr, json);
      } catch (FactoryException e) {
        throw new RuntimeException(e);
      }
    }

    json.key("fields").array();
    for (PropertyDescriptor desc : schema.getDescriptors()) {
      if (schema.getGeometryDescriptor() != null
          && !desc.getName().equals(schema.getGeometryDescriptor().getName())) {
        descriptorToJson(desc, json);
      }
    }
    json.endArray();

    try {
      json.key("features");
      json.array();
      while (iterator.hasNext()) {
        F feature = iterator.next();
        featureToJson(feature, json, returnGeometry);
      }
      json.endArray();
    } finally {
      iterator.close();
    }
    json.endObject();
  }
Exemplo n.º 3
0
  public static IGlobeFeatureCollection<
          IVector2, ? extends IBoundedGeometry2D<? extends IFinite2DBounds<?>>>
      readFeatures(final DataStore dataStore, final String layerName, final GProjection projection)
          throws Exception {

    final SimpleFeatureSource featureSource = dataStore.getFeatureSource(layerName);

    final SimpleFeatureCollection featuresCollection = featureSource.getFeatures();

    final GIntHolder validCounter = new GIntHolder(0);
    // final GIntHolder polygonsWithHolesCounter = new GIntHolder(0);
    final GIntHolder invalidCounter = new GIntHolder(0);
    //      final GIntHolder validVerticesCounter = new GIntHolder(0);
    final GIntHolder polygonsCounter = new GIntHolder(0);
    final GIntHolder linesCounter = new GIntHolder(0);
    final GIntHolder pointsCounter = new GIntHolder(0);

    final int featuresCount = featuresCollection.size();
    final ArrayList<IGlobeFeature<IVector2, IBoundedGeometry2D<? extends IFinite2DBounds<?>>>>
        euclidFeatures =
            new ArrayList<
                IGlobeFeature<IVector2, IBoundedGeometry2D<? extends IFinite2DBounds<?>>>>(
                featuresCount);

    final GProgress progress =
        new GProgress(featuresCount) {
          @Override
          public void informProgress(
              final double percent, final long elapsed, final long estimatedMsToFinish) {
            //            System.out.println("Loading \"" + fileName.buildPath() + "\" "
            //                               + progressString(percent, elapsed,
            // estimatedMsToFinish));
            System.out.println(
                "Loading data from data storage: "
                    + layerName
                    + " "
                    + progressString(percent, elapsed, estimatedMsToFinish));
          }
        };

    final FeatureIterator<SimpleFeature> iterator = featuresCollection.features();

    while (iterator.hasNext()) {
      final SimpleFeature feature = iterator.next();

      final GeometryAttribute geometryAttribute = feature.getDefaultGeometryProperty();

      final GeometryType type = geometryAttribute.getType();

      if (type.getBinding() == com.vividsolutions.jts.geom.MultiPolygon.class) {

        polygonsCounter.increment();

        final com.vividsolutions.jts.geom.MultiPolygon multipolygon =
            (com.vividsolutions.jts.geom.MultiPolygon) geometryAttribute.getValue();
        final int geometriesCount = multipolygon.getNumGeometries();

        final List<IPolygon2D> polygons = new ArrayList<IPolygon2D>(geometriesCount);
        for (int i = 0; i < geometriesCount; i++) {
          final com.vividsolutions.jts.geom.Polygon jtsPolygon =
              (com.vividsolutions.jts.geom.Polygon) multipolygon.getGeometryN(i);

          try {
            final IPolygon2D euclidPolygon = createEuclidPolygon(projection, jtsPolygon);

            if (euclidPolygon != null) {
              //                     euclidFeatures.add(createFeature(euclidPolygon, feature));
              polygons.add(euclidPolygon);
              validCounter.increment();
            }
          } catch (final IllegalArgumentException e) {
            //                     System.err.println(e.getMessage());
          }
        }

        if (!polygons.isEmpty()) {
          if (polygons.size() == 1) {
            euclidFeatures.add(createFeature(polygons.get(0), feature));
          } else {
            euclidFeatures.add(createFeature(new GMultiGeometry2D<IPolygon2D>(polygons), feature));
          }
        }

      } else if (type.getBinding() == com.vividsolutions.jts.geom.MultiLineString.class) {

        linesCounter.increment();

        final com.vividsolutions.jts.geom.MultiLineString multiline =
            (com.vividsolutions.jts.geom.MultiLineString) geometryAttribute.getValue();
        final int geometriesCount = multiline.getNumGeometries();

        final List<IPolygonalChain2D> lines = new ArrayList<IPolygonalChain2D>(geometriesCount);
        for (int i = 0; i < geometriesCount; i++) {
          final com.vividsolutions.jts.geom.LineString jtsLine =
              (com.vividsolutions.jts.geom.LineString) multiline.getGeometryN(i);

          try {
            final IPolygonalChain2D euclidLine = createLine(jtsLine.getCoordinates(), projection);

            // euclidFeatures.add(createFeature(euclidLines, feature));
            lines.add(euclidLine);
          } catch (final IllegalArgumentException e) {
            //                     System.err.println(e.getMessage());
          }
        }

        if (!lines.isEmpty()) {
          if (lines.size() == 1) {
            euclidFeatures.add(createFeature(lines.get(0), feature));
          } else {
            euclidFeatures.add(
                createFeature(new GMultiGeometry2D<IPolygonalChain2D>(lines), feature));
          }
        }

        validCounter.increment();
      } else if (type.getBinding() == com.vividsolutions.jts.geom.Point.class) {

        pointsCounter.increment();

        final IVector2 euclidPoint =
            createPoint(
                ((com.vividsolutions.jts.geom.Point) geometryAttribute.getValue()).getCoordinate(),
                projection);
        euclidFeatures.add(createFeature(euclidPoint, feature));

        validCounter.increment();
      } else if (type.getBinding() == com.vividsolutions.jts.geom.MultiPoint.class) {
        final IBoundedGeometry2D<? extends IFinite2DBounds<?>> euclidMultipoint =
            createEuclidMultiPoint(geometryAttribute, projection);
        euclidFeatures.add(createFeature(euclidMultipoint, feature));

        validCounter.increment();
      } else {
        invalidCounter.increment();
        System.out.println("invalid type: " + type);
      }

      progress.stepDone();
    }

    dataStore.dispose();

    euclidFeatures.trimToSize();

    System.out.println();
    System.out.println("Features: " + featuresCount);

    System.out.println();
    System.out.println("Read " + validCounter.get() + " valid geometries");

    System.out.println("  => " + polygonsCounter.get() + " valid polygons");
    System.out.println("  => " + linesCounter.get() + " valid lines");
    System.out.println("  => " + pointsCounter.get() + " valid points");
    System.out.println();

    if (invalidCounter.get() > 0) {
      System.out.println("Ignored " + invalidCounter.get() + " invalid geometries");
    }

    System.out.println();

    final SimpleFeatureType schema = featureSource.getSchema();
    final int fieldsCount = schema.getAttributeCount();
    final List<GField> fields = new ArrayList<GField>(fieldsCount);
    System.out.println("Fields count: " + fieldsCount);
    for (int i = 0; i < fieldsCount; i++) {
      final String fieldName = schema.getType(i).getName().getLocalPart();
      System.out.println("Fieldname: " + fieldName);
      final Class<?> fieldType = schema.getType(i).getBinding();

      fields.add(new GField(fieldName, fieldType));
    }

    return new GListFeatureCollection<IVector2, IBoundedGeometry2D<? extends IFinite2DBounds<?>>>(
        GProjection.EPSG_4326, fields, euclidFeatures, "uniqueId_000");
  }