Search in sources :

Example 31 with SimpleFeatureType

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

the class ApplyPatchOp method getFeatureType.

private RevFeatureType getFeatureType(FeatureDiff diff, RevFeature oldFeature, RevFeatureType oldRevFeatureType) {
    List<String> removed = Lists.newArrayList();
    List<AttributeDescriptor> added = Lists.newArrayList();
    Set<Entry<PropertyDescriptor, AttributeDiff>> featureDiffs = diff.getDiffs().entrySet();
    for (Iterator<Entry<PropertyDescriptor, AttributeDiff>> iterator = featureDiffs.iterator(); iterator.hasNext(); ) {
        Entry<PropertyDescriptor, AttributeDiff> entry = iterator.next();
        if (entry.getValue().getType() == TYPE.REMOVED) {
            removed.add(entry.getKey().getName().getLocalPart());
        } else if (entry.getValue().getType() == TYPE.ADDED) {
            PropertyDescriptor pd = entry.getKey();
            added.add((AttributeDescriptor) pd);
        }
    }
    SimpleFeatureType sft = (SimpleFeatureType) oldRevFeatureType.type();
    List<AttributeDescriptor> descriptors = (sft).getAttributeDescriptors();
    SimpleFeatureTypeBuilder featureTypeBuilder = new SimpleFeatureTypeBuilder();
    featureTypeBuilder.setCRS(sft.getCoordinateReferenceSystem());
    featureTypeBuilder.setDefaultGeometry(sft.getGeometryDescriptor().getLocalName());
    featureTypeBuilder.setName(sft.getName());
    for (int i = 0; i < descriptors.size(); i++) {
        AttributeDescriptor descriptor = descriptors.get(i);
        if (!removed.contains(descriptor.getName().getLocalPart())) {
            featureTypeBuilder.add(descriptor);
        }
    }
    for (AttributeDescriptor descriptor : added) {
        featureTypeBuilder.add(descriptor);
    }
    SimpleFeatureType featureType = featureTypeBuilder.buildFeatureType();
    return RevFeatureTypeImpl.build(featureType);
}
Also used : SimpleFeatureTypeBuilder(org.geotools.feature.simple.SimpleFeatureTypeBuilder) PropertyDescriptor(org.opengis.feature.type.PropertyDescriptor) AttributeDescriptor(org.opengis.feature.type.AttributeDescriptor) Entry(java.util.Map.Entry) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) AttributeDiff(org.locationtech.geogig.api.plumbing.diff.AttributeDiff)

Example 32 with SimpleFeatureType

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

the class ShpExportDiff method getFeatureType.

private SimpleFeatureType getFeatureType(String path, GeogigCLI cli) {
    checkParameter(path != null, "No path specified.");
    String refspec;
    if (path.contains(":")) {
        refspec = path;
    } else {
        refspec = "WORK_HEAD:" + path;
    }
    checkParameter(!refspec.endsWith(":"), "No path specified.");
    final GeoGIG geogig = cli.getGeogig();
    Optional<ObjectId> rootTreeId = geogig.command(ResolveTreeish.class).setTreeish(refspec.split(":")[0]).call();
    checkParameter(rootTreeId.isPresent(), "Couldn't resolve '" + refspec + "' to a treeish object");
    RevTree rootTree = geogig.getRepository().getTree(rootTreeId.get());
    Optional<NodeRef> featureTypeTree = geogig.command(FindTreeChild.class).setChildPath(refspec.split(":")[1]).setParent(rootTree).setIndex(true).call();
    checkParameter(featureTypeTree.isPresent(), "pathspec '" + refspec.split(":")[1] + "' did not match any valid path");
    Optional<RevObject> revObject = cli.getGeogig().command(RevObjectParse.class).setObjectId(featureTypeTree.get().getMetadataId()).call();
    if (revObject.isPresent() && revObject.get() instanceof RevFeatureType) {
        RevFeatureType revFeatureType = (RevFeatureType) revObject.get();
        if (revFeatureType.type() instanceof SimpleFeatureType) {
            return (SimpleFeatureType) revFeatureType.type();
        } else {
            throw new InvalidParameterException("Cannot find feature type for the specified path");
        }
    } else {
        throw new InvalidParameterException("Cannot find feature type for the specified path");
    }
}
Also used : NodeRef(org.locationtech.geogig.api.NodeRef) InvalidParameterException(org.locationtech.geogig.cli.InvalidParameterException) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) ObjectId(org.locationtech.geogig.api.ObjectId) RevObject(org.locationtech.geogig.api.RevObject) RevFeatureType(org.locationtech.geogig.api.RevFeatureType) GeoGIG(org.locationtech.geogig.api.GeoGIG) RevTree(org.locationtech.geogig.api.RevTree)

