Search in sources :

Example 1 with SimpleFeatureBuilder

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

the class ShapefileUtils method saveShapefile.

public static void saveShapefile(File shpfile, String wktString, String name) {
    try {
        final SimpleFeatureType type = createFeatureType();
        List<SimpleFeature> features = new ArrayList<SimpleFeature>();
        SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(type);
        WKTReader wkt = new WKTReader();
        Geometry geom = wkt.read(wktString);
        if (geom instanceof GeometryCollection) {
            GeometryCollection gc = (GeometryCollection) geom;
            for (int i = 0; i < gc.getNumGeometries(); i++) {
                Geometry g = gc.getGeometryN(i);
                if (g instanceof Polygon) {
                    g = new GeometryBuilder().multiPolygon((Polygon) g);
                }
                featureBuilder.add(g);
                SimpleFeature feature = featureBuilder.buildFeature(null);
                feature.setAttribute("name", name);
                features.add(feature);
            }
        } else {
            Geometry g = geom;
            if (g instanceof Polygon) {
                g = new GeometryBuilder().multiPolygon((Polygon) g);
            }
            featureBuilder.add(g);
            SimpleFeature feature = featureBuilder.buildFeature(null);
            features.add(feature);
        }
        ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
        Map<String, Serializable> params = new HashMap<String, Serializable>();
        params.put("url", shpfile.toURI().toURL());
        params.put("create spatial index", Boolean.TRUE);
        ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
        newDataStore.createSchema(type);
        newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
        Transaction transaction = new DefaultTransaction("create");
        String typeName = newDataStore.getTypeNames()[0];
        SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);
        if (featureSource instanceof SimpleFeatureStore) {
            SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
            DefaultFeatureCollection collection = new DefaultFeatureCollection();
            collection.addAll(features);
            featureStore.setTransaction(transaction);
            try {
                featureStore.addFeatures(collection);
                transaction.commit();
            } catch (Exception problem) {
                LOGGER.error("error pricessing shape file: " + shpfile.getAbsolutePath(), problem);
                transaction.rollback();
            } finally {
                transaction.close();
            }
        }
        LOGGER.debug("Active Area shapefile written to: " + shpfile.getAbsolutePath());
    } catch (Exception e) {
        LOGGER.error("Unable to save shapefile: " + shpfile.getAbsolutePath(), e);
    }
}
Also used : Serializable(java.io.Serializable) ShapefileDataStore(org.geotools.data.shapefile.ShapefileDataStore) HashMap(java.util.HashMap) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) ArrayList(java.util.ArrayList) WKTReader(com.vividsolutions.jts.io.WKTReader) SimpleFeature(org.opengis.feature.simple.SimpleFeature) Geometry(com.vividsolutions.jts.geom.Geometry) GeometryCollection(com.vividsolutions.jts.geom.GeometryCollection) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) SimpleFeatureStore(org.geotools.data.simple.SimpleFeatureStore) ShapefileDataStoreFactory(org.geotools.data.shapefile.ShapefileDataStoreFactory) MultiPolygon(com.vividsolutions.jts.geom.MultiPolygon) Polygon(com.vividsolutions.jts.geom.Polygon) GeometryBuilder(org.geotools.geometry.jts.GeometryBuilder) DefaultFeatureCollection(org.geotools.feature.DefaultFeatureCollection) SimpleFeatureBuilder(org.geotools.feature.simple.SimpleFeatureBuilder)

Example 2 with SimpleFeatureBuilder

use of org.geotools.feature.simple.SimpleFeatureBuilder in project GeoGig by boundlessgeo.

the class OSMHookTest method testOSMHook.

