Search in sources :

Example 6 with DefaultTransaction

use of org.geotools.data.DefaultTransaction 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 7 with DefaultTransaction

use of org.geotools.data.DefaultTransaction in project incubator-rya by apache.

the class GeoWaveFeatureReaderTest method setup.

@Before
public void setup() throws SchemaException, CQLException, Exception {
    setupConf();
    try (final GeoWaveGeoIndexer indexer = new GeoWaveGeoIndexer()) {
        indexer.setConf(conf);
        dataStore = indexer.getGeoToolsDataStore();
        // Clear old data
        indexer.purge(conf);
        type = DataUtilities.createType("GeoWaveFeatureReaderTest", "geometry:Geometry:srid=4326,start:Date,end:Date,pop:java.lang.Long,pid:String");
        dataStore.createSchema(type);
        stime = DateUtilities.parseISO("2005-05-15T20:32:56Z");
        etime = DateUtilities.parseISO("2005-05-20T20:32:56Z");
        final Transaction transaction1 = new DefaultTransaction();
        final FeatureWriter<SimpleFeatureType, SimpleFeature> writer = dataStore.getFeatureWriter(type.getTypeName(), transaction1);
        assertFalse(writer.hasNext());
        SimpleFeature newFeature = writer.next();
        newFeature.setAttribute("pop", Long.valueOf(100));
        newFeature.setAttribute("pid", "a" + UUID.randomUUID().toString());
        newFeature.setAttribute("start", stime);
        newFeature.setAttribute("end", etime);
        newFeature.setAttribute("geometry", factory.createPoint(new Coordinate(27.25, 41.25)));
        fids.add(newFeature.getID());
        pids.add(newFeature.getAttribute("pid").toString());
        writer.write();
        newFeature = writer.next();
        newFeature.setAttribute("pop", Long.valueOf(101));
        newFeature.setAttribute("pid", "b" + UUID.randomUUID().toString());
        newFeature.setAttribute("start", etime);
        newFeature.setAttribute("geometry", factory.createPoint(new Coordinate(28.25, 41.25)));
        fids.add(newFeature.getID());
        pids.add(newFeature.getAttribute("pid").toString());
        writer.write();
        writer.close();
        transaction1.commit();
        transaction1.close();
        query = new Query("GeoWaveFeatureReaderTest", ECQL.toFilter("IN ('" + fids.get(0) + "')"), new String[] { "geometry", "pid" });
    }
}
Also used : Transaction(org.geotools.data.Transaction) DefaultTransaction(org.geotools.data.DefaultTransaction) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) Query(org.geotools.data.Query) Coordinate(com.vividsolutions.jts.geom.Coordinate) DefaultTransaction(org.geotools.data.DefaultTransaction) SimpleFeature(org.opengis.feature.simple.SimpleFeature) Before(org.junit.Before)

Example 8 with DefaultTransaction

use of org.geotools.data.DefaultTransaction in project tutorials by eugenp.

the class ShapeFile method writeToFile.

private static void writeToFile(ShapefileDataStore dataStore, DefaultFeatureCollection collection) throws Exception {
    // If you decide to use the TYPE type and create a Data Store with it,
    // You will need to uncomment this line to set the Coordinate Reference System
    // newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
    Transaction transaction = new DefaultTransaction("create");
    String typeName = dataStore.getTypeNames()[0];
    SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName);
    if (featureSource instanceof SimpleFeatureStore) {
        SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
        featureStore.setTransaction(transaction);
        try {
            featureStore.addFeatures(collection);
            transaction.commit();
        } catch (Exception problem) {
            problem.printStackTrace();
            transaction.rollback();
        } finally {
            transaction.close();
        }
        // success!
        System.exit(0);
    } else {
        System.out.println(typeName + " does not support read/write access");
        System.exit(1);
    }
}
Also used : Transaction(org.geotools.data.Transaction) DefaultTransaction(org.geotools.data.DefaultTransaction) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) SimpleFeatureStore(org.geotools.data.simple.SimpleFeatureStore) DefaultTransaction(org.geotools.data.DefaultTransaction)

Example 9 with DefaultTransaction

use of org.geotools.data.DefaultTransaction in project polymap4-core by Polymap4.

the class UnitOfWork method prepare.

/**
 * Starts a new {@link Transaction} for the underlying {@link FeatureStore},
 * checks concurrent modifications and updates {@link FeatureStore}.
 *
 * @param monitor
 * @throws IOException
 * @throws {@link ConcurrentModificationException}
 */
