Search in sources :

Example 1 with SimpleFeatureSource

use of org.geotools.data.simple.SimpleFeatureSource 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 SimpleFeatureSource

use of org.geotools.data.simple.SimpleFeatureSource in project GeoGig by boundlessgeo.

the class SQLServerExport method runInternal.

/**
     * Executes the export command using the provided options.
     */
@Override
protected void runInternal(GeogigCLI cli) throws IOException {
    if (args.isEmpty()) {
        printUsage(cli);
        throw new CommandFailedException();
    }
    String path = args.get(0);
    String tableName = args.get(1);
    checkParameter(tableName != null && !tableName.isEmpty(), "No table name specified");
    DataStore dataStore = getDataStore();
    ObjectId featureTypeId = null;
    if (!Arrays.asList(dataStore.getTypeNames()).contains(tableName)) {
        SimpleFeatureType outputFeatureType;
        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 {
                SimpleFeatureType sft = getFeatureType(path, cli);
                outputFeatureType = new SimpleFeatureTypeImpl(new NameImpl(tableName), sft.getAttributeDescriptors(), sft.getGeometryDescriptor(), sft.isAbstract(), sft.getRestrictions(), sft.getSuper(), sft.getDescription());
            } catch (GeoToolsOpException e) {
                throw new CommandFailedException("No features to export.", e);
            }
        }
        try {
            dataStore.createSchema(outputFeatureType);
        } catch (IOException e) {
            throw new CommandFailedException("Cannot create new table in database", e);
        }
    } else {
        if (!overwrite) {
            throw new CommandFailedException("The selected table already exists. Use -o to overwrite");
        }
    }
    SimpleFeatureSource featureSource = dataStore.getFeatureSource(tableName);
    if (!(featureSource instanceof SimpleFeatureStore)) {
        throw new CommandFailedException("Can't write to the selected table");
    }
    SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
    if (overwrite) {
        try {
            featureStore.removeFeatures(Filter.INCLUDE);
        } catch (IOException e) {
            throw new CommandFailedException("Error accessing table: " + e.getMessage(), e);
        }
    }
    ExportOp op = cli.getGeogig().command(ExportOp.class).setFeatureStore(featureStore).setPath(path).setFilterFeatureTypeId(featureTypeId).setAlter(alter);
    if (defaultType) {
        op.exportDefaultFeatureType();
    }
    try {
        op.setProgressListener(cli.getProgressListener()).call();
    } catch (IllegalArgumentException iae) {
        throw new org.locationtech.geogig.cli.InvalidParameterException(iae.getMessage(), iae);
    } catch (GeoToolsOpException e) {
        switch(e.statusCode) {
            case MIXED_FEATURE_TYPES:
                throw new CommandFailedException("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);
        }
    }
    cli.getConsole().println(path + " exported successfully to " + tableName);
}
Also used : NameImpl(org.geotools.feature.NameImpl) ObjectId(org.locationtech.geogig.api.ObjectId) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) IOException(java.io.IOException) InvalidParameterException(org.locationtech.geogig.cli.InvalidParameterException) CommandFailedException(org.locationtech.geogig.cli.CommandFailedException) SimpleFeatureTypeImpl(org.geotools.feature.simple.SimpleFeatureTypeImpl) GeoToolsOpException(org.locationtech.geogig.geotools.plumbing.GeoToolsOpException) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) DataStore(org.geotools.data.DataStore) SimpleFeatureStore(org.geotools.data.simple.SimpleFeatureStore) ExportOp(org.locationtech.geogig.geotools.plumbing.ExportOp) TYPE(org.locationtech.geogig.api.RevObject.TYPE)

Example 3 with SimpleFeatureSource

use of org.geotools.data.simple.SimpleFeatureSource in project GeoGig by boundlessgeo.

the class ShpExport method runInternal.

/**
     * Executes the export command using the provided options.
     */
