Java Code Examples for org.geotools.data.simple.SimpleFeatureCollection#features()

The following examples show how to use org.geotools.data.simple.SimpleFeatureCollection#features() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ElasticGeometryFilterIT.java    From elasticgeo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testGeoPointAsArray() throws Exception {
    init("active","geo5");
    FilterFactory2 ff = (FilterFactory2) dataStore.getFilterFactory();
    GeometryFactory gf = new GeometryFactory();
    PackedCoordinateSequenceFactory sf = new PackedCoordinateSequenceFactory();
    Point ls = gf.createPoint(sf.create(new double[] { 0, 0 }, 2));
    DWithin f = ff.dwithin(ff.property("geo5"), ff.literal(ls), 3, "m");
    SimpleFeatureCollection features = featureSource.getFeatures(f);
    assertEquals(2, features.size());
    SimpleFeatureIterator fsi = features.features();
    assertTrue(fsi.hasNext());
    SimpleFeature feature = fsi.next();
    assertEquals(feature.getID(), "active.01");
    assertNotNull(feature.getDefaultGeometry());
    assertTrue(fsi.hasNext());
    feature = fsi.next();
    assertEquals(feature.getID(), "active.10");
    assertNotNull(feature.getDefaultGeometry());
}
 
Example 2
Source File: TestVectorFilter.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("nls")
public void testVectorFilter() throws Exception {
    SimpleFeatureCollection testFC = HMTestMaps.getTestFC();
    OmsVectorFilter filter = new OmsVectorFilter();
    filter.inVector = testFC;
    filter.pCql = "cat > 2";
    filter.process();
    SimpleFeatureCollection outFC = filter.outVector;

    assertTrue(outFC.size() == 1);

    FeatureIterator<SimpleFeature> featureIterator = outFC.features();
    SimpleFeature feature = featureIterator.next();
    assertNotNull(feature);

    Integer attribute = (Integer) feature.getAttribute("cat");
    assertEquals(3, attribute.intValue());
    featureIterator.close();

}
 
Example 3
Source File: ElasticTemporalFilterIT.java    From elasticgeo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testLessDateFilterLong() throws Exception {
    init();
    Date testDate = new Date(1005912798000L);
    FilterFactory ff = dataStore.getFilterFactory();

    Filter f = ff.lessOrEqual(ff.property("installed_td"), ff.literal(testDate.getTime()));
    SimpleFeatureCollection features = featureSource.getFeatures(f);
    assertEquals(4, features.size());
    SimpleFeatureIterator it = features.features();
    while (it.hasNext()) {
        SimpleFeature next = it.next();
        Date date = (Date) next.getAttribute("installed_td");
        assertTrue(date.before(testDate) || date.equals(testDate));
    }
    it.close();
}
 
Example 4
Source File: ElasticFeatureFilterIT.java    From elasticgeo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testReadStringArrayWithCsvStrategy() throws Exception {
    init();
    dataStore.setArrayEncoding(ArrayEncoding.CSV);
    FilterFactory ff = dataStore.getFilterFactory();
    PropertyIsEqualTo filter = ff.equals(ff.property("modem_b"), ff.literal(true));

    SimpleFeatureCollection features = featureSource.getFeatures(filter);
    assertEquals(8, features.size());

    try (SimpleFeatureIterator iterator = features.features()) {
        assertTrue(iterator.hasNext());
        SimpleFeature feature = iterator.next();
        String st = (String) feature.getAttribute("standard_ss");
        // changed from "IEEE 802.11b" in SolrFeatureSourceTest
        assertTrue(URLDecoder.decode(st, StandardCharsets.UTF_8.toString()).startsWith("IEEE 802.11"));
    }
}
 
Example 5
Source File: ElasticGeometryFilterIT.java    From elasticgeo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testDWithinFilter() throws Exception {
    init();
    FilterFactory2 ff = (FilterFactory2) dataStore.getFilterFactory();
    GeometryFactory gf = new GeometryFactory();
    PackedCoordinateSequenceFactory sf = new PackedCoordinateSequenceFactory();
    Point ls = gf.createPoint(sf.create(new double[] { 0, 0 }, 2));
    DWithin f = ff.dwithin(ff.property("geo"), ff.literal(ls), 3, "m");
    SimpleFeatureCollection features = featureSource.getFeatures(f);
    assertEquals(2, features.size());
    SimpleFeatureIterator fsi = features.features();
    assertTrue(fsi.hasNext());
    assertEquals(fsi.next().getID(), "active.01");
    assertTrue(fsi.hasNext());
    assertEquals(fsi.next().getID(), "active.10");
}
 
