Java Code Examples for org.geotools.feature.FeatureIterator#hasNext()

The following examples show how to use org.geotools.feature.FeatureIterator#hasNext() . 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: geoUtils.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
public static String getFileLayerAction(String layerUrl) throws JSONException, IOException, EMFUserError {
	IFeaturesProviderFileDAO featuresProvider = DAOFactory.getFeaturesProviderFileDAO();
	FeatureCollection outputFeatureCollection = featuresProvider.getAllFeatures(layerUrl);
	FeatureIterator it = outputFeatureCollection.features();
	List<SimpleFeature> list = new ArrayList<SimpleFeature>();
	while (it.hasNext()) {
		SimpleFeature f = (SimpleFeature) it.next();
		list.add(f);
	}

	FeatureCollection<SimpleFeatureType, SimpleFeature> filteredOutputFeatureCollection = DataUtilities.collection(list);

	Monitor.start("GetTargetLayerAction.flushResponse");
	FeatureJSON featureJSON = new FeatureJSON();
	String responseFeature = featureJSON.toString(filteredOutputFeatureCollection);

	return responseFeature;
}
 
Example 2
Source File: OaImporter.java    From TomboloDigitalConnector with MIT License 6 votes vote down vote up
@Override
protected void importDatasource(Datasource datasource, List<String> geographyScope, List<String> temporalScope,  List<String> datasourceLocation) throws Exception {
    InputStream inputStream = downloadUtils.fetchInputStream(new URL(OaType.valueOf(datasource.getDatasourceSpec().getId()).datafile), getProvider().getLabel(), ".json");
    FeatureIterator<SimpleFeature> featureIterator = new FeatureJSON().streamFeatureCollection(inputStream);

    List<Subject> subjects = new ArrayList<Subject>();
    while(featureIterator.hasNext()) {
        Feature feature = featureIterator.next();
        Geometry geometry = (Geometry) feature.getDefaultGeometryProperty().getValue();
        geometry.setSRID(Subject.SRID);

        subjects.add(new Subject(
                datasource.getUniqueSubjectType(),
                getFeatureSubjectLabel(feature),
                getFeatureSubjectName(feature),
                geometry
        ));
    }

    saveAndClearSubjectBuffer(subjects);
}
 
Example 3
Source File: OmsVectorReshaper.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
private SimpleFeature getSample() {
    FeatureIterator<SimpleFeature> iterator = inVector.features();
    try {
        if (!iterator.hasNext()) {
            throw new ModelsRuntimeException("Input featurecollection is empty.", this.getClass().getSimpleName());
        }
        return iterator.next();
    } finally {
        iterator.close();
    }
}
 
Example 4
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 5
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 6
Source File: TestVectorReader.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public void testPropertiesReader() throws Exception {

        URL dataUrl = this.getClass().getClassLoader().getResource("example.properties");
        String propertiesPath = new File(dataUrl.toURI()).getAbsolutePath();

        // now read it again
        OmsVectorReader reader = new OmsVectorReader();
        reader.file = propertiesPath;
        reader.process();
        SimpleFeatureCollection readFC = reader.outVector;

        FeatureIterator<SimpleFeature> featureIterator = readFC.features();
        while( featureIterator.hasNext() ) {
            SimpleFeature f = featureIterator.next();

            int id = ((Number) f.getAttribute("id")).intValue();
            Geometry geometry = (Geometry) f.getDefaultGeometry();
            Coordinate coordinate = geometry.getCoordinate();

            if (id == 1) {
                assertEquals(coordinate.x, 0.0);
                assertEquals(coordinate.y, 0.0);
            }
            if (id == 2) {
                assertEquals(coordinate.x, 10.0);
                assertEquals(coordinate.y, 10.0);
            }
            if (id == 3) {
                assertEquals(coordinate.x, 20.0);
                assertEquals(coordinate.y, 20.0);
            }
            if (id == 4) {
                String attribute = f.getAttribute("name").toString();
                assertEquals(attribute, "justin deolivera");
            }
        }

    }
 
