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;
}
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.");
}
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;
}
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();
}
Aggregations