use of org.geotools.feature.FeatureCollection in project GeoGig by boundlessgeo.
the class GeoJsonExport method runInternal.
/**
* Executes the export command using the provided options.
*/
@Override
protected void runInternal(GeogigCLI cli) throws InvalidParameterException, CommandFailedException, IOException {
if (args.isEmpty()) {
printUsage(cli);
throw new CommandFailedException();
}
String path = args.get(0);
String geojson = args.get(1);
File file = new File(geojson);
if (file.exists() && !overwrite) {
throw new CommandFailedException("The selected GeoJSON file already exists. Use -o to overwrite");
}
SimpleFeatureType outputFeatureType;
ObjectId featureTypeId;
if (sFeatureTypeId != null) {
// Check the feature type id string is a correct id
Optional<ObjectId> id = cli.getGeogig().command(RevParse.class).setRefSpec(sFeatureTypeId).call();
checkParameter(id.isPresent(), "Invalid feature type reference", sFeatureTypeId);
TYPE type = cli.getGeogig().command(ResolveObjectType.class).setObjectId(id.get()).call();
checkParameter(type.equals(TYPE.FEATURETYPE), "Provided reference does not resolve to a feature type: ", sFeatureTypeId);
outputFeatureType = (SimpleFeatureType) cli.getGeogig().command(RevObjectParse.class).setObjectId(id.get()).call(RevFeatureType.class).get().type();
featureTypeId = id.get();
} else {
try {
outputFeatureType = getFeatureType(path, cli);
featureTypeId = null;
} catch (GeoToolsOpException e) {
cli.getConsole().println("No features to export.");
return;
}
}
DataStore dataStore = new MemoryDataStore(outputFeatureType);
final String typeName = dataStore.getTypeNames()[0];
final SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName);
if (!(featureSource instanceof SimpleFeatureStore)) {
throw new CommandFailedException("Could not create feature store.");
}
final SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
ExportOp op = cli.getGeogig().command(ExportOp.class).setFeatureStore(featureStore).setPath(path).setFilterFeatureTypeId(featureTypeId).setAlter(alter);
op.setTransactional(false);
if (defaultType) {
op.exportDefaultFeatureType();
}
FileWriter writer = null;
try {
op.setProgressListener(cli.getProgressListener()).call();
FeatureJSON fjson = new FeatureJSON();
@SuppressWarnings("rawtypes") FeatureCollection fc = featureSource.getFeatures();
writer = new FileWriter(file);
fjson.writeFeatureCollection(fc, writer);
} catch (IllegalArgumentException iae) {
throw new org.locationtech.geogig.cli.InvalidParameterException(iae.getMessage(), iae);
} catch (GeoToolsOpException e) {
file.delete();
switch(e.statusCode) {
case MIXED_FEATURE_TYPES:
throw new CommandFailedException("Error: The selected tree contains mixed feature types. Use --defaulttype or --featuretype <feature_type_ref> to export.", e);
default:
throw new CommandFailedException("Could not export. Error:" + e.statusCode.name(), e);
}
} finally {
writer.flush();
writer.close();
}
cli.getConsole().println(path + " exported successfully to " + geojson);
}
use of org.geotools.feature.FeatureCollection in project chordatlas by twak.
the class Footprints method test.
public static void test() throws IOException, SAXException, ParserConfigurationException {
// create the parser with the gml 2.0 configuration
org.geotools.xml.Configuration configuration = new org.geotools.gml2.GMLConfiguration();
org.geotools.xml.Parser parser = new org.geotools.xml.Parser(configuration);
InputStream xml = new FileInputStream("/home/twak/data/around_ucl_buildings.gml");
// parse
FeatureCollection fc = (FeatureCollection) parser.parse(xml);
fc.accepts(new AbstractFeatureVisitor() {
public void visit(Feature feature) {
System.out.println(feature);
// SimpleFeature f = (Feature) i.next();
//
// Point point = (Point) f.getDefaultGeometry();
// String name = (String) f.getAttribute( "name" );
}
}, new NullProgressListener());
}
use of org.geotools.feature.FeatureCollection in project spatial-portal by AtlasOfLivingAustralia.
the class PointGenerationComposer method onFinish.
@Override
public boolean onFinish() {
SelectedArea sa = getSelectedArea();
double[][] bbox = null;
if (sa.getMapLayer() != null && sa.getMapLayer().getMapLayerMetadata() != null) {
List<Double> bb = sa.getMapLayer().getMapLayerMetadata().getBbox();
bbox = new double[2][2];
bbox[0][0] = bb.get(0);
bbox[0][1] = bb.get(1);
bbox[1][0] = bb.get(2);
bbox[1][1] = bb.get(3);
} else {
List<Double> bb = Util.getBoundingBox(sa.getWkt());
bbox = new double[][] { { bb.get(0), bb.get(1) }, { bb.get(2), bb.get(3) } };
}
// with bounding box, cut points
try {
String wkt = (sa.getMapLayer() != null ? sa.getMapLayer().getWKT() : sa.getWkt());
StringBuilder sb = new StringBuilder();
sb.append("longitude,latitude");
int count = 0;
int width = (int) Math.ceil((bbox[1][0] - bbox[0][0]) / resolution.getValue());
int height = (int) Math.ceil((bbox[1][1] - bbox[0][1]) / resolution.getValue());
double startx = Math.floor(bbox[0][0] / resolution.getValue()) * resolution.getValue();
double starty = Math.floor(bbox[0][1] / resolution.getValue()) * resolution.getValue();
if (wkt == null) {
if (sa.getFacets() != null) {
double[][] points = new double[(width + 1) * (height + 1)][2];
int pos = 0;
for (int i = 0; i <= width; i++) {
for (int j = 0; j <= height; j++) {
double lng = startx + i * resolution.getValue();
double lat = starty + j * resolution.getValue();
points[pos][0] = lng;
points[pos][1] = lat;
pos = pos + 1;
}
}
List<String> fields = new ArrayList<String>();
for (Facet f : sa.getFacets()) {
fields.add(f.getFields()[0]);
}
List<String[]> result = Sampling.sampling(fields, points);
for (int i = 0; i < result.size(); i++) {
Facet f = sa.getFacets().get(i);
String[] intersection = result.get(i);
for (int j = 0; j < intersection.length; j++) {
if (f.isValid("\"" + intersection[j] + "\"")) {
sb.append("\n");
sb.append(points[j][0]).append(",").append(points[j][1]);
count++;
}
}
}
} else {
LOGGER.error("invalid area selected for point generation");
getMapComposer().showMessage("Unsupported area selected for point generation. Choose a different area.");
return false;
}
} else {
// write temporary shapefile
File tmp = File.createTempFile("tmp", ".shp");
ShapefileUtils.saveShapefile(tmp, wkt, "tmp");
FileDataStore store = FileDataStoreFinder.getDataStore(tmp);
FeatureSource featureSource = store.getFeatureSource(store.getTypeNames()[0]);
FeatureCollection featureCollection = featureSource.getFeatures();
GeometryFactory gf = new GeometryFactory();
List<Geometry> geometry = new ArrayList<Geometry>();
FeatureIterator it = featureCollection.features();
while (it.hasNext()) {
SimpleFeature feature = (SimpleFeature) it.next();
geometry.add((Geometry) feature.getDefaultGeometry());
}
try {
it.close();
} catch (Exception e) {
}
for (int i = 0; i <= width; i++) {
for (int j = 0; j <= height; j++) {
double lng = startx + i * resolution.getValue();
double lat = starty + j * resolution.getValue();
Coordinate c = new Coordinate(lng, lat);
Geometry point = gf.createPoint(c);
for (Geometry geom : geometry) {
if (geom.contains(point)) {
sb.append("\n");
sb.append(lng).append(",").append(lat);
count++;
}
}
}
}
// close tmp file
try {
store.dispose();
} catch (Exception e) {
}
// delete tmp files
try {
FileUtils.deleteQuietly(tmp);
FileUtils.deleteQuietly(new File(tmp.getPath().replace(".shp", ".shx")));
FileUtils.deleteQuietly(new File(tmp.getPath().replace(".shp", ".fix")));
FileUtils.deleteQuietly(new File(tmp.getPath().replace(".shp", ".dbf")));
FileUtils.deleteQuietly(new File(tmp.getPath().replace(".shp", ".prj")));
} catch (Exception e) {
}
}
if (count <= 0) {
getMapComposer().showMessage("No points generated. Try again with a smaller resolution or larger area.");
} else if (count > Integer.parseInt(CommonData.getSettings().getProperty("max_record_count_upload"))) {
getMapComposer().showMessage(count + " points generated. Maximum is " + CommonData.getSettings().getProperty("generated_points_max") + ".\n" + "Try again with a larger resolution or smaller area.");
} else {
String name = tToolName.getValue();
try {
UploadSpeciesController.loadUserPoints(new UserDataDTO(name), new StringReader(sb.toString()), true, name, "points in " + getSelectedAreaDisplayName() + " on " + resolution.getValue() + " degree resolution grid.", getMapComposer(), null);
detach();
return true;
} catch (Exception e) {
LOGGER.error("failed to upload points");
}
}
} catch (Exception e) {
}
return false;
}
use of org.geotools.feature.FeatureCollection in project OpenTripPlanner by opentripplanner.
the class SurfaceResource method getIsochrone.
/**
* Create vector isochrones for a surface.
*/
@GET
@Path("/{surfaceId}/isochrone")
public Response getIsochrone(@PathParam("surfaceId") Integer surfaceId, @QueryParam("spacing") int spacing, @QueryParam("nMax") @DefaultValue("1") int nMax) {
final TimeSurface surf = otpServer.surfaceCache.get(surfaceId);
if (surf == null)
return badRequest("Invalid TimeSurface ID.");
if (spacing < 1)
spacing = 30;
List<IsochroneData> isochrones = getIsochronesAccumulative(surf, spacing, nMax);
// NOTE that cutoffMinutes in the surface must be properly set for the following call to work
final FeatureCollection fc = LIsochrone.makeContourFeatures(isochrones);
return Response.ok().entity(new StreamingOutput() {
@Override
public void write(OutputStream output) throws IOException {
FeatureJSON fj = new FeatureJSON();
fj.writeFeatureCollection(fc, output);
}
}).build();
}
Aggregations