org.geotools.feature.DefaultFeatureCollection Java Examples

The following examples show how to use org.geotools.feature.DefaultFeatureCollection. 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: IFeatureShape.java    From hortonmachine with GNU General Public License v3.0 7 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 #2
Source File: OmsGridsGenerator.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
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 #3
Source File: MapUtils.java    From dhis2-core with 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 #4
Source File: ImportVectorDataNodeFromShapefileAction.java    From snap-desktop with GNU General Public License v3.0 6 votes vote down vote up
@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 #5
Source File: AdaptiveTinFilter.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
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 #6
Source File: GeoWaveGeoIndexer.java    From rya with 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 #7
Source File: GeoMesaGeoIndexer.java    From rya with 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 #8
Source File: TinHandler.java    From hortonmachine with 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 #9
Source File: TinHandler.java    From hortonmachine with 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 #10
Source File: LasOnDtmBuildingsExtractor.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
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 #11
Source File: OmsLW06_SlopeToNetworkAdder.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
@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 #12
Source File: OmsLW04_BankfullWidthAnalyzer.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
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 #13
Source File: OmsGridsGenerator.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
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 #14
Source File: OmsLW04_BankfullWidthAnalyzer.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
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 #15
Source File: OmsLasConverter.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
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 #16
Source File: OmsLW04_BankfullWidthAnalyzer.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
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 #17
Source File: DatabaseController.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
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 #18
Source File: TestScanLineRasterizer.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
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 #19
Source File: TestProfile.java    From hortonmachine with 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 #20
Source File: OmsAdige.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
private void linkBasinWithNetwork() throws Exception {
    FeatureExtender fExt = new FeatureExtender(inNetwork.getSchema(), new String[]{NetworkChannel.NETNUMNAME},
            new Class[]{Integer.class});

    DefaultFeatureCollection newCollection = new DefaultFeatureCollection();

    SimpleFeatureIterator hillslopeFeatures = inHillslope.features();
    while( hillslopeFeatures.hasNext() ) {
        SimpleFeature hFeature = hillslopeFeatures.next();
        Object netNum = hFeature.getAttribute(NetworkChannel.NETNUMNAME);
        Geometry hGeometry = (Geometry) hFeature.getDefaultGeometry();
        PreparedGeometry preparedHGeometry = PreparedGeometryFactory.prepare(hGeometry);
        SimpleFeatureIterator netFeatures = inNetwork.features();
        while( netFeatures.hasNext() ) {
            SimpleFeature nFeature = netFeatures.next();
            Geometry geometry = (Geometry) nFeature.getDefaultGeometry();
            if (geometry.getNumGeometries() != 1) {
                throw new ModelsRuntimeException("The network geometries have to be single lines.", this);
            }
            LineString nLine = (LineString) geometry.getGeometryN(0);
            Point startPoint = nLine.getStartPoint();
            if (preparedHGeometry.contains(startPoint)) {
                SimpleFeature extendFeature = fExt.extendFeature(nFeature, new Object[]{netNum});
                newCollection.add(extendFeature);
                break;
            }
        }
    }
    inNetwork = newCollection;
}
 
Example #21
Source File: DatabaseViewer.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public boolean viewSpatialQueryResult( String tableName, String sqlText, IHMProgressMonitor pm, boolean isTableQuery ) {
    boolean hasError = false;
    if (sqlText.trim().length() == 0) {
        return false;
    }
    try {
        pm.beginTask("Run query: " + sqlText, IHMProgressMonitor.UNKNOWN);
        DefaultFeatureCollection fc = DbsHelper.runRawSqlToFeatureCollection(tableName, currentConnectedDatabase, sqlText,
                null);
        ReprojectingFeatureCollection rfc = new ReprojectingFeatureCollection(fc, NwwUtilities.GPS_CRS);

        Style[] styles = null;
        if (isTableQuery && tableName != null) {
            // try to get some style
            if (currentConnectedDatabase.getType() == EDb.GEOPACKAGE) {
                String sldString = ((GeopackageCommonDb) currentConnectedDatabase).getSldString(tableName);
                if (sldString != null) {
                    Style style = SldUtilities.getStyleFromSldString(sldString);
                    styles = new Style[]{style};
                }
            }
        }

        showInMapFrame(true, new SimpleFeatureCollection[]{rfc}, styles);

        addQueryToHistoryCombo(sqlText);

    } catch (Exception e1) {
        String localizedMessage = e1.getLocalizedMessage();
        hasError = true;
        pm.errorMessage("An error occurred: " + localizedMessage);
    } finally {
        pm.done();
    }
    return hasError;
}
 
