Examples of FeatureReader


Examples of org.geotools.data.FeatureReader

    void loadIntoDataStore(ImportTask task, DataStoreInfo store, VectorFormat format,
        VectorTransformChain tx) throws Exception {

        ImportData data = task.getData();
        FeatureReader reader = null;
        FeatureWriter writer = null;
        // using this exception to throw at the end
        Exception error = null;
        try {
            reader = format.read(data, task);

            SimpleFeatureType featureType = (SimpleFeatureType) reader.getFeatureType();
            final String featureTypeName = featureType.getName().getLocalPart();
   
            DataStore dataStore = (DataStore) store.getDataStore(null);
            FeatureDataConverter featureDataConverter = FeatureDataConverter.DEFAULT;
            if (isShapefileDataStore(dataStore)) {
                featureDataConverter = FeatureDataConverter.TO_SHAPEFILE;
            }
            else if (isOracleDataStore(dataStore)) {
                featureDataConverter = FeatureDataConverter.TO_ORACLE;
            }
            else if (isPostGISDataStore(dataStore)) {
                featureDataConverter = FeatureDataConverter.TO_POSTGIS;
            }
           
            featureType = featureDataConverter.convertType(featureType, format, data, task);
            UpdateMode updateMode = task.getUpdateMode();
            final String uniquifiedFeatureTypeName;
            if (updateMode == UpdateMode.CREATE) {
                //find a unique type name in the target store
                uniquifiedFeatureTypeName = findUniqueNativeFeatureTypeName(featureType, store);
                task.setOriginalLayerName(featureTypeName);
   
                if (!uniquifiedFeatureTypeName.equals(featureTypeName)) {
                    //update the metadata
                    task.getLayer().getResource().setName(uniquifiedFeatureTypeName);
                    task.getLayer().getResource().setNativeName(uniquifiedFeatureTypeName);
                   
                    //retype
                    SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
                    typeBuilder.setName(uniquifiedFeatureTypeName);
                    typeBuilder.addAll(featureType.getAttributeDescriptors());
                    featureType = typeBuilder.buildFeatureType();
                }
   
                // @todo HACK remove this at some point when timezone issues are fixed
                // this will force postgis to create timezone w/ timestamp fields
                if (dataStore instanceof JDBCDataStore) {
                    JDBCDataStore ds = (JDBCDataStore) dataStore;
                    // sniff for postgis (h2 is used in tests and will cause failure if this occurs)
                    if (ds.getSqlTypeNameToClassMappings().containsKey("timestamptz")) {
                        ds.getSqlTypeToSqlTypeNameOverrides().put(java.sql.Types.TIMESTAMP, "timestamptz");
                    }
                }
   
                //apply the feature type transform
                featureType = tx.inline(task, dataStore, featureType);
   
                dataStore.createSchema(featureType);
            } else {
                // @todo what to do if featureType transform is present?
               
                // @todo implement me - need to specify attribute used for id
                if (updateMode == UpdateMode.UPDATE) {
                    throw new UnsupportedOperationException("updateMode UPDATE is not supported yet");
                }
                uniquifiedFeatureTypeName = featureTypeName;
            }
               
            Transaction transaction = new DefaultTransaction();
           
            if (updateMode == UpdateMode.REPLACE) {
               
                FeatureStore fs = (FeatureStore) dataStore.getFeatureSource(featureTypeName);
                fs.setTransaction(transaction);
                fs.removeFeatures(Filter.INCLUDE);
            }
           
            //start writing features
            // @todo ability to collect transformation errors for use in a dry-run (auto-rollback)
           
            ProgressMonitor monitor = task.progress();
           
            // @todo need better way to communicate to client
            int skipped = 0;
            int cnt = 0;
            // metrics
            long startTime = System.currentTimeMillis();
            task.clearMessages();
           
            task.setTotalToProcess(format.getFeatureCount(task.getData(), task));
           
            LOGGER.info("begining import");
            try {
                writer = dataStore.getFeatureWriterAppend(uniquifiedFeatureTypeName, transaction);
               
                while(reader.hasNext()) {
                    if (monitor.isCanceled()){
                        break;
                    }
                    SimpleFeature feature = (SimpleFeature) reader.next();
                    SimpleFeature next = (SimpleFeature) writer.next();
   
                    //(JD) TODO: some formats will rearrange the geometry type (like shapefile) which
                    // makes the goemetry the first attribute reagardless, so blindly copying over
                    // attributes won't work unless the source type also  has the geometry as the
View Full Code Here

Examples of org.geotools.data.FeatureReader

                writer.setMaximunFractionDigits(layerConfig.getNumDecimals());
            } else {
                writer.setMaximunFractionDigits(defMaxDecimals);
            }

            FeatureReader featureReader = null;

            try {
                LOGGER.fine("obtaining FeatureReader for "
                    + layerConfig.getName());
                featureReader = results[i].reader();
                LOGGER.fine("got FeatureReader, now writing");

                String groupId = null;

                //modified ch = delegate now changes style names to style
                //objects, so execute takes a style array.
                //if (styles == null) {
                groupId = layerConfig.getTypeName();

                //} else {
                //groupId = (String) styles.get(i);
                //}
                writer.write("<g id=\"" + groupId + "\" class=\"" + groupId
                    + "\">\n");
                writeFeatures(featureReader);
                writer.write("</g>\n");
            } catch (IOException ex) {
                throw ex;
            } catch (AbortedException ae) {
                LOGGER.info("process aborted: " + ae.getMessage());
                throw ae;
            } catch (Throwable t) {
                LOGGER.warning("UNCAUGHT exception: " + t.getMessage());

                IOException ioe = new IOException("UNCAUGHT exception: "
                        + t.getMessage());
                ioe.setStackTrace(t.getStackTrace());
                throw ioe;
            } finally {
                if (featureReader != null) {
                    featureReader.close();
                }
            }
        }
    }
View Full Code Here

Examples of org.geotools.data.FeatureReader

        output = zipOut;
       
        List resultsList = results.getFeatures();
        FeatureResults[] featureResults = (FeatureResults[]) resultsList
            .toArray(new FeatureResults[resultsList.size()]);
        FeatureReader reader = featureResults[0].reader();
        String name = featureResults[0].getSchema().getTypeName();
       
        String namePath = tempDir+name;
       
        try {
View Full Code Here

Examples of org.geotools.data.FeatureReader

            FeatureResults features = source.getFeatures(curFilter);

            if( source instanceof FeatureLocking){
                ((FeatureLocking)source).setFeatureLock(fLock);
            }
            FeatureReader reader = null;

            try {
                for (reader = features.reader(); reader.hasNext();) {
                    Feature feature = reader.next();
                    String fid = feature.getID();
                    if( !(source instanceof FeatureLocking)){
                        LOGGER.fine("Lock " + fid +
                                " not supported by data store (authID:"
                                + fLock.getAuthorization() + ")");
                        lockFailedFids.add(fid);
                    }
                    else {
                        Filter fidFilter = filterFactory.createFidFilter(fid);

                        //DEFQuery is just some indirection, should be in the locking interface.
                        //int numberLocked = ((DEFQueryFeatureLocking)source).lockFeature(feature);
                        //HACK: Query.NO_NAMES isn't working in postgis right now,
                        //so we'll just use all.
                        Query query = new DefaultQuery(
                                meta.getTypeName(), fidFilter,
                                Query.DEFAULT_MAX, Query.ALL_NAMES,
                                curLock.getHandle());
                        int numberLocked = ((FeatureLocking)source).lockFeatures( query );

                        if (numberLocked == 1) {
                            LOGGER.fine("Lock " + fid + " (authID:"
                                + fLock.getAuthorization() + ")");
                            lockedFids.add(fid);
                        } else if (numberLocked == 0) {
                            LOGGER.fine("Lock " + fid + " conflict (authID:"
                                + fLock.getAuthorization() + ")");
                            lockFailedFids.add(fid);
                        } else {
                            LOGGER.warning("Lock " + numberLocked + " " + fid
                                + " (authID:" + fLock.getAuthorization()
                                + ") duplicated FeatureID!");
                            lockedFids.add(fid);
                        }
                    }
                }
            } catch (IllegalAttributeException e) {
                // TODO: JG - I really dont like this
                // reader says it will throw this if the attribtues do not match
                // the FeatureTypeInfo
                // I figure if this is thrown we are poorly configured or
                // the DataStoreInfo needs some quality control
                //
                // should rollback the lock as well :-(
                throw new WfsException("Lock request " + curFilter
                    + " did not match " + curTypeName);
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }
        }

        if (lockAll && !lockFailedFids.isEmpty()) {
View Full Code Here

Examples of org.geotools.data.FeatureReader

                    // geotools2 locking code
                    if (source instanceof FeatureLocking) {
                        ((FeatureLocking) source).setFeatureLock(featureLock);
                    }

                    FeatureReader reader = null;

                    try {
                        for (reader = features.reader(); reader.hasNext();) {
                            feature = reader.next();
                            fid = feature.getID();

                            if (!(source instanceof FeatureLocking)) {
                                LOGGER.finest("Lock " + fid
                                    + " not supported by data store (authID:"
                                    + featureLock.getAuthorization() + ")");
                                lockFailedFids.add(fid);

                                continue; // locking is not supported!
                            } else {
                                fidFilter = filterFactory.createFidFilter(fid);
                                numberLocked = ((FeatureLocking) source)
                                    .lockFeatures(fidFilter);

                                if (numberLocked == 1) {
                                    LOGGER.finest("Lock " + fid + " (authID:"
                                        + featureLock.getAuthorization() + ")");
                                    lockedFids.add(fid);
                                } else if (numberLocked == 0) {
                                    LOGGER.finest("Lock " + fid
                                        + " conflict (authID:"
                                        + featureLock.getAuthorization() + ")");
                                    lockFailedFids.add(fid);
                                } else {
                                    LOGGER.warning("Lock " + numberLocked + " "
                                        + fid + " (authID:"
                                        + featureLock.getAuthorization()
                                        + ") duplicated FeatureID!");
                                    lockedFids.add(fid);
                                }
                            }
                        }
                    } finally {
                        if (reader != null) {
                            reader.close();
                        }
                    }

                    if (!lockedFids.isEmpty()) {
                        Transaction t = new DefaultTransaction();
View Full Code Here

Examples of org.geotools.data.FeatureReader

        int defMaxDecimals = writer.getMaximunFractionDigits();
       
        FilterFactory fFac = FilterFactory.createFilterFactory();
        for (int i = 0; i < nLayers; i++) {
            MapLayer layer = layers[i];
            FeatureReader featureReader = null;
            FeatureSource fSource = layer.getFeatureSource();
            FeatureType schema = fSource.getSchema();
            try {
                Expression bboxExpression = fFac.createBBoxExpression(mapContext
                        .getAreaOfInterest());
                GeometryFilter bboxFilter = fFac.createGeometryFilter(FilterType.GEOMETRY_INTERSECTS);
                bboxFilter.addLeftGeometry(bboxExpression);
                bboxFilter.addRightGeometry(fFac.createAttributeExpression(
                        schema, schema.getDefaultGeometry().getName()));
               
                Query bboxQuery = new DefaultQuery(schema.getTypeName(),
                        bboxFilter);
               
                featureReader = fSource.getFeatures(bboxQuery).reader();
                FeatureCollection fc = fSource.getFeatures(bboxQuery);
                writer.writeFeatures(fc, layer.getStyle());
                LOGGER.fine("finished writing");
            } catch (IOException ex) {
                LOGGER.info("process failed: " + ex.getMessage());
                throw ex;
            } catch (AbortedException ae) {
                LOGGER.info("process aborted: " + ae.getMessage());
                throw ae;
            } catch (Throwable t) {
                LOGGER.warning("UNCAUGHT exception: " + t.getMessage());
               
                IOException ioe = new IOException("UNCAUGHT exception: "
                        + t.getMessage());
                ioe.setStackTrace(t.getStackTrace());
                throw ioe;
            } finally {
                if (featureReader != null) {
                    try{
                        featureReader.close();
                    }catch(IOException ioe){
                        //featureReader was probably closed already.
                    }
                }
            }
View Full Code Here

Examples of org.geotools.data.FeatureReader

                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);
View Full Code Here

Examples of org.geotools.data.FeatureReader

                }
            };

        try {
      // HACK: turned the collection into a feature reader for the validation processor
      FeatureReader fr = DataUtilities.reader(collection);
            validation.runFeatureTests(dsid, type, fr, results);
        } catch (Exception badIdea) {
            // ValidationResults should of handled stuff will redesign :-)
            throw new DataSourceException("Validation Failed", badIdea);
        }
View Full Code Here

Examples of org.geotools.data.FeatureReader

        Charset charSet = getRequest().getGeoServer().getCharSet();
        OutputStreamWriter osw = new OutputStreamWriter(out, charSet);
        PrintWriter writer = new PrintWriter(osw);
        writer.println("<html><body>");

        FeatureReader reader = null;
        try {
            for (int i = 0; i < results.size(); i++) {
                FeatureResults fr = (FeatureResults) results.get(i);
                FeatureType schema = fr.getSchema();

                writer.println("<table border='1'>");
                writer.println("<tr><th colspan=" + schema.getAttributeCount()
                    + " scope='col'>" + schema.getTypeName() + " </th></tr>");
                writer.println("<tr>");

                for (int j = 0; j < schema.getAttributeCount(); j++) {
                    writer.println("<td>"
                        + schema.getAttributeType(j).getName() + "</td>");
                }

                writer.println("</tr>");

                //writer.println("Found " + fr.getCount() + " in " + schema.getTypeName());
                reader = fr.reader();

                while (reader.hasNext()) {
                    Feature f = reader.next();
                    AttributeType[] types = schema.getAttributeTypes();
                    writer.println("<tr>");

                    for (int j = 0; j < types.length; j++) {
                        if (Geometry.class.isAssignableFrom(types[j].getType())) {
                            writer.println("<td>");
                            writer.println("[GEOMETRY]");
                            writer.println("</td>");
                        } else {
                            writer.println("<td>");
                            writer.print(f.getAttribute(types[j].getName()));
                            writer.println("</td>");
                        }
                    }

                    writer.println("</tr>");
                }

                writer.println("</table>");
                writer.println("<p>");
                writer.println("</body></html>");
            }
        } catch (IllegalAttributeException ife) {
            writer.println("Unable to generate information " + ife);
        }
        finally
    {
          if (reader != null)
            reader.close();
    }
       
        writer.flush();
    }
