Search in sources :

Example 36 with SimpleFeatureSource

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

the class OracleExport method runInternal.

/**
     * Executes the export command using the provided options.
     * 
     * @param cli
     */
@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 37 with SimpleFeatureSource

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

the class GeoJsonExport method runInternal.

/**
     * Executes the export command using the provided options.
     */
@Override
protected void runInternal(GeogigCLI cli) throws InvalidParameterException, CommandFailedException, IOException {
    if (args.isEmpty()) {
        printUsage(cli);
        throw new CommandFailedException();
    }
    String path = args.get(0);
    String geojson = args.get(1);
    File file = new File(geojson);
    if (file.exists() && !overwrite) {
        throw new CommandFailedException("The selected GeoJSON file already exists. Use -o to overwrite");
    }
    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 dataStore = new MemoryDataStore(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.");
    }
    final SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
    ExportOp op = cli.getGeogig().command(ExportOp.class).setFeatureStore(featureStore).setPath(path).setFilterFeatureTypeId(featureTypeId).setAlter(alter);
    op.setTransactional(false);
    if (defaultType) {
        op.exportDefaultFeatureType();
    }
    FileWriter writer = null;
    try {
        op.setProgressListener(cli.getProgressListener()).call();
        FeatureJSON fjson = new FeatureJSON();
        @SuppressWarnings("rawtypes") FeatureCollection fc = featureSource.getFeatures();
        writer = new FileWriter(file);
        fjson.writeFeatureCollection(fc, writer);
    } catch (IllegalArgumentException iae) {
        throw new org.locationtech.geogig.cli.InvalidParameterException(iae.getMessage(), iae);
    } catch (GeoToolsOpException e) {
        file.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);
        }
    } finally {
        writer.flush();
        writer.close();
    }
    cli.getConsole().println(path + " exported successfully to " + geojson);
}
Also used : ObjectId(org.locationtech.geogig.api.ObjectId) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) FileWriter(java.io.FileWriter) MemoryDataStore(org.geotools.data.memory.MemoryDataStore) InvalidParameterException(org.locationtech.geogig.cli.InvalidParameterException) CommandFailedException(org.locationtech.geogig.cli.CommandFailedException) GeoToolsOpException(org.locationtech.geogig.geotools.plumbing.GeoToolsOpException) FeatureJSON(org.geotools.geojson.feature.FeatureJSON) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) FeatureCollection(org.geotools.feature.FeatureCollection) MemoryDataStore(org.geotools.data.memory.MemoryDataStore) DataStore(org.geotools.data.DataStore) SimpleFeatureStore(org.geotools.data.simple.SimpleFeatureStore) ExportOp(org.locationtech.geogig.geotools.plumbing.ExportOp) File(java.io.File) TYPE(org.locationtech.geogig.api.RevObject.TYPE)

Example 38 with SimpleFeatureSource

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

the class OSMExportShp method exportRule.

private void exportRule(final MappingRule rule, final GeogigCLI cli, final File shapeFile) throws IOException {
    if (shapeFile.exists() && !overwrite) {
        throw new CommandFailedException("The selected shapefile already exists. Use -o to overwrite");
    }
    Function<Feature, Optional<Feature>> function = new Function<Feature, Optional<Feature>>() {

        @Override
        @Nullable
        public Optional<Feature> apply(@Nullable Feature feature) {
            Optional<Feature> mapped = rule.apply(feature);
            return mapped;
        }
    };
    SimpleFeatureType outputFeatureType = rule.getFeatureType();
    String path = getOriginTreesFromOutputFeatureType(outputFeatureType);
    ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
    Map<String, Serializable> params = new HashMap<String, Serializable>();
    params.put(ShapefileDataStoreFactory.URLP.key, shapeFile.toURI().toURL());
    params.put(ShapefileDataStoreFactory.CREATE_SPATIAL_INDEX.key, Boolean.TRUE);
    DataStore dataStore = dataStoreFactory.createNewDataStore(params);
    try {
        dataStore.createSchema(outputFeatureType);
        final String typeName = dataStore.getTypeNames()[0];
        final SimpleFeatureSource source = dataStore.getFeatureSource(typeName);
        checkParameter(source instanceof SimpleFeatureStore, "Could not create feature store. Shapefile may be read only");
        final SimpleFeatureStore store = (SimpleFeatureStore) source;
        ExportOp op = cli.getGeogig().command(ExportOp.class).setFeatureStore(store).setPath(path).setFeatureTypeConversionFunction(function);
        try {
            op.setProgressListener(cli.getProgressListener()).call();
            cli.getConsole().println("OSM data exported successfully to " + shapeFile);
        } catch (IllegalArgumentException iae) {
            shapeFile.delete();
            throw new org.locationtech.geogig.cli.InvalidParameterException(iae.getMessage(), iae);
        } catch (GeoToolsOpException e) {
            shapeFile.delete();
            throw new CommandFailedException("Could not export. Error:" + e.statusCode.name(), e);
        }
    } finally {
        dataStore.dispose();
    }
}
Also used : Serializable(java.io.Serializable) Optional(com.google.common.base.Optional) HashMap(java.util.HashMap) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) Feature(org.opengis.feature.Feature) CommandFailedException(org.locationtech.geogig.cli.CommandFailedException) GeoToolsOpException(org.locationtech.geogig.geotools.plumbing.GeoToolsOpException) Function(com.google.common.base.Function) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) DataStore(org.geotools.data.DataStore) SimpleFeatureStore(org.geotools.data.simple.SimpleFeatureStore) ExportOp(org.locationtech.geogig.geotools.plumbing.ExportOp) ShapefileDataStoreFactory(org.geotools.data.shapefile.ShapefileDataStoreFactory) Nullable(javax.annotation.Nullable)

