Package org.geotools.data

Examples of org.geotools.data.DefaultTransaction


        } finally {
            iterator.close();
        }

        {
            final Transaction transaction = new DefaultTransaction("testModifyFeaturesTransaction");
            store.setTransaction(transaction);

            try {
                final AttributeDescriptor propDescriptor = schema.getDescriptor("INT32_COL");
                store.modifyFeatures(propDescriptor.getName(), Integer.valueOf(-1000),
                        oldValueFilter);
                transaction.commit();
            } catch (Exception e) {
                transaction.rollback();
            } finally {
                transaction.close();
            }
        }
        store.setTransaction(Transaction.AUTO_COMMIT);

        final Query oldValueQuery = new Query(typeName, oldValueFilter);
View Full Code Here


            } finally {
                writer.close();
            }
        }

        final Transaction transaction = new DefaultTransaction("testUpdateAdjacentPolygons");
        store.setTransaction(transaction);
        final FilterFactory ff = CommonFactoryFinder.getFilterFactory(null);
        Filter fid1Filter = ff.id(Collections.singleton(ff.featureId(fid1)));
        Filter fid2Filter = ff.id(Collections.singleton(ff.featureId(fid2)));
        try {
            store.modifyFeatures(defaultGeometry.getName(), modif2, fid2Filter);
            store.modifyFeatures(defaultGeometry.getName(), modif1, fid1Filter);
            transaction.commit();
        } catch (Exception e) {
            transaction.rollback();
            throw e;
        } finally {
            transaction.close();
        }
        store.setTransaction(Transaction.AUTO_COMMIT);

        try {
            SimpleFeatureCollection features;
View Full Code Here

        // (the count is wraped inside an array to be able of declaring
        // the variable as final and accessing it from inside the anonymous
        // inner class)
        // final int[] featureAddedEventCount = { 0 };

        final Transaction transaction = new DefaultTransaction();
        final FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(
                typeName, Filter.INCLUDE, transaction);

        SimpleFeature source;
        SimpleFeature dest;

        int count = 0;
        try {
            for (SimpleFeatureIterator fi = testFeatures.features(); fi.hasNext(); count++) {
                if (count < initialCount) {
                    assertTrue("at index " + count, writer.hasNext());
                } else {
                    assertFalse("at index " + count, writer.hasNext());
                }

                source = fi.next();
                dest = writer.next();
                dest.setAttributes(source.getAttributes());
                writer.write();
            }
            transaction.commit();
        } catch (Exception e) {
            transaction.rollback();
            throw e;
        } finally {
            writer.close();
            transaction.close();
        }

        // was the features really inserted?
        int fcount = fsource.getCount(Query.ALL);
        assertEquals(writeCount, fcount);
View Full Code Here

        // another transaction
        // is set. Calling transaction.close() closes Transaction.State
        // held on it, allowing State objects to release resources. After
        // close() the transaction
        // is no longer valid.
        final Transaction transaction = new DefaultTransaction("test_handle");
        transFs.setTransaction(transaction);

        try {
            // create a feature to add
            SimpleFeatureBuilder builder = new SimpleFeatureBuilder(schema);
            builder.set("INT32_COL", Integer.valueOf(1000));
            builder.set("STRING_COL", "inside transaction");
            SimpleFeature feature = builder.buildFeature(null);

            // add the feature
            transFs.addFeatures(DataUtilities.collection(feature));

            // now confirm for that transaction the feature is fetched, and outside
            // it it's not.
            final Filter filterNewFeature = CQL.toFilter("INT32_COL = 1000");
            final Query newFeatureQuery = new Query(typeName, filterNewFeature);

            SimpleFeatureCollection features;
            features = transFs.getFeatures(filterNewFeature);
            int size = features.size();
            assertEquals(1, size);

            // ok transaction respected, assert the feature does not exist outside
            // it (except is the db is MS SQL Server)
            {
                FeatureReader<SimpleFeatureType, SimpleFeature> autoCommitReader;
                autoCommitReader = ds.getFeatureReader(newFeatureQuery, Transaction.AUTO_COMMIT);
                try {
                    if (databaseIsMsSqlServer) {
                        // SQL Server always is at READ UNCOMMITTED isolation level...
                        assertTrue(autoCommitReader.hasNext());
                    } else {
                        assertFalse(autoCommitReader.hasNext());
                    }
                } finally {
                    autoCommitReader.close();
                }
            }

            // ok, but what if we ask for a feature reader with the same transaction
            {
                FeatureReader<SimpleFeatureType, SimpleFeature> transactionReader;
                transactionReader = ds.getFeatureReader(newFeatureQuery, transaction);
                try {
                    assertTrue(transactionReader.hasNext());
                    transactionReader.next();
                    assertFalse(transactionReader.hasNext());
                } finally {
                    transactionReader.close();
                }
            }

            // now commit, and Transaction.AUTO_COMMIT should carry it over
            // do not close the transaction, we'll keep using it
            try {
                transaction.commit();
            } catch (IOException e) {
                transaction.rollback();
                throw e;
            }

            {
                FeatureReader<SimpleFeatureType, SimpleFeature> autoCommitReader;
                autoCommitReader = ds.getFeatureReader(newFeatureQuery, Transaction.AUTO_COMMIT);
                try {
                    assertTrue(autoCommitReader.hasNext());
                } finally {
                    autoCommitReader.close();
                }
            }

            // now keep using the transaction, it should still work
            transFs.removeFeatures(filterNewFeature);

            // no features removed yet outside the transaction
            {
                FeatureReader<SimpleFeatureType, SimpleFeature> autoCommitReader;
                autoCommitReader = ds.getFeatureReader(newFeatureQuery, Transaction.AUTO_COMMIT);
                try {
                    if (databaseIsMsSqlServer) {
                        // SQL Server always is at READ UNCOMMITTED isolation level...
                        assertFalse(autoCommitReader.hasNext());
                    } else {
                        assertTrue(autoCommitReader.hasNext());
                    }
                } finally {
                    autoCommitReader.close();
                }
            }

            // but yes inside it
            {
                FeatureReader<SimpleFeatureType, SimpleFeature> transactionReader;
                transactionReader = ds.getFeatureReader(newFeatureQuery, transaction);
                try {
                    assertFalse(transactionReader.hasNext());
                } finally {
                    transactionReader.close();
                }
            }

            {
                FeatureReader<SimpleFeatureType, SimpleFeature> autoCommitReader;
                try {
                    transaction.commit();
                    autoCommitReader = ds
                            .getFeatureReader(newFeatureQuery, Transaction.AUTO_COMMIT);
                    assertFalse(autoCommitReader.hasNext());
                } catch (Exception e) {
                    transaction.rollback();
                    throw e;
                }
            }
        } finally {
            transaction.close();
        }

    }