Example 7
Source File: TestVectorReprojector.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public void testVectorReprojector() throws Exception {

        SimpleFeatureCollection testFC = HMTestMaps.getTestFC();

        OmsVectorReprojector reprojector = new OmsVectorReprojector();
        reprojector.inVector = testFC;
        reprojector.pCode = "EPSG:4326";
        reprojector.pm = pm;
        reprojector.process();

        CoordinateReferenceSystem sourceCRS = HMTestMaps.getCrs();
        CoordinateReferenceSystem targetCRS = CrsUtilities.getCrsFromSrid(4326);

        MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS);

        SimpleFeatureCollection outFC = reprojector.outVector;
        FeatureIterator<SimpleFeature> featureIterator = outFC.features();
        SimpleFeatureIterator originalFeatureIterator = testFC.features();
        while( featureIterator.hasNext() ) {
            SimpleFeature feature = featureIterator.next();
            Geometry geometry = (Geometry) feature.getDefaultGeometry();
            Coordinate coordinate = geometry.getCoordinate();

            SimpleFeature originalFeature = originalFeatureIterator.next();
            Coordinate origCoord = ((Geometry) originalFeature.getDefaultGeometry()).getCoordinate();
            Coordinate reprojected = JTS.transform(origCoord, null, transform);

            assertEquals(reprojected.x, coordinate.x, delta);
            assertEquals(reprojected.y, coordinate.y, delta);
        }
        featureIterator.close();

    }
 
Example 8
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 9
Source File: VectorDataLayer.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private void updateFigureCollection() {
    FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection = vectorDataNode.getFeatureCollection();

    Figure[] figures = figureCollection.getFigures();
    Map<SimpleFeature, SimpleFeatureFigure> figureMap = new HashMap<>();
    for (Figure figure : figures) {
        if (figure instanceof SimpleFeatureFigure) {
            SimpleFeatureFigure simpleFeatureFigure = (SimpleFeatureFigure) figure;
            figureMap.put(simpleFeatureFigure.getSimpleFeature(), simpleFeatureFigure);
        }
    }

    FeatureIterator<SimpleFeature> featureIterator = featureCollection.features();
    while (featureIterator.hasNext()) {
        SimpleFeature simpleFeature = featureIterator.next();
        SimpleFeatureFigure featureFigure = figureMap.get(simpleFeature);
        if (featureFigure != null) {
            figureMap.remove(simpleFeature);
            Placemark placemark = vectorDataNode.getPlacemarkGroup().getPlacemark(simpleFeature);
            if(placemark != null) {
                String css = placemark.getStyleCss();
                final FigureStyle normalStyle = DefaultFigureStyle.createFromCss(css);
                final FigureStyle selectedStyle = getFigureFactory().deriveSelectedStyle(normalStyle);
                featureFigure.setNormalStyle(normalStyle);
                featureFigure.setSelectedStyle(selectedStyle);
            }
        } else {
            featureFigure = getFigureFactory().createSimpleFeatureFigure(simpleFeature, vectorDataNode.getDefaultStyleCss());
            figureCollection.addFigure(featureFigure);
        }
        featureFigure.forceRegeneration();
    }

    Collection<SimpleFeatureFigure> remainingFigures = figureMap.values();
    figureCollection.removeFigures(remainingFigures.toArray(new Figure[remainingFigures.size()]));

}
 
Example 10
Source File: ImportTrackAction.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private static void transformFeatureCollection(FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection, CoordinateReferenceSystem targetCRS) throws TransformException {
    final GeometryCoordinateSequenceTransformer transform = FeatureUtils.getTransform(DefaultGeographicCRS.WGS84, targetCRS);
    final FeatureIterator<SimpleFeature> features = featureCollection.features();
    final GeometryFactory geometryFactory = new GeometryFactory();
    while (features.hasNext()) {
        final SimpleFeature simpleFeature = features.next();
        final Point sourcePoint = (Point) simpleFeature.getDefaultGeometry();
        final Point targetPoint = transform.transformPoint(sourcePoint, geometryFactory);
        simpleFeature.setDefaultGeometry(targetPoint);
    }
}
 
