Java Code Examples for org.opengis.feature.simple.SimpleFeature#setDefaultGeometry()

The following examples show how to use org.opengis.feature.simple.SimpleFeature#setDefaultGeometry() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DxfUtils.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Write a {@link SimpleFeature} to dxf string.
 * 
 * @param featureMate the feature to convert.
 * @param layerName the layer name in case none is in the attributes.
 * @param elevationAttrName the attribute defining elevation or <code>null</code>.
 * @param suffix <code>true</code> if suffix is needed.
 * @param force2CoordsToLine if <code>true</code>, lines that are composed of just 2 coordinates
 *                      will be handled as LINE instead of the default which is POLYLINE.
 * @return the string representation.
 */
public static String feature2Dxf( FeatureMate featureMate, String layerName, String elevationAttrName, boolean suffix,
        boolean force2CoordsToLine ) {
    Geometry g = featureMate.getGeometry();

    if (EGeometryType.isPoint(g)) {
        return point2Dxf(featureMate, layerName, elevationAttrName);
    } else if (EGeometryType.isLine(g)) {
        return lineString2Dxf(featureMate, layerName, elevationAttrName, force2CoordsToLine);
    } else if (EGeometryType.isPolygon(g)) {
        return polygon2Dxf(featureMate, layerName, elevationAttrName, suffix);
    } else if (g instanceof GeometryCollection) {
        StringBuilder sb = new StringBuilder();
        for( int i = 0; i < g.getNumGeometries(); i++ ) {
            SimpleFeature ff = SimpleFeatureBuilder.copy(featureMate.getFeature());
            ff.setDefaultGeometry(g.getGeometryN(i));
            FeatureMate fm = new FeatureMate(ff);
            sb.append(feature2Dxf(fm, layerName, elevationAttrName, suffix, force2CoordsToLine));
        }
        return sb.toString();
    } else {
        return null;
    }
}
 
Example 2
Source File: GeometryUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
public static SimpleFeature crsTransform(
    final SimpleFeature entry,
    final SimpleFeatureType reprojectedType,
    final MathTransform transform) {
  SimpleFeature crsEntry = entry;

  if (transform != null) {
    // we can use the transform we have already calculated for this
    // feature
    try {

      // this will clone the feature and retype it to Index CRS
      crsEntry = SimpleFeatureBuilder.retype(entry, reprojectedType);

      // this will transform the geometry
      crsEntry.setDefaultGeometry(
          JTS.transform((Geometry) entry.getDefaultGeometry(), transform));
    } catch (MismatchedDimensionException | TransformException e) {
      LOGGER.warn(
          "Unable to perform transform to specified CRS of the index, the feature geometry will remain in its original CRS",
          e);
    }
  }

  return crsEntry;
}
 
Example 3
Source File: GeoWaveGeoIndexer.java    From rya with Apache License 2.0 5 votes vote down vote up
private static SimpleFeature createFeature(final SimpleFeatureType featureType, final Statement statement) throws ParseException {
    final String subject = StatementSerializer.writeSubject(statement);
    final String predicate = StatementSerializer.writePredicate(statement);
    final String object = StatementSerializer.writeObject(statement);
    final String context = StatementSerializer.writeContext(statement);

    // create the feature
    final Object[] noValues = {};

    // create the hash
    final String statementId = Md5Hash.md5Base64(StatementSerializer.writeStatement(statement));
    final SimpleFeature newFeature = SimpleFeatureBuilder.build(featureType, noValues, statementId);

    // write the statement data to the fields
    final Geometry geom = GeoParseUtils.getGeometry(statement, new GmlParser());
    if(geom == null || geom.isEmpty() || !geom.isValid()) {
        throw new ParseException("Could not create geometry for statement " + statement);
    }
    newFeature.setDefaultGeometry(geom);

    newFeature.setAttribute(SUBJECT_ATTRIBUTE, subject);
    newFeature.setAttribute(PREDICATE_ATTRIBUTE, predicate);
    newFeature.setAttribute(OBJECT_ATTRIBUTE, object);
    newFeature.setAttribute(CONTEXT_ATTRIBUTE, context);
    // GeoWave does not support querying based on a user generated feature ID
    // So, we create a separate ID attribute that it can query on.
    newFeature.setAttribute(GEO_ID_ATTRIBUTE, statementId);

    // preserve the ID that we created for this feature
    // (set the hint to FALSE to have GeoTools generate IDs)
    newFeature.getUserData().put(Hints.USE_PROVIDED_FID, java.lang.Boolean.TRUE);

    return newFeature;
}
 