@Test
public void testOSMHook() throws Exception {
    // set the hook that will trigger an unmapping when something is imported to the busstops
    // tree
    CharSequence commitPreHookCode = "var diffs = geogig.getFeaturesToCommit(\"busstops\", false);\n" + "if (diffs.length > 0){\n" + "\tvar params = {\"path\" : \"busstops\"};\n" + "\tgeogig.run(\"org.locationtech.geogig.osm.internal.OSMUnmapOp\", params)\n}";
    File hooksFolder = new File(geogig.getPlatform().pwd(), ".geogig/hooks");
    File commitPreHookFile = new File(hooksFolder, "pre_commit.js");
    Files.write(commitPreHookCode, commitPreHookFile, Charsets.UTF_8);
    // Import
    String filename = OSMImportOp.class.getResource("nodes.xml").getFile();
    File file = new File(filename);
    geogig.command(OSMImportOp.class).setDataSource(file.getAbsolutePath()).call();
    // Map
    Map<String, AttributeDefinition> fields = Maps.newHashMap();
    Map<String, List<String>> mappings = Maps.newHashMap();
    mappings.put("highway", Lists.newArrayList("bus_stop"));
    fields.put("geom", new AttributeDefinition("geom", FieldType.POINT));
    fields.put("name", new AttributeDefinition("name", FieldType.STRING));
    MappingRule mappingRule = new MappingRule("busstops", mappings, null, fields, null);
    List<MappingRule> mappingRules = Lists.newArrayList();
    mappingRules.add(mappingRule);
    Mapping mapping = new Mapping(mappingRules);
    geogig.command(AddOp.class).call();
    geogig.command(CommitOp.class).setMessage("msg").call();
    geogig.command(OSMMapOp.class).setMapping(mapping).call();
    Optional<RevFeature> revFeature = geogig.command(RevObjectParse.class).setRefSpec("HEAD:busstops/507464799").call(RevFeature.class);
    assertTrue(revFeature.isPresent());
    Optional<RevFeatureType> featureType = geogig.command(ResolveFeatureType.class).setRefSpec("HEAD:busstops/507464799").call();
    assertTrue(featureType.isPresent());
    ImmutableList<Optional<Object>> values = revFeature.get().getValues();
    assertEquals(3, values.size());
    String wkt = "POINT (7.1959361 50.739397)";
    assertEquals(wkt, values.get(2).get().toString());
    assertEquals(507464799l, values.get(0).get());
    // Modify a node
    GeometryFactory gf = new GeometryFactory();
    SimpleFeatureBuilder fb = new SimpleFeatureBuilder((SimpleFeatureType) featureType.get().type());
    fb.set("geom", gf.createPoint(new Coordinate(0, 1)));
    fb.set("name", "newname");
    fb.set("id", 507464799l);
    SimpleFeature newFeature = fb.buildFeature("507464799");
    geogig.getRepository().workingTree().insert("busstops", newFeature);
    geogig.command(AddOp.class).call();
    // this should trigger the hook
    geogig.command(CommitOp.class).setMessage("msg").call();
    // check that the unmapping has been triggered and the unmapped node has the changes we
    // introduced
    Optional<RevFeature> unmapped = geogig.command(RevObjectParse.class).setRefSpec("WORK_HEAD:node/507464799").call(RevFeature.class);
    assertTrue(unmapped.isPresent());
    values = unmapped.get().getValues();
    assertEquals("POINT (0 1)", values.get(6).get().toString());
    assertEquals("bus:yes|public_transport:platform|highway:bus_stop|VRS:ortsteil:Hoholz|name:newname|VRS:ref:68566|VRS:gemeinde:BONN", values.get(3).get().toString());
    // check that unchanged nodes keep their attributes
    Optional<RevFeature> unchanged = geogig.command(RevObjectParse.class).setRefSpec("WORK_HEAD:node/1633594723").call(RevFeature.class);
    values = unchanged.get().getValues();
    assertEquals("14220478", values.get(4).get().toString());
    assertEquals("1355097351000", values.get(2).get().toString());
    assertEquals("2", values.get(1).get().toString());
}
Also used : AddOp(org.locationtech.geogig.api.porcelain.AddOp) GeometryFactory(com.vividsolutions.jts.geom.GeometryFactory) Optional(com.google.common.base.Optional) SimpleFeature(org.opengis.feature.simple.SimpleFeature) Coordinate(com.vividsolutions.jts.geom.Coordinate) RevFeature(org.locationtech.geogig.api.RevFeature) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) File(java.io.File) RevFeatureType(org.locationtech.geogig.api.RevFeatureType) SimpleFeatureBuilder(org.geotools.feature.simple.SimpleFeatureBuilder) Test(org.junit.Test)

Example 3 with SimpleFeatureBuilder

use of org.geotools.feature.simple.SimpleFeatureBuilder in project GeoGig by boundlessgeo.

the class RemoteRepositoryTestCase method feature.