Example 6
Source File: ElasticTemporalFilterIT.java    From elasticgeo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testGreaterDateFilterLong() throws Exception {
    init();
    Date testDate = new Date(1005912798000L);
    FilterFactory ff = dataStore.getFilterFactory();

    Filter f = ff.greaterOrEqual(ff.property("installed_td"), ff.literal(testDate.getTime()));
    SimpleFeatureCollection features = featureSource.getFeatures(f);
    assertEquals(7, features.size());
    SimpleFeatureIterator it = features.features();
    while (it.hasNext()) {
        SimpleFeature next = it.next();
        Date date = (Date) next.getAttribute("installed_td");
        assertTrue(date.after(testDate) || date.equals(testDate));
    }
    it.close();
}
 
Example 7
Source File: TestVectorReshaper.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
public void testBuffer() throws Exception {
    String cql = "the_geom=buffer(the_geom, 20.0)";

    SimpleFeatureCollection testFC = HMTestMaps.getTestFC();
    OmsVectorReshaper reshaper = new OmsVectorReshaper();
    reshaper.inVector = testFC;
    reshaper.pCql = cql;
    reshaper.process();
    SimpleFeatureCollection outFC = reshaper.outVector;
    FeatureIterator<SimpleFeature> featureIterator = outFC.features();
    SimpleFeature feature = featureIterator.next();
    Geometry geometry = (Geometry) feature.getDefaultGeometry();
    String geometryType = geometry.getGeometryType();
    assertTrue(geometryType.toUpperCase().equals("POLYGON"));
    featureIterator.close();
}
 
Example 8
Source File: FeatureUtilities.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Extracts features from a {@link FeatureCollection} into an {@link STRtree}.
 * 
 * @param collection the feature collection.
 * @return the tree containing the features.
 */
public static STRtree featureCollectionToSTRtree( SimpleFeatureCollection collection ) {
    STRtree tree = new STRtree();
    SimpleFeatureIterator featureIterator = collection.features();
    while( featureIterator.hasNext() ) {
        SimpleFeature feature = featureIterator.next();
        Geometry geometry = (Geometry) feature.getDefaultGeometry();
        tree.insert(geometry.getEnvelopeInternal(), feature);
    }
    featureIterator.close();
    return tree;
}
 
Example 9
Source File: ElasticFeatureFilterIT.java    From elasticgeo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testGetFeaturesWithQuery() throws Exception {
    init();
    FilterFactory ff = dataStore.getFilterFactory();
    PropertyIsEqualTo filter = ff.equals(ff.property("modem_b"), ff.literal(true));

    Query query = new Query();
    query.setPropertyNames(new String[] { "standard_ss", "security_ss" });
    query.setFilter(filter);

    SimpleFeatureCollection features = featureSource.getFeatures(query);
    assertEquals(8, features.size());

    try (SimpleFeatureIterator iterator = features.features()) {
        assertTrue(iterator.hasNext());
        SimpleFeature feature = iterator.next();
        assertEquals(2, feature.getAttributeCount());
        String st = (String) feature.getAttribute("standard_ss");
        // changed from "IEEE 802.11b" in SolrFeatureSourceTest
        assertTrue(st.contains("IEEE 802.11b"));
    }
}
 
Example 10
Source File: TestVectorReshaper.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public void testConvexHull() throws Exception {
    String cql = "the_geom=convexHull(the_geom)";

    GeometryFactory gf = GeometryUtilities.gf();
    MultiPoint multiPoint = gf.createMultiPoint(new Coordinate[]{//
            HMTestMaps.getWestNorth(), HMTestMaps.getEastSouth(),
            HMTestMaps.getEastNorth()});
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName("test");
    b.setCRS(HMTestMaps.getCrs());
    b.add("the_geom", MultiPoint.class);
    SimpleFeatureType type = b.buildFeatureType();
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
    Object[] values = new Object[]{multiPoint};
    builder.addAll(values);
    SimpleFeature feature = builder.buildFeature(null);
    DefaultFeatureCollection newCollection = new DefaultFeatureCollection();
    newCollection.add(feature);

    OmsVectorReshaper reshaper = new OmsVectorReshaper();
    reshaper.inVector = newCollection;
    reshaper.pCql = cql;
    reshaper.process();
    SimpleFeatureCollection outFC = reshaper.outVector;
    FeatureIterator<SimpleFeature> featureIterator = outFC.features();
    SimpleFeature newFeature = featureIterator.next();
    Geometry geometry = (Geometry) newFeature.getDefaultGeometry();
    String geometryType = geometry.getGeometryType();
    assertTrue(geometryType.toUpperCase().equals("POLYGON"));
    featureIterator.close();
}
 