public void prepare(IProgressMonitor monitor) throws ConcurrentModificationException, IOException {
    assert tx == null : "Pending transaction found.";
    if (modified.isEmpty()) {
        return;
    }
    monitor.beginTask("Prepare commit: " + getLabel(), modified.size());
    // set transaction
    tx = new DefaultTransaction(getClass().getSimpleName() + "-" + hashCode());
    fs.setTransaction(tx);
    DefaultFeatureCollection added = new DefaultFeatureCollection();
    Set<Identifier> removed = new HashSet();
    int count = 0;
    for (FeatureBufferState buffered : modified.values()) {
        if (monitor.isCanceled()) {
            return;
        }
        if ((++count % 100) == 0) {
            monitor.subTask("(" + count + ")");
        }
        if (buffered.isAdded()) {
            // no check if fid was created already since it is propably the 'primary key'
            added.add((SimpleFeature) buffered.feature());
        } else if (buffered.isModified()) {
            checkSubmitModified(buffered);
        } else if (buffered.isRemoved()) {
            removed.add(buffered.feature().getIdentifier());
        } else {
            log.warn("Buffered feature is not added/removed/modified!");
        }
        monitor.worked(1);
    }
    if (!added.isEmpty()) {
        fs.addFeatures(added);
        monitor.worked(added.size());
    }
    if (!removed.isEmpty()) {
        fs.removeFeatures(ff.id(removed));
        monitor.worked(added.size());
    }
    monitor.done();
}
Also used : Identifier(org.opengis.filter.identity.Identifier) DefaultTransaction(org.geotools.data.DefaultTransaction) DefaultFeatureCollection(org.geotools.feature.DefaultFeatureCollection) HashSet(java.util.HashSet)

Example 10 with DefaultTransaction

use of org.geotools.data.DefaultTransaction in project OpenTripPlanner by opentripplanner.

the class LIsochrone method getZippedShapefileIsochrone.

@GET
@Produces("application/x-zip-compressed")
public Response getZippedShapefileIsochrone(@QueryParam("shpName") String shpName, @QueryParam("stream") @DefaultValue("true") boolean stream) throws Exception {
    SimpleFeatureCollection contourFeatures = makeContourFeatures(computeIsochrone());
    /* Output the staged features to Shapefile */
    final File shapeDir = Files.createTempDir();
    File shapeFile = new File(shapeDir, shpName + ".shp");
    LOG.debug("writing out shapefile {}", shapeFile);
    ShapefileDataStore outStore = new ShapefileDataStore(shapeFile.toURI().toURL());
    outStore.createSchema(contourSchema);
    Transaction transaction = new DefaultTransaction("create");
    SimpleFeatureStore featureStore = (SimpleFeatureStore) outStore.getFeatureSource();
    featureStore.setTransaction(transaction);
    try {
        featureStore.addFeatures(contourFeatures);
        transaction.commit();
    } catch (Exception e) {
        transaction.rollback();
        throw e;
    } finally {
        transaction.close();
    }
    // Note: the order is important
    shapeDir.deleteOnExit();
    for (File f : shapeDir.listFiles()) f.deleteOnExit();
    /* Zip up the shapefile components */
    StreamingOutput output = new DirectoryZipper(shapeDir);
    if (stream) {
        return Response.ok().entity(output).build();
    } else {
        File zipFile = new File(shapeDir, shpName + ".zip");
        OutputStream fos = new FileOutputStream(zipFile);
        output.write(fos);
        zipFile.deleteOnExit();
        return Response.ok().entity(zipFile).build();
    }
}
Also used : ShapefileDataStore(org.geotools.data.shapefile.ShapefileDataStore) Transaction(org.geotools.data.Transaction) DefaultTransaction(org.geotools.data.DefaultTransaction) SimpleFeatureStore(org.geotools.data.simple.SimpleFeatureStore) ZipOutputStream(java.util.zip.ZipOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) StreamingOutput(javax.ws.rs.core.StreamingOutput) File(java.io.File) DefaultTransaction(org.geotools.data.DefaultTransaction) IOException(java.io.IOException) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

DefaultTransaction (org.geotools.data.DefaultTransaction)20 Transaction (org.geotools.data.Transaction)17 SimpleFeature (org.opengis.feature.simple.SimpleFeature)15 SimpleFeatureType (org.opengis.feature.simple.SimpleFeatureType)14 Test (org.junit.Test)12 SimpleFeatureStore (org.geotools.data.simple.SimpleFeatureStore)9 ShapefileDataStore (org.geotools.data.shapefile.ShapefileDataStore)6 FeatureId (org.opengis.filter.identity.FeatureId)6 HashMap (java.util.HashMap)5 Map (java.util.Map)5 Query (org.geotools.data.Query)5 ObjectId (org.locationtech.geogig.api.ObjectId)5 IOException (java.io.IOException)4 FileDataStoreFactorySpi (org.geotools.data.FileDataStoreFactorySpi)4 SimpleFeatureCollection (org.geotools.data.simple.SimpleFeatureCollection)4 SimpleFeatureIterator (org.geotools.data.simple.SimpleFeatureIterator)4 SimpleFeatureBuilder (org.geotools.feature.simple.SimpleFeatureBuilder)4 AttributeDescriptor (org.opengis.feature.type.AttributeDescriptor)4 SimpleFeatureSource (org.geotools.data.simple.SimpleFeatureSource)3 Ignore (org.junit.Ignore)3