Example 33 with SimpleFeatureType

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

the class ShpExportDiff method runInternal.

/**
     * Executes the export command using the provided options.
     */
@Override
protected void runInternal(GeogigCLI cli) throws IOException {
    if (args.size() != 4) {
        printUsage(cli);
        throw new CommandFailedException();
    }
    String commitOld = args.get(0);
    String commitNew = args.get(1);
    String path = args.get(2);
    String shapefile = args.get(3);
    ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
    File file = new File(shapefile);
    if (file.exists() && !overwrite) {
        throw new CommandFailedException("The selected shapefile already exists. Use -o to overwrite");
    }
    Map<String, Serializable> params = new HashMap<String, Serializable>();
    params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
    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;
    try {
        outputFeatureType = getFeatureType(path, cli);
    } catch (GeoToolsOpException e) {
        cli.getConsole().println("No features to export.");
        return;
    }
    SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
    builder.add("geogig_fid", String.class);
    for (AttributeDescriptor descriptor : outputFeatureType.getAttributeDescriptors()) {
        builder.add(descriptor);
    }
    builder.setName(outputFeatureType.getName());
    builder.setCRS(outputFeatureType.getCoordinateReferenceSystem());
    outputFeatureType = builder.buildFeatureType();
    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.");
    }
    final SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
    Function<Feature, Optional<Feature>> function = getTransformingFunction(dataStore.getSchema());
    ExportDiffOp op = cli.getGeogig().command(ExportDiffOp.class).setFeatureStore(featureStore).setPath(path).setOldRef(commitOld).setNewRef(commitNew).setUseOld(old).setTransactional(false).setFeatureTypeConversionFunction(function);
    try {
        op.setProgressListener(cli.getProgressListener()).call();
    } 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.", 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) SimpleFeatureTypeBuilder(org.geotools.feature.simple.SimpleFeatureTypeBuilder) Optional(com.google.common.base.Optional) HashMap(java.util.HashMap) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) ExportDiffOp(org.locationtech.geogig.geotools.plumbing.ExportDiffOp) AttributeDescriptor(org.opengis.feature.type.AttributeDescriptor) InvalidParameterException(org.locationtech.geogig.cli.InvalidParameterException) Feature(org.opengis.feature.Feature) CommandFailedException(org.locationtech.geogig.cli.CommandFailedException) GeoToolsOpException(org.locationtech.geogig.geotools.plumbing.GeoToolsOpException) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) SimpleFeatureStore(org.geotools.data.simple.SimpleFeatureStore) ShapefileDataStoreFactory(org.geotools.data.shapefile.ShapefileDataStoreFactory) File(java.io.File)

Example 34 with SimpleFeatureType

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