Example 11
Source File: FeatureUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Extracts features from a {@link FeatureCollection} into an {@link ArrayList}.
 * 
 * @param collection the feature collection.
 * @return the list with the features or an empty list if no features present.
 */
public static List<SimpleFeature> featureCollectionToList( SimpleFeatureCollection collection ) {
    List<SimpleFeature> featuresList = new ArrayList<SimpleFeature>();
    if (collection == null) {
        return featuresList;
    }
    SimpleFeatureIterator featureIterator = collection.features();
    while( featureIterator.hasNext() ) {
        SimpleFeature feature = featureIterator.next();
        featuresList.add(feature);
    }
    featureIterator.close();
    return featuresList;
}
 
Example 12
Source File: TestRasterCatToFeatureAttribute.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public void testRasterCatToFeatureAttribute() throws Exception {

        double[][] elevationData = HMTestMaps.outPitData;
        HashMap<String, Double> envelopeParams = HMTestMaps.getEnvelopeparams();
        CoordinateReferenceSystem crs = HMTestMaps.getCrs();
        GridCoverage2D elevationCoverage = CoverageUtilities.buildCoverage("elevation", elevationData, envelopeParams, crs, true);

        SimpleFeatureCollection inFC = HMTestMaps.getTestFC();

        OmsRasterCatToFeatureAttribute rc2fa = new OmsRasterCatToFeatureAttribute();
        rc2fa.pm = pm;
        rc2fa.inRaster = elevationCoverage;
        rc2fa.inVector = inFC;
        rc2fa.fNew = "elev";
        rc2fa.process();

        SimpleFeatureCollection outMap = rc2fa.outVector;

        FeatureIterator<SimpleFeature> features = outMap.features();
        while( features.hasNext() ) {
            SimpleFeature feature = features.next();
            Object attribute = feature.getAttribute("elev");
            double value = ((Number) attribute).doubleValue();

            Object catObj = feature.getAttribute("cat");
            int cat = ((Number) catObj).intValue();
            if (cat == 1) {
                assertEquals(800.0, value, 0.000001);
            } else if (cat == 2) {
                assertEquals(1500.0, value, 0.000001);
            } else if (cat == 3) {
                assertEquals(700.0, value, 0.000001);
            }
        }

    }
 
Example 13
Source File: ElasticGeometryFilterIT.java    From elasticgeo with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testWithinFilter() throws Exception {
    init("not-active","geo3");
    FilterFactory2 ff = (FilterFactory2) dataStore.getFilterFactory();
    GeometryFactory gf = new GeometryFactory();
    PackedCoordinateSequenceFactory sf = new PackedCoordinateSequenceFactory();
    Polygon ls = gf.createPolygon(sf.create(new double[] { 0, 0, 0, 6, 6, 6, 6, 0, 0, 0 }, 2));
    Within f = ff.within(ff.property("geo3"), ff.literal(ls));
    SimpleFeatureCollection features = featureSource.getFeatures(f);
    assertEquals(1, features.size());
    SimpleFeatureIterator fsi = features.features();
    assertTrue(fsi.hasNext());
    assertEquals(fsi.next().getID(), "active.12");
}
 
Example 14
Source File: ElasticGeometryFilterIT.java    From elasticgeo with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testEqualFilter() throws Exception {
    init("not-active","geo3");
    FilterFactory2 ff = (FilterFactory2) dataStore.getFilterFactory();
    GeometryFactory gf = new GeometryFactory();
    PackedCoordinateSequenceFactory sf = new PackedCoordinateSequenceFactory();
    Polygon ls = gf.createPolygon(sf.create(new double[] { 3, 2, 6, 2, 6, 7, 3, 7, 3, 2 }, 2));
    Equals f = ff.equal(ff.property("geo3"), ff.literal(ls));
    SimpleFeatureCollection features = featureSource.getFeatures(f);
    assertEquals(1, features.size());
    SimpleFeatureIterator fsi = features.features();
    assertTrue(fsi.hasNext());
    assertEquals(fsi.next().getID(), "active.13");
}
 
