Search in sources :

Example 31 with SimpleFeatureCollection

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

the class SimpleIsochrone method zippedShapefileGet.

/**
 * @return Evenly spaced travel time contours (isochrones) as a zipped shapefile.
 */
@GET
@Produces("application/x-zip-compressed")
public Response zippedShapefileGet(@QueryParam("stream") @DefaultValue("true") boolean stream) throws Exception {
    SimpleFeatureCollection contourFeatures = makeContourFeatures();
    /* Output the staged features to Shapefile */
    final File shapeDir = Files.createTempDir();
    File shapeFile = new File(shapeDir, shpName + ".shp");
    LOG.debug("writing out shapefile {}", shapeFile);
    ShapefileDataStore outStore = new ShapefileDataStore(shapeFile.toURI().toURL());
    outStore.createSchema(contourSchema);
    /* "FeatureSource is used to read features, the subclass FeatureStore is used for 
         * read/write access. The way to tell if a File can be written to in GeoTools is to use an 
         * instanceof check. */
    SimpleFeatureStore featureStore = (SimpleFeatureStore) outStore.getFeatureSource();
    featureStore.addFeatures(contourFeatures);
    // close?
    // Note: the order is important
    shapeDir.deleteOnExit();
    for (File f : shapeDir.listFiles()) f.deleteOnExit();
    /* Zip up the shapefile components */
    StreamingOutput output = new DirectoryZipper(shapeDir);
    if (stream) {
        return Response.ok().entity(output).build();
    } else {
        File zipFile = new File(shapeDir, shpName + ".zip");
        OutputStream fos = new FileOutputStream(zipFile);
        output.write(fos);
        zipFile.deleteOnExit();
        return Response.ok().entity(zipFile).build();
    }
}
Also used : ShapefileDataStore(org.geotools.data.shapefile.ShapefileDataStore) SimpleFeatureStore(org.geotools.data.simple.SimpleFeatureStore) ZipOutputStream(java.util.zip.ZipOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) StreamingOutput(javax.ws.rs.core.StreamingOutput) File(java.io.File) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 32 with SimpleFeatureCollection

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

the class SimpleIsochrone method geoJsonGet.

/**
 * @return Evenly spaced travel time contours (isochrones) as GeoJSON.
 */
@GET
@Produces("application/json")
public Response geoJsonGet() throws Exception {
    /* QGIS seems to want multi-features rather than multi-geometries. */
    SimpleFeatureCollection contourFeatures = makeContourFeatures();
    /* Output the staged features to JSON */
    StringWriter writer = new StringWriter();
    FeatureJSON fj = new FeatureJSON();
    fj.writeFeatureCollection(contourFeatures, writer);
    return Response.ok().entity(writer.toString()).build();
}
Also used : FeatureJSON(org.geotools.geojson.feature.FeatureJSON) StringWriter(java.io.StringWriter) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 33 with SimpleFeatureCollection

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

use of org.geotools.data.simple.SimpleFeatureCollection in project hale by halestudio.

the class ShapefileInstanceWriter method writeToFile.

/**
 * Final step to write to the shape file using transaction.
 *
 * @param schemaDataStoreMap data store for the shape file.
 * @param schemaFtMap used as a template to describe the file contents.
 * @param schemaFeaturesMap for each schema, each geom list of features to
 *            be written to the shape file.
 * @throws IOException if any.
 */
private void writeToFile(Map<String, Map<String, ShapefileDataStore>> schemaDataStoreMap, Map<String, Map<String, SimpleFeatureType>> schemaFtMap, Map<String, Map<String, List<SimpleFeature>>> schemaFeaturesMap) throws IOException {
    // extract each schema
    for (Entry<String, Map<String, ShapefileDataStore>> schemaEntry : schemaDataStoreMap.entrySet()) {
        String localPart = schemaEntry.getKey();
        // extract each geometry.
        for (Entry<String, ShapefileDataStore> geomEntry : schemaEntry.getValue().entrySet()) {
            Transaction transaction = new DefaultTransaction(ShapefileConstants.CREATE_CONSTANT);
            String typeName = geomEntry.getValue().getTypeNames()[0];
            SimpleFeatureSource geomSpecificFeatureSource = geomEntry.getValue().getFeatureSource(typeName);
            if (geomSpecificFeatureSource instanceof SimpleFeatureStore) {
                SimpleFeatureStore geomSpecificFeatureStore = (SimpleFeatureStore) geomSpecificFeatureSource;
                // create collection to write to the shape file.
                SimpleFeatureCollection collection = new ListFeatureCollection(schemaFtMap.get(localPart).get(geomEntry.getKey()), schemaFeaturesMap.get(localPart).get(geomEntry.getKey()));
                geomSpecificFeatureStore.setTransaction(transaction);
                try {
                    geomSpecificFeatureStore.addFeatures(collection);
                    transaction.commit();
                } catch (IOException e) {
                    transaction.rollback();
                    throw e;
                } finally {
                    transaction.close();
                }
            } else {
                // throw exception
                transaction.close();
                throw new IOException(typeName + " does not support read/write access");
            }
        }
    }
}
Also used : ShapefileDataStore(org.geotools.data.shapefile.ShapefileDataStore) Transaction(org.geotools.data.Transaction) DefaultTransaction(org.geotools.data.DefaultTransaction) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) SimpleFeatureStore(org.geotools.data.simple.SimpleFeatureStore) ListFeatureCollection(org.geotools.data.collection.ListFeatureCollection) IOException(java.io.IOException) Map(java.util.Map) HashMap(java.util.HashMap) DefaultTransaction(org.geotools.data.DefaultTransaction) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection)

Example 35 with SimpleFeatureCollection

use of org.geotools.data.simple.SimpleFeatureCollection 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)

Aggregations

SimpleFeatureCollection (org.geotools.data.simple.SimpleFeatureCollection)43 SimpleFeature (org.opengis.feature.simple.SimpleFeature)27 SimpleFeatureIterator (org.geotools.data.simple.SimpleFeatureIterator)24 SimpleFeatureSource (org.geotools.data.simple.SimpleFeatureSource)21 IOException (java.io.IOException)15 SimpleFeatureStore (org.geotools.data.simple.SimpleFeatureStore)15 Test (org.junit.Test)15 SimpleFeatureType (org.opengis.feature.simple.SimpleFeatureType)12 Feature (org.opengis.feature.Feature)10 ArrayList (java.util.ArrayList)9 MemoryDataStore (org.geotools.data.memory.MemoryDataStore)9 SimpleFeatureBuilder (org.geotools.feature.simple.SimpleFeatureBuilder)9 ListFeatureCollection (org.geotools.data.collection.ListFeatureCollection)7 File (java.io.File)6 HashMap (java.util.HashMap)6 ShapefileDataStore (org.geotools.data.shapefile.ShapefileDataStore)6 AttributeDescriptor (org.opengis.feature.type.AttributeDescriptor)6 CoordinateReferenceSystem (org.opengis.referencing.crs.CoordinateReferenceSystem)6 DataStore (org.geotools.data.DataStore)5 Query (org.geotools.data.Query)5