Search in sources :

Example 36 with SimpleFeature

use of org.opengis.feature.simple.SimpleFeature in project spatial-portal by AtlasOfLivingAustralia.

the class AreaUploadShapefile method getKMLPolygonAsWKT.

/**
     * parse a KML containing a single placemark, or a placemark in a folder, into WKT.
     *
     * @param kmldata
     * @return WKT if valid, null on error, empty string "" when placemark not matched.
     */
private static String getKMLPolygonAsWKT(String kmldata) {
    try {
        Parser parser = new Parser(new org.geotools.kml.v22.KMLConfiguration());
        SimpleFeature f = (SimpleFeature) parser.parse(new StringReader(kmldata));
        Collection placemarks = (Collection) f.getAttribute(StringConstants.FEATURE);
        Geometry g = null;
        SimpleFeature sf = null;
        //for <Placemark>
        if (!placemarks.isEmpty() && !placemarks.isEmpty()) {
            sf = (SimpleFeature) placemarks.iterator().next();
            g = (Geometry) sf.getAttribute("Geometry");
        }
        //for <Folder><Placemark>
        if (g == null && sf != null) {
            placemarks = (Collection) sf.getAttribute(StringConstants.FEATURE);
            if (placemarks != null && !placemarks.isEmpty()) {
                g = (Geometry) ((SimpleFeature) placemarks.iterator().next()).getAttribute("Geometry");
            } else {
                placemarks = (Collection) sf.getAttribute("Folder");
                if (placemarks != null && !placemarks.isEmpty()) {
                    g = (Geometry) ((SimpleFeature) placemarks.iterator().next()).getAttribute("Geometry");
                }
            }
        }
        if (g != null) {
            WKTWriter wr = new WKTWriter();
            String wkt = wr.write(g);
            return wkt.replace(" (", "(").replace(", ", ",").replace(") ", ")");
        } else {
            return "";
        }
    } catch (SAXException e) {
        LOGGER.error("KML spec parse error", e);
    } catch (ParserConfigurationException e) {
        LOGGER.error("error converting KML to WKT", e);
    } catch (Exception e) {
        LOGGER.error("error reading KML", e);
    }
    return null;
}
Also used : WKTWriter(com.vividsolutions.jts.io.WKTWriter) SimpleFeature(org.opengis.feature.simple.SimpleFeature) ParseException(com.vividsolutions.jts.io.ParseException) SuspendNotAllowedException(org.zkoss.zk.ui.SuspendNotAllowedException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) Parser(org.geotools.xml.Parser) SAXException(org.xml.sax.SAXException) Geometry(com.vividsolutions.jts.geom.Geometry) Collection(java.util.Collection) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 37 with SimpleFeature

use of org.opengis.feature.simple.SimpleFeature 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 38 with SimpleFeature

use of org.opengis.feature.simple.SimpleFeature 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 39 with SimpleFeature

use of org.opengis.feature.simple.SimpleFeature in project ddf by codice.

the class TestPubSubOgcFilter method generateSampleFeature.

private SimpleFeature generateSampleFeature() {
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName("PubSubFeature");
    // add properties
    b.add("name", String.class);
    b.add("classification", Integer.class);
    b.add("height", Double.class);
    com.vividsolutions.jts.geom.GeometryFactory geoFactory = JTSFactoryFinder.getGeometryFactory(null);
    // add geo
    b.setCRS(DefaultGeographicCRS.WGS84);
    b.add("geo", Point.class);
    final SimpleFeatureType pubSubFeature = b.buildFeatureType();
    SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(pubSubFeature);
    featureBuilder.set("name", "FirstFeature");
    featureBuilder.set("classification", 10);
    featureBuilder.set("height", 5.8);
    com.vividsolutions.jts.geom.Point point = geoFactory.createPoint(new Coordinate(-112, 28));
    featureBuilder.set("geo", point);
    SimpleFeature feature = featureBuilder.buildFeature("f1");
    // it looks like if I add an attribute into the feature that is of geometry type, it
    // automatically
    // becomes the default geo property. If no geo is specified, getDefaultGeometryProperty
    // returns null
    GeometryAttribute defaultGeo = feature.getDefaultGeometryProperty();
    LOGGER.debug("geo name: {}", defaultGeo.getName());
    LOGGER.debug("geo: {}", defaultGeo);
    return feature;
}
Also used : SimpleFeatureTypeBuilder(org.geotools.feature.simple.SimpleFeatureTypeBuilder) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) Coordinate(com.vividsolutions.jts.geom.Coordinate) GeometryAttribute(org.opengis.feature.GeometryAttribute) Point(com.vividsolutions.jts.geom.Point) SimpleFeature(org.opengis.feature.simple.SimpleFeature) SimpleFeatureBuilder(org.geotools.feature.simple.SimpleFeatureBuilder)

