Search in sources :

Example 21 with SimpleFeatureIterator

use of org.geotools.data.simple.SimpleFeatureIterator in project activityinfo by bedatadriven.

the class ImportView method updateGeometry.

private void updateGeometry(GeoAdminClient client, Map<ResourceId, ResourceId> idMap) throws IOException {
    FeatureSourceStorageProvider catalog = new FeatureSourceStorageProvider();
    FeatureSourceStorage formStorage = (FeatureSourceStorage) catalog.getForm(getModel().getSourceFormId().get()).get();
    ResourceId targetFormId = getModel().getTargetFormId().get();
    FieldProfile targetField = getTargetProfile().get().getGeometryField();
    if (targetField == null) {
        System.err.println("No geometry field to update.");
        return;
    }
    int sourceIndex = formStorage.getGeometryAttributeIndex();
    if (sourceIndex == -1) {
        System.err.println("No source geometry field.");
        return;
    }
    SimpleFeatureSource featureSource = formStorage.getFeatureSource();
    GeometryType geometryType = (GeometryType) featureSource.getSchema().getDescriptor(sourceIndex).getType();
    GeometryConverter converter = new GeometryConverter(geometryType);
    SimpleFeatureIterator it = featureSource.getFeatures().features();
    while (it.hasNext()) {
        SimpleFeature feature = it.next();
        ResourceId sourceId = ResourceId.valueOf(feature.getID());
        ResourceId targetId = idMap.get(sourceId);
        if (targetId != null) {
            Geometry geometry = converter.toWgs84(feature.getAttribute(sourceIndex));
            System.out.print("Updating geometry for " + targetId + " [" + geometry.getGeometryType() + "] ... ");
            try {
                client.updateGeometry(targetFormId, targetId, targetField.getId(), geometry);
                System.out.println("OK");
            } catch (Exception e) {
                System.out.println("ERROR: " + e.getMessage());
            }
        }
    }
}
Also used : Geometry(com.vividsolutions.jts.geom.Geometry) FeatureSourceStorage(org.activityinfo.geoadmin.source.FeatureSourceStorage) GeometryType(org.opengis.feature.type.GeometryType) SimpleFeatureIterator(org.geotools.data.simple.SimpleFeatureIterator) ResourceId(org.activityinfo.model.resource.ResourceId) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) FieldProfile(org.activityinfo.geoadmin.merge2.view.profile.FieldProfile) GeometryConverter(org.activityinfo.geoadmin.source.GeometryConverter) FeatureSourceStorageProvider(org.activityinfo.geoadmin.source.FeatureSourceStorageProvider) SimpleFeature(org.opengis.feature.simple.SimpleFeature) IOException(java.io.IOException)

Example 22 with SimpleFeatureIterator

use of org.geotools.data.simple.SimpleFeatureIterator in project spatial-portal by AtlasOfLivingAustralia.

the class AreaUploadShapefileWizardController method loadShape.

