Search in sources :

Example 51 with SimpleFeatureSource

use of org.geotools.data.simple.SimpleFeatureSource 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 52 with SimpleFeatureSource

use of org.geotools.data.simple.SimpleFeatureSource 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 53 with SimpleFeatureSource

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

the class WFSExportClient method getFeatureCollection.

@Override
public SimpleFeatureCollection getFeatureCollection(String typeName, Filter filter) throws IOException {
    if (wfs == null) {
        throw new IllegalStateException("Must set up datastore prior to accessing wfs");
    }
    SimpleFeatureSource featureSource = wfs.getFeatureSource(typeName);
    SimpleFeatureCollection sfc = null;
    if (filter != null) {
        sfc = featureSource.getFeatures(filter);
    } else {
        sfc = featureSource.getFeatures();
    }
    return sfc;
}
Also used : SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection)

Example 54 with SimpleFeatureSource

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

the class FeatureCollectionExportTest method testWriteSolo.

@Test
@Ignore
public void testWriteSolo() throws Exception {
    WFSDataStoreFactory datastore = new WFSDataStoreFactory();
    Map params = new HashMap<>();
    params.put(WFSDataStoreFactory.URL.key, new URL("http://coastalmap.marine.usgs.gov/cmgp/National/cvi_WFS/MapServer/WFSServer?service=WFS&request=GetCapabilities&version=1.0.0"));
    params.put(WFSDataStoreFactory.WFS_STRATEGY.key, "arcgis");
    params.put(WFSDataStoreFactory.TIMEOUT.key, 15000);
    params.put(WFSDataStoreFactory.TRY_GZIP.key, "true");
    WFSDataStore wfs = datastore.createDataStore(params);
    String[] typeNames = wfs.getTypeNames();
    SimpleFeatureSource featureSource = wfs.getFeatureSource(typeNames[2]);
    SimpleFeatureType schema = featureSource.getSchema();
    FileDataStoreFactorySpi factory = FileDataStoreFinder.getDataStoreFactory("shp");
    Map datastoreConfig = new HashMap<>();
    datastoreConfig.put("url", FileUtils.getFile(FileUtils.getTempDirectory(), "test3.shp").toURI().toURL());
    ShapefileDataStore shpfileDataStore = (ShapefileDataStore) factory.createNewDataStore(datastoreConfig);
    shpfileDataStore.createSchema(schema);
    shpfileDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
    SimpleFeatureStore featureStore = (SimpleFeatureStore) shpfileDataStore.getFeatureSource();
    Transaction t = new DefaultTransaction();
    // Copied directly from Import process
    featureStore.setTransaction(t);
    Query query = new Query();
    query.setCoordinateSystem(DefaultGeographicCRS.WGS84);
    SimpleFeatureIterator fi = featureSource.getFeatures(query).features();
    SimpleFeatureBuilder fb = new SimpleFeatureBuilder(schema);
    while (fi.hasNext()) {
        SimpleFeature source = fi.next();
        fb.reset();
        for (AttributeDescriptor desc : schema.getAttributeDescriptors()) {
            fb.set(desc.getName(), source.getAttribute(desc.getName()));
        }
        SimpleFeature target = fb.buildFeature(null);
        target.setDefaultGeometry(source.getDefaultGeometry());
        featureStore.addFeatures(DataUtilities.collection(target));
    }
    t.commit();
    t.close();
}
Also used : ShapefileDataStore(org.geotools.data.shapefile.ShapefileDataStore) Query(org.geotools.data.Query) HashMap(java.util.HashMap) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) AttributeDescriptor(org.opengis.feature.type.AttributeDescriptor) WFSDataStore(org.geotools.data.wfs.WFSDataStore) URL(java.net.URL) DefaultTransaction(org.geotools.data.DefaultTransaction) SimpleFeature(org.opengis.feature.simple.SimpleFeature) 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) WFSDataStoreFactory(org.geotools.data.wfs.WFSDataStoreFactory) HashMap(java.util.HashMap) Map(java.util.Map) SimpleFeatureBuilder(org.geotools.feature.simple.SimpleFeatureBuilder) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

SimpleFeatureSource (org.geotools.data.simple.SimpleFeatureSource)54 SimpleFeatureType (org.opengis.feature.simple.SimpleFeatureType)29 IOException (java.io.IOException)28 SimpleFeatureStore (org.geotools.data.simple.SimpleFeatureStore)25 SimpleFeature (org.opengis.feature.simple.SimpleFeature)23 DataStore (org.geotools.data.DataStore)22 Test (org.junit.Test)21 SimpleFeatureCollection (org.geotools.data.simple.SimpleFeatureCollection)20 SimpleFeatureIterator (org.geotools.data.simple.SimpleFeatureIterator)19 Feature (org.opengis.feature.Feature)16 HashMap (java.util.HashMap)15 MemoryDataStore (org.geotools.data.memory.MemoryDataStore)13 URL (java.net.URL)10 CommandFailedException (org.locationtech.geogig.cli.CommandFailedException)10 GeoToolsOpException (org.locationtech.geogig.geotools.plumbing.GeoToolsOpException)10 ExportOp (org.locationtech.geogig.geotools.plumbing.ExportOp)9 ArrayList (java.util.ArrayList)8 Map (java.util.Map)8 SimpleFeatureBuilder (org.geotools.feature.simple.SimpleFeatureBuilder)8 InvalidParameterException (org.locationtech.geogig.cli.InvalidParameterException)8