Example 15
Source File: ElasticFeatureFilterIT.java    From elasticgeo with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testGetFeaturesWithNOTLogicFilter() throws Exception {
    init();
    FilterFactory ff = dataStore.getFilterFactory();
    PropertyIsEqualTo property1 = ff.equals(ff.property("vendor_s"), ff.literal("D-Link"));
    Not filter = ff.not(property1);
    SimpleFeatureCollection features = featureSource.getFeatures(filter);
    assertEquals(7, features.size());
    SimpleFeatureIterator iterator = features.features();
    while (iterator.hasNext()) {
        SimpleFeature f = iterator.next();
        assertTrue(!f.getAttribute("vendor_s").equals("D-Link"));
    }
}
 
Example 16
Source File: OmsKriging.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Extract the coordinate of a FeatureCollection in a HashMap with an ID as
 * a key.
 * 
 * @param nStaz
 * @param collection
 * @throws Exception
 *             if a fiel of elevation isn't the same of the collection
 */
private LinkedHashMap<Integer, Coordinate> getCoordinate( int nStaz, SimpleFeatureCollection collection, String idField )
        throws Exception {
    LinkedHashMap<Integer, Coordinate> id2CoordinatesMap = new LinkedHashMap<Integer, Coordinate>();
    FeatureIterator<SimpleFeature> iterator = collection.features();
    Coordinate coordinate = null;
    try {
        while( iterator.hasNext() ) {
            SimpleFeature feature = iterator.next();
            int name = ((Number) feature.getAttribute(idField)).intValue();
            coordinate = ((Geometry) feature.getDefaultGeometry()).getCentroid().getCoordinate();
            double z = 0;
            if (fPointZ != null) {
                try {
                    z = ((Number) feature.getAttribute(fPointZ)).doubleValue();
                } catch (NullPointerException e) {
                    pm.errorMessage(msg.message("kriging.noPointZ"));
                    throw new Exception(msg.message("kriging.noPointZ"));
                }
            }
            coordinate.z = z;
            id2CoordinatesMap.put(name, coordinate);
        }
    } finally {
        iterator.close();
    }

    return id2CoordinatesMap;
}
 
Example 17
Source File: GamaGeoJsonFile.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public void readShapes(final IScope scope) {
	final IList<IShape> list = getBuffer();
	int size = 0;
	final SimpleFeatureCollection fc = getFeatureCollection(scope);
	if (fc == null) { return; }
	final Envelope3D env = Envelope3D.of(fc.getBounds());
	size = fc.size();
	int index = 0;
	computeProjection(scope, env);
	try (SimpleFeatureIterator reader = fc.features()) {
		while (reader.hasNext()) {
			index++;
			if (index % 20 == 0) {
				scope.getGui().getStatus(scope).setSubStatusCompletion(index / (double) size);
			}
			final SimpleFeature feature = reader.next();
			Geometry g = (Geometry) feature.getDefaultGeometry();
			if (g != null && !g.isEmpty() /* Fix for Issue 725 && 677 */ ) {
				g = gis.transform(g);
				if (!with3D) {
					g.apply(ZERO_Z);
					g.geometryChanged();
				}
				list.add(new GamaGisGeometry(g, feature));
			} else if (g == null) {
				// See Issue 725
				GAMA.reportError(scope,
						GamaRuntimeException
								.warning("GamaGeoJsonFile.fillBuffer; geometry could not be added  as it is "
										+ "nil: " + feature.getIdentifier(), scope),
						false);
			}
		}
	}
	if (size > list.size()) {
		GAMA.reportError(scope, GamaRuntimeException.warning("Problem with file " + getFile(scope) + ": only "
				+ list.size() + " of the " + size + " geometries could be added", scope), false);
	}
}
 
Example 18
Source File: TestRasterCatToFeatureAttribute.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public void testRasterCatToFeatureAttributePolygon() throws Exception {

        double[][] elevationData = HMTestMaps.outPitData;
        HashMap<String, Double> envelopeParams = HMTestMaps.getEnvelopeparams();
        CoordinateReferenceSystem crs = HMTestMaps.getCrs();
        GridCoverage2D elevationCoverage = CoverageUtilities.buildCoverage("elevation", elevationData, envelopeParams, crs, true);

        SimpleFeatureCollection inFC = HMTestMaps.getTestLeftFC();

        OmsRasterCatToFeatureAttribute rc2fa = new OmsRasterCatToFeatureAttribute();
        rc2fa.pm = pm;
        rc2fa.inRaster = elevationCoverage;
        rc2fa.inVector = inFC;
        rc2fa.fNew = "elev";
        rc2fa.process();

        SimpleFeatureCollection outMap = rc2fa.outVector;

        FeatureIterator<SimpleFeature> features = outMap.features();
        while( features.hasNext() ) {
            SimpleFeature feature = features.next();
            String attr = "elev_min";
            double value = getAttr(feature, attr);
            System.out.println(value);
            attr = "elev_max";
            value = getAttr(feature, attr);
            System.out.println(value);
            attr = "elev_avg";
            value = getAttr(feature, attr);
            System.out.println(value);
            attr = "elev_sum";
            value = getAttr(feature, attr);
            System.out.println(value);
        }
    }
 