View Full Code Here

        testData.insertTestData();
        final SimpleFeatureCollection featuresToSet = testData.createTestFeatures(Point.class, 5);
        final DataStore ds = testData.getDataStore();
        final String typeName = testData.getTempTableName();

        final Transaction transaction = new DefaultTransaction("testSetFeaturesTransaction handle");
        final SimpleFeatureStore store;
        store = (SimpleFeatureStore) ds.getFeatureSource(typeName);
        store.setTransaction(transaction);

        final int initialCount = store.getCount(Query.ALL);
        assertTrue(initialCount > 0);
        assertTrue(initialCount != 5);

        try {
            store.setFeatures(DataUtilities.reader(featuresToSet));
            final int countInsideTransaction = store.getCount(Query.ALL);
            assertEquals(5, countInsideTransaction);

            final SimpleFeatureSource sourceNoTransaction;
            sourceNoTransaction = ds.getFeatureSource(typeName);
            int countNoTransaction = sourceNoTransaction.getCount(Query.ALL);

            if (databaseIsMsSqlServer) {
                // SQL Server always is at READ UNCOMMITTED isolation level...
                assertEquals(countInsideTransaction, countNoTransaction);
            } else {
                assertEquals(initialCount, countNoTransaction);
            }
            // now commit
            transaction.commit();
            countNoTransaction = sourceNoTransaction.getCount(Query.ALL);
            assertEquals(5, countNoTransaction);
        } catch (Exception e) {
            transaction.rollback();
            throw e;
        } catch (AssertionFailedError e) {
            transaction.rollback();
            throw e;
        } finally {
            transaction.close();
        }
    }
