Java Code Examples for org.geotools.feature.DefaultFeatureCollection

The following examples show how to use org.geotools.feature.DefaultFeatureCollection. These examples are extracted from open source projects. 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 Project: dhis2-core   Source File: MapUtils.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Creates a feature layer based on a map object.
 */
public static Layer createFeatureLayerFromMapObject( InternalMapObject mapObject )
{
    Style style = mapObject.getStyle();
    
    SimpleFeatureType featureType = mapObject.getFeatureType();
    SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder( featureType );
    DefaultFeatureCollection featureCollection = new DefaultFeatureCollection();
    
    featureBuilder.add( mapObject.getGeometry() );
    SimpleFeature feature = featureBuilder.buildFeature( null );

    featureCollection.add( feature );

    return new FeatureLayer( featureCollection, style );
}
 
Example 2
Source Project: rya   Source File: GeoWaveGeoIndexer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void storeStatements(final Collection<RyaStatement> ryaStatements) throws IOException {
    // create a feature collection
    final DefaultFeatureCollection featureCollection = new DefaultFeatureCollection();
    for (final RyaStatement ryaStatement : ryaStatements) {
        final Statement statement = RyaToRdfConversions.convertStatement(ryaStatement);
        // if the predicate list is empty, accept all predicates.
        // Otherwise, make sure the predicate is on the "valid" list
        final boolean isValidPredicate = validPredicates.isEmpty() || validPredicates.contains(statement.getPredicate());

        if (isValidPredicate && (statement.getObject() instanceof Literal)) {
            try {
                final SimpleFeature feature = createFeature(featureType, statement);
                featureCollection.add(feature);
            } catch (final ParseException e) {
                logger.warn("Error getting geo from statement: " + statement.toString(), e);
            }
        }
    }

    // write this feature collection to the store
    if (!featureCollection.isEmpty()) {
        featureStore.addFeatures(featureCollection);
    }
}
 
Example 3
Source Project: rya   Source File: GeoMesaGeoIndexer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void storeStatements(final Collection<RyaStatement> ryaStatements) throws IOException {
    // create a feature collection
    final DefaultFeatureCollection featureCollection = new DefaultFeatureCollection();
    for (final RyaStatement ryaStatement : ryaStatements) {
        final Statement statement = RyaToRdfConversions.convertStatement(ryaStatement);
        // if the predicate list is empty, accept all predicates.
        // Otherwise, make sure the predicate is on the "valid" list
        final boolean isValidPredicate = validPredicates.isEmpty() || validPredicates.contains(statement.getPredicate());

        if (isValidPredicate && (statement.getObject() instanceof Literal)) {
            try {
                final SimpleFeature feature = createFeature(featureType, statement);
                featureCollection.add(feature);
            } catch (final ParseException e) {
                logger.warn("Error getting geo from statement: " + statement.toString(), e);
            }
        }
    }

    // write this feature collection to the store
    if (!featureCollection.isEmpty()) {
        featureStore.addFeatures(featureCollection);
    }
}
 
Example 4
private void createPolygons( CoordinateReferenceSystem crs, GeometryFactory gf, List<Geometry> polygons ) {
    outMap = new DefaultFeatureCollection();
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName(POLYGON);
    b.setCRS(crs);
    b.add("the_geom", Polygon.class);
    b.add("id", Long.class);
    SimpleFeatureType type = b.buildFeatureType();
    SimpleFeatureBuilder fbuilder = new SimpleFeatureBuilder(type);

    long index = 0;
    int numGeometries = polygons.size();
    for( int i = 0; i < numGeometries; i++ ) {
        Geometry geometry = polygons.get(i);
        Object[] values = new Object[]{geometry, index++};
        fbuilder.addAll(values);
        SimpleFeature feature = fbuilder.buildFeature(null);
        ((DefaultFeatureCollection) outMap).add(feature);
    }
}
 
