Package org.geotools.feature

Examples of org.geotools.feature.FeatureIterator


    }
   
    private BigInteger countFeature(FeatureCollectionResponse fct) {
        BigInteger count = BigInteger.valueOf(0);
        for (int fcIndex = 0; fcIndex < fct.getFeature().size(); fcIndex++) {
            FeatureIterator i = null;
            try {
                for (i = (((FeatureCollection) fct.getFeature().get(fcIndex)).features()); i
                        .hasNext(); i.next()) {
                    count = count.add(BigInteger.ONE);
                }
            } finally {
                if (i != null) {
                    i.close();
                }
            }
        }
        return count;
    }
View Full Code Here


    private Feature getSampleFeature(FeatureTypeInfo layerInfo) throws IOException {
        FeatureSource fs = layerInfo.getFeatureSource(null, null);
        Query q = new Query();
        q.setMaxFeatures(1);
        FeatureCollection features = fs.getFeatures(q);
        FeatureIterator fi = null;
        Feature sample = null;
        try {
            fi = features.features();
            sample = fi.next();
        } finally {
            fi.close();
        }
        return sample;
    }
View Full Code Here

        }
    }

    @Override
    public Object evaluate(Object object) {
        FeatureIterator fi = null;
        try {
            // extract layer
            String layerName = getParameters().get(0).evaluate(object, String.class);
            if (layerName == null) {
                throw new IllegalArgumentException(
                        "The first argument should be a vector layer name");
            }
            FeatureTypeInfo ft = catalog.getFeatureTypeByName(layerName);
            if (ft == null) {
                throw new IllegalArgumentException("Could not find vector layer " + layerName
                        + " in the GeoServer catalog");
            }

            // extract and check the attribute
            String attribute = getParameters().get(1).evaluate(object, String.class);
            if (attribute == null) {
                throw new IllegalArgumentException("The second argument of the query "
                        + "function should be the attribute name");
            }
            CoordinateReferenceSystem crs = null;
            PropertyDescriptor ad = ft.getFeatureType().getDescriptor(attribute);
            if (ad == null) {
                throw new IllegalArgumentException("Attribute " + attribute
                        + " could not be found in layer " + layerName);
            } else if(ad instanceof GeometryDescriptor) {
                crs = ((GeometryDescriptor) ad).getCoordinateReferenceSystem();
                if(crs == null) {
                    crs = ft.getCRS();
                }
            }

            // extract and check the filter
            String cql = getParameters().get(2).evaluate(object, String.class);
            if (cql == null) {
                throw new IllegalArgumentException("The third argument of the query "
                        + "function should be a valid (E)CQL filter");
            }
            Filter filter;
            try {
                filter = (Filter) ECQL.toFilter(cql);
            } catch (Exception e) {
                throw new IllegalArgumentException("The third argument of the query "
                        + "function should be a valid (E)CQL filter", e);
            }

            // perform the query
            Query query = new Query(null, filter, new String[] { attribute });
            // .. just enough to judge if we went beyond the limit
            query.setMaxFeatures(maxResults + 1);
            FeatureSource fs = ft.getFeatureSource(null, null);
            fi = fs.getFeatures(query).features();
            List<Object> results = new ArrayList<Object>(maxResults);
            while (fi.hasNext()) {
                Feature f = fi.next();
                Object value = f.getProperty(attribute).getValue();
                if(value instanceof Geometry && crs != null) {
                    // if the crs is not associated with the geometry do so, this
                    // way other code will get to know the crs (e.g. for reprojection purposes)
                    Geometry geom = (Geometry) value;
                    geom.apply(new GeometryCRSFilter(crs));
                }
                results.add(value);
            }

            if (results.size() == 0) {
                return null;
            }
            if (maxResults > 0 && results.size() > maxResults && !single) {
                throw new IllegalStateException("The query in " + getName() + " returns too many "
                        + "features, the limit is " + maxResults);
            }
            if (maxResults == 1) {
                return results.get(0);
            } else {
                return results;
            }

        } catch (IOException e) {
            throw new RuntimeException("Failed to evaluated the query: " + e.getMessage(), e);
        } finally {
            if (fi != null) {
                fi.close();
            }
        }

    }