the class ExportDiffOp 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 SimpleFeatureStore targetStore = getTargetStore();
    final String refspec = old ? oldRef : newRef;
    final RevTree rootTree = resolveRootTree(refspec);
    final NodeRef typeTreeRef = resolTypeTreeRef(refspec, path, rootTree);
    final ObjectId defaultMetadataId = typeTreeRef.getMetadataId();
    final ProgressListener progressListener = getProgressListener();
    progressListener.started();
    progressListener.setDescription("Exporting diffs for path '" + path + "'... ");
    FeatureCollection<SimpleFeatureType, SimpleFeature> asFeatureCollection = new BaseFeatureCollection<SimpleFeatureType, SimpleFeature>() {

        @Override
        public FeatureIterator<SimpleFeature> features() {
            Iterator<DiffEntry> diffs = command(DiffOp.class).setOldVersion(oldRef).setNewVersion(newRef).setFilter(path).call();
            final Iterator<SimpleFeature> plainFeatures = getFeatures(diffs, old, stagingDatabase(), defaultMetadataId, progressListener);
            Iterator<Optional<Feature>> transformed = Iterators.transform(plainFeatures, ExportDiffOp.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) ObjectId(org.locationtech.geogig.api.ObjectId) IOException(java.io.IOException) RevFeature(org.locationtech.geogig.api.RevFeature) SimpleFeature(org.opengis.feature.simple.SimpleFeature) Feature(org.opengis.feature.Feature) 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) RevTree(org.locationtech.geogig.api.RevTree) DiffEntry(org.locationtech.geogig.api.plumbing.diff.DiffEntry)

Example 35 with SimpleFeatureType

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

the class GeogigFeatureSource method getReaderInternal.

@Override
protected FeatureReader<SimpleFeatureType, SimpleFeature> getReaderInternal(final Query query) throws IOException {
    FeatureReader<SimpleFeatureType, SimpleFeature> reader;
    final boolean naturalOrder = isNaturalOrder(query.getSortBy());
    final int startIndex = Optional.fromNullable(query.getStartIndex()).or(Integer.valueOf(0));
    final Integer maxFeatures = query.getMaxFeatures() == Integer.MAX_VALUE ? null : query.getMaxFeatures();
    final Filter filter = query.getFilter();
    final ScreenMap screenMap = (ScreenMap) query.getHints().get(Hints.SCREENMAP);
    final String[] propertyNames = query.getPropertyNames();
    if (naturalOrder) {
        reader = getNativeReader(propertyNames, filter, startIndex, maxFeatures, screenMap);
    } else {
        reader = getNativeReader(propertyNames, filter, null, null, screenMap);
        // sorting
        reader = new SortedFeatureReader(DataUtilities.simple(reader), query);
        if (startIndex > 0) {
            // skip the first n records
            for (int i = 0; i < startIndex && reader.hasNext(); i++) {
                reader.next();
            }
        }
        if (maxFeatures != null && maxFeatures > 0) {
            reader = new MaxFeatureReader<SimpleFeatureType, SimpleFeature>(reader, maxFeatures);
        }
    }
    return reader;
}
Also used : SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) Filter(org.opengis.filter.Filter) ScreenMap(org.geotools.renderer.ScreenMap) SortedFeatureReader(org.geotools.data.sort.SortedFeatureReader) SimpleFeature(org.opengis.feature.simple.SimpleFeature)

Aggregations

SimpleFeatureType (org.opengis.feature.simple.SimpleFeatureType)149 SimpleFeature (org.opengis.feature.simple.SimpleFeature)75 Test (org.junit.Test)47 IOException (java.io.IOException)46 SimpleFeatureSource (org.geotools.data.simple.SimpleFeatureSource)29 SimpleFeatureBuilder (org.geotools.feature.simple.SimpleFeatureBuilder)24 DataStore (org.geotools.data.DataStore)23 AttributeDescriptor (org.opengis.feature.type.AttributeDescriptor)23 SimpleFeatureStore (org.geotools.data.simple.SimpleFeatureStore)21 HashMap (java.util.HashMap)20 ObjectId (org.locationtech.geogig.api.ObjectId)20 SimpleFeatureTypeBuilder (org.geotools.feature.simple.SimpleFeatureTypeBuilder)19 RevFeatureType (org.locationtech.geogig.api.RevFeatureType)18 Feature (org.opengis.feature.Feature)18 ArrayList (java.util.ArrayList)16 File (java.io.File)15 SimpleFeatureIterator (org.geotools.data.simple.SimpleFeatureIterator)15 NodeRef (org.locationtech.geogig.api.NodeRef)15 InvalidParameterException (org.locationtech.geogig.cli.InvalidParameterException)15 DefaultTransaction (org.geotools.data.DefaultTransaction)14