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