View Full Code Here

    public FeatureReader read(ImportData data, ImportTask item) throws IOException {
        final SimpleFeatureType featureType =
            (SimpleFeatureType) item.getMetadata().get(FeatureType.class);
        FeatureJSON json = new FeatureJSON();
        json.setFeatureType(featureType);
        final FeatureIterator it = json.streamFeatureCollection(file(data, item));

        return new FeatureReader() {

            @Override
            public FeatureType getFeatureType() {
                return featureType;
            }

            @Override
            public boolean hasNext() throws IOException {
                return it.hasNext();
            }

            @Override
            public Feature next() throws IOException, IllegalArgumentException,
                    NoSuchElementException {
                return it.next();
            }

            @Override
            public void close() throws IOException {
                it.close();
            }
        };
    }
View Full Code Here

                    .getRichStringCellValue().toString());
        }

        // check some selected values to see if the content and data type is the one
        // we expect
        FeatureIterator fi = fs.getFeatures().features();
        SimpleFeature sf = (SimpleFeature) fi.next();
        fi.close();

        // ... a string cell
        Cell cell = sheet.getRow(1).getCell(1);
        assertEquals( Cell.CELL_TYPE_STRING, cell.getCellType() );
        assertEquals(sf.getAttribute(0), cell.getRichStringCellValue().toString());
View Full Code Here

        return false;
    }

    SimpleFeature sniff(File file) {
        try {
            FeatureIterator it = new FeatureJSON().streamFeatureCollection(file);
            try {
                if (it.hasNext()) {
                    return (SimpleFeature) it.next();
                }
            }
            finally {
                it.close();
            }
        } catch (Exception e) {
            LOG.log(Level.FINER, "Error reading file as json", e);
        }
        return null;
View Full Code Here

    }

    public int size() {
        //overriding size implementation
        //simply counting!
        FeatureIterator iterator = features();
        int count = 0;
        while (iterator.hasNext()) {
            count++;
            iterator.next();
        }
        return count;
    }
View Full Code Here

     */
    private Set<String> computeFids(Tile tile, Connection conn)
            throws Exception {
        Set<String> parentFids = getUpwardFids(tile.getParent(), conn);
        Set<String> currFids = new HashSet<String>();
        FeatureIterator fi = null;
        try {
            // grab the features
            FeatureSource fs = featureType.getFeatureSource(null,null);
            GeometryDescriptor geom = fs.getSchema().getGeometryDescriptor();
            CoordinateReferenceSystem nativeCrs = geom
                    .getCoordinateReferenceSystem();

            ReferencedEnvelope nativeTileEnvelope = null;

            if (!CRS.equalsIgnoreMetadata(WGS84, nativeCrs)) {
                try {
                    nativeTileEnvelope = tile.getEnvelope().transform(nativeCrs, true);
                } catch (ProjectionException pe) {
                    // the WGS84 envelope of the tile is too big for this project,
                    // let's intersect it with the declared lat/lon bounds then
                    LOGGER.log(Level.INFO, "Could not reproject the current tile bounds "
                            + tile.getEnvelope() + " to the native SRS, intersecting with "
                            + "the layer declared lat/lon bounds and retrying");
                   
                    // let's compare against the declared data bounds then
                    ReferencedEnvelope llEnv = featureType.getLatLonBoundingBox();
                    Envelope reduced = tile.getEnvelope().intersection(llEnv);
                    if(reduced.isNull() || reduced.getWidth() == 0 || reduced.getHeight() == 0) {
                        // no overlap, no party, the tile will be empty
                        return Collections.emptySet();
                    }
                   
                    // there is some overlap, let's try the reprojection again.
                    // if even this fails, the user has evidently setup the
                    // geographics bounds improperly
                    ReferencedEnvelope refRed = new ReferencedEnvelope(reduced,
                            tile.getEnvelope().getCoordinateReferenceSystem());
                    nativeTileEnvelope = refRed.transform(nativeCrs, true);
                }
            } else {
                nativeTileEnvelope = tile.getEnvelope();
            }

            fi = getSortedFeatures(geom, tile.getEnvelope(), nativeTileEnvelope, conn);

            // if the crs is not wgs84, we'll need to transform the point
            MathTransform tx = null;
            double[] coords = new double[2];

            // scan counting how many fids we've collected
            boolean first = true;
            while (fi.hasNext() && currFids.size() < featuresPerTile) {
                // grab the feature, skip it if it's already in a parent element
                SimpleFeature f = (SimpleFeature) fi.next();
                if (parentFids.contains(f.getID()))
                    continue;

                // check the need for a transformation
                if (first) {
                    first = false;
                    CoordinateReferenceSystem nativeCRS = f.getType()
                            .getCoordinateReferenceSystem();
                    featureType.getFeatureType().getCoordinateReferenceSystem();
                    if (nativeCRS != null
                            && !CRS.equalsIgnoreMetadata(nativeCRS, WGS84)) {
                        tx = CRS.findMathTransform(nativeCRS, WGS84);
                    }
                }

                // see if the features is to be included in this tile
                Point p = ((Geometry) f.getDefaultGeometry()).getCentroid();
                coords[0] = p.getX();
                coords[1] = p.getY();
                if (tx != null)
                    tx.transform(coords, 0, coords, 0, 1);
                if (tile.contains(coords[0], coords[1]))
                    currFids.add(f.getID());
            }
        } finally {
            if (fi != null)
                fi.close();
        }
        return currFids;
    }