Example 19
Source File: InternalDistributedRenderProcess.java    From geowave with Apache License 2.0 5 votes vote down vote up
@DescribeResult(
    name = "result",
    description = "This is just a pass-through, the key is to provide enough information within invertQuery to perform a map to screen transform")
public GridCoverage2D execute(
    @DescribeParameter(
        name = "data",
        description = "Feature collection containing the rendered image") final SimpleFeatureCollection features)
    throws ProcessException {
  // vector-to-raster render transform that take a single feature that
  // wraps a distributed render result and converts it to a GridCoverage2D
  if (features != null) {
    final SimpleFeatureIterator it = features.features();
    if (it.hasNext()) {
      final SimpleFeature resultFeature = features.features().next();
      final DistributedRenderResult actualResult =
          (DistributedRenderResult) resultFeature.getAttribute(0);
      final DistributedRenderOptions renderOptions =
          (DistributedRenderOptions) resultFeature.getAttribute(1);
      // convert to the GridCoverage2D required for output
      final GridCoverageFactory gcf =
          CoverageFactoryFinder.getGridCoverageFactory(GeoTools.getDefaultHints());
      final BufferedImage result = actualResult.renderComposite(renderOptions);
      final GridCoverage2D gridCov =
          gcf.create("Process Results", result, renderOptions.getEnvelope());
      return gridCov;
    }
  }
  return null;
}
 
Example 20
Source File: SeaRouting.java    From searoute with European Union Public License 1.2 4 votes vote down vote up
public SeaRouting(int resKM) {
	try {

		//load marnet
		DataStore store = null;
		SimpleFeatureCollection fc = null;
		/*try {
			URL url = getClass().getResource("/marnet/marnet_plus_"+resKM+"km.gpkg");
			HashMap<String, Object> map = new HashMap<>();
			map.put(GeoPkgDataStoreFactory.DBTYPE.key, "geopkg");
			map.put(GeoPkgDataStoreFactory.DATABASE.key, url.getFile());
			map.put("url", url);
			store = DataStoreFinder.getDataStore(map);
			fc = store.getFeatureSource(store.getTypeNames()[0]).getFeatures();
		} catch (Exception e) {*/
			//URL url = new URL(path);
			HashMap<String, Object> map = new HashMap<>();
			map.put(GeoPkgDataStoreFactory.DBTYPE.key, "geopkg");
			map.put(GeoPkgDataStoreFactory.DATABASE.key, "marnet/marnet_plus_"+resKM+"km.gpkg");
			map.put("url", "marnet/marnet_plus_"+resKM+"km.gpkg");
			store = DataStoreFinder.getDataStore(map);
			fc = store.getFeatureSource(store.getTypeNames()[0]).getFeatures();
		//}

		//build graph
		FeatureIterator<?> it = fc.features();
		FeatureGraphGenerator gGen = new FeatureGraphGenerator(new LineStringGraphGenerator());
		while(it.hasNext()) gGen.add(it.next());
		g = gGen.getGraph();
		it.close();
		store.dispose();
	} catch (Exception e) { e.printStackTrace(); }

	//link nodes around the globe
	for(Object o : g.getNodes()){
		Node n = (Node)o;
		Coordinate c = ((Point)n.getObject()).getCoordinate();
		if(c.x==180) {
			Node n_ = getNode(new Coordinate(-c.x,c.y));
			if(LOGGER.isTraceEnabled()) LOGGER.trace(c + " -> " + ((Point)n_.getObject()).getCoordinate());
			BasicEdge be = new BasicEdge(n, n_);
			n.add(be);
			n_.add(be);
			g.getEdges().add(be);
		}
	}

	//define weighters
	defaultWeighter = buildEdgeWeighter(true, true);
	noSuezWeighter = buildEdgeWeighter(false, true);
	noPanamaWeighter = buildEdgeWeighter(true, false);
	noSuezNoPanamaWeighter = buildEdgeWeighter(false, false);
}