@Override
protected void runInternal(GeogigCLI cli) throws IOException {
    if (args.isEmpty()) {
        printUsage(cli);
        throw new CommandFailedException();
    }
    String path = args.get(0);
    String shapefile = args.get(1);
    ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
    File targetShapefile = new File(shapefile);
    if (!targetShapefile.isAbsolute()) {
        File pwd = cli.getGeogig().getPlatform().pwd();
        String relativePath = targetShapefile.getPath();
        targetShapefile = new File(pwd, relativePath);
    }
    if (targetShapefile.exists() && !overwrite) {
        throw new CommandFailedException("The selected shapefile already exists. Use -o to overwrite");
    }
    Map<String, Serializable> params = new HashMap<String, Serializable>();
    URL targetShapefileAsUrl = targetShapefile.toURI().toURL();
    params.put(ShapefileDataStoreFactory.URLP.key, targetShapefileAsUrl);
    params.put(ShapefileDataStoreFactory.CREATE_SPATIAL_INDEX.key, Boolean.FALSE);
    params.put(ShapefileDataStoreFactory.ENABLE_SPATIAL_INDEX.key, Boolean.FALSE);
    ShapefileDataStore dataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
    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.createSchema(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.");
    }
    Function<Feature, Optional<Feature>> function = getTransformingFunction(dataStore.getSchema());
    final SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
    ExportOp op = cli.getGeogig().command(ExportOp.class).setFeatureStore(featureStore).setPath(path).setFilterFeatureTypeId(featureTypeId).setAlter(alter).setFeatureTypeConversionFunction(function);
    // shapefile transactions are memory bound, so avoid them
    op.setTransactional(false);
    if (defaultType) {
        op.exportDefaultFeatureType();
    }
    try {
        op.setProgressListener(cli.getProgressListener()).call();
    } catch (IllegalArgumentException iae) {
        throw new org.locationtech.geogig.cli.InvalidParameterException(iae.getMessage(), iae);
    } catch (GeoToolsOpException e) {
        targetShapefile.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);
        }
    }
    cli.getConsole().println(path + " exported successfully to " + shapefile);
}
Also used : Serializable(java.io.Serializable) ShapefileDataStore(org.geotools.data.shapefile.ShapefileDataStore) Optional(com.google.common.base.Optional) HashMap(java.util.HashMap) ObjectId(org.locationtech.geogig.api.ObjectId) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) InvalidParameterException(org.locationtech.geogig.cli.InvalidParameterException) Feature(org.opengis.feature.Feature) CommandFailedException(org.locationtech.geogig.cli.CommandFailedException) URL(java.net.URL) GeoToolsOpException(org.locationtech.geogig.geotools.plumbing.GeoToolsOpException) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) SimpleFeatureStore(org.geotools.data.simple.SimpleFeatureStore) ExportOp(org.locationtech.geogig.geotools.plumbing.ExportOp) ShapefileDataStoreFactory(org.geotools.data.shapefile.ShapefileDataStoreFactory) File(java.io.File) TYPE(org.locationtech.geogig.api.RevObject.TYPE)

Example 4 with SimpleFeatureSource

use of org.geotools.data.simple.SimpleFeatureSource in project GeoGig by boundlessgeo.

the class PGExport method runInternal.

/**
     * Executes the export command using the provided options.
     */