View Full Code Here

    }
   
    void buildIndex(Connection conn) throws Exception {
        Statement st = null;
        PreparedStatement ps = null;
        FeatureIterator fi = null;
        try {
            st = conn.createStatement();
            st.execute("CREATE TABLE FEATUREIDX(" //
                    + "X NUMBER, " //
                    + "Y NUMBER, " //
                    + "FID VARCHAR(64), " //
                    + "ORDER_FIELD " + h2Type + ")");
            st.execute("CREATE INDEX FEATUREIDX_COORDS ON FEATUREIDX(X, Y)");
            st.execute("CREATE INDEX FEATUREIDX_ORDER_FIELD ON FEATUREIDX(ORDER_FIELD)");

            // prepare this statement so that the sql parser has to deal
            // with it just once
            ps = conn.prepareStatement("INSERT INTO "
                    + "FEATUREIDX(X, Y, FID, ORDER_FIELD) VALUES (?, ?, ?, ?)");

            // build an optimized query, loading only the necessary attributes
            GeometryDescriptor geom = fs.getSchema()
                    .getGeometryDescriptor();
            CoordinateReferenceSystem nativeCrs = geom
                    .getCoordinateReferenceSystem();
            Query q = new Query();
           
            if (geom.getLocalName().equals(attribute)) {
                q.setPropertyNames(new String[] { geom.getLocalName() });
            } else {
                q.setPropertyNames(new String[] { attribute, geom.getLocalName() });
            }
           
            // setup the eventual transform
            MathTransform tx = null;
            double[] coords = new double[2];
            if (!CRS.equalsIgnoreMetadata(nativeCrs, WGS84))
                tx = CRS.findMathTransform(nativeCrs, WGS84, true);

            // read all the features and fill the index table
            // make it so the insertion is a single big transaction, should
            // be faster,
            // provided it does not kill H2...
            conn.setAutoCommit(false);
            fi = fs.getFeatures(q).features();
            while (fi.hasNext()) {
                // grab the centroid and transform it in 4326 if necessary
                SimpleFeature f = (SimpleFeature) fi.next();
                Geometry g = (Geometry) f.getDefaultGeometry();
                Point centroid = g.getCentroid();
               
                //robustness check for bad geometries
                if ( Double.isNaN( centroid.getX() ) || Double.isNaN( centroid.getY() ) ) {
                    LOGGER.warning( "Could not calculate centroid for feature " + f.getID() + "; g =  " + g.toText() );
                    continue;
                }
               
                coords[0] = centroid.getX();
                coords[1] = centroid.getY();
                if (tx != null)
                    tx.transform(coords, 0, coords, 0, 1);

                // insert
                ps.setDouble(1, coords[0]);
                ps.setDouble(2, coords[1]);
                ps.setString(3, f.getID());
                ps.setObject(4, getSortAttributeValue(f));
                ps.execute();
            }
            // todo: commit every 1000 features or so. No transaction is
            // slower, but too big transaction imposes a big overhead on the db
            conn.commit();
           
            // hum, shall we kick H2 so that it updates the statistics?
        } finally {
            conn.setAutoCommit(true);
            JDBCUtils.close(st);
            JDBCUtils.close(ps);
            if (fi != null)
                fi.close();
        }
    }
View Full Code Here

    void addFeatures(FeatureStore fs, FeatureCollection features) throws Exception {
        SimpleFeatureBuilder b = new SimpleFeatureBuilder((SimpleFeatureType) fs.getSchema());
       
        DefaultFeatureCollection toAdd = new DefaultFeatureCollection(null, null);
        FeatureIterator it = features.features();
        try {
            SimpleFeature f = null;
            int i = 0;
            while(it.hasNext()) {
                f = (SimpleFeature) it.next();
                b.init(f);
                b.add(f.getAttribute("pointProperty"));
                b.add(i++);
                toAdd.add(b.buildFeature(null));
            }
        }
        finally {
            it.close();
        }
        fs.addFeatures(toAdd);
    }
View Full Code Here

TOP

Related Classes of org.geotools.feature.FeatureIterator

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.