private void loadShape(String filename) {
    CommonFactoryFinder.getFilterFactory(GeoTools.getDefaultHints());
    try {
        FileDataStore store = FileDataStoreFinder.getDataStore(new File(filename));
        source = store.getFeatureSource();
        features = source.getFeatures();
        Listhead lhd = new Listhead();
        SimpleFeatureType schema = features.getSchema();
        Listheader lh = new Listheader(StringConstants.ID);
        lh.setParent(lhd);
        for (AttributeType at : schema.getTypes()) {
            if (schema.getDescriptor(at.getName()) == null) {
                continue;
            }
            lh = new Listheader(at.getName().toString());
            lh.setParent(lhd);
        }
        lhd.setParent(lAttributes);
        SimpleFeatureIterator fi = features.features();
        while (fi.hasNext()) {
            SimpleFeature f = fi.next();
            Listitem li = new Listitem();
            Listcell lc;
            String value;
            // add identifier
            lc = new Listcell(f.getIdentifier().getID());
            lc.setParent(li);
            for (AttributeType at : schema.getTypes()) {
                if (schema.getDescriptor(at.getName()) == null) {
                    continue;
                }
                Object obj = f.getAttribute(at.getName());
                if (obj == null) {
                    value = f.getID();
                } else {
                    value = String.valueOf(obj);
                }
                lc = new Listcell(value);
                lc.setParent(li);
            }
            li.setValue(f.getIdentifier());
            li.setParent(lAttributes);
        }
        // loadFeatures
        // check if only a single feature,
        // if so, then select it and map it automatically
        LOGGER.debug("features.size(): " + features.size());
        if (features.size() > 1) {
            executeShapeImageRenderer(null);
        } else {
            LOGGER.debug("only a single feature, bypassing wizard...");
            fi = features.features();
            Set<FeatureId> ids = new HashSet<FeatureId>();
            ids.add(fi.next().getIdentifier());
            loadOnMap(ids, filename);
            // echo detach
            Events.echoEvent("onClick$btnCancel", this, null);
        }
        try {
            fi.close();
        } catch (Exception e) {
        }
    } catch (IOException e) {
        LOGGER.debug("IO Exception ", e);
    } catch (Exception e) {
        LOGGER.debug("Generic exception", e);
    }
}
Also used : IOException(java.io.IOException) SimpleFeature(org.opengis.feature.simple.SimpleFeature) ParseException(com.vividsolutions.jts.io.ParseException) IOException(java.io.IOException) FeatureId(org.opengis.filter.identity.FeatureId) SimpleFeatureIterator(org.geotools.data.simple.SimpleFeatureIterator) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) AttributeType(org.opengis.feature.type.AttributeType) FileDataStore(org.geotools.data.FileDataStore) File(java.io.File)

Example 23 with SimpleFeatureIterator

use of org.geotools.data.simple.SimpleFeatureIterator in project OpenTripPlanner by opentripplanner.

the class PointSet method fromShapefile.

public static PointSet fromShapefile(File file, String originIDField, List<String> propertyFields) throws IOException, NoSuchAuthorityCodeException, FactoryException, EmptyPolygonException, UnsupportedGeometryException {
    if (!file.exists())
        throw new RuntimeException("Shapefile does not exist.");
    FileDataStore store = FileDataStoreFinder.getDataStore(file);
    SimpleFeatureSource featureSource = store.getFeatureSource();
    CoordinateReferenceSystem sourceCRS = featureSource.getInfo().getCRS();
    CoordinateReferenceSystem WGS84 = CRS.decode("EPSG:4326", true);
    Query query = new Query();
    query.setCoordinateSystem(sourceCRS);
    query.setCoordinateSystemReproject(WGS84);
    SimpleFeatureCollection featureCollection = featureSource.getFeatures(query);
    // Set up fields based on first feature in collection
    // This assumes that all features have the same set of properties, which I think is always the case for shapefiles
    SimpleFeatureIterator it = featureCollection.features();
    SimpleFeature protoFt = it.next();
    if (propertyFields == null) {
        propertyFields = new ArrayList<String>();
        // No property fields specified, so use all property fields
        for (Property p : protoFt.getProperties()) {
            propertyFields.add(p.getName().toString());
        }
        // If ID field is specified, don't use it as a property
        if (originIDField != null && propertyFields.contains(originIDField)) {
            propertyFields.remove(originIDField);
        }
    }
    // Reset iterator
    it = featureCollection.features();
    PointSet ret = new PointSet(featureCollection.size());
    int i = 0;
    while (it.hasNext()) {
        SimpleFeature feature = it.next();
        Geometry geom = (Geometry) feature.getDefaultGeometry();
        PointFeature ft = new PointFeature();
        ft.setGeom(geom);
        // Set feature's ID to the specified ID field, or to index if none is specified
        if (originIDField == null) {
            ft.setId(Integer.toString(i));
        } else {
            ft.setId(feature.getProperty(originIDField).getValue().toString());
        }
        for (Property prop : feature.getProperties()) {
            String propName = prop.getName().toString();
            if (propertyFields.contains(propName)) {
                Object binding = prop.getType().getBinding();
                // attempt to coerce the prop's value into an integer
                int val;
                if (binding.equals(Integer.class)) {
                    val = (Integer) prop.getValue();
                } else if (binding.equals(Long.class)) {
                    val = ((Long) prop.getValue()).intValue();
                } else if (binding.equals(String.class)) {
                    try {
                        val = Integer.parseInt((String) prop.getValue());
                    } catch (NumberFormatException ex) {
                        continue;
                    }
                } else {
                    LOG.debug("Property {} of feature {} could not be interpreted as int, skipping", prop.getName().toString(), ft.getId());
                    continue;
                }
                ft.addAttribute(propName, val);
            } else {
                LOG.debug("Property {} not requested; igoring", propName);
            }
        }
        ret.addFeature(ft, i);
        i++;
    }
    ArrayList<String> IDlist = new ArrayList<String>();
    for (String id : ret.ids) {
        IDlist.add(id);
    }
    LOG.debug("Created PointSet from shapefile with IDs {}", IDlist);
    return ret;
}
Also used : Query(org.geotools.data.Query) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) ArrayList(java.util.ArrayList) SimpleFeature(org.opengis.feature.simple.SimpleFeature) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) Geometry(com.vividsolutions.jts.geom.Geometry) SimpleFeatureIterator(org.geotools.data.simple.SimpleFeatureIterator) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) FileDataStore(org.geotools.data.FileDataStore) Property(org.opengis.feature.Property)

