@Test public void testWithNull() throws Exception { SimpleFeatureSource source = getFeatureSource(MockData.BASIC_POLYGONS); SimpleFeatureCollection fc = source.getFeatures(); SimpleFeatureIterator i = fc.features(); try { SimpleFeature f = (SimpleFeature) i.next(); FeatureTemplate template = new FeatureTemplate(); template.description(f); // set a value to null f.setAttribute(1, null); try { template.description(f); } catch (Exception e) { e.printStackTrace(); fail("template threw exception on null value"); } } finally { i.close(); } }
public void setupInstance(String shapeFileName) { File file = new File(shapeFileName); // TODO what if the file doesn't exist? ShapefileDataStore store = null; SimpleFeatureCollection collection = null; try { store = (ShapefileDataStore) FileDataStoreFinder.getDataStore(file); SimpleFeatureSource featureSource = store.getFeatureSource(); collection = featureSource.getFeatures(); } catch (IOException e) { logger.error("Could not retrieve collection", e); return; } geometryFactory = new GeometryFactory(); geometryList = new ArrayList<Geometry>(); SimpleFeatureIterator iter = collection.features(); while (iter.hasNext()) { SimpleFeature feature = iter.next(); Geometry geometry = (Geometry) feature.getDefaultGeometry(); geometryList.add(geometry); } iter.close(); }
@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")); }
/** * <b>validateMultipleLayers Purpose:</b> <br> * * <p>This validation tests for a geometry containing another geometry. Uses JTS' * Geometry.contains(Geometry) method. DE-9IM intersection matrix is T*F**F***. * <b>Description:</b><br> * * <p>The function filters the FeatureSources using the given bounding box. It creates iterators * over both filtered FeatureSources. It calls contains() using the geometries in the * SimpleFeatureSource layers. Tests the results of the method call against the given expected * results. Returns true if the returned results and the expected results are true, false * otherwise. Author: bowens<br> * Created on: Apr 27, 2004<br> * * @param featureSourceA - the SimpleFeatureSource to pull the original geometries from. This * geometry is the one that is tested for containing the other * @param featureSourceB - the SimpleFeatureSource to pull the other geometries from - these * geometries will be those that may be contained within the first geometry * @param expected - boolean value representing the user's expected outcome of the test * @param results - ValidationResults * @param bBox - Envelope - the bounding box within which to perform the contains() * @return boolean result of the test * @throws Exception - IOException if iterators improperly closed */ private boolean validateMultipleLayers( SimpleFeatureSource featureSourceA, SimpleFeatureSource featureSourceB, boolean expected, ValidationResults results, Envelope bBox) throws Exception { boolean success = true; FilterFactory ff = CommonFactoryFinder.getFilterFactory(null); Filter filter = null; SimpleFeatureCollection featureResultsA = featureSourceA.getFeatures(filter); SimpleFeatureCollection featureResultsB = featureSourceB.getFeatures(filter); SimpleFeatureIterator fr1 = null; SimpleFeatureIterator fr2 = null; try { fr1 = featureResultsA.features(); if (fr1 == null) return false; while (fr1.hasNext()) { SimpleFeature f1 = fr1.next(); Geometry g1 = (Geometry) f1.getDefaultGeometry(); fr2 = featureResultsB.features(); try { while (fr2 != null && fr2.hasNext()) { SimpleFeature f2 = fr2.next(); Geometry g2 = (Geometry) f2.getDefaultGeometry(); if (g1.contains(g2) != expected) { results.error( f1, ((Geometry) f1.getDefaultGeometry()).getGeometryType() + " " + getGeomTypeRefA() + " contains " + getGeomTypeRefB() + "(" + f2.getID() + "), Result was not " + expected); success = false; } } } finally { fr2.close(); } } } finally { fr1.close(); fr2.close(); } return success; }
public void selectFeatures(int x, int y) { int pixelDelta = 2; LatLon clickUL = Main.map.mapView.getLatLon(x - pixelDelta, y - pixelDelta); LatLon clickLR = Main.map.mapView.getLatLon(x + pixelDelta, y + pixelDelta); Envelope envelope = new Envelope( Math.min(clickUL.lon(), clickLR.lon()), Math.max(clickUL.lon(), clickLR.lon()), Math.min(clickUL.lat(), clickLR.lat()), Math.max(clickUL.lat(), clickLR.lat())); ReferencedEnvelope mapArea = new ReferencedEnvelope(envelope, crsOSMI); Intersects filter = ff.intersects(ff.property("msGeometry"), ff.literal(mapArea)); // // Select features in all layers // content.layers().clear(); // Iterate through features and build a list that intersects the above // envelope for (int idx = 0; idx < arrFeatures.size(); ++idx) { OSMIFeatureTracker tracker = arrFeatures.get(idx); FeatureCollection<SimpleFeatureType, SimpleFeature> features = tracker.getFeatures(); SimpleFeatureSource tempfs = DataUtilities.source(features); FeatureCollection<SimpleFeatureType, SimpleFeature> selectedFeatures; try { selectedFeatures = tempfs.getFeatures(filter); Set<FeatureId> IDs = new HashSet<>(); try (FeatureIterator<SimpleFeature> iter = selectedFeatures.features()) { Main.info("Selected features " + selectedFeatures.size()); while (iter.hasNext()) { SimpleFeature feature = iter.next(); IDs.add(feature.getIdentifier()); } } geometryType = selectGeomType.get(idx + layerOffset); Style style = createDefaultStyle(idx + layerOffset, IDs); content.addLayer(new FeatureLayer(features, style)); } catch (IOException e) { Main.error(e); } } bIsChanged = true; }
@Before public void findFeature() throws Exception { SimpleFeatureSource source = getFeatureSource(MockData.PRIMITIVEGEOFEATURE); SimpleFeatureCollection features = source.getFeatures(); FeatureIterator<SimpleFeature> iterator = features.features(); while (iterator.hasNext()) { SimpleFeature f = iterator.next(); if (f.getAttribute("dateProperty") != null) { feature = f; break; } } features.close(iterator); }
/** * Generate squares inside given bounds * * @param bounds * @param size * @return * @throws IOException */ private SimpleFeatureIterator squares(ReferencedEnvelope bounds, double size) throws IOException { // Limit squares to bounding box FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(null); Filter filter = ff.bbox(ff.property(GEOM), bounds); // Align bound to square size and expand by 150% bounds = align(bounds, size, 1.5); // Create grid for given bounds SimpleFeatureSource grid = Grids.createSquareGrid(bounds, size); // Finished return grid.getFeatures(filter).features(); }
@Test public void testAlternateLookup() throws Exception { SimpleFeatureSource source = getFeatureSource(MockData.PRIMITIVEGEOFEATURE); SimpleFeatureCollection fc = source.getFeatures(); SimpleFeatureIterator features = fc.features(); try { SimpleFeature f = features.next(); FeatureTemplate template = new FeatureTemplate(); String result = template.template(f, "dummy.ftl", Dummy.class); assertEquals("dummy", result); } finally { features.close(); } }
@Test public void testTypes() throws IOException, NoSuchElementException { if (url == null) return; WFS_1_0_0_DataStore wfs; try { wfs = WFSDataStoreReadTest.getDataStore(url); } catch (ConnectException e) { e.printStackTrace(System.err); return; } catch (UnknownHostException e) { e.printStackTrace(System.err); return; } catch (NoRouteToHostException e) { e.printStackTrace(System.err); return; } String types[] = wfs.getTypeNames(); String typeName = "unknown"; for (int i = 0; i < types.length; i++) { typeName = types[i]; if (typeName.equals("topp:geometrytype")) continue; SimpleFeatureType type = wfs.getSchema(typeName); type.getTypeName(); type.getName().getNamespaceURI(); SimpleFeatureSource source = wfs.getFeatureSource(typeName); source.getBounds(); SimpleFeatureCollection features = source.getFeatures(); features.getBounds(); features.getSchema(); // features.getFeatureType(); Query query = new Query(typeName, Filter.INCLUDE, 20, Query.ALL_NAMES, "work already"); features = source.getFeatures(query); features.size(); SimpleFeatureIterator iterator = features.features(); try { while (iterator.hasNext()) { SimpleFeature feature = (SimpleFeature) iterator.next(); } } finally { iterator.close(); } } }
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); } }
@DescribeResult(name = "result", description = "The grid") public SimpleFeatureCollection execute( @DescribeParameter(name = "features", description = "The grid bounds") ReferencedEnvelope bounds, @DescribeParameter( name = "width", description = "Cell width (in the same uom as the bounds referencing system)") double width, @DescribeParameter( name = "height", description = "Cell height (optional, used only for rectangular grids, " + "if not provided it is assumed equals to the width)", min = 0) Double height, @DescribeParameter( name = "vertexSpacing", description = "Distance between vertices (used to create densified " + "sides suitable for reprojection)", min = 0) Double vertexSpacing, @DescribeParameter(name = "mode", description = "The type of grid to be generated", min = 0) GridMode mode) throws ProcessException { final GridFeatureBuilder builder = new GridFeatureBuilderImpl(bounds.getCoordinateReferenceSystem()); double h = height != null ? height : width; SimpleFeatureSource source; if (mode == null || mode == GridMode.Rectangular) { source = Oblongs.createGrid(bounds, width, h, builder); } else if (mode == GridMode.HexagonFlat) { source = Hexagons.createGrid(bounds, width, HexagonOrientation.FLAT, builder); } else { source = Hexagons.createGrid(bounds, width, HexagonOrientation.ANGLED, builder); } try { return source.getFeatures(); } catch (IOException e) { throw new ProcessException("Unexpected exception while grabbing features", e); } }
@Test public void testRawValue() throws Exception { SimpleFeatureSource source = getFeatureSource(MockData.PRIMITIVEGEOFEATURE); SimpleFeatureCollection fc = source.getFeatures(); SimpleFeatureIterator i = fc.features(); try { SimpleFeature f = (SimpleFeature) i.next(); FeatureTemplate template = new FeatureTemplate(); try { template.template(f, "rawValues.ftl", FeatureTemplateTest.class); } catch (Exception e) { e.printStackTrace(); throw (e); } } finally { i.close(); } }
public CoordinateReferenceSystem getCoordinateReferenceSystem() { if (layerInfo != null) { return layerInfo.getResource().getCRS(); } if (remoteFeatureSource != null) { SimpleFeatureType schema = remoteFeatureSource.getSchema(); return schema.getCoordinateReferenceSystem(); } throw new IllegalStateException(); }
public static void printID(String filename) { File file = new File(filename); FileDataStore store = null; try { store = FileDataStoreFinder.getDataStore(file); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } SimpleFeatureSource featureSource = null; try { featureSource = store.getFeatureSource(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } SimpleFeatureCollection featureCollection = null; try { featureCollection = featureSource.getFeatures(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // get features from source int sizeFeatureCollection = featureCollection.size(); System.out.println( "The number of features in the shapefile is: " + sizeFeatureCollection + "."); SimpleFeatureIterator iterator = featureCollection.features(); // List<Geometry> GeometryList = new ArrayList<Geometry>(sizeFeatureCollection); try { while (iterator.hasNext()) { SimpleFeature feature = iterator.next(); System.out.println(feature.getID()); } } finally { iterator.close(); store.dispose(); } }
/** 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 testAttributeReader() throws IOException { URL u = TestData.url(TestCaseSupport.class, SHPFILE); File shpFile = DataUtilities.urlToFile(u); // open the test shapefile ShapefileDataStore store = new ShapefileDataStore(shpFile.toURI().toURL()); SimpleFeatureSource source = store.getFeatureSource(); // read the first feature SimpleFeatureIterator iter = source.getFeatures().features(); SimpleFeature feature = iter.next(); iter.close(); // get the value of the duplicate column & compare it against expectation assertEquals(expectedValue, feature.getAttribute(testColumn)); // cleanup store.dispose(); }
@Test public void testWithDateAndBoolean() throws Exception { SimpleFeatureSource source = getFeatureSource(MockData.PRIMITIVEGEOFEATURE); SimpleFeatureCollection fc = source.getFeatures(); SimpleFeatureIterator i = fc.features(); try { SimpleFeature f = (SimpleFeature) i.next(); FeatureTemplate template = new FeatureTemplate(); try { template.description(f); } catch (Exception e) { e.printStackTrace(); fail("template threw exception on null value"); } } finally { i.close(); } }
@Test public void testFeautureSourceFidFilter() throws Exception { // grab the last feature in the collection (there are more than one) SimpleFeatureSource fs = rts.getFeatureSource(RENAMED); // build a filter that will retrieve that feature only FilterFactory ff = CommonFactoryFinder.getFilterFactory(null); final String fid = RENAMED + ".f001"; Filter fidFilter = ff.id(Collections.singleton(ff.featureId(fid))); SimpleFeatureCollection fc = fs.getFeatures(new Query(RENAMED, fidFilter)); assertEquals(RENAMED, fc.getSchema().getName().getLocalPart()); assertEquals(1, fc.size()); FeatureIterator<SimpleFeature> it = fc.features(); assertTrue(it.hasNext()); SimpleFeature sf = it.next(); assertFalse(it.hasNext()); it.close(); assertEquals(fid, sf.getID()); }
public String wfsRequest() { // String getCapabilities = // "http://"+host+":"+port+"/geoserver/"+workspace+"/wfs?REQUEST=GetCapabilities&version=1.0.0"; String getCapabilities = "http://" + host + ":" + port + "/geoserver/" + workspace + "/ows?REQUEST=GetCapabilities&version=1.1.1&service=WFS"; Map connectionParameters = new HashMap(); connectionParameters.put("WFSDataStoreFactory:GET_CAPABILITIES_URL", getCapabilities); connectionParameters.put("WFSDataStoreFactory:USERNAME", "admin"); connectionParameters.put("WFSDataStoreFactory:PASSWORD", "geoserver"); connectionParameters.put("WFSDataStoreFactory:WFS_STRATEGY", "geoserver"); connectionParameters.put("WFSDataStoreFactory:MAXFEATURES", 1000); WFSDataStoreFactory dsf = new WFSDataStoreFactory(); try { // WFS_1_0_0_DataStore wfs = dsf.createDataStore(connectionParameters); WFSDataStore dataStore = dsf.createDataStore(connectionParameters); String[] typeNames = dataStore.getTypeNames(); System.out.println(ArrayUtils.toString(typeNames)); SimpleFeatureSource source = dataStore.getFeatureSource(workspace + ":" + layer); SimpleFeatureCollection fc = source.getFeatures(); StringWriter writer = new StringWriter(); while (fc.features().hasNext()) { SimpleFeature sf = fc.features().next(); System.out.println(sf.getAttribute("myname")); FeatureJSON fjson = new FeatureJSON(); fjson.writeFeature(sf, writer); } String geojson = writer.toString(); return geojson; } catch (IOException ex) { ex.printStackTrace(); } return null; }
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 feature source bounds. Mind, it might be null, in that case, grab the lat/lon bounding box * and reproject to the native bounds. * * @return Envelope the feature source bounds. * @throws Exception */ public ReferencedEnvelope getBoundingBox() throws Exception { if (layerInfo != null) { ResourceInfo resource = layerInfo.getResource(); ReferencedEnvelope bbox = resource.boundingBox(); // if(bbox == null){ // bbox = resource.getLatLonBoundingBox(); // } return bbox; } else if (this.type == TYPE_REMOTE_VECTOR) { return remoteFeatureSource.getBounds(); } return null; }
@Test public void testSingleType() throws IOException, NoSuchElementException { if (url == null) return; WFS_1_0_0_DataStore wfs; try { wfs = WFSDataStoreReadTest.getDataStore(url); } catch (ConnectException e) { e.printStackTrace(System.err); return; } catch (UnknownHostException e) { e.printStackTrace(System.err); return; } catch (NoRouteToHostException e) { e.printStackTrace(System.err); return; } String typeName = "tiger:poi"; SimpleFeatureType type = wfs.getSchema(typeName); type.getTypeName(); type.getName().getNamespaceURI(); SimpleFeatureSource source = wfs.getFeatureSource(typeName); source.getBounds(); SimpleFeatureCollection features = source.getFeatures(); features.getBounds(); features.getSchema(); // features.getFeatureType(); Query query = new Query(typeName, Filter.INCLUDE, 20, Query.ALL_NAMES, "work already"); features = source.getFeatures(query); features.size(); SimpleFeatureIterator iterator = features.features(); while (iterator.hasNext()) { SimpleFeature feature = iterator.next(); } iterator.close(); }
@Override public boolean getCreateFeature(GridElement el) { Coordinate c = ((PolygonElement) el).getCenter(); Geometry p = gf.createPoint(c); Filter filter = ff2.intersects(ff2.property("the_geom"), ff2.literal(p)); boolean result = false; try { result = !source.getFeatures(filter).isEmpty(); } catch (IOException ex) { throw new IllegalStateException(ex); } return result; }
private Id createFidFilter(SimpleFeatureSource fs) throws IOException { SimpleFeatureIterator iter = fs.getFeatures().features(); FilterFactory2 ffac = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints()); Set fids = new HashSet(); try { while (iter.hasNext()) { String id = iter.next().getID(); FeatureId fid = ffac.featureId(id); fids.add(fid); } Id filter = ffac.id(fids); return filter; } finally { iter.close(); } }
@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); }
private void run2(final Network network) throws Exception { log.info("running " + this.getClass().getName() + " module..."); NetworkExpandNode neModule = new NetworkExpandNode(network, expansionRadius, this.linkSeparation); TreeMap<String, TreeMap<Integer, Id<Link>>> mSequences = new TreeMap<>(); try (FileInputStream fis = new FileInputStream(this.mpDbfFileName)) { DbaseFileReader r = new DbaseFileReader(fis.getChannel(), true, IOUtils.CHARSET_WINDOWS_ISO88591); // get header indices int mpIdNameIndex = -1; int mpSeqNrNameIndex = -1; int mpTrpelIDNameIndex = -1; for (int i = 0; i < r.getHeader().getNumFields(); i++) { if (r.getHeader().getFieldName(i).equals(MP_ID_NAME)) { mpIdNameIndex = i; } if (r.getHeader().getFieldName(i).equals(MP_SEQNR_NAME)) { mpSeqNrNameIndex = i; } if (r.getHeader().getFieldName(i).equals(MP_TRPELID_NAME)) { mpTrpelIDNameIndex = i; } } if (mpIdNameIndex < 0) { throw new NoSuchFieldException("Field name '" + MP_ID_NAME + "' not found."); } if (mpSeqNrNameIndex < 0) { throw new NoSuchFieldException("Field name '" + MP_SEQNR_NAME + "' not found."); } if (mpTrpelIDNameIndex < 0) { throw new NoSuchFieldException("Field name '" + MP_TRPELID_NAME + "' not found."); } log.trace(" FieldName-->Index:"); log.trace(" " + MP_ID_NAME + "-->" + mpIdNameIndex); log.trace(" " + MP_SEQNR_NAME + "-->" + mpSeqNrNameIndex); log.trace(" " + MP_TRPELID_NAME + "-->" + mpTrpelIDNameIndex); // create mp data structure // TreeMap<mpId,TreeMap<mpSeqNr,linkId>> log.info(" parsing meneuver paths dbf file..."); while (r.hasNext()) { Object[] entries = r.readEntry(); String mpId = entries[mpIdNameIndex].toString(); int mpSeqNr = Integer.parseInt(entries[mpSeqNrNameIndex].toString()); Id<Link> linkId = Id.create(entries[mpTrpelIDNameIndex].toString(), Link.class); TreeMap<Integer, Id<Link>> mSequence = mSequences.get(mpId); if (mSequence == null) { mSequence = new TreeMap<>(); mSequences.put(mpId, mSequence); } if (mSequence.put(mpSeqNr, linkId) != null) { fis.close(); throw new IllegalArgumentException( MP_ID_NAME + "=" + mpId + ": " + MP_SEQNR_NAME + " " + mpSeqNr + " already exists."); } } log.info(" " + mSequences.size() + " maneuvers sequences stored."); log.info(" done."); r.close(); } // store the maneuver list of the nodes // TreeMap<NodeId,ArrayList<Tuple<MnId,MnFeatType>>> log.info(" parsing meneuver shape file..."); TreeMap<Id<Node>, ArrayList<Tuple<String, Integer>>> maneuvers = new TreeMap<>(); SimpleFeatureSource fs = ShapeFileReader.readDataFile(this.mnShpFileName); SimpleFeatureIterator fIt = fs.getFeatures().features(); while (fIt.hasNext()) { SimpleFeature f = fIt.next(); int featType = Integer.parseInt(f.getAttribute(MN_FEATTYP_NAME).toString()); if ((featType == 2103) || (featType == 2102) || (featType == 2101)) { // keep 'Prohibited Maneuver' (2103), 'Restricted Maneuver' (2102) and 'Calculated/Derived // Prohibited Maneuver' (2101) Id<Node> nodeId = Id.create(f.getAttribute(MN_JNCTID_NAME).toString(), Node.class); ArrayList<Tuple<String, Integer>> ms = maneuvers.get(nodeId); if (ms == null) { ms = new ArrayList<>(); } Tuple<String, Integer> m = new Tuple<>(f.getAttribute(MN_ID_NAME).toString(), featType); ms.add(m); maneuvers.put(nodeId, ms); } else if ((featType == 9401) || (featType == 2104)) { // ignore 'Bifurcation' (9401) and 'Priority Maneuver' (2104) } else { throw new IllegalArgumentException( "mnId=" + f.getAttribute(MN_ID_NAME) + ": " + MN_FEATTYP_NAME + "=" + featType + " not known."); } } fIt.close(); log.info(" " + maneuvers.size() + " nodes with maneuvers stored."); log.info(" done."); // create a maneuver matrix for each given node and // expand those nodes log.info(" expand nodes according to the given manveuvers..."); int nodesIgnoredCnt = 0; int nodesAssignedCnt = 0; int maneuverIgnoredCnt = 0; int maneuverAssignedCnt = 0; int virtualNodesCnt = 0; int virtualLinksCnt = 0; for (Map.Entry<Id<Node>, ArrayList<Tuple<String, Integer>>> entry : maneuvers.entrySet()) { Id<Node> nodeId = entry.getKey(); if (network.getNodes().get(nodeId) == null) { log.trace( " nodeid=" + nodeId + ": maneuvers exist for that node but node is missing. Ignoring and proceeding anyway..."); nodesIgnoredCnt++; } else { // node found Node n = network.getNodes().get(nodeId); // init maneuver matrix // TreeMap<fromLinkId,TreeMap<toLinkId,turnAllowed>> TreeMap<Id<Link>, TreeMap<Id<Link>, Boolean>> mmatrix = new TreeMap<>(); // assign maneuvers for given node to the matrix ArrayList<Tuple<String, Integer>> ms = entry.getValue(); for (Tuple<String, Integer> m : ms) { // get maneuver path sequence for given maneuver TreeMap<Integer, Id<Link>> mSequence = mSequences.get(m.getFirst()); if (mSequence == null) { throw new Exception( "nodeid=" + nodeId + "; mnId=" + m.getFirst() + ": no maneuver sequence given."); } if (mSequence.size() < 2) { throw new Exception( "nodeid=" + nodeId + "; mnId=" + m.getFirst() + ": mSequenceSize=" + mSequence.size() + " not alowed!"); } // get the first element of the sequence, defining the start link for the maneuver Id<Link> firstLinkid = mSequence.values().iterator().next(); // go through each other element (target link of the maneuver) of the sequence by sequence // number for (Id<Link> otherLinkId : mSequence.values()) { // get the start link and the target link of the maneuver Link inLink = n.getInLinks().get(Id.create(firstLinkid + "FT", Link.class)); if (inLink == null) { inLink = n.getInLinks().get(Id.create(firstLinkid + "TF", Link.class)); } Link outLink = n.getOutLinks().get(Id.create(otherLinkId + "FT", Link.class)); if (outLink == null) { outLink = n.getOutLinks().get(Id.create(otherLinkId + "TF", Link.class)); } if ((inLink != null) && (outLink != null)) { // start and target link found and they are incident to the given node if (m.getSecond() == 2102) { // restricted maneuver: given start and target link path is allowed to drive // store it to the matrix TreeMap<Id<Link>, Boolean> outLinkMap = mmatrix.get(inLink.getId()); if (outLinkMap == null) { outLinkMap = new TreeMap<>(); } outLinkMap.put(outLink.getId(), Boolean.TRUE); mmatrix.put(inLink.getId(), outLinkMap); } else { // prohibited maneuver: given start and target link path is not allowed to drive // store it to the matrix TreeMap<Id<Link>, Boolean> outLinkMap = mmatrix.get(inLink.getId()); if (outLinkMap == null) { outLinkMap = new TreeMap<>(); } outLinkMap.put(outLink.getId(), Boolean.FALSE); mmatrix.put(inLink.getId(), outLinkMap); } maneuverAssignedCnt++; } else { maneuverIgnoredCnt++; } } } // complete the matrix for (TreeMap<Id<Link>, Boolean> fromLinkEntry : mmatrix.values()) { // detect inlinks with restricted maneuvers boolean hasRestrictedManeuver = false; for (Boolean b : fromLinkEntry.values()) { if (b) { hasRestrictedManeuver = true; } } // add missing toLink maneuvers for (Id<Link> toLinkId : n.getOutLinks().keySet()) { if (!fromLinkEntry.containsKey(toLinkId)) { fromLinkEntry.put(toLinkId, !hasRestrictedManeuver); } } } // add allowed maneuvers for fromLinks which were not assigned yet. for (Id<Link> fromLinkId : n.getInLinks().keySet()) { if (!mmatrix.containsKey(fromLinkId)) { mmatrix.put(fromLinkId, new TreeMap<Id<Link>, Boolean>()); for (Id<Link> toLinkId : n.getOutLinks().keySet()) { mmatrix.get(fromLinkId).put(toLinkId, Boolean.TRUE); } } } // remove all U-turns from the matrix if (this.removeUTurns) { for (Id<Link> fromLinkId : n.getInLinks().keySet()) { String str1 = fromLinkId.toString().substring(0, fromLinkId.toString().length() - 2); for (Id<Link> toLinkId : n.getOutLinks().keySet()) { String str2 = toLinkId.toString().substring(0, toLinkId.toString().length() - 2); if (str1.equals(str2)) { mmatrix.get(fromLinkId).put(toLinkId, Boolean.FALSE); } } } } // create arraylist with turn tuples ArrayList<TurnInfo> turns = new ArrayList<>(); for (Map.Entry<Id<Link>, TreeMap<Id<Link>, Boolean>> fromLinkEntry : mmatrix.entrySet()) { Id<Link> fromLinkId = fromLinkEntry.getKey(); for (Map.Entry<Id<Link>, Boolean> toLinkEntry : fromLinkEntry.getValue().entrySet()) { if (toLinkEntry.getValue()) { turns.add(new TurnInfo(fromLinkId, toLinkEntry.getKey())); } } } // expand the node Tuple<List<Node>, List<Link>> t = neModule.expandNode(nodeId, turns); virtualNodesCnt += t.getFirst().size(); virtualLinksCnt += t.getSecond().size(); nodesAssignedCnt++; } } log.info(" " + nodesAssignedCnt + " nodes expanded."); log.info(" " + maneuverAssignedCnt + " maneuvers assigned."); log.info(" " + virtualNodesCnt + " new nodes created."); log.info(" " + virtualLinksCnt + " new links created."); log.info( " " + nodesIgnoredCnt + " nodes with given maneuvers (2103, 2102 or 2101) ignored."); log.info(" " + maneuverIgnoredCnt + " maneuvers ignored (while node was found)."); log.info(" done."); log.info("done."); }
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"); }