Example 39 with SimpleFeatureSource

use of org.geotools.data.simple.SimpleFeatureSource in project hale by halestudio.

the class ShapeInstanceReader method execute.

/**
 * @see AbstractIOProvider#execute(ProgressIndicator, IOReporter)
 */
@Override
protected IOReport execute(ProgressIndicator progress, IOReporter reporter) throws IOProviderConfigurationException, IOException {
    // $NON-NLS-1$
    progress.begin(Messages.getString("ShapeSchemaProvider.1"), ProgressIndicator.UNKNOWN);
    // DataStore store = new ShapefileDataStoreFactory().createDataStore(location.toURL());
    // DataStore store = FileDataStoreFinder.getDataStore(getSource().getLocation().toURL());
    ShapefileDataStore store = new ShapefileDataStore(getSource().getLocation().toURL());
    store.setCharset(getCharset());
    progress.setCurrentTask("Extracting shape instances");
    String typename = getParameter(PARAM_TYPENAME).as(String.class);
    TypeDefinition defaultType = null;
    if (typename != null && !typename.isEmpty()) {
        try {
            defaultType = getSourceSchema().getType(QName.valueOf(typename));
        } catch (Exception e) {
        // ignore
        }
    }
    if (defaultType == null) {
        // check if typename was supplied w/o namespace
        try {
            defaultType = getSourceSchema().getType(new QName(ShapefileConstants.SHAPEFILE_NS, typename));
        } catch (Exception e) {
        // ignore
        // TODO report?
        }
    }
    if (defaultType == null) {
        reporter.info(new IOMessageImpl("No type name supplied as parameter, trying to auto-detect the schema type.", null));
        TypeDefinition dataType = ShapeSchemaReader.readShapeType(getSource());
        if (dataType == null) {
            throw new IOException("Could not read shapefile structure information");
        }
        String preferredName = null;
        Name name = store.getNames().iterator().next();
        if (name != null) {
            preferredName = name.getLocalPart();
        }
        Pair<TypeDefinition, Integer> tp = getMostCompatibleShapeType(getSourceSchema(), dataType, preferredName);
        if (tp == null) {
            throw new IOProviderConfigurationException("No schema type specified and auto-detection failed");
        }
        defaultType = tp.getFirst();
        reporter.info(new IOMessageImpl(MessageFormat.format("Auto-deteted {0} as schema type, with a {1}% compatibility rating.", defaultType.getName(), tp.getSecond()), null));
    }
    Map<TypeDefinition, InstanceCollection> collections = new HashMap<>();
    // create a collection for each type
    for (Name name : store.getNames()) {
        SimpleFeatureSource features = store.getFeatureSource(name);
        TypeDefinition type = defaultType;
        if (type == null) {
            QName typeName = new QName(ShapefileConstants.SHAPEFILE_NS, name.getLocalPart());
            type = getSourceSchema().getType(typeName);
        }
        collections.put(type, new ShapesInstanceCollection(features, type, getCrsProvider(), name.getLocalPart()));
    }
    instances = new PerTypeInstanceCollection(collections);
    reporter.setSuccess(true);
    return reporter;
}
Also used : ShapefileDataStore(org.geotools.data.shapefile.ShapefileDataStore) HashMap(java.util.HashMap) QName(javax.xml.namespace.QName) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) PerTypeInstanceCollection(eu.esdihumboldt.hale.common.instance.model.ext.impl.PerTypeInstanceCollection) InstanceCollection(eu.esdihumboldt.hale.common.instance.model.InstanceCollection) IOMessageImpl(eu.esdihumboldt.hale.common.core.io.report.impl.IOMessageImpl) IOException(java.io.IOException) IOProviderConfigurationException(eu.esdihumboldt.hale.common.core.io.IOProviderConfigurationException) IOException(java.io.IOException) TypeDefinition(eu.esdihumboldt.hale.common.schema.model.TypeDefinition) Name(org.opengis.feature.type.Name) QName(javax.xml.namespace.QName) IOProviderConfigurationException(eu.esdihumboldt.hale.common.core.io.IOProviderConfigurationException) PerTypeInstanceCollection(eu.esdihumboldt.hale.common.instance.model.ext.impl.PerTypeInstanceCollection)