Example 24 with SimpleFeatureIterator

use of org.geotools.data.simple.SimpleFeatureIterator in project OpenTripPlanner by opentripplanner.

the class ShapefilePopulation method createIndividuals.

@Override
public void createIndividuals() {
    String filename = this.sourceFilename;
    LOG.debug("Loading population from shapefile {}", filename);
    LOG.debug("Feature attributes: input data in {}, labeled with {}", inputAttribute, labelAttribute);
    try {
        File file = new File(filename);
        if (!file.exists())
            throw new RuntimeException("Shapefile does not exist.");
        FileDataStore store = FileDataStoreFinder.getDataStore(file);
        SimpleFeatureSource featureSource = store.getFeatureSource();
        CoordinateReferenceSystem sourceCRS = featureSource.getInfo().getCRS();
        CoordinateReferenceSystem WGS84 = CRS.decode("EPSG:4326", true);
        Query query = new Query();
        query.setCoordinateSystem(sourceCRS);
        query.setCoordinateSystemReproject(WGS84);
        SimpleFeatureCollection featureCollection = featureSource.getFeatures(query);
        SimpleFeatureIterator it = featureCollection.features();
        int i = 0;
        while (it.hasNext()) {
            SimpleFeature feature = it.next();
            Geometry geom = (Geometry) feature.getDefaultGeometry();
            Point point = null;
            if (geom instanceof Point) {
                point = (Point) geom;
            } else if (geom instanceof Polygon) {
                point = ((Polygon) geom).getCentroid();
            } else if (geom instanceof MultiPolygon) {
                point = ((MultiPolygon) geom).getCentroid();
            } else {
                throw new RuntimeException("Shapefile must contain either points or polygons.");
            }
            String label;
            if (labelAttribute == null) {
                label = Integer.toString(i);
            } else {
                label = feature.getAttribute(labelAttribute).toString();
            }
            double input = 0.0;
            if (inputAttribute != null) {
                Number n = (Number) feature.getAttribute(inputAttribute);
                input = n.doubleValue();
            }
            Individual individual = new Individual(label, point.getX(), point.getY(), input);
            this.addIndividual(individual);
            i += 1;
        }
        LOG.debug("loaded {} features", i);
        it.close();
    } catch (Exception ex) {
        LOG.error("Error loading population from shapefile: {}", ex.getMessage());
        throw new RuntimeException(ex);
    }
    LOG.debug("Done loading shapefile.");
}
Also used : Query(org.geotools.data.Query) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) Point(com.vividsolutions.jts.geom.Point) Point(com.vividsolutions.jts.geom.Point) SimpleFeature(org.opengis.feature.simple.SimpleFeature) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) Geometry(com.vividsolutions.jts.geom.Geometry) SimpleFeatureIterator(org.geotools.data.simple.SimpleFeatureIterator) MultiPolygon(com.vividsolutions.jts.geom.MultiPolygon) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) MultiPolygon(com.vividsolutions.jts.geom.MultiPolygon) Polygon(com.vividsolutions.jts.geom.Polygon) File(java.io.File) FileDataStore(org.geotools.data.FileDataStore)

Example 25 with SimpleFeatureIterator

