Search in sources :

Example 1 with FeatureIterator

use of org.geotools.feature.FeatureIterator in project spatial-portal by AtlasOfLivingAustralia.

the class ShapefileUtils method loadShapefile.

public static Map loadShapefile(File shpfile) {
    try {
        FileDataStore store = FileDataStoreFinder.getDataStore(shpfile);
        LOGGER.debug("Loading shapefile. Reading content:");
        LOGGER.debug(store.getTypeNames()[0]);
        FeatureSource featureSource = store.getFeatureSource(store.getTypeNames()[0]);
        FeatureCollection featureCollection = featureSource.getFeatures();
        FeatureIterator it = featureCollection.features();
        Map shape = new HashMap();
        StringBuilder sb = new StringBuilder();
        StringBuilder sbGeometryCollection = new StringBuilder();
        boolean isGeometryCollection = false;
        while (it.hasNext()) {
            SimpleFeature feature = (SimpleFeature) it.next();
            Geometry geom = (Geometry) feature.getDefaultGeometry();
            WKTWriter wkt = new WKTWriter();
            String wktString = wkt.write(geom);
            wktString = wktString.replaceAll(", ", ",");
            boolean valid = true;
            boolean multipolygon = false;
            boolean polygon = false;
            boolean geometrycollection = false;
            if (wktString.startsWith(StringConstants.MULTIPOLYGON + " ")) {
                wktString = wktString.substring((StringConstants.MULTIPOLYGON + " (").length(), wktString.length() - 1);
                multipolygon = true;
            } else if (wktString.startsWith(StringConstants.POLYGON + " ")) {
                wktString = wktString.substring((StringConstants.POLYGON + " ").length());
                polygon = true;
            } else if (wktString.startsWith(StringConstants.GEOMETRYCOLLECTION + " (")) {
                wktString = wktString.substring((StringConstants.GEOMETRYCOLLECTION + " (").length(), wktString.length() - 1);
                geometrycollection = true;
                isGeometryCollection = true;
            } else {
                valid = false;
            }
            if (valid) {
                if (sb.length() > 0) {
                    sb.append(",");
                    sbGeometryCollection.append(",");
                }
                sb.append(wktString);
                if (multipolygon) {
                    sbGeometryCollection.append(StringConstants.MULTIPOLYGON).append("(").append(wktString.replace("(((", "(("));
                    if (!wktString.endsWith(")))")) {
                        sbGeometryCollection.append(")");
                    }
                } else if (polygon) {
                    sbGeometryCollection.append(StringConstants.POLYGON).append(wktString);
                } else if (geometrycollection) {
                    sbGeometryCollection.append(wktString);
                }
            }
        }
        if (!isGeometryCollection) {
            if (!sb.toString().contains(")))")) {
                sb.append(")");
            }
            shape.put(StringConstants.WKT, StringConstants.MULTIPOLYGON + "(" + sb.toString().replace("(((", "(("));
        } else {
            sbGeometryCollection.append(")");
            shape.put(StringConstants.WKT, StringConstants.GEOMETRYCOLLECTION + "(" + sbGeometryCollection);
        }
        try {
            it.close();
        } catch (Exception e) {
        }
        return shape;
    } catch (Exception e) {
        LOGGER.error("Unable to load shapefile: ", e);
    }
    return null;
}
Also used : SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) WKTWriter(com.vividsolutions.jts.io.WKTWriter) HashMap(java.util.HashMap) SimpleFeature(org.opengis.feature.simple.SimpleFeature) FeatureIterator(org.geotools.feature.FeatureIterator) Geometry(com.vividsolutions.jts.geom.Geometry) DefaultFeatureCollection(org.geotools.feature.DefaultFeatureCollection) FeatureCollection(org.geotools.feature.FeatureCollection) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with FeatureIterator

use of org.geotools.feature.FeatureIterator in project GeoGig by boundlessgeo.

the class ImportOp method getFeatureSource.

