Package org.geotools.data

Examples of org.geotools.data.FeatureStore


            // see if there is anything at all to do, if both sides have no changes there
            // is no point eating away a revision number (this avoid the local revision number to
            // skyrocket for nothing if there are frequent synchronisations)
            String tableName = request.getTypeName().getLocalPart();
            VersioningFeatureStore fs = (VersioningFeatureStore) ds.getFeatureSource(tableName);
            FeatureStore history = (FeatureStore) ds.getFeatureSource(SYNCH_HISTORY);
            PropertyIsEqualTo ftSyncRecord = ff.equals(ff.property("table_name"), ff.literal(tableName));
            TransactionType changes = request.getTransaction();
            int changesCount = core.countChanges(changes);
            // ... if we have no changes from remote
            if(changesCount == 0) {
                // ... and we have no changes locally
                String lastLocalRevisionId = lastLocalRevision != -1 ? String.valueOf(lastLocalRevision) : "FIRST";
                if(fs.getLog(lastLocalRevisionId, "LAST", null, null, 1).size() == 0) {
                    // add a new record without the need to grab a new local revision
                    // (if necessary, that is, if at least the Central revision changed or if
                    // we don't have a synch history at all)
                    long newCentralRevision = request.getToVersion();
                    if(lastCentralRevision != newCentralRevision || record == null) {
                        SimpleFeatureType hft = (SimpleFeatureType) history.getSchema();
                        SimpleFeature f = SimpleFeatureBuilder.build(hft, new Object[] { tableName,
                                lastLocalRevision, newCentralRevision }, null);
                        history.addFeatures(DataUtilities.collection(f));
                    }
                   
                    // ... let's just return directly, no need to store or do anything
                    return new PostDiffResponseType();
                }
            }
           
            // setup the commit message and author
            transaction.putProperty(VersioningDataStore.AUTHOR, "gss");
            transaction.putProperty(VersioningDataStore.MESSAGE, "Applying " + changesCount
                    + " changes coming from Central on layer '" + tableName + "'");

            // grab the feature stores and bind them all to the same transaction
            VersioningFeatureStore conflicts = (VersioningFeatureStore) ds
                    .getFeatureSource(SYNCH_CONFLICTS);
            conflicts.setTransaction(transaction);
            history.setTransaction(transaction);
            fs.setTransaction(transaction);

            // get a hold on a revision number early so that we don't get concurrent changes
            // from the user (the datastore will make it so that no new revision numbers will
            // be generated until we commit or rollback this transaction
            long newLocalRevision = Long.parseLong(conflicts.getVersion());

            // apply changes
            LOGGER.info("About to apply " + core.countChanges(changes)
                    + " changes coming from Central");
            if (core.countChanges(changes) > 0) {
                List<DeleteElementType> deletes = changes.getDelete();
                List<UpdateElementType> updates = changes.getUpdate();

                // We need to find conflicts: local changes occurred since last synchronisation
                // that hit the same features contained in this changeset. For those we need
                // to create a conflict record and revert the local changes so that we
                // can apply the central ones
                Set<FeatureId> deletedFids = getEObjectFids(deletes);
                Set<FeatureId> updatedFids = getEObjectFids(updates);
                Set<FeatureId> changedFids = new HashSet<FeatureId>();
                changedFids.addAll(deletedFids);
                changedFids.addAll(updatedFids);

                // any possibility of conflict? If empty grabbing the corresponding local changes
                // will fail
                if (changedFids.size() > 0) {
                    // limit the changeset to the window between the last and the current
                    // synchronization
                    String newLocalRevisionId = String.valueOf(newLocalRevision);
                    String lastLocalRevisionId = lastLocalRevision != -1 ? String.valueOf(lastLocalRevision) : "FIRST";
                    FeatureDiffReader localChanges = fs.getDifferences(lastLocalRevisionId,
                            newLocalRevisionId, ff.id(changedFids), null);
                    while (localChanges.hasNext()) {
                        FeatureDiff fd = localChanges.next();
                        FeatureId diffFeatureId = ff.featureId(fd.getID());
                        if (fd.getState() == FeatureDiff.INSERTED) {
                            throw new GSSException(
                                    "A new locally inserted feature has the same "
                                            + "id as a modified feature coming from Central, this is impossible, "
                                            + "there is either a bug in ID generation or someone manually tampered with it!");
                        } else if (fd.getState() == FeatureDiff.DELETED) {
                            if (deletedFids.contains(diffFeatureId)) {
                                saveCleanMergeMarker(fs, conflicts, lastLocalRevisionId,
                                        newLocalRevision, fd.getID());
                            } else {
                                handleDeletionConflict(fs, conflicts, lastLocalRevisionId,
                                        newLocalRevision, fd.getID());
                            }
                        } else {
                            if (updatedFids.contains(diffFeatureId)) {
                                if (isSameUpdate(fd, findUpdate(fd.getID(), updates))) {
                                    saveCleanMergeMarker(fs, conflicts, lastLocalRevisionId,
                                            newLocalRevision, fd.getID());
                                } else {
                                    handleUpdateConflict(fs, conflicts, lastLocalRevisionId,
                                            newLocalRevision, fd.getID());
                                }
                            } else {
                                handleUpdateConflict(fs, conflicts, lastLocalRevisionId,
                                        newLocalRevision, fd.getID());
                            }
                        }
                    }
                    localChanges.close();
                }

                // now that conflicting local changes have been moved out of the way, apply the
                // central ones
                core.applyChanges(changes, fs);

            }

            // save/update the synchronisation metadata
            long newCentralRevision = request.getToVersion();
            SimpleFeatureType hft = (SimpleFeatureType) history.getSchema();
            SimpleFeature f = SimpleFeatureBuilder.build(hft, new Object[] { tableName,
                    newLocalRevision, newCentralRevision }, null);
            history.addFeatures(DataUtilities.collection(f));

            // commit all the changes
            transaction.commit();

            LOGGER.info(core.countChanges(changes)
View Full Code Here


      File file = new File(tempDir, name/*+".zip"*/);
     
      ShapefileDataStore sfds = new ShapefileDataStore(file.toURL());
      sfds.createSchema(featureResults[0].getSchema());
     
      FeatureStore store = (FeatureStore) sfds.getFeatureSource(name);
      store.addFeatures(reader);
    }