Example 40 with SimpleFeature

use of org.opengis.feature.simple.SimpleFeature in project GeoGig by boundlessgeo.

the class GeoGigDataStoreTest method testFeatureWriterAppend.

@Test
public void testFeatureWriterAppend() throws Exception {
    dataStore.createSchema(linesType);
    Transaction tx = new DefaultTransaction();
    FeatureWriter<SimpleFeatureType, SimpleFeature> fw = dataStore.getFeatureWriterAppend(linesTypeName.getLocalPart(), tx);
    LineString line = new GeometryBuilder().lineString(0, 0, 1, 1);
    SimpleFeature f = (SimpleFeature) fw.next();
    f.setAttribute("sp", "foo");
    f.setAttribute("ip", 10);
    f.setAttribute("pp", line);
    fw.write();
    fw.close();
    tx.commit();
    FeatureSource<SimpleFeatureType, SimpleFeature> source = dataStore.getFeatureSource(linesTypeName);
    assertEquals(1, source.getCount(null));
    FeatureReader<SimpleFeatureType, SimpleFeature> r = dataStore.getFeatureReader(new Query(linesTypeName.getLocalPart()), Transaction.AUTO_COMMIT);
    assertTrue(r.hasNext());
    f = r.next();
    assertEquals("foo", f.getAttribute("sp"));
    assertEquals(10, f.getAttribute("ip"));
    assertTrue(line.equals((Geometry) f.getAttribute("pp")));
}
Also used : Geometry(com.vividsolutions.jts.geom.Geometry) Transaction(org.geotools.data.Transaction) DefaultTransaction(org.geotools.data.DefaultTransaction) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) Query(org.geotools.data.Query) LineString(com.vividsolutions.jts.geom.LineString) GeometryBuilder(org.geotools.geometry.jts.GeometryBuilder) DefaultTransaction(org.geotools.data.DefaultTransaction) SimpleFeature(org.opengis.feature.simple.SimpleFeature) Test(org.junit.Test)

Aggregations

SimpleFeature (org.opengis.feature.simple.SimpleFeature)66 SimpleFeatureType (org.opengis.feature.simple.SimpleFeatureType)32 Test (org.junit.Test)27 SimpleFeatureBuilder (org.geotools.feature.simple.SimpleFeatureBuilder)21 RevFeature (org.locationtech.geogig.api.RevFeature)17 RevFeatureType (org.locationtech.geogig.api.RevFeatureType)16 Optional (com.google.common.base.Optional)15 Coordinate (com.vividsolutions.jts.geom.Coordinate)15 NodeRef (org.locationtech.geogig.api.NodeRef)13 ObjectId (org.locationtech.geogig.api.ObjectId)13 GeometryFactory (com.vividsolutions.jts.geom.GeometryFactory)12 File (java.io.File)10 ArrayList (java.util.ArrayList)10 DefaultTransaction (org.geotools.data.DefaultTransaction)10 WorkingTree (org.locationtech.geogig.repository.WorkingTree)10 IOException (java.io.IOException)9 List (java.util.List)9 Feature (org.opengis.feature.Feature)9 Function (com.google.common.base.Function)8 Transaction (org.geotools.data.Transaction)8