Example 40 with SimpleFeatureSource

use of org.geotools.data.simple.SimpleFeatureSource in project sldeditor by robward-scisys.

the class InLineFeatureModel method removeColumn.

/**
 * Removes the column.
 *
 * @param columnName the column name
 */
public void removeColumn(String columnName) {
    if (featureCollection != null) {
        if (columnList.contains(columnName)) {
            columnList.remove(columnName);
            // Find field name to remote
            SimpleFeatureTypeBuilder featureTypeBuilder = new SimpleFeatureTypeBuilder();
            featureTypeBuilder.init(featureCollection.getSchema());
            featureTypeBuilder.remove(columnName);
            SimpleFeatureType newFeatureType = featureTypeBuilder.buildFeatureType();
            int attributeToRemoveIndex = 0;
            for (AttributeDescriptor descriptor : newFeatureType.getAttributeDescriptors()) {
                if (descriptor.getLocalName().compareTo(columnName) == 0) {
                    break;
                }
                attributeToRemoveIndex++;
            }
            String typeName = userLayer.getInlineFeatureType().getTypeName();
            try {
                SimpleFeatureSource featureSource = userLayer.getInlineFeatureDatastore().getFeatureSource(typeName);
                SimpleFeatureBuilder sfb = new SimpleFeatureBuilder(newFeatureType);
                ArrayList<SimpleFeature> featureList = new ArrayList<SimpleFeature>();
                SimpleFeatureIterator it = featureSource.getFeatures().features();
                try {
                    while (it.hasNext()) {
                        SimpleFeature sf = it.next();
                        List<Object> attributes = sf.getAttributes();
                        attributes.remove(attributeToRemoveIndex);
                        sfb.addAll(attributes);
                        featureList.add(sfb.buildFeature(null));
                    }
                } finally {
                    it.close();
                }
                SimpleFeatureCollection collection = new ListFeatureCollection(newFeatureType, featureList);
                featureCollection = collection;
                cachedFeature = null;
                lastRow = -1;
                DataStore dataStore = DataUtilities.dataStore(collection);
                userLayer.setInlineFeatureDatastore(dataStore);
                userLayer.setInlineFeatureType(newFeatureType);
            } catch (IOException e) {
                ConsoleManager.getInstance().exception(this, e);
            }
            this.fireTableStructureChanged();
            this.fireTableDataChanged();
            if (parentObj != null) {
                parentObj.inlineFeatureUpdated();
            }
        }
    }
}
Also used : SimpleFeatureTypeBuilder(org.geotools.feature.simple.SimpleFeatureTypeBuilder) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) ArrayList(java.util.ArrayList) AttributeDescriptor(org.opengis.feature.type.AttributeDescriptor) IOException(java.io.IOException) SimpleFeature(org.opengis.feature.simple.SimpleFeature) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) SimpleFeatureIterator(org.geotools.data.simple.SimpleFeatureIterator) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) DataStore(org.geotools.data.DataStore) ListFeatureCollection(org.geotools.data.collection.ListFeatureCollection) SimpleFeatureBuilder(org.geotools.feature.simple.SimpleFeatureBuilder)

Aggregations

SimpleFeatureSource (org.geotools.data.simple.SimpleFeatureSource)54 SimpleFeatureType (org.opengis.feature.simple.SimpleFeatureType)29 IOException (java.io.IOException)28 SimpleFeatureStore (org.geotools.data.simple.SimpleFeatureStore)25 SimpleFeature (org.opengis.feature.simple.SimpleFeature)23 DataStore (org.geotools.data.DataStore)22 Test (org.junit.Test)21 SimpleFeatureCollection (org.geotools.data.simple.SimpleFeatureCollection)20 SimpleFeatureIterator (org.geotools.data.simple.SimpleFeatureIterator)19 Feature (org.opengis.feature.Feature)16 HashMap (java.util.HashMap)15 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 ExportOp (org.locationtech.geogig.geotools.plumbing.ExportOp)9 ArrayList (java.util.ArrayList)8 Map (java.util.Map)8 SimpleFeatureBuilder (org.geotools.feature.simple.SimpleFeatureBuilder)8 InvalidParameterException (org.locationtech.geogig.cli.InvalidParameterException)8