Example 5
private void createPoints( CoordinateReferenceSystem crs, GeometryFactory gf, List<LineString> verticals,
        List<LineString> horizontals ) {
    outMap = new DefaultFeatureCollection();
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName(POINT);
    b.setCRS(crs);
    b.add("the_geom", Point.class);
    b.add("id", Long.class);
    SimpleFeatureType type = b.buildFeatureType();
    SimpleFeatureBuilder fbuilder = new SimpleFeatureBuilder(type);

    Geometry gVer = gf.createMultiLineString(verticals.toArray(new LineString[0]));
    Geometry gHor = gf.createMultiLineString(horizontals.toArray(new LineString[0]));

    Geometry intersection = gHor.intersection(gVer);

    long index = 0;
    int numGeometries = intersection.getNumGeometries();
    for( int i = 0; i < numGeometries; i++ ) {
        Geometry geometry = intersection.getGeometryN(i);
        Object[] values = new Object[]{geometry, index++};
        fbuilder.addAll(values);
        SimpleFeature feature = fbuilder.buildFeature(null);
        ((DefaultFeatureCollection) outMap).add(feature);
    }
}
 
Example 6
private void createBboxGeometry( CoordinateReferenceSystem crs, File lasFile, SimpleFeatureCollection outGeodata )
        throws Exception {
    final ReferencedEnvelope3D envelope = lasReader.getHeader().getDataEnvelope();
    ReferencedEnvelope env2d = new ReferencedEnvelope(envelope);
    final Polygon polygon = FeatureUtilities.envelopeToPolygon(new Envelope2D(env2d));

    final SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName("lasdataenvelope");
    b.setCRS(crs);
    b.add("the_geom", Polygon.class);
    b.add("id", String.class);
    final SimpleFeatureType type = b.buildFeatureType();

    final SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
    final Object[] values = new Object[]{polygon, lasFile.getName()};
    builder.addAll(values);
    final SimpleFeature feature = builder.buildFeature(null);
    ((DefaultFeatureCollection) outGeodata).add(feature);
    OmsVectorWriter.writeVector(outFile, outGeodata);
}
 
Example 7
Source Project: hortonmachine   Source File: TestProfile.java    License: GNU General Public License v3.0 6 votes vote down vote up
private SimpleFeatureCollection doCollection() {
    CoordinateReferenceSystem crs = HMTestMaps.getCrs();
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName("typename");
    b.setCRS(crs);
    b.add("the_geom", LineString.class);
    SimpleFeatureType type = b.buildFeatureType();
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);

    Coordinate one = new Coordinate(westNorth.x + ep.getXres() / 2, centerCoord.y + ep.getYres() / 2);
    Coordinate two = new Coordinate(eastSouth.x - ep.getXres() / 2, centerCoord.y + ep.getYres() / 2);

    LineString lineString = GeometryUtilities.gf().createLineString(new Coordinate[]{one, two});
    Object[] values = new Object[]{lineString};
    builder.addAll(values);
    SimpleFeature feature = builder.buildFeature(null);
    DefaultFeatureCollection newCollection = new DefaultFeatureCollection();
    newCollection.add(feature);
    return newCollection;
}
 
Example 8
private SimpleFeatureCollection doCollection( RegionMap envelopeParams ) {

        SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
        b.setName("typename");
        b.setCRS(crs);
        b.add("the_geom", Polygon.class);
        b.add("cat", Double.class);
        SimpleFeatureType type = b.buildFeatureType();
        SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
        Object[] values = new Object[]{polygon, 1.0};
        builder.addAll(values);
        SimpleFeature feature = builder.buildFeature(null);
        DefaultFeatureCollection newCollection = new DefaultFeatureCollection();
        newCollection.add(feature);
        return newCollection;
    }
 
Example 9
Source Project: hortonmachine   Source File: IFeatureShape.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Add a feature to the store.
 * 
 * @param feature the feature to add.
 */
