Search in sources :

Example 66 with SimpleFeatureType

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

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

the class GeogigFeatureSource method getNativeType.

SimpleFeatureType getNativeType() {
    final NodeRef typeRef = getTypeRef();
    final String treePath = typeRef.path();
    final ObjectId metadataId = typeRef.getMetadataId();
    Context commandLocator = getCommandLocator();
    Optional<RevFeatureType> revType = commandLocator.command(RevObjectParse.class).setObjectId(metadataId).call(RevFeatureType.class);
    if (!revType.isPresent()) {
        throw new IllegalStateException(String.format("Feature type for tree %s not found", treePath));
    }
    SimpleFeatureType featureType = (SimpleFeatureType) revType.get().type();
    return featureType;
}
Also used : Context(org.locationtech.geogig.api.Context) NodeRef(org.locationtech.geogig.api.NodeRef) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) ObjectId(org.locationtech.geogig.api.ObjectId) RevFeatureType(org.locationtech.geogig.api.RevFeatureType)

Example 68 with SimpleFeatureType

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

the class GeogigFeatureSource method getBoundsInternal.

@Override
protected ReferencedEnvelope getBoundsInternal(Query query) throws IOException {
    final Filter filter = (Filter) query.getFilter().accept(new SimplifyingFilterVisitor(), null);
    final CoordinateReferenceSystem crs = getSchema().getCoordinateReferenceSystem();
    if (Filter.INCLUDE.equals(filter) && oldRoot == null && ChangeType.ADDED.equals(changeType())) {
        NodeRef typeRef = getTypeRef();
        ReferencedEnvelope bounds = new ReferencedEnvelope(crs);
        typeRef.getNode().expand(bounds);
        return bounds;
    }
    if (Filter.EXCLUDE.equals(filter)) {
        return ReferencedEnvelope.create(crs);
    }
    FeatureReader<SimpleFeatureType, SimpleFeature> features;
    if (isNaturalOrder(query.getSortBy())) {
        Integer offset = query.getStartIndex();
        Integer maxFeatures = query.getMaxFeatures() == Integer.MAX_VALUE ? null : query.getMaxFeatures();
        ScreenMap screenMap = (ScreenMap) query.getHints().get(Hints.SCREENMAP);
        features = getNativeReader(Query.NO_NAMES, filter, offset, maxFeatures, screenMap);
    } else {
        features = getReader(query);
    }
    ReferencedEnvelope bounds = new ReferencedEnvelope(crs);
    try {
        while (features.hasNext()) {
            bounds.expandToInclude((ReferencedEnvelope) features.next().getBounds());
        }
    } finally {
        features.close();
    }
    return bounds;
}
Also used : NodeRef(org.locationtech.geogig.api.NodeRef) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) Filter(org.opengis.filter.Filter) ScreenMap(org.geotools.renderer.ScreenMap) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) SimplifyingFilterVisitor(org.geotools.filter.visitor.SimplifyingFilterVisitor) SimpleFeature(org.opengis.feature.simple.SimpleFeature)

Example 69 with SimpleFeatureType

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

the class ExportOp method _call.

/**
     * Executes the export operation using the parameters that have been specified.
     * 
     * @return a FeatureCollection with the specified features
     */