@SuppressWarnings({ "rawtypes", "unchecked" })
private FeatureSource getFeatureSource(String typeName) {
    FeatureSource featureSource;
    try {
        featureSource = dataStore.getFeatureSource(typeName);
    } catch (Exception e) {
        throw new GeoToolsOpException(StatusCode.UNABLE_TO_GET_FEATURES);
    }
    return new ForwardingFeatureSource(featureSource) {

        @Override
        public FeatureCollection getFeatures(Query query) throws IOException {
            final FeatureCollection features = super.getFeatures(query);
            return new ForwardingFeatureCollection(features) {

                @Override
                public FeatureIterator features() {
                    final FeatureType featureType = getSchema();
                    final String fidPrefix = featureType.getName().getLocalPart() + ".";
                    FeatureIterator iterator = delegate.features();
                    return new FidAndFtReplacerIterator(iterator, fidAttribute, fidPrefix, (SimpleFeatureType) featureType);
                }
            };
        }
    };
}
Also used : FeatureIterator(org.geotools.feature.FeatureIterator) ForwardingFeatureIterator(org.locationtech.geogig.api.data.ForwardingFeatureIterator) ForwardingFeatureSource(org.locationtech.geogig.api.data.ForwardingFeatureSource) JDBCFeatureSource(org.geotools.jdbc.JDBCFeatureSource) FeatureSource(org.geotools.data.FeatureSource) ResolveFeatureType(org.locationtech.geogig.api.plumbing.ResolveFeatureType) RevFeatureType(org.locationtech.geogig.api.RevFeatureType) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) FeatureType(org.opengis.feature.type.FeatureType) Query(org.geotools.data.Query) ForwardingFeatureCollection(org.locationtech.geogig.api.data.ForwardingFeatureCollection) ForwardingFeatureCollection(org.locationtech.geogig.api.data.ForwardingFeatureCollection) FeatureCollection(org.geotools.feature.FeatureCollection) ForwardingFeatureSource(org.locationtech.geogig.api.data.ForwardingFeatureSource) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException)

Example 3 with FeatureIterator

use of org.geotools.feature.FeatureIterator 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;
}
Also used : GeometryFactory(com.vividsolutions.jts.geom.GeometryFactory) SelectedArea(au.org.emii.portal.menu.SelectedArea) ArrayList(java.util.ArrayList) FeatureIterator(org.geotools.feature.FeatureIterator) StringReader(java.io.StringReader) UserDataDTO(au.org.ala.spatial.dto.UserDataDTO) FileDataStore(org.geotools.data.FileDataStore) Facet(au.org.ala.legend.Facet) FeatureSource(org.geotools.data.FeatureSource) SimpleFeature(org.opengis.feature.simple.SimpleFeature) Geometry(com.vividsolutions.jts.geom.Geometry) FeatureCollection(org.geotools.feature.FeatureCollection) Coordinate(com.vividsolutions.jts.geom.Coordinate) File(java.io.File)

Aggregations

FeatureCollection (org.geotools.feature.FeatureCollection)3 FeatureIterator (org.geotools.feature.FeatureIterator)3 Geometry (com.vividsolutions.jts.geom.Geometry)2 FeatureSource (org.geotools.data.FeatureSource)2 SimpleFeature (org.opengis.feature.simple.SimpleFeature)2 Facet (au.org.ala.legend.Facet)1 UserDataDTO (au.org.ala.spatial.dto.UserDataDTO)1 SelectedArea (au.org.emii.portal.menu.SelectedArea)1 Coordinate (com.vividsolutions.jts.geom.Coordinate)1 GeometryFactory (com.vividsolutions.jts.geom.GeometryFactory)1 WKTWriter (com.vividsolutions.jts.io.WKTWriter)1 File (java.io.File)1 IOException (java.io.IOException)1 StringReader (java.io.StringReader)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 FileDataStore (org.geotools.data.FileDataStore)1 Query (org.geotools.data.Query)1