use of org.geotools.data.simple.SimpleFeatureIterator in project coastal-hazards by USGS-CIDA.

the class FeatureCollectionExport method writeToShapefile.

public boolean writeToShapefile() throws MalformedURLException, IOException {
    boolean success = false;
    // SimpleFeatureIterator features = simpleFeatureCollection.features();
    SimpleFeatureType type = buildFeatureType();
    FileDataStoreFactorySpi factory = FileDataStoreFinder.getDataStoreFactory("shp");
    File shpFile = checkAndCreateFile();
    Map datastoreConfig = new HashMap<>();
    datastoreConfig.put("url", shpFile.toURI().toURL());
    ShapefileDataStore shpfileDataStore = (ShapefileDataStore) factory.createNewDataStore(datastoreConfig);
    shpfileDataStore.createSchema(type);
    shpfileDataStore.forceSchemaCRS(this.crs);
    // DataStore dataStore = factory.createNewDataStore(datastoreConfig);
    SimpleFeatureStore featureStore = (SimpleFeatureStore) shpfileDataStore.getFeatureSource(type.getName());
    Transaction t = new DefaultTransaction();
    SimpleFeatureIterator fi = null;
    try {
        // Copied directly from Import process
        featureStore.setTransaction(t);
        fi = simpleFeatureCollection.features();
        SimpleFeatureBuilder fb = new SimpleFeatureBuilder(type);
        while (fi.hasNext()) {
            SimpleFeature source = fi.next();
            fb.reset();
            for (AttributeDescriptor desc : type.getAttributeDescriptors()) {
                Name attributeName = desc.getName();
                Object attributeValue = source.getAttribute(attributeName);
                if (null == attributeValue) {
                    attributeValue = NULL_PLACEHOLDER;
                }
                fb.set(attributeName, attributeValue);
            }
            SimpleFeature target = fb.buildFeature(null);
            featureStore.addFeatures(DataUtilities.collection(target));
        }
        // successful if it made it this far
        success = true;
    } finally {
        t.commit();
        t.close();
        IOUtils.closeQuietly(fi);
    }
    return success;
}
Also used : ShapefileDataStore(org.geotools.data.shapefile.ShapefileDataStore) HashMap(java.util.HashMap) AttributeDescriptor(org.opengis.feature.type.AttributeDescriptor) DefaultTransaction(org.geotools.data.DefaultTransaction) SimpleFeature(org.opengis.feature.simple.SimpleFeature) Name(org.opengis.feature.type.Name) FileDataStoreFactorySpi(org.geotools.data.FileDataStoreFactorySpi) SimpleFeatureIterator(org.geotools.data.simple.SimpleFeatureIterator) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) Transaction(org.geotools.data.Transaction) DefaultTransaction(org.geotools.data.DefaultTransaction) SimpleFeatureStore(org.geotools.data.simple.SimpleFeatureStore) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map) SimpleFeatureBuilder(org.geotools.feature.simple.SimpleFeatureBuilder)

Aggregations

SimpleFeatureIterator (org.geotools.data.simple.SimpleFeatureIterator)33 SimpleFeature (org.opengis.feature.simple.SimpleFeature)33 SimpleFeatureCollection (org.geotools.data.simple.SimpleFeatureCollection)24 SimpleFeatureSource (org.geotools.data.simple.SimpleFeatureSource)19 SimpleFeatureType (org.opengis.feature.simple.SimpleFeatureType)15 SimpleFeatureStore (org.geotools.data.simple.SimpleFeatureStore)13 Test (org.junit.Test)13 SimpleFeatureBuilder (org.geotools.feature.simple.SimpleFeatureBuilder)10 IOException (java.io.IOException)9 ArrayList (java.util.ArrayList)9 MemoryDataStore (org.geotools.data.memory.MemoryDataStore)9 Feature (org.opengis.feature.Feature)9 AttributeDescriptor (org.opengis.feature.type.AttributeDescriptor)8 HashMap (java.util.HashMap)6 Query (org.geotools.data.Query)6 Geometry (com.vividsolutions.jts.geom.Geometry)5 Map (java.util.Map)5 DataStore (org.geotools.data.DataStore)5 ListFeatureCollection (org.geotools.data.collection.ListFeatureCollection)5 File (java.io.File)4