@Override
protected SimpleFeatureStore _call() {
    final StagingDatabase database = stagingDatabase();
    if (filterFeatureTypeId != null) {
        RevObject filterType = database.getIfPresent(filterFeatureTypeId);
        checkArgument(filterType instanceof RevFeatureType, "Provided filter feature type is does not exist");
    }
    final SimpleFeatureStore targetStore = getTargetStore();
    final String refspec = resolveRefSpec();
    final String treePath = refspec.substring(refspec.indexOf(':') + 1);
    final RevTree rootTree = resolveRootTree(refspec);
    final NodeRef typeTreeRef = resolTypeTreeRef(refspec, treePath, rootTree);
    final ObjectId defaultMetadataId = typeTreeRef.getMetadataId();
    final RevTree typeTree = database.getTree(typeTreeRef.objectId());
    final ProgressListener progressListener = getProgressListener();
    progressListener.started();
    progressListener.setDescription("Exporting from " + path + " to " + targetStore.getName().getLocalPart() + "... ");
    FeatureCollection<SimpleFeatureType, SimpleFeature> asFeatureCollection = new BaseFeatureCollection<SimpleFeatureType, SimpleFeature>() {

        @Override
        public FeatureIterator<SimpleFeature> features() {
            final Iterator<SimpleFeature> plainFeatures = getFeatures(typeTree, database, defaultMetadataId, progressListener);
            Iterator<SimpleFeature> adaptedFeatures = adaptToArguments(plainFeatures, defaultMetadataId);
            Iterator<Optional<Feature>> transformed = Iterators.transform(adaptedFeatures, ExportOp.this.function);
            Iterator<SimpleFeature> filtered = Iterators.filter(Iterators.transform(transformed, new Function<Optional<Feature>, SimpleFeature>() {

                @Override
                public SimpleFeature apply(Optional<Feature> input) {
                    return (SimpleFeature) (input.isPresent() ? input.get() : null);
                }
            }), Predicates.notNull());
            return new DelegateFeatureIterator<SimpleFeature>(filtered);
        }
    };
    // add the feature collection to the feature store
    final Transaction transaction;
    if (transactional) {
        transaction = new DefaultTransaction("create");
    } else {
        transaction = Transaction.AUTO_COMMIT;
    }
    try {
        targetStore.setTransaction(transaction);
        try {
            targetStore.addFeatures(asFeatureCollection);
            transaction.commit();
        } catch (final Exception e) {
            if (transactional) {
                transaction.rollback();
            }
            Throwables.propagateIfInstanceOf(e, GeoToolsOpException.class);
            throw new GeoToolsOpException(e, StatusCode.UNABLE_TO_ADD);
        } finally {
            transaction.close();
        }
    } catch (IOException e) {
        throw new GeoToolsOpException(e, StatusCode.UNABLE_TO_ADD);
    }
    progressListener.complete();
    return targetStore;
}
Also used : DelegateFeatureIterator(org.geotools.feature.collection.DelegateFeatureIterator) Optional(com.google.common.base.Optional) RevObject(org.locationtech.geogig.api.RevObject) ObjectId(org.locationtech.geogig.api.ObjectId) IOException(java.io.IOException) SimpleFeature(org.opengis.feature.simple.SimpleFeature) Feature(org.opengis.feature.Feature) RevFeature(org.locationtech.geogig.api.RevFeature) SimpleFeature(org.opengis.feature.simple.SimpleFeature) DefaultTransaction(org.geotools.data.DefaultTransaction) IOException(java.io.IOException) NodeRef(org.locationtech.geogig.api.NodeRef) Function(com.google.common.base.Function) ProgressListener(org.locationtech.geogig.api.ProgressListener) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) Transaction(org.geotools.data.Transaction) DefaultTransaction(org.geotools.data.DefaultTransaction) SimpleFeatureStore(org.geotools.data.simple.SimpleFeatureStore) BaseFeatureCollection(org.geotools.feature.collection.BaseFeatureCollection) RevFeatureType(org.locationtech.geogig.api.RevFeatureType) RevTree(org.locationtech.geogig.api.RevTree) StagingDatabase(org.locationtech.geogig.storage.StagingDatabase)

Example 70 with SimpleFeatureType

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

the class ImportOp method checkPreconditions.

private String[] checkPreconditions() {
    if (dataStore == null) {
        throw new GeoToolsOpException(StatusCode.DATASTORE_NOT_DEFINED);
    }
    if ((table == null || table.isEmpty()) && !(all)) {
        throw new GeoToolsOpException(StatusCode.TABLE_NOT_DEFINED);
    }
    if (table != null && !table.isEmpty() && all) {
        throw new GeoToolsOpException(StatusCode.ALL_AND_TABLE_DEFINED);
    }
    String[] typeNames;
    if (all) {
        try {
            typeNames = dataStore.getTypeNames();
        } catch (Exception e) {
            throw new GeoToolsOpException(StatusCode.UNABLE_TO_GET_NAMES);
        }
        if (typeNames.length == 0) {
            throw new GeoToolsOpException(StatusCode.NO_FEATURES_FOUND);
        }
    } else {
        SimpleFeatureType schema;
        try {
            schema = dataStore.getSchema(table);
        } catch (IOException e) {
            throw new GeoToolsOpException(StatusCode.TABLE_NOT_FOUND);
        }
        Preconditions.checkNotNull(schema);
        typeNames = new String[] { table };
    }
    if (typeNames.length > 1 && alter && all) {
        throw new GeoToolsOpException(StatusCode.ALTER_AND_ALL_DEFINED);
    }
    return typeNames;
}
Also used : SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException)

Aggregations

SimpleFeatureType (org.opengis.feature.simple.SimpleFeatureType)80 SimpleFeature (org.opengis.feature.simple.SimpleFeature)35 Test (org.junit.Test)22 IOException (java.io.IOException)20 ObjectId (org.locationtech.geogig.api.ObjectId)20 RevFeatureType (org.locationtech.geogig.api.RevFeatureType)18 SimpleFeatureStore (org.geotools.data.simple.SimpleFeatureStore)17 SimpleFeatureSource (org.geotools.data.simple.SimpleFeatureSource)15 NodeRef (org.locationtech.geogig.api.NodeRef)15 InvalidParameterException (org.locationtech.geogig.cli.InvalidParameterException)15 Feature (org.opengis.feature.Feature)14 SimpleFeatureBuilder (org.geotools.feature.simple.SimpleFeatureBuilder)12 SimpleFeatureTypeBuilder (org.geotools.feature.simple.SimpleFeatureTypeBuilder)12 Optional (com.google.common.base.Optional)10 RevTree (org.locationtech.geogig.api.RevTree)10 CommandFailedException (org.locationtech.geogig.cli.CommandFailedException)10 GeoToolsOpException (org.locationtech.geogig.geotools.plumbing.GeoToolsOpException)10 DefaultTransaction (org.geotools.data.DefaultTransaction)9 ExportOp (org.locationtech.geogig.geotools.plumbing.ExportOp)9 Function (com.google.common.base.Function)8