Example 4
Source File: GeoMesaGeoIndexer.java    From rya with Apache License 2.0 5 votes vote down vote up
private static SimpleFeature createFeature(final SimpleFeatureType featureType, final Statement statement) throws ParseException {
    final String subject = StatementSerializer.writeSubject(statement);
    final String predicate = StatementSerializer.writePredicate(statement);
    final String object = StatementSerializer.writeObject(statement);
    final String context = StatementSerializer.writeContext(statement);

    // create the feature
    final Object[] noValues = {};

    // create the hash
    final String statementId = Md5Hash.md5Base64(StatementSerializer.writeStatement(statement));
    final SimpleFeature newFeature = SimpleFeatureBuilder.build(featureType, noValues, statementId);

    // write the statement data to the fields
    final Geometry geom = GeoParseUtils.getGeometry(statement, new GmlParser());
    if(geom == null || geom.isEmpty() || !geom.isValid()) {
        throw new ParseException("Could not create geometry for statement " + statement);
    }
    newFeature.setDefaultGeometry(geom);

    newFeature.setAttribute(SUBJECT_ATTRIBUTE, subject);
    newFeature.setAttribute(PREDICATE_ATTRIBUTE, predicate);
    newFeature.setAttribute(OBJECT_ATTRIBUTE, object);
    newFeature.setAttribute(CONTEXT_ATTRIBUTE, context);

    // preserve the ID that we created for this feature
    // (set the hint to FALSE to have GeoTools generate IDs)
    newFeature.getUserData().put(Hints.USE_PROVIDED_FID, java.lang.Boolean.TRUE);

    return newFeature;
}
 
Example 5
Source File: ImportTrackAction.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private static void transformFeatureCollection(FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection, CoordinateReferenceSystem targetCRS) throws TransformException {
    final GeometryCoordinateSequenceTransformer transform = FeatureUtils.getTransform(DefaultGeographicCRS.WGS84, targetCRS);
    final FeatureIterator<SimpleFeature> features = featureCollection.features();
    final GeometryFactory geometryFactory = new GeometryFactory();
    while (features.hasNext()) {
        final SimpleFeature simpleFeature = features.next();
        final Point sourcePoint = (Point) simpleFeature.getDefaultGeometry();
        final Point targetPoint = transform.transformPoint(sourcePoint, geometryFactory);
        simpleFeature.setDefaultGeometry(targetPoint);
    }
}
 