protected Feature feature(SimpleFeatureType type, String id, Object... values) throws ParseException {
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
    for (int i = 0; i < values.length; i++) {
        Object value = values[i];
        if (type.getDescriptor(i) instanceof GeometryDescriptor) {
            if (value instanceof String) {
                value = new WKTReader2().read((String) value);
            }
        }
        builder.set(i, value);
    }
    return builder.buildFeature(id);
}
Also used : GeometryDescriptor(org.opengis.feature.type.GeometryDescriptor) WKTReader2(org.geotools.geometry.jts.WKTReader2) SimpleFeatureBuilder(org.geotools.feature.simple.SimpleFeatureBuilder)

Example 4 with SimpleFeatureBuilder

use of org.geotools.feature.simple.SimpleFeatureBuilder in project GeoGig by boundlessgeo.

the class Insert method createFeature.

private Feature createFeature(List<String> featureChanges, Map<String, SimpleFeatureBuilder> featureTypes) {
    String path = featureChanges.get(0);
    String tree = NodeRef.parentPath(path);
    String featureId = NodeRef.nodeFromPath(path);
    if (!featureTypes.containsKey(tree)) {
        Optional<RevFeatureType> opt = geogig.command(ResolveFeatureType.class).setRefSpec("WORK_HEAD:" + tree).call();
        checkParameter(opt.isPresent(), "The parent tree does not exist: " + tree);
        SimpleFeatureBuilder builder = new SimpleFeatureBuilder((SimpleFeatureType) opt.get().type());
        featureTypes.put(tree, builder);
    }
    SimpleFeatureBuilder ftb = featureTypes.get(tree);
    SimpleFeatureType ft = ftb.getFeatureType();
    for (int i = 1; i < featureChanges.size(); i++) {
        String[] tokens = featureChanges.get(i).split("\t");
        Preconditions.checkArgument(tokens.length == 2, "Wrong attribute definition: " + featureChanges.get(i));
        String fieldName = tokens[0];
        AttributeDescriptor desc = ft.getDescriptor(fieldName);
        Preconditions.checkNotNull(desc, "Wrong attribute in feature description");
        FieldType type = FieldType.forBinding(desc.getType().getBinding());
        Object value = TextValueSerializer.fromString(type, tokens[1]);
        ftb.set(tokens[0], value);
    }
    return ftb.buildFeature(featureId);
}
Also used : SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) AttributeDescriptor(org.opengis.feature.type.AttributeDescriptor) RevFeatureType(org.locationtech.geogig.api.RevFeatureType) SimpleFeatureBuilder(org.geotools.feature.simple.SimpleFeatureBuilder) FieldType(org.locationtech.geogig.storage.FieldType)

Example 5 with SimpleFeatureBuilder

use of org.geotools.feature.simple.SimpleFeatureBuilder in project GeoGig by boundlessgeo.

the class OSMUnmapOp method _call.