View Full Code Here

                continue;
            }
            try {
                FeatureSource source = meta.getFeatureSource();
                if (source instanceof FeatureStore) {
                    FeatureStore store = (FeatureStore) source;
                    store.setTransaction(transaction);
                    stores.put( elementName, source );
                    stores2.put( typeRef, source );
                } else {
                    throw new WfsTransactionException(elementName
                        + " is read-only", element.getHandle(),
                        request.getHandle());
                }
            } catch (IOException ioException) {
                throw new WfsTransactionException(elementName
                    + " is not available:" + ioException,
                    element.getHandle(), request.getHandle());
            }
        }

        // provide authorization for transaction
        //
        String authorizationID = request.getLockId();

        if (authorizationID != null) {
            if ((request.getWFS().getServiceLevel() & WFSDTO.SERVICE_LOCKING) == 0) {
                // could we catch this during the handler, rather than during execution?
                throw new ServiceException("Lock support is not enabled");
            }
            LOGGER.finer("got lockId: " + authorizationID);

            if (!catalog.lockExists(authorizationID)) {
                String mesg = "Attempting to use a lockID that does not exist"
                    + ", it has either expired or was entered wrong.";
                throw new WfsException(mesg);
            }

            try {
                transaction.addAuthorization(authorizationID);
            } catch (IOException ioException) {
                // This is a real failure - not associated with a element
                //
                throw new WfsException("Authorization ID '" + authorizationID
                    + "' not useable", ioException);
            }
        }

        // execute elements in order,
        // recording results as we go
        //
        // I will need to record the damaged area for
        // pre commit validation checks
        //
        Envelope envelope = new Envelope();

        for (int i = 0; i < request.getSubRequestSize(); i++) {
            SubTransactionRequest element = request.getSubRequest(i);
           
            // We expect element name to be of the format prefix:typeName
            // We take care to force the insert element to have this format above.
            //
            String elementName = element.getTypeName();
            String handle = element.getHandle();
            FeatureStore store = (FeatureStore) stores.get(elementName);
            if( store == null ){
              throw new ServiceException( "Could not locate FeatureStore for '"+elementName+"'" );                       
            }
            String typeName = store.getSchema().getTypeName();
           
            if (element instanceof DeleteRequest) {
                if ((request.getWFS().getServiceLevel() & WFSDTO.SERVICE_DELETE) == 0) {
                    // could we catch this during the handler, rather than during execution?
                    throw new ServiceException(
                        "Transaction Delete support is not enabled");
                }
               
                DeleteRequest delete = (DeleteRequest) element;
               
                //do a check for Filter.NONE, the spec specifically does not
                // allow this
                if (delete.getFilter() == Filter.NONE) {
                  throw new ServiceException(
                  "Filter must be supplied for Transaction Delete"
                  );
                }
               
                LOGGER.finer( "Transaction Delete:"+element );
                try {
                    Filter filter = delete.getFilter();

                    Envelope damaged = store.getBounds(new DefaultQuery(
                                delete.getTypeName(), filter));

                    if (damaged == null) {
                        damaged = store.getFeatures(filter).getBounds();
                    }

                    if ((request.getLockId() != null)
                            && store instanceof FeatureLocking
                            && (request.getReleaseAction() == TransactionRequest.SOME)) {
                        FeatureLocking locking = (FeatureLocking) store;

                        // TODO: Revisit Lock/Delete interaction in gt2
                        if (false) {
                            // REVISIT: This is bad - by releasing locks before
                            // we remove features we open ourselves up to the danger
                            // of someone else locking the features we are about to
                            // remove.
                            //
                            // We cannot do it the other way round, as the Features will
                            // not exist
                            //
                            // We cannot grab the fids offline using AUTO_COMMIT
                            // because we may have removed some of them earlier in the
                            // transaction
                            //
                            locking.unLockFeatures(filter);
                            store.removeFeatures(filter);
                        } else {
                            // This a bit better and what should be done, we will
                            // need to rework the gt2 locking api to work with
                            // fids or something
                            //
                            // The only other thing that would work would be
                            // to specify that FeatureLocking is required to
                            // remove locks when removing Features.
                            //
                            // While that sounds like a good idea, it would be
                            // extra work when doing release mode ALL.
                            //
                            DataStore data = store.getDataStore();
                            FilterFactory factory = FilterFactory
                                .createFilterFactory();
                            FeatureWriter writer;                           
                            writer = data.getFeatureWriter(typeName, filter,
                                    transaction);

                            try {
                                while (writer.hasNext()) {
                                    String fid = writer.next().getID();
                                    locking.unLockFeatures(factory
                                        .createFidFilter(fid));
                                    writer.remove();
                                }
                            } finally {
                                writer.close();
                            }

                            store.removeFeatures(filter);
                        }
                    } else {
                        // We don't have to worry about locking right now
                        //
                        store.removeFeatures(filter);
                    }

                    envelope.expandToInclude(damaged);
                } catch (IOException ioException) {
                    throw new WfsTransactionException(ioException.getMessage(),
                        element.getHandle(), request.getHandle());
                }
            }

            if (element instanceof InsertRequest) {
                if ((request.getWFS().getServiceLevel() & WFSDTO.SERVICE_INSERT) == 0) {
                    // could we catch this during the handler, rather than during execution?
                    throw new ServiceException(
                        "Transaction INSERT support is not enabled");
                }
                LOGGER.finer( "Transasction Insert:"+element );
                try {
                    InsertRequest insert = (InsertRequest) element;
                    FeatureCollection collection = insert.getFeatures();

                    FeatureReader reader = DataUtilities.reader(collection);
                    FeatureType schema = store.getSchema();

                    // Need to use the namespace here for the lookup, due to our weird
                    // prefixed internal typenames.  see
                    //   http://jira.codehaus.org/secure/ViewIssue.jspa?key=GEOS-143
                   
                    // Once we get our datastores making features with the correct namespaces
                    // we can do something like this:
                    // FeatureTypeInfo typeInfo = catalog.getFeatureTypeInfo(schema.getTypeName(), schema.getNamespace());
                    // until then (when geos-144 is resolved) we're stuck with:
                    FeatureTypeInfo typeInfo = catalog.getFeatureTypeInfo(element.getTypeName() );

                    // this is possible with the insert hack above.
                    LOGGER.finer("Use featureValidation to check contents of insert" );
                    featureValidation( typeInfo.getDataStoreInfo().getId(), schema, collection );

                    Set fids = store.addFeatures(reader);
                    build.addInsertResult(element.getHandle(), fids);

                    //
                    // Add to validation check envelope                               
                    envelope.expandToInclude(collection.getBounds());
                } catch (IOException ioException) {
                    throw new WfsTransactionException(ioException,
                        element.getHandle(), request.getHandle());
                }
            }

            if (element instanceof UpdateRequest) {
                if ((request.getWFS().getServiceLevel() & WFSDTO.SERVICE_UPDATE) == 0) {
                    // could we catch this during the handler, rather than during execution?
                    throw new ServiceException(
                        "Transaction Update support is not enabled");
                }
                LOGGER.finer( "Transaction Update:"+element);
                try {
                    UpdateRequest update = (UpdateRequest) element;
                    Filter filter = update.getFilter();

                    AttributeType[] types = update.getTypes(store.getSchema());
                    Object[] values = update.getValues();

                    DefaultQuery query = new DefaultQuery(update.getTypeName(),
                            filter);

                    // Pass through data to collect fids and damaged region
                    // for validation
                    //
                    Set fids = new HashSet();
                    LOGGER.finer("Preprocess to remember modification as a set of fids" );                   
                    FeatureReader preprocess = store.getFeatures( filter ).reader();
                    try {
                        while( preprocess.hasNext() ){
                            Feature feature = preprocess.next();
                            fids.add( feature.getID() );
                            envelope.expandToInclude( feature.getBounds() );
                        }
                    } catch (NoSuchElementException e) {
                        throw new ServiceException( "Could not aquire FeatureIDs", e );
                    } catch (IllegalAttributeException e) {
                        throw new ServiceException( "Could not aquire FeatureIDs", e );
                    }
                    finally {
                        preprocess.close();
                    }
                   
                    try{
                      if (types.length == 1) {
                          store.modifyFeatures(types[0], values[0], filter);
                      } else {
                          store.modifyFeatures(types, values, filter);
                      }
                }catch (IOException e//DJB: this is for cite tests.  We should probaby do this for all the exceptions here - throw a transaction FAIL instead of serice exception 
        {
                  //this failed - we want a FAILED not a service exception!
                  build = new WfsTransResponse(WfsTransResponse.FAILED,
                            transactionRequest.getGeoServer().isVerbose());
                   // add in exception details here??
                      build.setMessage(e.getLocalizedMessage());
                  response = build;
                  // DJB: it looks like the transaction is rolled back in writeTo()
                  return;
          }                   
                    if ((request.getLockId() != null)
                            && store instanceof FeatureLocking
                            && (request.getReleaseAction() == TransactionRequest.SOME)) {
                        FeatureLocking locking = (FeatureLocking) store;
                        locking.unLockFeatures(filter);
                    }
                   
                    // Post process - check features for changed boundary and
                    // pass them off to the ValidationProcessor
                    //
                    if( !fids.isEmpty() ) {
                        LOGGER.finer("Post process update for boundary update and featureValidation");
                        FidFilter modified = FilterFactory.createFilterFactory().createFidFilter();
                        modified.addAllFids( fids );
                   
                        FeatureCollection changed = store.getFeatures( modified ).collection();
                        envelope.expandToInclude( changed.getBounds() );
                   
                        FeatureTypeInfo typeInfo = catalog.getFeatureTypeInfo(element.getTypeName());
                        featureValidation(typeInfo.getDataStoreInfo().getId(),store.getSchema(), changed);                   
                    }
                } catch (IOException ioException) {
                    throw new WfsTransactionException(ioException,
                        element.getHandle(), request.getHandle());
                } catch (SchemaException typeException) {
View Full Code Here

                        LOGGER.warning(featureTypeName + " is not writable, skipping");
                        continue;
                    }
                   
                    Transaction tx = new DefaultTransaction();
                    FeatureStore featureStore = (FeatureStore) featureSource;
                    featureStore.setTransaction(tx);
                   
                    try {
                        //figure out update mode, whether we should kill existing data or append
                        String update = form.getFirstValue("update");
                        if ("overwrite".equalsIgnoreCase(update)) {
                            LOGGER.fine("Removing existing features from " + featureTypeName);
                            //kill all features
                            featureStore.removeFeatures(Filter.INCLUDE);
                        }
                       
                        LOGGER.fine("Adding features to " + featureTypeName);
                        FeatureCollection features = source.getFeatureSource(featureTypeName).getFeatures();
                        featureStore.addFeatures(features);
                       
                        tx.commit();
                    }
                    catch(Exception e) {
                        tx.rollback();
View Full Code Here

TOP

Related Classes of org.geotools.data.FeatureStore

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.