Example 6
Source File: ExportGeometryAction.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private static Map<Class<?>, List<SimpleFeature>> createGeometryToFeaturesListMap(VectorDataNode vectorNode) throws TransformException,
                                                                                                                    SchemaException {
    FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection = vectorNode.getFeatureCollection();
    CoordinateReferenceSystem crs = vectorNode.getFeatureType().getCoordinateReferenceSystem();
    if (crs == null) {   // for pins and GCPs crs is null
        crs = vectorNode.getProduct().getSceneCRS();
    }
    final CoordinateReferenceSystem modelCrs;
    if (vectorNode.getProduct().getSceneGeoCoding() instanceof CrsGeoCoding) {
        modelCrs = vectorNode.getProduct().getSceneCRS();
    } else {
        modelCrs = DefaultGeographicCRS.WGS84;
    }

    // Not using ReprojectingFeatureCollection - it is reprojecting all geometries of a feature
    // but we want to reproject the default geometry only
    GeometryCoordinateSequenceTransformer transformer = createTransformer(crs, modelCrs);

    Map<Class<?>, List<SimpleFeature>> featureListMap = new HashMap<>();
    final FeatureIterator<SimpleFeature> featureIterator = featureCollection.features();
    // The schema needs to be reprojected. We need to build a new feature be cause we can't change the schema.
    // It is necessary to have this reprojected schema, because otherwise the shapefile is not correctly georeferenced.
    SimpleFeatureType schema = featureCollection.getSchema();
    SimpleFeatureType transformedSchema = FeatureTypes.transform(schema, modelCrs);
    while (featureIterator.hasNext()) {
        SimpleFeature feature = featureIterator.next();
        Object defaultGeometry = feature.getDefaultGeometry();
        feature.setDefaultGeometry(transformer.transform((Geometry) defaultGeometry));

        Class<?> geometryType = defaultGeometry.getClass();
        List<SimpleFeature> featureList = featureListMap.computeIfAbsent(geometryType, k -> new ArrayList<>());
        SimpleFeature exportFeature = SimpleFeatureBuilder.build(transformedSchema, feature.getAttributes(), feature.getID());
        featureList.add(exportFeature);
    }
    return featureListMap;
}
 
Example 7
Source File: InsertWktGeometryAction.java    From snap-desktop with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void actionPerformed(ActionEvent event) {
    JTextArea textArea = new JTextArea(16, 32);
    textArea.setEditable(true);

    JPanel contentPanel = new JPanel(new BorderLayout(4, 4));
    contentPanel.add(new JLabel("Geometry Well-Known-Text (WKT):"), BorderLayout.NORTH);
    contentPanel.add(new JScrollPane(textArea), BorderLayout.CENTER);

    SnapApp snapApp = SnapApp.getDefault();
    ModalDialog modalDialog = new ModalDialog(snapApp.getMainFrame(),
                                              Bundle.CTL_InsertWktGeometryAction_DialogTitle(),
                                              ModalDialog.ID_OK_CANCEL, null);
    modalDialog.setContent(contentPanel);
    modalDialog.center();
    if (modalDialog.show() == ModalDialog.ID_OK) {
        String wellKnownText = textArea.getText();
        if (wellKnownText == null || wellKnownText.isEmpty()) {
            return;
        }
        ProductSceneView sceneView = snapApp.getSelectedProductSceneView();
        VectorDataLayer vectorDataLayer = InsertFigureInteractorInterceptor.getActiveVectorDataLayer(sceneView);
        if (vectorDataLayer == null) {
            return;
        }

        SimpleFeatureType wktFeatureType = PlainFeatureFactory.createDefaultFeatureType(DefaultGeographicCRS.WGS84);
        ListFeatureCollection newCollection = new ListFeatureCollection(wktFeatureType);
        SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(wktFeatureType);
        SimpleFeature wktFeature = featureBuilder.buildFeature("ID" + Long.toHexString(currentFeatureId++));
        Geometry geometry;
        try {
            geometry = new WKTReader().read(wellKnownText);
        } catch (ParseException e) {
            snapApp.handleError("Failed to convert WKT into geometry", e);
            return;
        }
        wktFeature.setDefaultGeometry(geometry);
        newCollection.add(wktFeature);

        FeatureCollection<SimpleFeatureType, SimpleFeature> productFeatures = FeatureUtils.clipFeatureCollectionToProductBounds(
                newCollection,
                sceneView.getProduct(),
                null,
                ProgressMonitor.NULL);
        if (productFeatures.isEmpty()) {
            Dialogs.showError(Bundle.CTL_InsertWktGeometryAction_MenuText(),
                              "The geometry is not contained in the product.");
        } else {
            vectorDataLayer.getVectorDataNode().getFeatureCollection().addAll(productFeatures);
        }
    }
}
 