@Override
protected void runInternal(GeogigCLI cli) throws IOException {
    if (args.isEmpty()) {
        printUsage(cli);
        throw new CommandFailedException();
    }
    String path = args.get(0);
    String tableName = args.get(1);
    checkParameter(tableName != null && !tableName.isEmpty(), "No table name specified");
    DataStore dataStore = getDataStore();
    ObjectId featureTypeId = null;
    if (!Arrays.asList(dataStore.getTypeNames()).contains(tableName)) {
        SimpleFeatureType outputFeatureType;
        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 {
                SimpleFeatureType sft = getFeatureType(path, cli);
                outputFeatureType = new SimpleFeatureTypeImpl(new NameImpl(tableName), sft.getAttributeDescriptors(), sft.getGeometryDescriptor(), sft.isAbstract(), sft.getRestrictions(), sft.getSuper(), sft.getDescription());
            } catch (GeoToolsOpException e) {
                throw new CommandFailedException("No features to export.", e);
            }
        }
        try {
            dataStore.createSchema(outputFeatureType);
        } catch (IOException e) {
            throw new CommandFailedException("Cannot create new table in database", e);
        }
    } else {
        if (!overwrite) {
            throw new InvalidParameterException("The selected table already exists. Use -o to overwrite");
        }
    }
    SimpleFeatureSource featureSource;
    try {
        featureSource = dataStore.getFeatureSource(tableName);
    } catch (IOException e) {
        throw new CommandFailedException("Can't aquire the feature source", e);
    }
    if (featureSource instanceof SimpleFeatureStore) {
        SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
        if (overwrite) {
            try {
                featureStore.removeFeatures(Filter.INCLUDE);
            } catch (IOException e) {
                throw new CommandFailedException("Error trying to remove features", e);
            }
        }
        ExportOp op = cli.getGeogig().command(ExportOp.class).setFeatureStore(featureStore).setPath(path).setFilterFeatureTypeId(featureTypeId).setAlter(alter);
        if (defaultType) {
            op.exportDefaultFeatureType();
        }
        try {
            op.setProgressListener(cli.getProgressListener()).call();
        } catch (IllegalArgumentException iae) {
            throw new org.locationtech.geogig.cli.InvalidParameterException(iae.getMessage(), iae);
        } catch (GeoToolsOpException e) {
            switch(e.statusCode) {
                case MIXED_FEATURE_TYPES:
                    throw new CommandFailedException("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);
            }
        }
        cli.getConsole().println(path + " exported successfully to " + tableName);
    } else {
        throw new CommandFailedException("Can't write to the selected table");
    }
}
Also used : NameImpl(org.geotools.feature.NameImpl) ObjectId(org.locationtech.geogig.api.ObjectId) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) IOException(java.io.IOException) InvalidParameterException(org.locationtech.geogig.cli.InvalidParameterException) CommandFailedException(org.locationtech.geogig.cli.CommandFailedException) SimpleFeatureTypeImpl(org.geotools.feature.simple.SimpleFeatureTypeImpl) GeoToolsOpException(org.locationtech.geogig.geotools.plumbing.GeoToolsOpException) InvalidParameterException(org.locationtech.geogig.cli.InvalidParameterException) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) DataStore(org.geotools.data.DataStore) SimpleFeatureStore(org.geotools.data.simple.SimpleFeatureStore) ExportOp(org.locationtech.geogig.geotools.plumbing.ExportOp) TYPE(org.locationtech.geogig.api.RevObject.TYPE)

Example 5 with SimpleFeatureSource

use of org.geotools.data.simple.SimpleFeatureSource in project GeoGig by boundlessgeo.

the class SLExport method runInternal.

/**
     * Executes the export command using the provided options.
     */
