Example #1
0
  public static SimpleFeatureType toReShapeFeatureType(
      SimpleFeatureCollection delegate, List<Definition> definitionList) {

    SimpleFeature sample = null;
    SimpleFeatureIterator iterator = delegate.features();
    try {
      if (iterator.hasNext()) {
        sample = iterator.next();
      }
    } finally {
      iterator.close(); // good bye
    }

    SimpleFeatureTypeBuilder build = new SimpleFeatureTypeBuilder();
    SimpleFeatureType origional = delegate.getSchema();

    for (Definition def : definitionList) {
      String name = def.name;
      Expression expression = def.expression;

      Object value = null;
      if (sample != null) {
        value = expression.evaluate(sample);
      }
      Class<?> binding = def.binding; // make use of any default binding hint provided by user
      if (value == null) {
        if (expression instanceof PropertyName) {
          PropertyName propertyName = (PropertyName) expression;
          String path = propertyName.getPropertyName();
          AttributeDescriptor descriptor = origional.getDescriptor(name);
          AttributeType attributeType = descriptor.getType();
          binding = attributeType.getBinding();
        }
      } else {
        binding = value.getClass();
      }

      if (binding == null) {
        // note we could consider scanning through additional samples until we get a non null hit
        throw new IllegalArgumentException("Unable to determine type for " + name);
      }

      if (Geometry.class.isAssignableFrom(binding)) {
        CoordinateReferenceSystem crs;
        AttributeType originalAttributeType = origional.getType(name);
        if (originalAttributeType != null && originalAttributeType instanceof GeometryType) {
          GeometryType geometryType = (GeometryType) originalAttributeType;
          crs = geometryType.getCoordinateReferenceSystem();
        } else {
          crs = origional.getCoordinateReferenceSystem();
        }
        build.crs(crs);
        build.add(name, binding);
      } else {
        build.add(name, binding);
      }
    }
    build.setName(origional.getTypeName());
    return build.buildFeatureType();
  }
 private GeometryDescriptor reprojectGeometry(GeometryDescriptor descr) {
   if (descr == null) {
     return null;
   }
   GeometryType type =
       ftf.createGeometryType(
           descr.getType().getName(),
           descr.getType().getBinding(),
           reprojection,
           descr.getType().isIdentified(),
           descr.getType().isAbstract(),
           descr.getType().getRestrictions(),
           descr.getType().getSuper(),
           descr.getType().getDescription());
   type.getUserData().putAll(descr.getType().getUserData());
   GeometryDescriptor gd =
       ftf.createGeometryDescriptor(
           type,
           descr.getName(),
           descr.getMinOccurs(),
           descr.getMaxOccurs(),
           descr.isNillable(),
           descr.getDefaultValue());
   gd.getUserData().putAll(descr.getUserData());
   return gd;
 }
  /**
   * 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));
  }
  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();
  }
 private void printAttributeDescriptor(Writer w, PropertyDescriptor attrib)
     throws IOException {
   print(w, attrib.getName().toString());
   print(w, "\t");
   print(w, FieldType.forBinding(attrib.getType().getBinding()).name());
   print(w, "\t");
   print(w, Integer.toString(attrib.getMinOccurs()));
   print(w, "\t");
   print(w, Integer.toString(attrib.getMaxOccurs()));
   print(w, "\t");
   print(w, Boolean.toString(attrib.isNillable()));
   PropertyType attrType = attrib.getType();
   if (attrType instanceof GeometryType) {
     GeometryType gt = (GeometryType) attrType;
     CoordinateReferenceSystem crs = gt.getCoordinateReferenceSystem();
     String crsText = CrsTextSerializer.serialize(crs);
     print(w, "\t");
     println(w, crsText);
   } else {
     println(w, "");
   }
 }
  /**
   * Clones the given schema, changing the geometry attribute to match the given dimensionality.
   *
   * @param schema schema to clone
   * @param dimensionality dimensionality for the geometry 1= points, 2= lines, 3= polygons
   */
  private FeatureType cloneWithDimensionality(FeatureType schema, int dimensionality) {
    SimpleFeatureType simpleFt = (SimpleFeatureType) schema;
    SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
    builder.setName(schema.getName());
    builder.setCRS(schema.getCoordinateReferenceSystem());
    for (AttributeDescriptor desc : simpleFt.getAttributeDescriptors()) {
      if (isMixedGeometry(desc)) {
        GeometryDescriptor geomDescriptor = (GeometryDescriptor) desc;
        GeometryType geomType = geomDescriptor.getType();

        Class<?> geometryClass = getGeometryForDimensionality(dimensionality);

        GeometryType gt =
            new GeometryTypeImpl(
                geomType.getName(),
                geometryClass,
                geomType.getCoordinateReferenceSystem(),
                geomType.isIdentified(),
                geomType.isAbstract(),
                geomType.getRestrictions(),
                geomType.getSuper(),
                geomType.getDescription());

        builder.add(
            new GeometryDescriptorImpl(
                gt,
                geomDescriptor.getName(),
                geomDescriptor.getMinOccurs(),
                geomDescriptor.getMaxOccurs(),
                geomDescriptor.isNillable(),
                geomDescriptor.getDefaultValue()));
      } else {
        builder.add(desc);
      }
    }
    schema = builder.buildFeatureType();
    return schema;
  }
Example #7
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");
  }