@Test public void testGetFeaturesFeatureSource() throws Exception { // check the schemas in feature source and feature collection SimpleFeatureSource fs = rts.getFeatureSource(RENAMED); assertEquals(primitive, fs.getSchema()); SimpleFeatureCollection fc = fs.getFeatures(); assertEquals(primitive, fc.getSchema()); assertTrue(fc.size() > 0); // make sure the feature schema is good as well FeatureIterator<SimpleFeature> it = fc.features(); SimpleFeature sf = it.next(); it.close(); assertEquals(primitive, sf.getFeatureType()); // check the feature ids have been renamed as well assertTrue( "Feature id has not been renamed, it's still " + sf.getID(), sf.getID().startsWith(RENAMED)); // check mappings occurred assertEquals("description-f001", sf.getAttribute("description")); assertTrue( new WKTReader() .read("MULTIPOINT(39.73245 2.00342)") .equalsExact((Geometry) sf.getAttribute("pointProperty"))); assertEquals(new Long(155), sf.getAttribute("intProperty")); assertNull(sf.getAttribute("newProperty")); }
public MapLayerInfo(SimpleFeatureSource remoteSource) { this.remoteFeatureSource = remoteSource; this.layerInfo = null; name = remoteFeatureSource.getSchema().getTypeName(); label = name; description = "Remote WFS"; type = TYPE_REMOTE_VECTOR; }
/* (non-Javadoc) * @see org.geotools.validation.IntegrityValidation#validate(java.util.Map, com.vividsolutions.jts.geom.Envelope, org.geotools.validation.ValidationResults) */ public boolean validate(Map layers, Envelope envelope, ValidationResults results) throws Exception { LOGGER.finer("Starting test " + getName() + " (" + getClass().getName() + ")"); String typeRef1 = getGeomTypeRefA(); LOGGER.finer(typeRef1 + ": looking up SimpleFeatureSource "); SimpleFeatureSource geomSource1 = (SimpleFeatureSource) layers.get(typeRef1); LOGGER.finer(typeRef1 + ": found " + geomSource1.getSchema().getTypeName()); String typeRef2 = getGeomTypeRefB(); if (typeRef2 == EMPTY || typeRef1.equals(typeRef2)) return validateSingleLayer(geomSource1, isExpected(), results, envelope); else { LOGGER.finer(typeRef2 + ": looking up SimpleFeatureSource "); SimpleFeatureSource geomSource2 = (SimpleFeatureSource) layers.get(typeRef2); LOGGER.finer(typeRef2 + ": found " + geomSource2.getSchema().getTypeName()); return validateMultipleLayers(geomSource1, geomSource2, isExpected(), results, envelope); } }
public CoordinateReferenceSystem getCoordinateReferenceSystem() { if (layerInfo != null) { return layerInfo.getResource().getCRS(); } if (remoteFeatureSource != null) { SimpleFeatureType schema = remoteFeatureSource.getSchema(); return schema.getCoordinateReferenceSystem(); } throw new IllegalStateException(); }
private static String getFieldForColour(SimpleFeatureSource source) throws Exception { String selectedField = new String(); String[] fieldNames = new String[source.getSchema().getAttributeCount()]; int k = 0; for (AttributeDescriptor desc : source.getSchema().getAttributeDescriptors()) { fieldNames[k++] = desc.getLocalName(); } selectedField = JOptionPane.showInputDialog( null, "Choose an attribute for colouring", "Feature attribute", JOptionPane.PLAIN_MESSAGE, null, fieldNames, fieldNames[0]) .toString(); return selectedField; }
@SuppressWarnings("unchecked") private static Style createStyle(SimpleFeatureSource source, String fieldName) throws Exception { StyleFactory styleFactory = CommonFactoryFinder.getStyleFactory(); FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(); Function colourFn = ff.function("colorlookup", ff.literal(source), ff.property(fieldName)); Stroke stroke = styleFactory.createStroke( colourFn, ff.literal(1.0f), // line // width ff.literal(1.0f)); // opacity Fill fill = styleFactory.createFill(colourFn, ff.literal(1.0f)); // opacity Class<?> geomClass = source.getSchema().getGeometryDescriptor().getType().getBinding(); Symbolizer sym = null; Geometries geomType = Geometries.getForBinding((Class<? extends Geometry>) geomClass); switch (geomType) { case POLYGON: case MULTIPOLYGON: sym = styleFactory.createPolygonSymbolizer(stroke, fill, null); break; case LINESTRING: case MULTILINESTRING: sym = styleFactory.createLineSymbolizer(stroke, null); break; case POINT: case MULTIPOINT: Graphic gr = styleFactory.createDefaultGraphic(); gr.graphicalSymbols().clear(); Mark mark = styleFactory.getCircleMark(); mark.setFill(fill); mark.setStroke(stroke); gr.graphicalSymbols().add(mark); gr.setSize(ff.literal(10.0f)); sym = styleFactory.createPointSymbolizer(gr, null); break; default: throw new IllegalArgumentException("Unsupported geometry type"); } Style style = SLD.wrapSymbolizers(sym); return style; }
/** The constructor. */ public ViewTest() { // Create a map content and add our shapefile to it map = new MapContent(); map.setTitle("simple map content"); // hey, try for an image aswell String path = "/Users/ian/Desktop/ukrasterchart/2_BRITISH_ISLES.tif"; File chartFile = new File(path); if (!chartFile.exists()) System.err.println("CANNOT FILE THE CHART FILE!!!"); WorldImageFormat format = new WorldImageFormat(); AbstractGridCoverage2DReader tiffReader = format.getReader(chartFile); if (tiffReader != null) { StyleFactoryImpl sf = new StyleFactoryImpl(); RasterSymbolizer symbolizer = sf.getDefaultRasterSymbolizer(); Style defaultStyle = SLD.wrapSymbolizers(symbolizer); GeneralParameterValue[] params = null; GridReaderLayer res = new GridReaderLayer(tiffReader, defaultStyle, params); map.addLayer(res); } try { URL url = GtActivator.getDefault().getBundle().getEntry("data/50m_admin_0_countries.shp"); String filePath = FileLocator.resolve(url).getFile(); File file = new File(filePath); if (!file.exists()) System.err.println("can't find file!!!"); FileDataStore store = FileDataStoreFinder.getDataStore(file); if (store != null) { SimpleFeatureSource featureSource = store.getFeatureSource(); Style style = SLD.createSimpleStyle(featureSource.getSchema()); Layer layer = new FeatureLayer(featureSource, style); map.addLayer(layer); } } catch (IOException e) { } // }
@Test public void testInfiniteLoopAvoidance() throws Exception { final Exception sentinel = new RuntimeException("This is the one that should be thrown in hasNext()"); // setup the mock necessary to have the renderer hit into the exception in hasNext() SimpleFeatureIterator it2 = createNiceMock(SimpleFeatureIterator.class); expect(it2.hasNext()).andThrow(sentinel).anyTimes(); replay(it2); SimpleFeatureCollection fc = createNiceMock(SimpleFeatureCollection.class); expect(fc.features()).andReturn(it2); expect(fc.size()).andReturn(200); expect(fc.getSchema()).andReturn(testLineFeatureType).anyTimes(); replay(fc); SimpleFeatureSource fs = createNiceMock(SimpleFeatureSource.class); expect(fs.getFeatures((Query) anyObject())).andReturn(fc); expect(fs.getSchema()).andReturn(testLineFeatureType).anyTimes(); expect(fs.getSupportedHints()).andReturn(new HashSet()).anyTimes(); replay(fs); // build map context MapContext mapContext = new DefaultMapContext(DefaultGeographicCRS.WGS84); mapContext.addLayer(fs, createLineStyle()); // setup the renderer and listen for errors final StreamingRenderer sr = new StreamingRenderer(); sr.setContext(mapContext); sr.addRenderListener( new RenderListener() { public void featureRenderer(SimpleFeature feature) { features++; } public void errorOccurred(Exception e) { errors++; if (errors > 2) { // we dont' want to block the loop in case of regression on this bug sr.stopRendering(); } // but we want to make sure we're getting Throwable t = e; while (t != sentinel && t.getCause() != null) t = t.getCause(); assertSame(sentinel, t); } }); errors = 0; features = 0; BufferedImage image = new BufferedImage(200, 200, BufferedImage.TYPE_4BYTE_ABGR); ReferencedEnvelope reWgs = new ReferencedEnvelope(new Envelope(-180, -170, 20, 40), DefaultGeographicCRS.WGS84); sr.paint((Graphics2D) image.getGraphics(), new Rectangle(200, 200), reWgs); // we should get two errors since there are two features that cannot be // projected but the renderer itself should not throw exceptions assertEquals(0, features); assertEquals(1, errors); }
/** * Loads the feature collection based on the current styling and the scale denominator. If no * feature is going to be returned a null feature collection will be returned instead * * @param featureSource * @param layer * @param mapContent * @param wms * @param scaleDenominator * @return * @throws Exception */ public static SimpleFeatureCollection loadFeatureCollection( SimpleFeatureSource featureSource, Layer layer, WMSMapContent mapContent, WMS wms, double scaleDenominator) throws Exception { SimpleFeatureType schema = featureSource.getSchema(); Envelope envelope = mapContent.getRenderingArea(); ReferencedEnvelope aoi = new ReferencedEnvelope(envelope, mapContent.getCoordinateReferenceSystem()); CoordinateReferenceSystem sourceCrs = schema.getCoordinateReferenceSystem(); boolean reprojectBBox = (sourceCrs != null) && !CRS.equalsIgnoreMetadata(aoi.getCoordinateReferenceSystem(), sourceCrs); if (reprojectBBox) { aoi = aoi.transform(sourceCrs, true); } Filter filter = createBBoxFilter(schema, aoi); // now build the query using only the attributes and the bounding // box needed Query q = new Query(schema.getTypeName()); q.setFilter(filter); // now, if a definition query has been established for this layer, // be sure to respect it by combining it with the bounding box one. Query definitionQuery = layer.getQuery(); if (definitionQuery != Query.ALL) { if (q == Query.ALL) { q = (Query) definitionQuery; } else { q = (Query) DataUtilities.mixQueries(definitionQuery, q, "KMLEncoder"); } } // handle startIndex requested by client query q.setStartIndex(definitionQuery.getStartIndex()); // check the regionating strategy RegionatingStrategy regionatingStrategy = null; String stratname = (String) mapContent.getRequest().getFormatOptions().get("regionateBy"); if (("auto").equals(stratname)) { Catalog catalog = wms.getGeoServer().getCatalog(); Name name = layer.getFeatureSource().getName(); stratname = catalog .getFeatureTypeByName(name) .getMetadata() .get("kml.regionateStrategy", String.class); if (stratname == null || "".equals(stratname)) { stratname = "best_guess"; LOGGER.log( Level.FINE, "No default regionating strategy has been configured in " + name + "; using automatic best-guess strategy."); } } if (stratname != null) { regionatingStrategy = findStrategyByName(stratname); // if a strategy was specified but we did not find it, let the user // know if (regionatingStrategy == null) throw new ServiceException("Unknown regionating strategy " + stratname); } // try to load less features by leveraging regionating strategy and the // SLD Filter regionatingFilter = Filter.INCLUDE; if (regionatingStrategy != null) regionatingFilter = regionatingStrategy.getFilter(mapContent, layer); Filter ruleFilter = summarizeRuleFilters( getLayerRules(featureSource.getSchema(), layer.getStyle()), scaleDenominator); Filter finalFilter = joinFilters(q.getFilter(), ruleFilter, regionatingFilter); if (finalFilter == Filter.EXCLUDE) { // if we don't have any feature to return return null; } q.setFilter(finalFilter); // make sure we output in 4326 since that's what KML mandates CoordinateReferenceSystem wgs84; try { wgs84 = CRS.decode("EPSG:4326"); } catch (Exception e) { throw new RuntimeException( "Cannot decode EPSG:4326, the CRS subsystem must be badly broken..."); } if (sourceCrs != null && !CRS.equalsIgnoreMetadata(wgs84, sourceCrs)) { return new ReprojectFeatureResults(featureSource.getFeatures(q), wgs84); } return featureSource.getFeatures(q); }
public static IGlobeFeatureCollection< IVector2, ? extends IBoundedGeometry2D<? extends IFinite2DBounds<?>>> readFeatures(final DataStore dataStore, final String layerName, final GProjection projection) throws Exception { final SimpleFeatureSource featureSource = dataStore.getFeatureSource(layerName); final SimpleFeatureCollection featuresCollection = featureSource.getFeatures(); final GIntHolder validCounter = new GIntHolder(0); // final GIntHolder polygonsWithHolesCounter = new GIntHolder(0); final GIntHolder invalidCounter = new GIntHolder(0); // final GIntHolder validVerticesCounter = new GIntHolder(0); final GIntHolder polygonsCounter = new GIntHolder(0); final GIntHolder linesCounter = new GIntHolder(0); final GIntHolder pointsCounter = new GIntHolder(0); final int featuresCount = featuresCollection.size(); final ArrayList<IGlobeFeature<IVector2, IBoundedGeometry2D<? extends IFinite2DBounds<?>>>> euclidFeatures = new ArrayList< IGlobeFeature<IVector2, IBoundedGeometry2D<? extends IFinite2DBounds<?>>>>( featuresCount); final GProgress progress = new GProgress(featuresCount) { @Override public void informProgress( final double percent, final long elapsed, final long estimatedMsToFinish) { // System.out.println("Loading \"" + fileName.buildPath() + "\" " // + progressString(percent, elapsed, // estimatedMsToFinish)); System.out.println( "Loading data from data storage: " + layerName + " " + progressString(percent, elapsed, estimatedMsToFinish)); } }; final FeatureIterator<SimpleFeature> iterator = featuresCollection.features(); while (iterator.hasNext()) { final SimpleFeature feature = iterator.next(); final GeometryAttribute geometryAttribute = feature.getDefaultGeometryProperty(); final GeometryType type = geometryAttribute.getType(); if (type.getBinding() == com.vividsolutions.jts.geom.MultiPolygon.class) { polygonsCounter.increment(); final com.vividsolutions.jts.geom.MultiPolygon multipolygon = (com.vividsolutions.jts.geom.MultiPolygon) geometryAttribute.getValue(); final int geometriesCount = multipolygon.getNumGeometries(); final List<IPolygon2D> polygons = new ArrayList<IPolygon2D>(geometriesCount); for (int i = 0; i < geometriesCount; i++) { final com.vividsolutions.jts.geom.Polygon jtsPolygon = (com.vividsolutions.jts.geom.Polygon) multipolygon.getGeometryN(i); try { final IPolygon2D euclidPolygon = createEuclidPolygon(projection, jtsPolygon); if (euclidPolygon != null) { // euclidFeatures.add(createFeature(euclidPolygon, feature)); polygons.add(euclidPolygon); validCounter.increment(); } } catch (final IllegalArgumentException e) { // System.err.println(e.getMessage()); } } if (!polygons.isEmpty()) { if (polygons.size() == 1) { euclidFeatures.add(createFeature(polygons.get(0), feature)); } else { euclidFeatures.add(createFeature(new GMultiGeometry2D<IPolygon2D>(polygons), feature)); } } } else if (type.getBinding() == com.vividsolutions.jts.geom.MultiLineString.class) { linesCounter.increment(); final com.vividsolutions.jts.geom.MultiLineString multiline = (com.vividsolutions.jts.geom.MultiLineString) geometryAttribute.getValue(); final int geometriesCount = multiline.getNumGeometries(); final List<IPolygonalChain2D> lines = new ArrayList<IPolygonalChain2D>(geometriesCount); for (int i = 0; i < geometriesCount; i++) { final com.vividsolutions.jts.geom.LineString jtsLine = (com.vividsolutions.jts.geom.LineString) multiline.getGeometryN(i); try { final IPolygonalChain2D euclidLine = createLine(jtsLine.getCoordinates(), projection); // euclidFeatures.add(createFeature(euclidLines, feature)); lines.add(euclidLine); } catch (final IllegalArgumentException e) { // System.err.println(e.getMessage()); } } if (!lines.isEmpty()) { if (lines.size() == 1) { euclidFeatures.add(createFeature(lines.get(0), feature)); } else { euclidFeatures.add( createFeature(new GMultiGeometry2D<IPolygonalChain2D>(lines), feature)); } } validCounter.increment(); } else if (type.getBinding() == com.vividsolutions.jts.geom.Point.class) { pointsCounter.increment(); final IVector2 euclidPoint = createPoint( ((com.vividsolutions.jts.geom.Point) geometryAttribute.getValue()).getCoordinate(), projection); euclidFeatures.add(createFeature(euclidPoint, feature)); validCounter.increment(); } else if (type.getBinding() == com.vividsolutions.jts.geom.MultiPoint.class) { final IBoundedGeometry2D<? extends IFinite2DBounds<?>> euclidMultipoint = createEuclidMultiPoint(geometryAttribute, projection); euclidFeatures.add(createFeature(euclidMultipoint, feature)); validCounter.increment(); } else { invalidCounter.increment(); System.out.println("invalid type: " + type); } progress.stepDone(); } dataStore.dispose(); euclidFeatures.trimToSize(); System.out.println(); System.out.println("Features: " + featuresCount); System.out.println(); System.out.println("Read " + validCounter.get() + " valid geometries"); System.out.println(" => " + polygonsCounter.get() + " valid polygons"); System.out.println(" => " + linesCounter.get() + " valid lines"); System.out.println(" => " + pointsCounter.get() + " valid points"); System.out.println(); if (invalidCounter.get() > 0) { System.out.println("Ignored " + invalidCounter.get() + " invalid geometries"); } System.out.println(); final SimpleFeatureType schema = featureSource.getSchema(); final int fieldsCount = schema.getAttributeCount(); final List<GField> fields = new ArrayList<GField>(fieldsCount); System.out.println("Fields count: " + fieldsCount); for (int i = 0; i < fieldsCount; i++) { final String fieldName = schema.getType(i).getName().getLocalPart(); System.out.println("Fieldname: " + fieldName); final Class<?> fieldType = schema.getType(i).getBinding(); fields.add(new GField(fieldName, fieldType)); } return new GListFeatureCollection<IVector2, IBoundedGeometry2D<? extends IFinite2DBounds<?>>>( GProjection.EPSG_4326, fields, euclidFeatures, "uniqueId_000"); }