@Override
protected void runInternal(GeogigCLI cli) throws IOException {
    if (args.isEmpty()) {
        printUsage(cli);
        throw new CommandFailedException();
    }
    String path = args.get(0);
    String tableName = args.get(1);
    checkParameter(tableName != null && !tableName.isEmpty(), "No table name specified");
    DataStore dataStore = getDataStore();
    ObjectId featureTypeId = null;
    if (!Arrays.asList(dataStore.getTypeNames()).contains(tableName)) {
        SimpleFeatureType outputFeatureType;
        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 {
                SimpleFeatureType sft = getFeatureType(path, cli);
                outputFeatureType = new SimpleFeatureTypeImpl(new NameImpl(tableName), sft.getAttributeDescriptors(), sft.getGeometryDescriptor(), sft.isAbstract(), sft.getRestrictions(), sft.getSuper(), sft.getDescription());
            } catch (GeoToolsOpException e) {
                throw new CommandFailedException("No features to export.", e);
            }
        }
        try {
            dataStore.createSchema(outputFeatureType);
        } catch (IOException e) {
            throw new CommandFailedException("Cannot create new table in database", e);
        }
    } else {
        if (!overwrite) {
            throw new CommandFailedException("The selected table already exists. Use -o to overwrite");
        }
    }
    SimpleFeatureSource featureSource = dataStore.getFeatureSource(tableName);
    if (!(featureSource instanceof SimpleFeatureStore)) {
        throw new CommandFailedException("Can't write to the selected table");
    }
    SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
    if (overwrite) {
        try {
            featureStore.removeFeatures(Filter.INCLUDE);
        } catch (IOException e) {
            throw new CommandFailedException("Error truncating table: " + e.getMessage(), e);
        }
    }
    ExportOp op = cli.getGeogig().command(ExportOp.class).setFeatureStore(featureStore).setPath(path).setFilterFeatureTypeId(featureTypeId).setAlter(alter);
    if (defaultType) {
        op.exportDefaultFeatureType();
    }
    try {
        op.setProgressListener(cli.getProgressListener()).call();
    } catch (IllegalArgumentException iae) {
        throw new org.locationtech.geogig.cli.InvalidParameterException(iae.getMessage(), iae);
    } catch (GeoToolsOpException e) {
        switch(e.statusCode) {
            case MIXED_FEATURE_TYPES:
                throw new CommandFailedException("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);
        }
    }
    cli.getConsole().println(path + " exported successfully to " + tableName);
}
Also used : NameImpl(org.geotools.feature.NameImpl) ObjectId(org.locationtech.geogig.api.ObjectId) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) IOException(java.io.IOException) InvalidParameterException(org.locationtech.geogig.cli.InvalidParameterException) CommandFailedException(org.locationtech.geogig.cli.CommandFailedException) SimpleFeatureTypeImpl(org.geotools.feature.simple.SimpleFeatureTypeImpl) GeoToolsOpException(org.locationtech.geogig.geotools.plumbing.GeoToolsOpException) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) DataStore(org.geotools.data.DataStore) SimpleFeatureStore(org.geotools.data.simple.SimpleFeatureStore) ExportOp(org.locationtech.geogig.geotools.plumbing.ExportOp) TYPE(org.locationtech.geogig.api.RevObject.TYPE)

Aggregations

SimpleFeatureSource (org.geotools.data.simple.SimpleFeatureSource)55 IOException (java.io.IOException)29 SimpleFeatureType (org.opengis.feature.simple.SimpleFeatureType)29 SimpleFeatureStore (org.geotools.data.simple.SimpleFeatureStore)26 SimpleFeature (org.opengis.feature.simple.SimpleFeature)23 DataStore (org.geotools.data.DataStore)22 SimpleFeatureCollection (org.geotools.data.simple.SimpleFeatureCollection)21 Test (org.junit.Test)21 SimpleFeatureIterator (org.geotools.data.simple.SimpleFeatureIterator)19 HashMap (java.util.HashMap)16 Feature (org.opengis.feature.Feature)16 MemoryDataStore (org.geotools.data.memory.MemoryDataStore)13 URL (java.net.URL)10 CommandFailedException (org.locationtech.geogig.cli.CommandFailedException)10 GeoToolsOpException (org.locationtech.geogig.geotools.plumbing.GeoToolsOpException)10 Map (java.util.Map)9 ExportOp (org.locationtech.geogig.geotools.plumbing.ExportOp)9 ArrayList (java.util.ArrayList)8 SimpleFeatureBuilder (org.geotools.feature.simple.SimpleFeatureBuilder)8 InvalidParameterException (org.locationtech.geogig.cli.InvalidParameterException)8