View Full Code Here

Examples of org.geotools.data.FeatureReader

        //DJB: this is to limit the number of features read - as per the spec 7.3.3.7 FEATURE_COUNT
       
        int featuresPrinted = 0// how many features we've actually printed so far!
        int maxfeatures = getRequest().getFeatureCount(); // will default to 1 if not specified in the request
       
        FeatureReader reader = null;
        try {
            for (int i = 0; i < results.size(); i++//for each layer queried
            {
                FeatureResults fr = (FeatureResults) results.get(i);

                reader = fr.reader();
               
                if ( reader.hasNext() && (featuresPrinted<maxfeatures) ) // if this layer has a hit and we're going to print it
               
                  writer.println("Results for FeatureType '"+ reader.getFeatureType().getTypeName() + "':");
                }

                while (reader.hasNext())
                {
                    Feature f = reader.next();

                    FeatureType schema = f.getFeatureType();
                    AttributeType[] types = schema.getAttributeTypes();

                    if (featuresPrinted<maxfeatures)
          {
                      writer.println("--------------------------------------------");
                      for (int j = 0; j < types.length; j++) //for each column in the featuretype
                      {      
                          if (Geometry.class.isAssignableFrom(types[j].getType()))
                          {
                              //writer.println(types[j].getName() + " = [GEOMETRY]");
                           
                            //DJB: changed this to print out WKT - its very nice for users
                            //Geometry g = (Geometry) f.getAttribute(types[j].getName());
                              //writer.println(types[j].getName() + " = [GEOMETRY] = "+g.toText() );
                           
                            //DJB: decided that all the geometry info was too much - they should use GML version if they want those details
                            Geometry g = (Geometry) f.getAttribute(types[j].getName());
                            writer.println(types[j].getName() + " = [GEOMETRY ("+g.getGeometryType()+") with "+g.getNumPoints()+" points]");
                           
                          } else {
                              writer.println(types[j].getName() + " = "
                                  + f.getAttribute(types[j].getName()));
                          }                                        
                      }
                      writer.println("--------------------------------------------");
                      featuresPrinted++;
          }
                }
            }
        }
        catch (IllegalAttributeException ife) {
            writer.println("Unable to generate information " + ife);
        }
        finally
    {
          if (reader != null)
            reader.close();
    }
       
        if (featuresPrinted ==0)
        {
          writer.println("no features were found");
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. 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.