Example 8
Source File: ShapefileTool.java    From geowave with Apache License 2.0 4 votes vote down vote up
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
    value = "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE",
    justification = "Directories may alreadybe there")
public static void writeShape(final String typeName, final File dir, final Geometry[] shapes)
    throws IOException {

  FileUtils.deleteDirectory(dir);

  dir.mkdirs();

  final SimpleFeatureBuilder featureBuilder =
      new SimpleFeatureBuilder(createFeatureType(typeName, shapes[0] instanceof Point));

  final ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();

  final Map<String, Serializable> params = new HashMap<>();
  params.put("url", new File(dir.getAbsolutePath() + "/" + typeName + ".shp").toURI().toURL());
  params.put("create spatial index", Boolean.TRUE);

  final ShapefileDataStore newDataStore =
      (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
  newDataStore.createSchema(createFeatureType(typeName, shapes[0] instanceof Point));
  final Transaction transaction = new DefaultTransaction("create");

  try (final FeatureWriter<SimpleFeatureType, SimpleFeature> writer =
      newDataStore.getFeatureWriterAppend(typeName, transaction)) {
    final int i = 1;
    for (final Geometry shape : shapes) {
      featureBuilder.add(shape);
      featureBuilder.add(Integer.valueOf(i));
      final SimpleFeature feature = featureBuilder.buildFeature(null);
      final SimpleFeature copy = writer.next();
      for (final AttributeDescriptor attrD : feature.getFeatureType().getAttributeDescriptors()) {
        // the null case should only happen for geometry
        if (copy.getFeatureType().getDescriptor(attrD.getName()) != null) {
          copy.setAttribute(attrD.getName(), feature.getAttribute(attrD.getName()));
        }
      }
      // shape files force geometry name to be 'the_geom'. So isolate
      // this change
      copy.setDefaultGeometry(feature.getDefaultGeometry());
      writer.write();
    }
  } catch (final IOException e) {
    LOGGER.warn("Problem with the FeatureWritter", e);
    transaction.rollback();
  } finally {
    transaction.commit();
    transaction.close();
  }
}
 
Example 9
Source File: ShapefileTool.java    From geowave with Apache License 2.0 4 votes vote down vote up
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
    value = "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE",
    justification = "Directories may alreadybe there")
public static void writeShape(final File dir, final List<SimpleFeature> shapes)
    throws IOException {

  FileUtils.deleteDirectory(dir);

  dir.mkdirs();

  final ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
  final String typeName = shapes.get(0).getType().getTypeName();
  final Map<String, Serializable> params = new HashMap<>();
  params.put("url", new File(dir.getAbsolutePath() + "/" + typeName + ".shp").toURI().toURL());
  params.put("create spatial index", Boolean.TRUE);

  final ShapefileDataStore newDataStore =
      (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
  newDataStore.createSchema(shapes.get(0).getFeatureType());
  final Transaction transaction = new DefaultTransaction("create");

  try (final FeatureWriter<SimpleFeatureType, SimpleFeature> writer =
      newDataStore.getFeatureWriterAppend(typeName, transaction)) {
    for (final SimpleFeature shape : shapes) {
      final SimpleFeature copy = writer.next();
      for (final AttributeDescriptor attrD : copy.getFeatureType().getAttributeDescriptors()) {
        // the null case should only happen for geometry
        if (copy.getFeatureType().getDescriptor(attrD.getName()) != null) {
          copy.setAttribute(attrD.getName(), shape.getAttribute(attrD.getName()));
        }
      }
      // shape files force geometry name to be 'the_geom'. So isolate
      // this change
      copy.setDefaultGeometry(shape.getDefaultGeometry());
      writer.write();
    }
  } catch (final IOException e) {
    LOGGER.warn("Problem with the FeatureWritter", e);
    transaction.rollback();
  } finally {
    transaction.commit();
    transaction.close();
  }
}