use of org.geotools.data.Query in project polymap4-core by Polymap4.
the class PipelineReadTest method testBounds.
@Test
public void testBounds() throws IOException {
PipelineFeatureSource fs = pipeDs.getFeatureSource();
Query query = Query.ALL;
assertEquals(expected.BOUNDS, fs.getBounds(query));
query = new Query(null, Filter.INCLUDE);
assertEquals(expected.BOUNDS, fs.getBounds(query));
query = new Query(null, Filter.EXCLUDE);
assertEquals(null, fs.getBounds(query));
}
use of org.geotools.data.Query in project polymap4-core by Polymap4.
the class FeatureRenameProcessor method transformQuery.
protected Query transformQuery(Query query, ProcessorContext context) throws Exception {
assert schema != null : "Source schema is not yet initialized. Call getSchema() first.";
// FilterFactory ff = CommonFactoryFinder.getFilterFactory( GeoTools.getDefaultHints() );
// transform query
Query result = new Query(query);
result.setTypeName(srcSchema.getName().getLocalPart());
if (srcSchema.getName().getNamespaceURI() != null) {
result.setNamespace(new URI(srcSchema.getName().getNamespaceURI()));
}
// no attribute mapping
result.setPropertyNames(query.getPropertyNames());
result.setFilter(query.getFilter());
return result;
}
use of org.geotools.data.Query in project OpenTripPlanner by opentripplanner.
the class ShapefileStreetModule method buildGraph.
@Override
public void buildGraph(Graph graph, HashMap<Class<?>, Object> extra) {
try {
FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = _featureSourceFactory.getFeatureSource();
CoordinateReferenceSystem sourceCRS = featureSource.getInfo().getCRS();
Hints hints = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE);
CRSAuthorityFactory factory = ReferencingFactoryFinder.getCRSAuthorityFactory("EPSG", hints);
CoordinateReferenceSystem worldCRS = factory.createCoordinateReferenceSystem("EPSG:4326");
Query query = new Query();
query.setCoordinateSystem(sourceCRS);
query.setCoordinateSystemReproject(worldCRS);
FeatureCollection<SimpleFeatureType, SimpleFeature> features = featureSource.getFeatures(query);
features = featureSource.getFeatures(query);
HashMap<String, HashMap<Coordinate, Integer>> intersectionNameToId = new HashMap<String, HashMap<Coordinate, Integer>>();
SimpleFeatureConverter<String> streetIdConverter = _schema.getIdConverter();
SimpleFeatureConverter<String> streetNameConverter = _schema.getNameConverter();
SimpleFeatureConverter<P2<StreetTraversalPermission>> permissionConverter = _schema.getPermissionConverter();
SimpleFeatureConverter<String> noteConverter = _schema.getNoteConverter();
HashMap<Coordinate, IntersectionVertex> intersectionsByLocation = new HashMap<Coordinate, IntersectionVertex>();
SimpleFeatureConverter<P2<Double>> safetyConverter = _schema.getBicycleSafetyConverter();
SimpleFeatureConverter<Boolean> slopeOverrideCoverter = _schema.getSlopeOverrideConverter();
SimpleFeatureConverter<Boolean> featureSelector = _schema.getFeatureSelector();
// Keep track of features that are duplicated so we don't have duplicate streets
Set<Object> seen = new HashSet<Object>();
List<SimpleFeature> featureList = new ArrayList<SimpleFeature>();
FeatureIterator<SimpleFeature> it2 = features.features();
while (it2.hasNext()) {
SimpleFeature feature = it2.next();
if (featureSelector != null && !featureSelector.convert(feature)) {
continue;
}
featureList.add(feature);
}
it2.close();
it2 = null;
HashMap<Coordinate, TreeSet<String>> coordinateToStreetNames = getCoordinatesToStreetNames(featureList);
for (SimpleFeature feature : featureList) {
if (feature.getDefaultGeometry() == null) {
log.warn("feature has no geometry: " + feature.getIdentifier());
continue;
}
LineString geom = toLineString((Geometry) feature.getDefaultGeometry());
Object o = streetIdConverter.convert(feature);
String label = "" + o;
if (o != null && seen.contains(label)) {
continue;
}
seen.add(label);
String name = streetNameConverter.convert(feature);
Coordinate[] coordinates = geom.getCoordinates();
if (coordinates.length < 2) {
// not a real linestring
log.warn("Bad geometry for street with label " + label + " name " + name);
continue;
}
// this rounding is a total hack, to work around
// http://jira.codehaus.org/browse/GEOT-2811
Coordinate startCoordinate = new Coordinate(Math.round(coordinates[0].x * 1048576) / 1048576.0, Math.round(coordinates[0].y * 1048576) / 1048576.0);
Coordinate endCoordinate = new Coordinate(Math.round(coordinates[coordinates.length - 1].x * 1048576) / 1048576.0, Math.round(coordinates[coordinates.length - 1].y * 1048576) / 1048576.0);
String startIntersectionName = getIntersectionName(coordinateToStreetNames, intersectionNameToId, startCoordinate);
if (startIntersectionName == "null") {
log.warn("No intersection name for " + name);
}
String endIntersectionName = getIntersectionName(coordinateToStreetNames, intersectionNameToId, endCoordinate);
IntersectionVertex startIntersection = intersectionsByLocation.get(startCoordinate);
if (startIntersection == null) {
startIntersection = new IntersectionVertex(graph, startIntersectionName, startCoordinate.x, startCoordinate.y, new NonLocalizedString(startIntersectionName));
intersectionsByLocation.put(startCoordinate, startIntersection);
}
IntersectionVertex endIntersection = intersectionsByLocation.get(endCoordinate);
if (endIntersection == null) {
endIntersection = new IntersectionVertex(graph, endIntersectionName, endCoordinate.x, endCoordinate.y, new NonLocalizedString(endIntersectionName));
intersectionsByLocation.put(endCoordinate, endIntersection);
}
double length = 0;
for (int i = 0; i < coordinates.length - 1; ++i) {
length += JTS.orthodromicDistance(coordinates[i], coordinates[i + 1], worldCRS);
}
P2<StreetTraversalPermission> permissions = permissionConverter.convert(feature);
// TODO Set appropriate car speed from shapefile source.
StreetEdge street = edgeFactory.createEdge(startIntersection, endIntersection, geom, new NonLocalizedString(name), length, permissions.first, false);
LineString reversed = (LineString) geom.reverse();
StreetEdge backStreet = edgeFactory.createEdge(endIntersection, startIntersection, reversed, new NonLocalizedString(name), length, permissions.second, true);
backStreet.shareData(street);
if (noteConverter != null) {
String note = noteConverter.convert(feature);
if (note != null && note.length() > 0) {
Alert noteAlert = Alert.createSimpleAlerts(note);
graph.streetNotesService.addStaticNote(street, noteAlert, StreetNotesService.ALWAYS_MATCHER);
graph.streetNotesService.addStaticNote(backStreet, noteAlert, StreetNotesService.ALWAYS_MATCHER);
}
}
boolean slopeOverride = slopeOverrideCoverter.convert(feature);
street.setSlopeOverride(slopeOverride);
backStreet.setSlopeOverride(slopeOverride);
if (safetyConverter != null) {
P2<Double> safetyFactors = safetyConverter.convert(feature);
if (safetyFactors != null) {
street.setBicycleSafetyFactor(safetyFactors.first.floatValue());
backStreet.setBicycleSafetyFactor(safetyFactors.second.floatValue());
}
}
}
} catch (Exception ex) {
throw new IllegalStateException("error loading shapefile street data", ex);
} finally {
_featureSourceFactory.cleanup();
}
}
use of org.geotools.data.Query 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.Query 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.");
}
Aggregations