@Override
protected RevTree _call() {
    Optional<OSMMappingLogEntry> entry = command(ReadOSMMappingLogEntry.class).setPath(path).call();
    if (entry.isPresent()) {
        Optional<Mapping> opt = command(ReadOSMMapping.class).setEntry(entry.get()).call();
        if (opt.isPresent()) {
            mapping = opt.get();
        }
    }
    Iterator<NodeRef> iter = command(LsTreeOp.class).setReference(path).setStrategy(Strategy.FEATURES_ONLY).call();
    FeatureMapFlusher flusher = new FeatureMapFlusher(workingTree());
    while (iter.hasNext()) {
        NodeRef node = iter.next();
        RevFeature revFeature = command(RevObjectParse.class).setObjectId(node.objectId()).call(RevFeature.class).get();
        RevFeatureType revFeatureType = command(RevObjectParse.class).setObjectId(node.getMetadataId()).call(RevFeatureType.class).get();
        List<PropertyDescriptor> descriptors = revFeatureType.sortedDescriptors();
        ImmutableList<Optional<Object>> values = revFeature.getValues();
        SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder((SimpleFeatureType) revFeatureType.type());
        String id = null;
        for (int i = 0; i < descriptors.size(); i++) {
            PropertyDescriptor descriptor = descriptors.get(i);
            if (descriptor.getName().getLocalPart().equals("id")) {
                id = values.get(i).get().toString();
            }
            Optional<Object> value = values.get(i);
            featureBuilder.set(descriptor.getName(), value.orNull());
        }
        Preconditions.checkNotNull(id, "No 'id' attribute found");
        SimpleFeature feature = featureBuilder.buildFeature(id);
        unmapFeature(feature, flusher);
    }
    flusher.flushAll();
    if (entry.isPresent()) {
        Iterator<DiffEntry> diffs = command(DiffTree.class).setPathFilter(path).setNewTree(workingTree().getTree().getId()).setOldTree(entry.get().getPostMappingId()).call();
        while (diffs.hasNext()) {
            DiffEntry diff = diffs.next();
            if (diff.changeType().equals(DiffEntry.ChangeType.REMOVED)) {
                ObjectId featureId = diff.getOldObject().getNode().getObjectId();
                RevFeature revFeature = command(RevObjectParse.class).setObjectId(featureId).call(RevFeature.class).get();
                RevFeatureType revFeatureType = command(RevObjectParse.class).setObjectId(diff.getOldObject().getMetadataId()).call(RevFeatureType.class).get();
                List<PropertyDescriptor> descriptors = revFeatureType.sortedDescriptors();
                ImmutableList<Optional<Object>> values = revFeature.getValues();
                SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder((SimpleFeatureType) revFeatureType.type());
                String id = null;
                for (int i = 0; i < descriptors.size(); i++) {
                    PropertyDescriptor descriptor = descriptors.get(i);
                    if (descriptor.getName().getLocalPart().equals("id")) {
                        id = values.get(i).get().toString();
                    }
                    Optional<Object> value = values.get(i);
                    featureBuilder.set(descriptor.getName(), value.orNull());
                }
                Preconditions.checkNotNull(id, "No 'id' attribute found");
                SimpleFeature feature = featureBuilder.buildFeature(id);
                Class<?> clazz = feature.getDefaultGeometryProperty().getType().getBinding();
                String deletePath = clazz.equals(Point.class) ? OSMUtils.NODE_TYPE_NAME : OSMUtils.WAY_TYPE_NAME;
                workingTree().delete(deletePath, id);
            }
        }
    }
    return workingTree().getTree();
}
Also used : ReadOSMMapping(org.locationtech.geogig.osm.internal.log.ReadOSMMapping) LineString(com.vividsolutions.jts.geom.LineString) ReadOSMMappingLogEntry(org.locationtech.geogig.osm.internal.log.ReadOSMMappingLogEntry) OSMMappingLogEntry(org.locationtech.geogig.osm.internal.log.OSMMappingLogEntry) NodeRef(org.locationtech.geogig.api.NodeRef) RevFeature(org.locationtech.geogig.api.RevFeature) RevFeatureType(org.locationtech.geogig.api.RevFeatureType) DiffEntry(org.locationtech.geogig.api.plumbing.diff.DiffEntry) PropertyDescriptor(org.opengis.feature.type.PropertyDescriptor) Optional(com.google.common.base.Optional) ObjectId(org.locationtech.geogig.api.ObjectId) Point(com.vividsolutions.jts.geom.Point) Point(com.vividsolutions.jts.geom.Point) SimpleFeature(org.opengis.feature.simple.SimpleFeature) LsTreeOp(org.locationtech.geogig.api.plumbing.LsTreeOp) RevObjectParse(org.locationtech.geogig.api.plumbing.RevObjectParse) SimpleFeatureBuilder(org.geotools.feature.simple.SimpleFeatureBuilder)

Aggregations

SimpleFeatureBuilder (org.geotools.feature.simple.SimpleFeatureBuilder)56 SimpleFeature (org.opengis.feature.simple.SimpleFeature)34 SimpleFeatureType (org.opengis.feature.simple.SimpleFeatureType)25 Optional (com.google.common.base.Optional)17 ArrayList (java.util.ArrayList)15 RevFeature (org.locationtech.geogig.api.RevFeature)14 RevFeatureType (org.locationtech.geogig.api.RevFeatureType)13 Test (org.junit.Test)11 SimpleFeatureCollection (org.geotools.data.simple.SimpleFeatureCollection)10 SimpleFeatureIterator (org.geotools.data.simple.SimpleFeatureIterator)10 File (java.io.File)9 IOException (java.io.IOException)9 HashMap (java.util.HashMap)9 SimpleFeatureSource (org.geotools.data.simple.SimpleFeatureSource)9 Coordinate (com.vividsolutions.jts.geom.Coordinate)8 GeometryFactory (com.vividsolutions.jts.geom.GeometryFactory)8 Point (com.vividsolutions.jts.geom.Point)8 SimpleFeatureStore (org.geotools.data.simple.SimpleFeatureStore)8 Geometry (com.vividsolutions.jts.geom.Geometry)7 List (java.util.List)7