Example #22
Source File: DatabaseViewer.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public boolean viewSpatialQueryResult3D( String title, String sqlText, IHMProgressMonitor pm ) {
    boolean hasError = false;
    if (sqlText.trim().length() == 0) {
        return false;
    }
    try {
        if (toolsPanelController == null) {
            openNww();
        }
        pm.beginTask("Run query: " + sqlText, IHMProgressMonitor.UNKNOWN);
        DefaultFeatureCollection fc = DbsHelper.runRawSqlToFeatureCollection(title, currentConnectedDatabase, sqlText, null);
        ReprojectingFeatureCollection rfc = new ReprojectingFeatureCollection(fc, NwwUtilities.GPS_CRS);

        if (toolsPanelController != null) {
            if (title == null) {
                title = "QueryLayer";
            }
            toolsPanelController.loadFeatureCollection(null, title, null, rfc, null);
            addQueryToHistoryCombo(sqlText);
        }

    } catch (Exception e1) {
        String localizedMessage = e1.getLocalizedMessage();
        hasError = true;
        e1.printStackTrace();
        pm.errorMessage("An error occurred: " + localizedMessage);
    } finally {
        pm.done();
    }
    return hasError;
}
 
Example #23
Source File: RasterizedSpatialiteLayer.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
private static GTRenderer getRenderer( ASpatialDb db, String tableName, int featureLimit, Style style ) {
    MapContent mapContent = new MapContent();

    // read data and convert it to featurecollection
    try {
        long t1 = System.currentTimeMillis();
        System.out.println("STARTED READING: " + tableName);

        String databasePath = db.getDatabasePath();
        File dbFile = new File(databasePath);
        File parentFolder = dbFile.getParentFile();
        if (style == null) {
            File sldFile = new File(parentFolder, tableName + ".sld");
            if (sldFile.exists()) {
                style = SldUtilities.getStyleFromFile(sldFile);
            }
        }

        DefaultFeatureCollection fc = SpatialDbsImportUtils.tableToFeatureFCollection(db, tableName, featureLimit,
                NwwUtilities.GPS_CRS_SRID, null);
        long t2 = System.currentTimeMillis();
        System.out.println("FINISHED READING: " + tableName + " -> " + ((t2 - t1) / 1000) + "sec");
        if (style == null) {
            style = SLD.createSimpleStyle(fc.getSchema());
        }
        FeatureLayer layer = new FeatureLayer(fc, style);

        long t3 = System.currentTimeMillis();
        System.out.println("FINISHED BUILDING: " + tableName + " -> " + ((t3 - t2) / 1000) + "sec");

        mapContent.addLayer(layer);
    } catch (Exception e) {
        e.printStackTrace();
    }
    GTRenderer renderer = new StreamingRenderer();
    renderer.setMapContent(mapContent);
    return renderer;
}
 
Example #24
Source File: GeoToolsLayer.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = { Throwable.class })
public Object create(Object feature) throws LayerException {
	SimpleFeatureSource source = getFeatureSource();
	if (source instanceof SimpleFeatureStore) {
		SimpleFeatureStore store = (SimpleFeatureStore) source;
		DefaultFeatureCollection collection = new DefaultFeatureCollection();
		collection.add((SimpleFeature) feature);
		transactionSynchronization.synchTransaction(store);
		try {
			List<FeatureId> ids = store.addFeatures(collection);
			// fetch it again to get the generated values !!!
			if (ids.size() == 1) {
				return read(ids.get(0).getID());
			}
		} catch (IOException ioe) {
			featureModelUsable = false;
			throw new LayerException(ioe, ExceptionCode.LAYER_MODEL_IO_EXCEPTION);
		}
		return feature;
	} else {
		log.error("Don't know how to create or update " + getFeatureSourceName() + ", class "
				+ source.getClass().getName() + " does not implement SimpleFeatureStore");
		throw new LayerException(ExceptionCode.CREATE_OR_UPDATE_NOT_IMPLEMENTED, getFeatureSourceName(), source
				.getClass().getName());
	}
}
 
Example #25
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 #26
Source File: TestVectorFieldRounder.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public void testVectorFieldRounder() throws Exception {

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

        DefaultFeatureCollection newCollection = new DefaultFeatureCollection();
        SimpleFeatureType type = b.buildFeatureType();
        SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
        Point point = GeometryUtilities.gf().createPoint(new Coordinate(0, 0));
        Object[] values = new Object[]{point, 123.456789};
        builder.addAll(values);
        SimpleFeature feature = builder.buildFeature(type.getTypeName() + ".0");
        newCollection.add(feature);

        OmsVectorFieldRounder rounder = new OmsVectorFieldRounder();
        rounder.inVector = newCollection;
        rounder.fRound = "area";
        rounder.pPattern = ".##";
        rounder.process();
        SimpleFeatureCollection outFeatures = rounder.outVector;

        SimpleFeature f = FeatureUtilities.featureCollectionToList(outFeatures).get(0);
        String areaStr = f.getAttribute("area").toString();

        assertTrue(areaStr.equals("123.46"));
    }
 