Example 11
Source File: ExportGeometryAction.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private static Map<Class<?>, List<SimpleFeature>> createGeometryToFeaturesListMap(VectorDataNode vectorNode) throws TransformException,
                                                                                                                    SchemaException {
    FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection = vectorNode.getFeatureCollection();
    CoordinateReferenceSystem crs = vectorNode.getFeatureType().getCoordinateReferenceSystem();
    if (crs == null) {   // for pins and GCPs crs is null
        crs = vectorNode.getProduct().getSceneCRS();
    }
    final CoordinateReferenceSystem modelCrs;
    if (vectorNode.getProduct().getSceneGeoCoding() instanceof CrsGeoCoding) {
        modelCrs = vectorNode.getProduct().getSceneCRS();
    } else {
        modelCrs = DefaultGeographicCRS.WGS84;
    }

    // Not using ReprojectingFeatureCollection - it is reprojecting all geometries of a feature
    // but we want to reproject the default geometry only
    GeometryCoordinateSequenceTransformer transformer = createTransformer(crs, modelCrs);

    Map<Class<?>, List<SimpleFeature>> featureListMap = new HashMap<>();
    final FeatureIterator<SimpleFeature> featureIterator = featureCollection.features();
    // The schema needs to be reprojected. We need to build a new feature be cause we can't change the schema.
    // It is necessary to have this reprojected schema, because otherwise the shapefile is not correctly georeferenced.
    SimpleFeatureType schema = featureCollection.getSchema();
    SimpleFeatureType transformedSchema = FeatureTypes.transform(schema, modelCrs);
    while (featureIterator.hasNext()) {
        SimpleFeature feature = featureIterator.next();
        Object defaultGeometry = feature.getDefaultGeometry();
        feature.setDefaultGeometry(transformer.transform((Geometry) defaultGeometry));

        Class<?> geometryType = defaultGeometry.getClass();
        List<SimpleFeature> featureList = featureListMap.computeIfAbsent(geometryType, k -> new ArrayList<>());
        SimpleFeature exportFeature = SimpleFeatureBuilder.build(transformedSchema, feature.getAttributes(), feature.getID());
        featureList.add(exportFeature);
    }
    return featureListMap;
}
 
Example 12
Source File: ShapeInMemLayer.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Finish initializing the layer.
 *
 * @throws LayerException oops
 */
@PostConstruct
protected void initFeatures() throws LayerException {
	crs = geoService.getCrs2(layerInfo.getCrs());
	try {
		setFeatureSourceName(layerInfo.getFeatureInfo().getDataSourceName());
		featureModel = new ShapeInMemFeatureModel(getDataStore(), layerInfo.getFeatureInfo().getDataSourceName(),
				geoService.getSridFromCrs(layerInfo.getCrs()), converterService);
		featureModel.setLayerInfo(layerInfo);
		FeatureCollection<SimpleFeatureType, SimpleFeature> col = getFeatureSource().getFeatures();
		FeatureIterator<SimpleFeature> iterator = col.features();
		int lastIndex = 0;
		while (iterator.hasNext()) {
			SimpleFeature feature = iterator.next();
			String id = featureModel.getId(feature);
			features.put(id, feature);
			int intId = Integer.parseInt(id.substring(id.lastIndexOf('.') + 1));
			if (intId > lastIndex) {
				lastIndex = intId;
			}
		}
		iterator.close();
		((ShapeInMemFeatureModel) featureModel).setNextId(++lastIndex);
	} catch (NumberFormatException nfe) {
		throw new LayerException(nfe, ExceptionCode.FEATURE_MODEL_PROBLEM, url);
	} catch (MalformedURLException e) {
		throw new LayerException(e, ExceptionCode.INVALID_SHAPE_FILE_URL, url);
	} catch (IOException ioe) {
		throw new LayerException(ioe, ExceptionCode.CANNOT_CREATE_LAYER_MODEL, url);
	} catch (GeomajasException ge) {
		throw new LayerException(ge, ExceptionCode.CANNOT_CREATE_LAYER_MODEL, url);
	}
}
 
Example 13
Source File: WmsLayer.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
private List<Feature> getGmlFeatures(InputStream stream, Version version) throws IOException, SAXException,
		ParserConfigurationException {
	List<Feature> features = new ArrayList<Feature>();
	GML gml = new GML(version);
	FeatureCollection<?, SimpleFeature> collection = gml.decodeFeatureCollection(stream);
	FeatureIterator<SimpleFeature> it = collection.features();

	while (it.hasNext()) {
		features.add(toDto(it.next()));
	}
	return features;
}
 
