Search in sources :

Example 1 with FileDataStore

use of org.geotools.data.FileDataStore in project eol-globi-data by jhpoelen.

the class StudyImporterForSzoboszlai method importShapes.

protected Map<Integer, LatLng> importShapes() throws StudyImporterException {
    Map<Integer, LatLng> localityMap = new TreeMap<>();
    FileDataStore dataStore = null;
    try {
        InputStream shapeZipArchive = getDataset().getResource("shapes");
        File tmpFolder = new File(FileUtils.getTempDirectory(), UUID.randomUUID().toString());
        tmpFolder.deleteOnExit();
        unpackZip(shapeZipArchive, tmpFolder);
        dataStore = FileDataStoreFinder.getDataStore(new File(tmpFolder, "LocatPolygonsPoints.shp"));
        if (dataStore == null) {
            throw new StudyImporterException("failed to parse shapefiles");
        }
        FeatureReader<SimpleFeatureType, SimpleFeature> featureReader = dataStore.getFeatureReader();
        while (featureReader.hasNext()) {
            SimpleFeature feature = featureReader.next();
            Object geom = feature.getAttribute("the_geom");
            if (geom instanceof Point) {
                Coordinate coordinate = ((Point) geom).getCoordinate();
                Object localNum = feature.getAttribute("LocatNum");
                if (localNum instanceof Integer) {
                    localityMap.put((Integer) localNum, new LatLng(coordinate.y, coordinate.x));
                }
            }
        }
        featureReader.close();
    } catch (IOException e) {
        throw new StudyImporterException(e);
    } finally {
        if (dataStore != null) {
            dataStore.dispose();
        }
    }
    return localityMap;
}
Also used : ZipInputStream(java.util.zip.ZipInputStream) InputStream(java.io.InputStream) Point(com.vividsolutions.jts.geom.Point) IOException(java.io.IOException) TreeMap(java.util.TreeMap) SimpleFeature(org.opengis.feature.simple.SimpleFeature) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) Coordinate(com.vividsolutions.jts.geom.Coordinate) LatLng(org.eol.globi.geo.LatLng) FileDataStore(org.geotools.data.FileDataStore) File(java.io.File)

Example 2 with FileDataStore

use of org.geotools.data.FileDataStore 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);
    }
}
Also used : IOException(java.io.IOException) SimpleFeature(org.opengis.feature.simple.SimpleFeature) ParseException(com.vividsolutions.jts.io.ParseException) IOException(java.io.IOException) FeatureId(org.opengis.filter.identity.FeatureId) SimpleFeatureIterator(org.geotools.data.simple.SimpleFeatureIterator) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) AttributeType(org.opengis.feature.type.AttributeType) FileDataStore(org.geotools.data.FileDataStore) File(java.io.File)

Example 3 with FileDataStore

use of org.geotools.data.FileDataStore 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)

Example 4 with FileDataStore

use of org.geotools.data.FileDataStore 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;
}
Also used : Query(org.geotools.data.Query) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) ArrayList(java.util.ArrayList) SimpleFeature(org.opengis.feature.simple.SimpleFeature) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) Geometry(com.vividsolutions.jts.geom.Geometry) SimpleFeatureIterator(org.geotools.data.simple.SimpleFeatureIterator) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) FileDataStore(org.geotools.data.FileDataStore) Property(org.opengis.feature.Property)

Example 5 with FileDataStore

use of org.geotools.data.FileDataStore 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.");
}
Also used : Query(org.geotools.data.Query) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) Point(com.vividsolutions.jts.geom.Point) Point(com.vividsolutions.jts.geom.Point) SimpleFeature(org.opengis.feature.simple.SimpleFeature) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) Geometry(com.vividsolutions.jts.geom.Geometry) SimpleFeatureIterator(org.geotools.data.simple.SimpleFeatureIterator) MultiPolygon(com.vividsolutions.jts.geom.MultiPolygon) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) MultiPolygon(com.vividsolutions.jts.geom.MultiPolygon) Polygon(com.vividsolutions.jts.geom.Polygon) File(java.io.File) FileDataStore(org.geotools.data.FileDataStore)

Aggregations

FileDataStore (org.geotools.data.FileDataStore)5 SimpleFeature (org.opengis.feature.simple.SimpleFeature)5 File (java.io.File)4 Geometry (com.vividsolutions.jts.geom.Geometry)3 SimpleFeatureIterator (org.geotools.data.simple.SimpleFeatureIterator)3 Coordinate (com.vividsolutions.jts.geom.Coordinate)2 Point (com.vividsolutions.jts.geom.Point)2 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 Query (org.geotools.data.Query)2 SimpleFeatureCollection (org.geotools.data.simple.SimpleFeatureCollection)2 SimpleFeatureSource (org.geotools.data.simple.SimpleFeatureSource)2 SimpleFeatureType (org.opengis.feature.simple.SimpleFeatureType)2 CoordinateReferenceSystem (org.opengis.referencing.crs.CoordinateReferenceSystem)2 Facet (au.org.ala.legend.Facet)1 UserDataDTO (au.org.ala.spatial.dto.UserDataDTO)1 SelectedArea (au.org.emii.portal.menu.SelectedArea)1 GeometryFactory (com.vividsolutions.jts.geom.GeometryFactory)1 MultiPolygon (com.vividsolutions.jts.geom.MultiPolygon)1 Polygon (com.vividsolutions.jts.geom.Polygon)1