Example #27
Source File: TestVectorTableJoiner.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public void testVectorTableJoiner() 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();
        SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
        Point point = GeometryUtilities.gf().createPoint(new Coordinate(0, 0));
        Object[] values = new Object[]{point, 1};
        builder.addAll(values);
        SimpleFeature feature = builder.buildFeature(type.getTypeName() + ".0");
        newCollection.add(feature);

        HashMap<String, List<Object>> tabledata = new HashMap<String, List<Object>>();
        List<Object> id = Arrays.asList(new Object[]{1});
        tabledata.put("id", id);
        List<Object> area = Arrays.asList(new Object[]{123.45});
        tabledata.put("area", area);
        List<Object> area2 = Arrays.asList(new Object[]{67.89});
        tabledata.put("area2", area2);

        OmsVectorTableJoiner joiner = new OmsVectorTableJoiner();
        joiner.inVector = newCollection;
        joiner.tabledata = tabledata;
        joiner.fCommon = "id";
        joiner.pFields = "area";
        joiner.process();
        SimpleFeatureCollection outFeatures = joiner.outVector;

        SimpleFeature f = FeatureUtilities.featureCollectionToList(outFeatures).get(0);
        String areaStr = f.getAttribute("area").toString();

        assertTrue(areaStr.equals("123.45"));
    }
 
Example #28
Source File: TestVectorTransformer.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public void testVectorTransformer() 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();
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
    Point point = GeometryUtilities.gf().createPoint(new Coordinate(0, 0));
    Object[] values = new Object[]{point, 1};
    builder.addAll(values);
    SimpleFeature feature = builder.buildFeature(type.getTypeName() + ".0");
    newCollection.add(feature);

    OmsVectorTransformer transformer = new OmsVectorTransformer();
    transformer.inVector = newCollection;
    transformer.pTransX = 1.0;
    transformer.pTransY = -1.0;
    transformer.process();
    SimpleFeatureCollection outFeatures = transformer.outVector;

    Geometry g = FeatureUtilities.featureCollectionToGeometriesList(outFeatures, false, null).get(0);
    Coordinate coord = g.getCoordinate();

    assertEquals(coord.x, 1.0, 0.00001);
    assertEquals(coord.y, -1.0, 0.00001);
}
 
Example #29
Source File: TinHandler.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a {@link SimpleFeatureCollection FeatureCollection} from the current tin triangles
 * with information about the vertexes elevation.
 * 
 * @return the feature collection of the tin.
 */
public SimpleFeatureCollection toFeatureCollection() {
    checkTinGeometries();
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName("triangle");
    b.setCRS(crs);

    DefaultFeatureCollection newCollection = new DefaultFeatureCollection();
    b.add("the_geom", Polygon.class);
    b.add("elev0", Double.class);
    b.add("elev1", Double.class);
    b.add("elev2", Double.class);
    SimpleFeatureType type = b.buildFeatureType();
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
    for( Geometry g : tinGeometries ) {
        Coordinate[] coordinates = g.getCoordinates();

        Object[] values;
        int windingRule = GeometryUtilities.getTriangleWindingRule(coordinates[0], coordinates[1], coordinates[2]);
        if (windingRule > 0) {
            // need to reverse the triangle
            values = new Object[]{g, coordinates[0].z, coordinates[2].z, coordinates[1].z};
        } else {
            values = new Object[]{g, coordinates[0].z, coordinates[1].z, coordinates[2].z};
        }

        builder.addAll(values);
        SimpleFeature feature = builder.buildFeature(null);
        newCollection.add(feature);
    }
    return newCollection;
}
 
Example #30
Source File: ShapeFile.java    From tutorials with MIT License 5 votes vote down vote up
static void addLocations(SimpleFeatureType CITY, DefaultFeatureCollection collection) {

        Map<String, List<Double>> locations = new HashMap<>();

        double lat = 13.752222;
        double lng = 100.493889;
        addToLocationMap("Bangkok", lat, lng, locations);

        lat = 53.083333;
        lng = -0.15;
        addToLocationMap("New York", lat, lng, locations);

        lat = -33.925278;
        lng = 18.423889;
        addToLocationMap("Cape Town", lat, lng, locations);

        lat = -33.859972;
        lng = 151.211111;
        addToLocationMap("Sydney", lat, lng, locations);

        lat = 45.420833;
        lng = -75.69;
        addToLocationMap("Ottawa", lat, lng, locations);

        lat = 30.07708;
        lng = 31.285909;
        addToLocationMap("Cairo", lat, lng, locations);

        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);

        locations.entrySet().stream()
          .map(toFeature(CITY, geometryFactory))
          .forEach(collection::add);
    }