Example 14
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);
}
 
Example 15
Source File: TestVectorReader.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
public void testShapefileReader() throws Exception {

        SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
        b.setName("test");
        b.setCRS(DefaultGeographicCRS.WGS84);
        b.add("the_geom", Point.class);
        b.add("id", Integer.class);

        DefaultFeatureCollection newCollection = new DefaultFeatureCollection();
        SimpleFeatureType type = b.buildFeatureType();
        for( int i = 0; i < 2; i++ ) {
            SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);

            Point point = GeometryUtilities.gf().createPoint(new Coordinate(i, i));
            Object[] values = new Object[]{point, i};
            builder.addAll(values);
            SimpleFeature feature = builder.buildFeature(type.getTypeName() + "." + i);
            newCollection.add(feature);
        }

        File tmpShape = File.createTempFile("testshp", ".shp");
        if (tmpShape.exists()) {
            if (!tmpShape.delete())
                throw new IOException();
        }
        OmsVectorWriter writer = new OmsVectorWriter();
        writer.file = tmpShape.getAbsolutePath();
        writer.inVector = newCollection;
        writer.process();

        // now read it again
        OmsVectorReader reader = new OmsVectorReader();
        reader.file = tmpShape.getAbsolutePath();
        reader.process();
        SimpleFeatureCollection readFC = reader.outVector;

        FeatureIterator<SimpleFeature> featureIterator = readFC.features();
        while( featureIterator.hasNext() ) {
            SimpleFeature f = featureIterator.next();

            int id = ((Number) f.getAttribute("id")).intValue();
            Geometry geometry = (Geometry) f.getDefaultGeometry();
            Coordinate coordinate = geometry.getCoordinate();

            if (id == 0) {
                assertEquals(coordinate.x, 0.0);
                assertEquals(coordinate.y, 0.0);
            }
            if (id == 1) {
                assertEquals(coordinate.x, 1.0);
                assertEquals(coordinate.y, 1.0);
            }
            if (id == 2) {
                assertEquals(coordinate.x, 2.0);
                assertEquals(coordinate.y, 2.0);
            }
        }

        if (tmpShape.exists()) {
            tmpShape.deleteOnExit();
        }
    }
 
Example 16
Source File: TestBasinShape.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("nls")
public void testBasinShape() throws Exception {
    HashMap<String, Double> envelopeParams = HMTestMaps.getEnvelopeparams();
    CoordinateReferenceSystem crs = HMTestMaps.getCrs();

    double[][] pitData = HMTestMaps.pitData;
    GridCoverage2D pitCoverage = CoverageUtilities.buildCoverage("pit", pitData, envelopeParams, crs, true);
    double[][] basinsData = HMTestMaps.basinShapeData;
    GridCoverage2D basinsCoverage = CoverageUtilities.buildCoverage("basins", basinsData, envelopeParams, crs, true);

    OmsBasinShape basin = new OmsBasinShape();
    basin.inElev = pitCoverage;
    basin.inBasins = basinsCoverage;
    basin.pm = pm;

    basin.process();

    SimpleFeatureCollection basinsFC = basin.outBasins;

    FeatureIterator<SimpleFeature> basinsIter = basinsFC.features();
    while( basinsIter.hasNext() ) {
        SimpleFeature feature = basinsIter.next();
        Geometry line = (Geometry) feature.getDefaultGeometry();

        int numGeometries = line.getNumGeometries();
        for( int i = 0; i < numGeometries; i++ ) {
            Geometry geometryN = line.getGeometryN(i);
            int length = geometryN.getCoordinates().length;
            if (length == 9) {
                Geometry g1 = new WKTReader().read(geom1Txt);
                assertTrue(geometryN.equals(g1));
            }
            if (length == 5) {
                Geometry g2 = new WKTReader().read(geom2Txt);
                assertTrue(geometryN.equals(g2));
            }
        }
    }
    basinsIter.close();

}