use of org.geotools.util.factory.Hints in project core-geonetwork by geonetwork.
the class DirectoryApi method shapeFileToFeatureCollection.
private SimpleFeatureCollection shapeFileToFeatureCollection(File shapefile) throws IOException {
Map<String, Object> map = new HashMap<>();
map.put("url", shapefile.toURI().toURL());
DataStore dataStore = DataStoreFinder.getDataStore(map);
String typeName = dataStore.getTypeNames()[0];
SimpleFeatureSource source = dataStore.getFeatureSource(typeName);
Query query = new Query(typeName, Filter.INCLUDE);
query.setHints(new Hints(Hints.FEATURE_2D, true));
return source.getFeatures(query);
}
use of org.geotools.util.factory.Hints in project georchestra by georchestra.
the class WcsCoverageReader method geotoolsTranformation.
private void geotoolsTranformation(final File sourceFile, final File file, final WcsReaderRequest request, final CoordinateReferenceSystem original) throws IOException {
LOG.info("using Geotools libraries to tranform the coverage");
CoverageTransformation<Object> transformation = new CoverageTransformation<Object>() {
@Override
public Object transform(final GridCoverage coverage) throws IOException, FactoryException {
boolean writeToTmp = sourceFile.equals(file);
Hints hints = new Hints(GeoTools.getDefaultHints());
hints.put(Hints.LENIENT_DATUM_SHIFT, Boolean.TRUE);
GeoTools.init(hints);
Coverage transformed = Operations.DEFAULT.resample(coverage, original);
AbstractGridFormat format = Formats.getFormat(request.format);
if (writeToTmp) {
File tmpDir = FileUtils.createTempDirectory();
try {
File tmpFile = new File(tmpDir, file.getName());
// write must be to tmpFile because Geotools does not always
// load coverages into memory but reads off disk
GridCoverageWriter writer = format.getWriter(tmpFile);
file.delete();
ParameterValue<String> formatParam = FORMAT.createValue();
formatParam.setValue(request.format);
writer.write((GridCoverage) transformed, new GeneralParameterValue[] { formatParam });
// so move all files in the tmpDir
for (File f : tmpDir.listFiles()) {
File dest = new File(file.getParentFile(), f.getName());
FileUtils.moveFile(f, dest);
}
} finally {
FileUtils.delete(tmpDir);
}
} else {
GridCoverageWriter writer = format.getWriter(file);
writer.write((GridCoverage) transformed, null);
}
LOG.debug("Finished reprojecting output");
return null;
}
};
CoverageTransformation.perform(sourceFile, transformation);
}
use of org.geotools.util.factory.Hints in project r5 by conveyal.
the class DataSourcePreviewGenerator method wgsPreviewGeometries.
/**
* As a simplification when generating previews for some kinds of DataSources, return JTS Geometries rather than
* complete GeoTools features. These Geometries will be converted to features for serialization to GeoJSON.
* The userData on the first geometry in the list will determine the attribute schema. This userData must be null
* or a Map<String, Object>. The user data on all subsequent features must have the same fields and types.
* All geometries in the list must be of the same type. They must all be in longitude-first WGS84, as JTS
* geometries do not have rich CRS data associated with them and cannot be automatically reprojected by GeoTools
* when it writes GeoJSON.
* @return wgs84 geometries with a map of attributes in userData, which can be converted to GeoTools features.
*/
private List<Geometry> wgsPreviewGeometries(DataSource dataSource) {
if (dataSource.fileFormat == FileStorageFormat.GEOTIFF) {
try {
// FIXME this duplicates a lot of code in RasterDataSourceSampler, raster reading should be factored out.
// This is crazy verbose considering that we're taking an Envelope with CRS from a GeoTools object
// and have the final objective of turning it into a GeoTools feature, but we're passing through JTS
// where we lose the CRS information.
File localRasterFile = fileStorage.getFile(dataSource.fileStorageKey());
AbstractGridFormat format = GridFormatFinder.findFormat(localRasterFile);
// Only relevant for certain files with WGS CRS?
Hints hints = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE);
GridCoverage2DReader coverageReader = format.getReader(localRasterFile, hints);
GridCoverage2D coverage = coverageReader.read(null);
// Set CRS transform from WGS84 to coverage, if any.
CoordinateReferenceSystem crs = coverage.getCoordinateReferenceSystem2D();
MathTransform coverageToWgs = CRS.findMathTransform(crs, DefaultGeographicCRS.WGS84);
Polygon projectedPolygon = JTS.toPolygon(coverage.getEnvelope2D());
Geometry wgsGeometry = JTS.transform(projectedPolygon, coverageToWgs);
wgsGeometry.setUserData(Map.of("name", dataSource.name));
return List.of(wgsGeometry);
} catch (Exception e) {
throw new RuntimeException("Exception reading raster:", e);
}
}
return defaultWgsPreviewGeometries(dataSource);
}
use of org.geotools.util.factory.Hints in project OpenTripPlanner by opentripplanner.
the class ShapefileStreetModule method buildGraph.
@Override
public void buildGraph(Graph graph, HashMap<Class<?>, Object> extra, DataImportIssueStore issueStore) {
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) {
StreetNote noteAlert = new StreetNote(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.util.factory.Hints in project hortonmachine by TheHortonMachine.
the class OmsRasterWriter method writeGeotiff.
private void writeGeotiff(File mapFile) throws Exception {
final GeoTiffFormat format = new GeoTiffFormat();
final GeoTiffWriteParams wp = new GeoTiffWriteParams();
wp.setCompressionMode(GeoTiffWriteParams.MODE_DEFAULT);
wp.setTilingMode(GeoToolsWriteParams.MODE_DEFAULT);
final ParameterValueGroup paramWrite = format.getWriteParameters();
paramWrite.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString()).setValue(wp);
// (GeoTiffWriter) format.getWriter(mapFile);
GeoTiffWriter gtw = new GeoTiffWriter(mapFile, new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE));
gtw.write(inRaster, (GeneralParameterValue[]) paramWrite.values().toArray(new GeneralParameterValue[1]));
}
Aggregations