View Full Code Here

        final SimpleFeatureCollection testFeatures = testData.createTestFeatures(LineString.class,
                featureCount);

        final DataStore ds = testData.getDataStore();
        final SimpleFeatureStore fStore = (SimpleFeatureStore) ds.getFeatureSource(typeName);
        final Transaction transaction = new DefaultTransaction("testTransactionMultithreadAccess");
        fStore.setTransaction(transaction);

        final boolean[] done = { false, false };
        final Throwable[] errors = new Throwable[2];

        Runnable worker1 = new Runnable() {
            public void run() {
                try {
                    System.err.println("adding..");
                    List<FeatureId> addedFids = fStore.addFeatures(testFeatures);
                    System.err.println("got " + addedFids);
                    final FilterFactory ff = CommonFactoryFinder.getFilterFactory(null);

                    final Set<FeatureId> fids = new HashSet<FeatureId>();
                    for (FeatureId fid : addedFids) {
                        fids.add(fid);
                    }
                    final Id newFidsFilter = ff.id(fids);

                    System.err.println("querying..");
                    SimpleFeatureCollection features = fStore.getFeatures(newFidsFilter);
                    System.err.println("querying returned...");

                    int size = features.size();
                    System.err.println("Collection Size: " + size);
                    assertEquals(2, size);

                    System.err.println("commiting...");
                    transaction.commit();
                    System.err.println("commited.");

                    size = fStore.getCount(new Query(typeName, newFidsFilter));
                    System.err.println("Size: " + size);
                    assertEquals(2, size);
                } catch (Throwable e) {
                    errors[0] = e;
                    try {
                        System.err.println("rolling back!.");
                        transaction.rollback();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                } finally {
                    done[0] = true;
                }
            }
        };

        Runnable worker2 = new Runnable() {
            public void run() {
                try {
                    System.err.println("worker2 calling getFeartures()");
                    SimpleFeatureCollection collection = fStore.getFeatures();
                    System.err.println("worker2 opening iterator...");
                    SimpleFeatureIterator features = collection.features();
                    try {
                        System.err.println("worker2 iterating...");
                        while (features.hasNext()) {
                            SimpleFeature next = features.next();
                            System.out.println("**Got feature " + next.getID());
                        }
                        System.err.println("worker2 closing FeatureCollection");
                    } finally {
                        features.close();
                    }
                    System.err.println("worker2 done.");
                } catch (Throwable e) {
                    errors[1] = e;
                } finally {
                    done[1] = true;
                }
            }
        };

        Thread thread1 = new Thread(worker1, "worker1");
        Thread thread2 = new Thread(worker2, "worker2");
        thread1.start();
        thread2.start();
        while (!(done[0] && done[1])) {
            Thread.sleep(100);
        }
        try {
            System.err.println("closing transaction.");
            transaction.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Throwable worker1Error = errors[0];
        Throwable worker2Error = errors[1];
View Full Code Here

            final SimpleFeatureStore store;

            source = dataStore.getFeatureSource(tableName);
            store = (SimpleFeatureStore) dataStore.getFeatureSource(tableName);

            Transaction transaction = new DefaultTransaction();
            store.setTransaction(transaction);

            ArcSdeResourceInfo info = (ArcSdeResourceInfo) store.getInfo();
            assertTrue(info.isVersioned());

            final SimpleFeatureType schema = store.getSchema();

            final int initialCount = store.getCount(Query.ALL);
            assertEquals(0, initialCount);

            final WKTReader reader = new WKTReader();
            Object[] content = new Object[2];
            SimpleFeature feature;
            SimpleFeatureCollection collection;
            int count;

            content[0] = "Feature name 1";
            content[1] = reader.read("POINT (10 10)");
            feature = SimpleFeatureBuilder.build(schema, content, (String) null);
            collection = DataUtilities.collection(feature);

            store.addFeatures(collection);

            count = store.getCount(Query.ALL);
            assertEquals(1, count);
            assertEquals(0, source.getCount(Query.ALL));

            {
                SimpleFeatureIterator features = store.getFeatures().features();
                SimpleFeature f = features.next();
                features.close();
                Object obj = f.getDefaultGeometry();
                assertTrue(obj instanceof Point);
                Point p = (Point) obj;
                double x = p.getX();
                double y = p.getY();
                assertEquals(10D, x, 1E-5);
                assertEquals(10D, y, 1E-5);
            }

            transaction.commit();
            assertEquals(1, source.getCount(Query.ALL));

            content[0] = "Feature name 2";
            content[1] = reader.read("POINT (2 2)");
            feature = SimpleFeatureBuilder.build(schema, content, (String) null);
            collection = DataUtilities.collection(feature);

            store.addFeatures(collection);

            count = store.getCount(Query.ALL);
            assertEquals(2, count);

            assertEquals(1, source.getCount(Query.ALL));
            transaction.rollback();
            assertEquals(1, store.getCount(Query.ALL));

            transaction.close();

            {
                SimpleFeatureIterator features = source.getFeatures().features();
                SimpleFeature f = features.next();
                features.close();
View Full Code Here

            FileUtils.deleteDirectory(parentLocation);
        }
        assertTrue(parentLocation.mkdir());
        final String databaseName = "test";
        CoverageSlicesCatalog sliceCat = null;
        final Transaction t = new DefaultTransaction(Long.toString(System.nanoTime()));
        try {
            sliceCat = new CoverageSlicesCatalog(databaseName, parentLocation);
            String[] typeNames = sliceCat.getTypeNames();
            assertNull(typeNames);

            // create new schema 1
            final String schemaDef1 = "the_geom:Polygon,coverage:String,imageindex:Integer,cloud_formations:Integer";
            sliceCat.createType("1", schemaDef1);
            typeNames = sliceCat.getTypeNames();
            assertNotNull(typeNames);
            assertEquals(1, typeNames.length);

            // add features to it
            SimpleFeatureType schema = DataUtilities.createType("1", schemaDef1);
            SimpleFeature feat = DataUtilities.template(schema);
            feat.setAttribute("coverage", "a");
            feat.setAttribute("imageindex", Integer.valueOf(0));
            feat.setAttribute("cloud_formations", Integer.valueOf(3));
            ReferencedEnvelope referencedEnvelope = new ReferencedEnvelope(-180, 180, -90, 90,
                    DefaultGeographicCRS.WGS84);
            feat.setAttribute("the_geom", GEOM_FACTORY.toGeometry(referencedEnvelope));
            sliceCat.addGranule("1", feat, t);

            feat = DataUtilities.template(schema);
            feat.setAttribute("coverage", "a");
            feat.setAttribute("imageindex", Integer.valueOf(1));
            feat.setAttribute("cloud_formations", Integer.valueOf(2));
            feat.setAttribute("the_geom", GEOM_FACTORY.toGeometry(referencedEnvelope));
            sliceCat.addGranule("1", feat, t);
            t.commit();

            // read back
            CountVisitor cv = new CountVisitor();
            Query q = new Query("1");
            q.setFilter(Filter.INCLUDE);
            sliceCat.computeAggregateFunction(q, cv);
            assertEquals(2, cv.getCount());

            // create new schema 2
            final String schemaDef2 = "the_geom:Polygon,coverage:String,imageindex:Integer,new:Double";
            sliceCat.createType("2", schemaDef2);
            typeNames = sliceCat.getTypeNames();
            assertNotNull(typeNames);
            assertEquals(2, typeNames.length);

            // add features to it
            schema = DataUtilities.createType("2", schemaDef2);
            feat = DataUtilities.template(schema);
            feat.setAttribute("coverage", "b");
            feat.setAttribute("imageindex", Integer.valueOf(0));
            feat.setAttribute("new", Double.valueOf(3.22));
            feat.setAttribute("the_geom", GEOM_FACTORY.toGeometry(referencedEnvelope));
            sliceCat.addGranule("2", feat, t);

            feat = DataUtilities.template(schema);
            feat.setAttribute("coverage", "b");
            feat.setAttribute("imageindex", Integer.valueOf(1));
            feat.setAttribute("new", Double.valueOf(1.12));
            feat.setAttribute("the_geom", GEOM_FACTORY.toGeometry(referencedEnvelope));
            sliceCat.addGranule("2", feat, t);

            feat = DataUtilities.template(schema);
            feat.setAttribute("coverage", "b");
            feat.setAttribute("imageindex", Integer.valueOf(2));
            feat.setAttribute("new", Double.valueOf(1.32));
            feat.setAttribute("the_geom", GEOM_FACTORY.toGeometry(referencedEnvelope));
            sliceCat.addGranule("2", feat, t);

            t.commit();

            // read back
            cv = new CountVisitor();
            q = new Query("2");
            q.setFilter(Filter.INCLUDE);
            sliceCat.computeAggregateFunction(q, cv);
            assertEquals(3, cv.getCount());
           
            // Get the CoverageSlices
            List<CoverageSlice> slices = sliceCat.getGranules(q);
            double[] news = new double[]{3.22, 1.12, 1.32};
            for(int i = 0; i < news.length; i++){
                CoverageSlice slice = slices.get(i);
                assertTrue(slice.getGranuleBBOX().contains(referencedEnvelope));
                double newAttr = (double) slice.getOriginator().getAttribute("new");
                assertEquals(newAttr, news[i], DELTA);
            }
           
            // Creating a CoverageSliceCatalogSource and check if it behaves correctly
            CoverageSlicesCatalogSource src = new CoverageSlicesCatalogSource(sliceCat, "2");
            assertEquals(3, src.getCount(q));
            SimpleFeatureCollection coll = src.getGranules(q);
            cv.reset();
            coll.accepts(cv, null);
            assertEquals(3, cv.getCount());
            assertTrue(src.getBounds(q).contains(
                    referencedEnvelope.toBounds(referencedEnvelope.getCoordinateReferenceSystem())));
            assertEquals(src.getSchema(), schema);

            // remove
            sliceCat.removeGranules("1", Filter.INCLUDE, t);
            sliceCat.removeGranules("2", Filter.INCLUDE, t);
            t.commit();
            // check
            q = new Query("1");
            q.setFilter(Filter.INCLUDE);
            sliceCat.computeAggregateFunction(q, cv);
            assertEquals(0, cv.getCount());
            q = new Query("2");
            sliceCat.computeAggregateFunction(q, cv);
            assertEquals(0, cv.getCount());

        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            t.rollback();
        } finally {
            if (sliceCat != null) {
                sliceCat.dispose();
            }

            t.close();

            FileUtils.deleteDirectory(parentLocation);
        }

    }
View Full Code Here

        // Reader Catalog
        CoverageSlicesCatalog sliceCat = reader.getCatalog();
        assertNotNull(sliceCat);

        final Transaction t = new DefaultTransaction(Long.toString(System.nanoTime()));
        try {
            String[] typeNames = sliceCat.getTypeNames();
            assertNull(typeNames);

            // create new schema 1
            final String schemaDef1 = "the_geom:Polygon,coverage:String,imageindex:Integer";
            sliceCat.createType("1", schemaDef1);
            typeNames = sliceCat.getTypeNames();
            assertNotNull(typeNames);
            assertEquals(1, typeNames.length);

            // add features to it
            SimpleFeatureType schema = DataUtilities.createType("1", schemaDef1);
            SimpleFeature feat = DataUtilities.template(schema);
            feat.setAttribute("coverage", "a");
            feat.setAttribute("imageindex", Integer.valueOf(0));
            ReferencedEnvelope referencedEnvelope = new ReferencedEnvelope(-180, 180, -90, 90,
                    DefaultGeographicCRS.WGS84);
            feat.setAttribute("the_geom", GEOM_FACTORY.toGeometry(referencedEnvelope));
            sliceCat.addGranule("1", feat, t);
            t.commit();
           
            // Check if present
           
            Query q = new Query("1");
            q.setFilter(Filter.INCLUDE);
            // Get ImageIndexes
            List<Integer> indexes = reader.getImageIndex(q);
            assertNotNull(indexes);
            assertTrue(!indexes.isEmpty());
        } catch (Exception e) {
            t.rollback();
        } finally {
            if (sliceCat != null) {
                sliceCat.dispose();
            }

            t.close();

            FileUtils.deleteDirectory(parentLocation);
        }

        String auxiliaryFilesPath = "file:/path";
View Full Code Here

     * @return
     * @throws InvalidRangeException
     * @throws IOException
     */
    protected int initIndex() throws InvalidRangeException, IOException {
        DefaultTransaction transaction = new DefaultTransaction("indexTransaction" + System.nanoTime());
        int numImages = 0;
        try {

            // init slice catalog
            final File sliceIndexFile = ancillaryFileManager.getSlicesIndexFile();
            initCatalog(sliceIndexFile.getParentFile(),
                FilenameUtils.removeExtension(FilenameUtils.getName(sliceIndexFile.getCanonicalPath())).replace(".", ""));
            final List<Variable> variables = dataset.getVariables();
            if (variables != null) {

                // cycle on all variables to get parse them
                for (final Variable var_ : variables) {
                    if (var_ != null && var_ instanceof VariableDS) {
                        final VariableDS variable= (VariableDS) var_;
                       
                        // get the name
                        // check if it is filtered or not
                        String varName = variable.getFullName();
                        if (!ancillaryFileManager.acceptsVariable(varName)) {
                            continue;
                        }

                        // is it acceptable?
                        if (!NetCDFUtilities.isVariableAccepted(variable, checkType)) {
                            continue;
                        }

                        // COVERAGE NAME
                        // Add the accepted variable to the list of coverages name
                        final Name coverageName = getCoverageName(varName);
                        final CoordinateSystem cs = NetCDFCRSUtilities.getCoordinateSystem(variable);

                        final SimpleFeatureType indexSchema = getIndexSchema(coverageName, cs);
                        // get variable adapter which maps to a coverage in the end
                        final VariableAdapter vaAdapter = getCoverageDescriptor(coverageName);

                        if (indexSchema == null) {
                            throw new IllegalStateException("Unable to created index schema for coverage:"+coverageName);
                        }

                        final int variableImageStartIndex = numImages;
                        final int numberOfSlices = vaAdapter.getNumberOfSlices();
                        numImages += numberOfSlices;

                        int startPagingIndex = 0;
                        final int limit = INTERNAL_INDEX_CREATION_PAGE_SIZE;
                        final ListFeatureCollection collection = new ListFeatureCollection(indexSchema);

                        int writtenFeatures = 0;
                        while (writtenFeatures < numberOfSlices) {
                            // Get a bunch of features
                            vaAdapter.getFeatures(startPagingIndex, limit, collection);
                            if (variableImageStartIndex != 0) {
                                // Need to updated the imageIndex of the features since all indexes
                                // are zero based inside each variable but we need to index them inside
                                // the whole NetCDF dataset.
                                updateFeaturesIndex(collection, variableImageStartIndex);
                            }
                            final int features = collection.size();
                            if (features > 0) {
                                // adding granules to the catalog and updating the number of written features
                                getCatalog().addGranules(indexSchema.getTypeName(), collection, transaction);
                                collection.clear();
                                startPagingIndex += features;
                            }
                            writtenFeatures += features;
                        }
                    }
                }
            }
            // write things to disk
            ancillaryFileManager.writeToDisk();
            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.fine("Committing changes to the DB");
            }
            transaction.commit();
        } catch (Throwable e) {
            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.fine("Rollback");
            }
            if (transaction != null) {
                transaction.rollback();
            }
            throw new IOException(e);
        } finally {
            try {
                if (transaction != null) {
                    transaction.close();
                }
            } catch (Throwable t) {

            }
        }
View Full Code Here

TOP

Related Classes of org.geotools.data.DefaultTransaction

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.