default public void addFeature( SimpleFeature feature) {
    FeatureStoreInfo featureStoreInfo = getFeatureStoreInfo();
    SimpleFeatureStore featureStore = featureStoreInfo.getFeatureStore();
    if (featureStore != null) {
        Transaction transaction = new DefaultTransaction("add");
        featureStore.setTransaction(transaction);
        
        try {
            DefaultFeatureCollection fc = new DefaultFeatureCollection();
            fc.add(feature);
            featureStore.addFeatures(fc);
            transaction.commit();
        } catch (Exception eek) {
            try {
                transaction.rollback();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
 
Example 10
protected boolean runQueryToShapefile( String sqlText, File selectedFile, IHMProgressMonitor pm ) {
    boolean hasError = false;
    if (sqlText.trim().length() == 0) {
        return false;
    }
    try {
        pm.beginTask("Run query: " + sqlText + "\ninto shapefile: " + selectedFile, IHMProgressMonitor.UNKNOWN);
        DefaultFeatureCollection fc = DbsHelper.runRawSqlToFeatureCollection(null, currentConnectedDatabase, sqlText, null);
        OmsVectorWriter.writeVector(selectedFile.getAbsolutePath(), fc);
        addQueryToHistoryCombo(sqlText);
    } catch (Exception e1) {
        String localizedMessage = e1.getLocalizedMessage();
        hasError = true;
        pm.errorMessage("An error occurred: " + localizedMessage);
    } finally {
        pm.done();
    }
    return hasError;
}
 
Example 11
private DefaultFeatureCollection getNetworkPoints( CoordinateReferenceSystem crs,
        LinkedHashMap<SimpleFeature, double[]> validPointsMap ) throws Exception {

    FeatureExtender ext = null;
    DefaultFeatureCollection newCollection = new DefaultFeatureCollection();
    Set<Entry<SimpleFeature, double[]>> entrySet = validPointsMap.entrySet();
    for( Entry<SimpleFeature, double[]> entry : entrySet ) {
        SimpleFeature pointFeature = entry.getKey();

        if (ext == null) {
            ext = new FeatureExtender(pointFeature.getFeatureType(), new String[]{WIDTH, WIDTH_FROM},
                    new Class[]{Double.class, Double.class});
        }

        double[] attributes = entry.getValue();
        Object[] attrObj = new Object[attributes.length];
        for( int i = 0; i < attrObj.length; i++ ) {
            attrObj[i] = attributes[i];
        }
        SimpleFeature extendedFeature = ext.extendFeature(pointFeature, attrObj);
        newCollection.add(extendedFeature);
    }

    return newCollection;
}
 
Example 12
private DefaultFeatureCollection getProblemPoints( CoordinateReferenceSystem crs,
        LinkedHashMap<SimpleFeature, String> problemPointsMap ) throws Exception {

    FeatureExtender ext = null;

    DefaultFeatureCollection newCollection = new DefaultFeatureCollection();
    Set<Entry<SimpleFeature, String>> entrySet = problemPointsMap.entrySet();
    for( Entry<SimpleFeature, String> entry : entrySet ) {
        SimpleFeature pointFeature = entry.getKey();
        String notes = entry.getValue();

        if (ext == null) {
            ext = new FeatureExtender(pointFeature.getFeatureType(), new String[]{NOTES}, new Class[]{String.class});
        }

        SimpleFeature extendedFeature = ext.extendFeature(pointFeature, new Object[]{notes});
        newCollection.add(extendedFeature);
    }

    return newCollection;
}
 
Example 13
private DefaultFeatureCollection getWidthLines( CoordinateReferenceSystem crs,
        ConcurrentLinkedQueue<Object[]> validPointsLineList ) throws Exception {
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName("net");
    b.setCRS(crs);
    b.add("the_geom", LineString.class);
    b.add(PFAF, String.class);
    b.add(LINKID, Integer.class);
    b.add(ARiverSectionsExtractor.FIELD_SECTION_ID, Integer.class);
    b.add(ARiverSectionsExtractor.FIELD_PROGRESSIVE, Double.class);
    SimpleFeatureType type = b.buildFeatureType();
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);

    DefaultFeatureCollection newCollection = new DefaultFeatureCollection();

    for( Object[] objects : validPointsLineList ) {
        builder.addAll(objects);
        SimpleFeature feature = builder.buildFeature(null);
        newCollection.add(feature);
    }

    return newCollection;
}
 
Example 14
@Execute
public void process() throws Exception {

    // creates the schema for the output shapefile
    FeatureExtender ext = new FeatureExtender(inNetPoints.getSchema(), new String[]{SLOPE}, new Class[]{Double.class});
    pm.beginTask("extract points...", inNetPoints.size());
    /*
     * reads the network
     */
    List<SimpleFeature> netList = FeatureUtilities.featureCollectionToList(inNetPoints);
    outNetPoints = new DefaultFeatureCollection();

    for( SimpleFeature netFeature : netList ) {
        Geometry geometry = (Geometry) netFeature.getDefaultGeometry();
        Coordinate coordinate = geometry.getCoordinate();

        // gets the slope in the correspondent raster cell
        double slope = CoverageUtilities.getValue(inSlope, coordinate);
        // extents and adds the data to the output FC
        SimpleFeature extendedFeature = ext.extendFeature(netFeature, new Object[]{slope});
        ((DefaultFeatureCollection) outNetPoints).add(extendedFeature);
        pm.worked(1);
    }
    pm.done();

}
 
Example 15
private DefaultFeatureCollection removeNonBuildings( ALasDataManager lasHandler, SimpleFeatureCollection buildingsFC,
        GridCoverage2D dem, double buildingsBuffer ) throws Exception {
    final List<SimpleFeature> buildingsList = FeatureUtilities.featureCollectionToList(buildingsFC);

    final List<SimpleFeature> checkedBuildings = new ArrayList<SimpleFeature>();
    pm.beginTask("Removing buildings...", buildingsList.size());
    for( int i = 0; i < buildingsList.size(); i++ ) {
        SimpleFeature building = buildingsList.get(i);
        Geometry buildingGeom = (Geometry) building.getDefaultGeometry();

        Geometry bufferedGeom = buildingGeom.buffer(buildingsBuffer);
        List<LasRecord> points = lasHandler.getPointsInGeometry(bufferedGeom, false);
        int percOfOnes = checkReturnNum(points, bufferedGeom);
        if (percOfOnes >= 96) {
            checkedBuildings.add(building);
        }
        pm.worked(1);
    }
    pm.done();

    DefaultFeatureCollection fc = new DefaultFeatureCollection();
    fc.addAll(checkedBuildings);
    return fc;
}
 
Example 16
Source Project: hortonmachine   Source File: TinHandler.java    License: GNU General Public License v3.0 6 votes vote down vote up
public SimpleFeatureCollection toFeatureCollectionOthers() {
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName("points");
    b.setCRS(crs);

    DefaultFeatureCollection newCollection = new DefaultFeatureCollection();
    b.add("the_geom", Point.class);
    b.add("elev", Double.class);
    SimpleFeatureType type = b.buildFeatureType();
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
    for( Coordinate c : leftOverCoordinateList ) {
        Object[] values = new Object[]{gf.createPoint(c), c.z};
        builder.addAll(values);
        SimpleFeature feature = builder.buildFeature(null);
        newCollection.add(feature);
    }
    return newCollection;
}
 
Example 17
Source Project: hortonmachine   Source File: TinHandler.java    License: GNU General Public License v3.0 6 votes vote down vote up
public SimpleFeatureCollection toFeatureCollectionTinPoints() {
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName("points");
    b.setCRS(crs);

    DefaultFeatureCollection newCollection = new DefaultFeatureCollection();
    b.add("the_geom", Point.class);
    b.add("elev", Double.class);
    SimpleFeatureType type = b.buildFeatureType();
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
    for( Coordinate c : tinCoordinateList ) {
        Object[] values = new Object[]{gf.createPoint(c), c.z};
        builder.addAll(values);
        SimpleFeature feature = builder.buildFeature(null);
        newCollection.add(feature);
    }
    return newCollection;
}
 
Example 18
private SimpleFeatureCollection featureCollectionFromNonGroundCoordinates( CoordinateReferenceSystem crs,
        List<Coordinate> nonGroundCoordinateList ) {
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName("nongroundpoints");
    b.setCRS(crs);

    DefaultFeatureCollection newCollection = new DefaultFeatureCollection();
    b.add("the_geom", Point.class);
    b.add("elev", Double.class);
    SimpleFeatureType type = b.buildFeatureType();
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
    for( Coordinate c : nonGroundCoordinateList ) {
        Point g = gf.createPoint(c);
        Object[] values = new Object[]{g, c.z};
        builder.addAll(values);
        SimpleFeature feature = builder.buildFeature(null);
        newCollection.add(feature);
    }
    return newCollection;
}
 
Example 19
@Override
public VectorDataNode readVectorDataNode(File file, Product product, ProgressMonitor pm) throws IOException {

    DefaultFeatureCollection featureCollection = FeatureUtils.loadShapefileForProduct(file,
                                                                                      product,
                                                                                      crsProvider,
                                                                                      pm);
    Style[] styles = SLDUtils.loadSLD(file);
    ProductNodeGroup<VectorDataNode> vectorDataGroup = product.getVectorDataGroup();
    String name = VectorDataNodeImporter.findUniqueVectorDataNodeName(featureCollection.getSchema().getName().getLocalPart(),
                                                                      vectorDataGroup);
    if (styles.length > 0) {
        SimpleFeatureType featureType = SLDUtils.createStyledFeatureType(featureCollection.getSchema());


        VectorDataNode vectorDataNode = new VectorDataNode(name, featureType);
        DefaultFeatureCollection styledCollection = vectorDataNode.getFeatureCollection();
        String defaultCSS = vectorDataNode.getDefaultStyleCss();
        SLDUtils.applyStyle(styles[0], defaultCSS, featureCollection, styledCollection);
        return vectorDataNode;
    } else {
        return new VectorDataNode(name, featureCollection);
    }
}
 
Example 20
Source Project: tutorials   Source File: ShapeFile.java    License: MIT License 5 votes vote down vote up
private static void writeToFile(ShapefileDataStore dataStore, DefaultFeatureCollection collection) throws Exception {

        // If you decide to use the TYPE type and create a Data Store with it,
        // You will need to uncomment this line to set the Coordinate Reference System
        // newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);

        Transaction transaction = new DefaultTransaction("create");

        String typeName = dataStore.getTypeNames()[0];
        SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName);

        if (featureSource instanceof SimpleFeatureStore) {
            SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;

            featureStore.setTransaction(transaction);
            try {
                featureStore.addFeatures(collection);
                transaction.commit();
            } catch (Exception problem) {
                problem.printStackTrace();
                transaction.rollback();
            } finally {
                transaction.close();
            }
            System.exit(0); // success!
        } else {
            System.out.println(typeName + " does not support read/write access");
            System.exit(1);
        }
    }
 
Example 21
Source Project: gama   Source File: SaveStatement.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void saveGeoJSonFile(final IScope scope, final File f, final List<? extends IShape> agents,
		/* final String featureTypeName, */final String specs, final Map<String, IExpression> attributes,
		final IProjection gis) throws IOException, SchemaException, GamaRuntimeException {
	// AD 11/02/15 Added to allow saving to new directories
	if (agents == null || agents.isEmpty()) { return; }

	// The name of the type and the name of the feature source shoud now be
	// the same.
	final SimpleFeatureType type = DataUtilities.createType("geojson", specs);
	final SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
	final DefaultFeatureCollection featureCollection = new DefaultFeatureCollection();

	// AD Builds once the list of agent attributes to evaluate
	final Collection<IExpression> attributeValues =
			attributes == null ? Collections.EMPTY_LIST : attributes.values();
	int i = 0;
	for (final IShape ag : agents) {
		final SimpleFeature ff = builder.buildFeature(i + "");
		i++;
		final boolean ok = buildFeature(scope, ff, ag, gis, attributeValues);
		if (!ok) {
			continue;
		}
		featureCollection.add(ff);
	}

	final FeatureJSON io = new FeatureJSON();
	io.writeFeatureCollection(featureCollection, f.getAbsolutePath());

}
 
Example 22
Source Project: elasticgeo   Source File: TestUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static SimpleFeatureCollection createAggregationFeatures(List<Map<String,Object>> data) {
    final SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
    builder.setName( "testType" );
    builder.add("_aggregation", HashMap.class );
    builder.add("aString", String.class );
    final SimpleFeatureType featureType = builder.buildFeatureType();
    final DefaultFeatureCollection collection = new DefaultFeatureCollection();
    final SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType);
    data.forEach(item -> {
        item.keySet().forEach(key -> featureBuilder.set(key, item.get(key)));
        collection.add(featureBuilder.buildFeature(null));
    });
    return collection;
}
 
Example 23
Source Project: elasticgeo   Source File: GeoHashGridTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testGeoHashGridWithNoFeatures() throws Exception {
    features = new DefaultFeatureCollection();
    ReferencedEnvelope envelope = new ReferencedEnvelope(-180,180,-90,90,CRS.decode("EPSG:4326"));
    geohashGrid.initalize(envelope, features);
    IntStream.range(0, geohashGrid.getGrid().length).forEach(i-> assertArrayEquals(new float[geohashGrid.getGrid()[i].length], geohashGrid.getGrid()[i], 0.0f));
}
 
Example 24
Source Project: elasticgeo   Source File: GeoHashGridTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testGeoHashGrid_emptyCellValue() throws Exception {
    float emptyCellValue = -1.0f;
    features = new DefaultFeatureCollection();
    ReferencedEnvelope envelope = new ReferencedEnvelope(-180,180,-90,90,CRS.decode("EPSG:4326"));
    geohashGrid.setEmptyCellValue(emptyCellValue);
    geohashGrid.initalize(envelope, features);
    IntStream.range(0, geohashGrid.getGrid().length).forEach(row-> IntStream.range(0, geohashGrid.getGrid()[row].length).forEach(column-> assertEquals(emptyCellValue, geohashGrid.getGrid()[row][column], 0.0)));
}
 
Example 25
Source Project: elasticgeo   Source File: GeoHashGridTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testGeoHashGrid_nullEmptyCellValue() throws Exception {
    features = new DefaultFeatureCollection();
    ReferencedEnvelope envelope = new ReferencedEnvelope(-180,180,-90,90,CRS.decode("EPSG:4326"));
    geohashGrid.setEmptyCellValue(null);
    geohashGrid.initalize(envelope, features);
    IntStream.range(0, geohashGrid.getGrid().length).forEach(row-> IntStream.range(0, geohashGrid.getGrid()[row].length).forEach(column-> assertEquals(0.0, geohashGrid.getGrid()[row][column], 0.0)));
}
 
Example 26
Source Project: rya   Source File: GeoMesaGeoIndexer.java    License: Apache License 2.0 5 votes vote down vote up
private void deleteStatements(final Collection<RyaStatement> ryaStatements) throws IOException {
    // create a feature collection
    final DefaultFeatureCollection featureCollection = new DefaultFeatureCollection();

    for (final RyaStatement ryaStatement : ryaStatements) {
        final Statement statement = RyaToRdfConversions.convertStatement(ryaStatement);
        // if the predicate list is empty, accept all predicates.
        // Otherwise, make sure the predicate is on the "valid" list
        final boolean isValidPredicate = validPredicates.isEmpty() || validPredicates.contains(statement.getPredicate());

        if (isValidPredicate && (statement.getObject() instanceof Literal)) {
            try {
                final SimpleFeature feature = createFeature(featureType, statement);
                featureCollection.add(feature);
            } catch (final ParseException e) {
                logger.warn("Error getting geo from statement: " + statement.toString(), e);
            }
        }
    }

    // remove this feature collection from the store
    if (!featureCollection.isEmpty()) {
        final Set<Identifier> featureIds = new HashSet<Identifier>();
        final FilterFactory filterFactory = CommonFactoryFinder.getFilterFactory(null);
        final Set<String> stringIds = DataUtilities.fidSet(featureCollection);
        for (final String id : stringIds) {
            featureIds.add(filterFactory.featureId(id));
        }
        final Filter filter = filterFactory.id(featureIds);
        featureStore.removeFeatures(filter);
    }
}
 
Example 27
@Execute
public void process() throws Exception {
    checkNull(inVectors);

    SimpleFeatureType firstType = null;

    FeatureExtender fEx = null;

    pm.beginTask("Merging features...", inVectors.size());
    try {
        outVector = new DefaultFeatureCollection();
        for( SimpleFeatureCollection featureCollection : inVectors ) {
            if (firstType == null) {
                firstType = featureCollection.getSchema();
                fEx = new FeatureExtender(firstType, new String[0], new Class< ? >[0]);
            } else {
                SimpleFeatureType schema = featureCollection.getSchema();
                int compare = DataUtilities.compare(firstType, schema);
                if (compare != 0) {
                    throw new ModelsIllegalargumentException("Merging is done only on same feature types.", this, pm);
                }
            }
            SimpleFeatureIterator featureIterator = featureCollection.features();
            while( featureIterator.hasNext() ) {
                SimpleFeature f = featureIterator.next();

                SimpleFeature extendFeature = fEx.extendFeature(f, new Object[0]);

                ((DefaultFeatureCollection) outVector).add(extendFeature);
            }
            pm.worked(1);
        }
    } finally {
        pm.done();
    }
}
 
Example 28
/**
 * Create a featurecollection from a vector of features
 * 
 * @param features - the vectore of features
 * @return the created featurecollection
 */
public static SimpleFeatureCollection createFeatureCollection( SimpleFeature... features ) {
    DefaultFeatureCollection fcollection = new DefaultFeatureCollection();

    for( SimpleFeature feature : features ) {
        fcollection.add(feature);
    }
    return fcollection;
}
 
Example 29
/**
 * Convert the logs to a featurecollection.
 * 
 * @param pm the monitor.
 * @param logsList the list of logs as gathered from {@link #getGpsLogsList(IHMConnection)}.
 * @return the extracted collection.
 * @throws Exception
 */
public static DefaultFeatureCollection getLogLinesFeatureCollection( IHMProgressMonitor pm, List<GpsLog> logsList ) {
    GeometryFactory gf = GeometryUtilities.gf();
    SimpleFeatureType featureType = GeopaparazziUtilities.getGpsLogLinesFeatureType();
    pm.beginTask("Import gps to lines...", logsList.size());
    DefaultFeatureCollection newCollection = new DefaultFeatureCollection();
    for( GpsLog log : logsList ) {
        List<GpsPoint> points = log.points;

        List<Coordinate> coordList = new ArrayList<>();
        String startDate = ETimeUtilities.INSTANCE.TIME_FORMATTER_LOCAL.format(new Date(log.startTime));
        String endDate = ETimeUtilities.INSTANCE.TIME_FORMATTER_LOCAL.format(new Date(log.endTime));
        for( GpsPoint gpsPoint : points ) {
            Coordinate c = new Coordinate(gpsPoint.lon, gpsPoint.lat);
            coordList.add(c);
        }
        Coordinate[] coordArray = coordList.toArray(new Coordinate[coordList.size()]);
        if (coordArray.length < 2) {
            continue;
        }
        LineString lineString = gf.createLineString(coordArray);
        MultiLineString multiLineString = gf.createMultiLineString(new LineString[]{lineString});

        SimpleFeatureBuilder builder = new SimpleFeatureBuilder(featureType);
        Object[] values = new Object[]{multiLineString, startDate, endDate, log.text};
        builder.addAll(values);
        SimpleFeature feature = builder.buildFeature(null);

        newCollection.add(feature);
        pm.worked(1);
    }
    pm.done();
    return newCollection;
}
 
Example 30
public static SimpleFeatureCollection media2IdBasedFeatureCollection( IHMConnection connection, IHMProgressMonitor pm )
        throws Exception, IOException, FileNotFoundException {
    try {

        GeometryFactory gf = GeometryUtilities.gf();

        /*
         * create the points fc
         */
        DefaultFeatureCollection newCollection = new DefaultFeatureCollection();

        SimpleFeatureType featureType = GeopaparazziUtilities.getMediaFeaturetype();

        List<Image> imagesList = DaoImages.getImagesList(connection);
        pm.beginTask("Importing media...", imagesList.size());

        for( Image image : imagesList ) {
            Point point = gf.createPoint(new Coordinate(image.getLon(), image.getLat()));
            long ts = image.getTs();
            String dateTimeString = ETimeUtilities.INSTANCE.TIME_FORMATTER_LOCAL.format(new Date(ts));

            Object[] values = new Object[]{point, image.getAltim(), dateTimeString, image.getAzim(), image.getImageDataId()};

            SimpleFeatureBuilder builder = new SimpleFeatureBuilder(featureType);
            builder.addAll(values);
            SimpleFeature feature = builder.buildFeature(null);
            newCollection.add(feature);
            pm.worked(1);
        }
        return newCollection;

    } finally {
        pm.done();
    }
}