/**
  * Test that point features are rendered at the expected image coordinates when the map is
  * rotated. StreamingRenderer
  *
  * @throws Exception
  */
 @Test
 public void testRotatedTransform() throws Exception {
   // If we rotate the world rectangle + 90 degrees around (0,0), we get the screen rectangle
   final Rectangle screen = new Rectangle(0, 0, 100, 50);
   final Envelope world = new Envelope(0, 50, 0, -100);
   final AffineTransform worldToScreen =
       AffineTransform.getRotateInstance(Math.toRadians(90), 0, 0);
   DefaultFeatureCollection fc = new DefaultFeatureCollection();
   fc.add(createPoint(0, 0));
   fc.add(createPoint(world.getMaxX(), world.getMinY()));
   MapContext mapContext = new DefaultMapContext(DefaultGeographicCRS.WGS84);
   mapContext.addLayer((FeatureCollection) fc, createPointStyle());
   BufferedImage image =
       new BufferedImage(screen.width, screen.height, BufferedImage.TYPE_4BYTE_ABGR);
   final StreamingRenderer sr = new StreamingRenderer();
   sr.setContext(mapContext);
   sr.paint(image.createGraphics(), screen, worldToScreen);
   assertTrue("Pixel should be drawn at 0,0 ", image.getRGB(0, 0) != 0);
   assertTrue(
       "Pixel should not be drawn in image centre ",
       image.getRGB(screen.width / 2, screen.height / 2) == 0);
   assertTrue(
       "Pixel should be drawn at image max corner ",
       image.getRGB(screen.width - 1, screen.height - 1) != 0);
 }
  @SuppressWarnings("unchecked")
  public void createMapFor(
      final CoordinateReferenceSystem crs,
      final com.vividsolutions.jts.geom.Envelope areaOfInterest,
      final Graphics2D graphics)
      throws IOException {

    Geometry geographicBoundingBox = getGeographicBoundingBox(crs);
    MapContext mapContext = getMapContext(crs, geographicBoundingBox, areaOfInterest);

    graphics.setColor(new Color(153, 179, 204));
    graphics.fillRect(0, 0, mapWidth, mapHeight);

    Rectangle paintArea = new Rectangle(mapWidth, mapHeight);

    mapContext.setAreaOfInterest(areaOfInterest, crs);

    GTRenderer renderer = new StreamingRenderer();
    renderer.setContext(mapContext);
    RenderingHints hints =
        new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    renderer.setJava2DHints(hints);

    Map renderingHints = new HashMap();
    renderingHints.put("optimizedDataLoadingEnabled", Boolean.TRUE);
    renderingHints.put(StreamingRenderer.ADVANCED_PROJECTION_HANDLING_KEY, Boolean.TRUE);
    renderingHints.put(StreamingRenderer.CONTINUOUS_MAP_WRAPPING, Boolean.TRUE);
    renderer.setRendererHints(renderingHints);
    renderer.paint(graphics, paintArea, areaOfInterest);
  }
  public void testSkipProjectionErrors() throws Exception {
    // build map context
    MapContext mapContext = new DefaultMapContext(DefaultGeographicCRS.WGS84);
    mapContext.addLayer(createLineCollection(), createLineStyle());

    // build projected envelope to work with (small one around the area of
    // validity of utm zone 1, which being a Gauss projection is a vertical
    // slice parallel to the central meridian, -177°)
    ReferencedEnvelope reWgs =
        new ReferencedEnvelope(new Envelope(-180, -170, 20, 40), DefaultGeographicCRS.WGS84);
    CoordinateReferenceSystem utm1N = CRS.decode("EPSG:32601");
    System.out.println(CRS.getGeographicBoundingBox(utm1N));
    ReferencedEnvelope reUtm = reWgs.transform(utm1N, true);

    BufferedImage image = new BufferedImage(200, 200, BufferedImage.TYPE_4BYTE_ABGR);

    // setup the renderer and listen for errors
    StreamingRenderer sr = new StreamingRenderer();
    sr.setRendererHints(Collections.singletonMap(sr.OPTIMIZED_DATA_LOADING_KEY, Boolean.FALSE));
    sr.setContext(mapContext);
    sr.addRenderListener(
        new RenderListener() {
          public void featureRenderer(SimpleFeature feature) {}

          public void errorOccurred(Exception e) {
            e.printStackTrace();
            errors++;
          }
        });
    errors = 0;
    sr.paint((Graphics2D) image.getGraphics(), new Rectangle(200, 200), reUtm);
    // we should get two errors since there are two features that cannot be
    // projected but the renderer itself should not throw exceptions
    assertEquals(2, errors);
  }
  public void handleAction(final FlowModel flowModel) throws OgcFlowException {

    WFSLayer wfsLayer = findWFSLayer(flowModel);
    log.debug("Drawing image for wfs layer '" + wfsLayer.getName(locale) + "'");
    List<Future<WFSResponseCapsule>> futures = new ArrayList<Future<WFSResponseCapsule>>();
    /* Create workers */
    log.debug("We have " + wfsLayer.getSelectedFeatureTypes().size() + " selected feature types");
    for (SelectedFeatureType sft : wfsLayer.getSelectedFeatureTypes()) {
      FeatureType ft = sft.getFeatureType();
      log.debug("Processing featuretype '", ft.getTitle(locale), "'...");

      /* Create filter */
      String geomName = ft.getBboxParameterName();
      FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints());

      GetFeaturesWorker worker =
          new GetFeaturesWorker(sft, getExtendedMapViewBbox(ff, geomName, flowModel), false);
      Future<WFSResponseCapsule> future = WfsExecutorService.schedule(worker);
      futures.add(future);
    }

    /* collect results */
    FeatureCollection<SimpleFeatureType, SimpleFeature> features =
        WfsExecutorService.collectFeaturesFromFutures(futures);
    String[] bbox = getBbox(flowModel);
    Double bboxMinX = Double.parseDouble(bbox[0]);
    Double bboxMinY = Double.parseDouble(bbox[1]);
    Double bboxMaxX = Double.parseDouble(bbox[2]);
    Double bboxMaxY = Double.parseDouble(bbox[3]);

    MapContext mapContext = buildMapContext();
    ReferencedEnvelope bounds =
        new ReferencedEnvelope(
            bboxMaxX, bboxMinX, bboxMaxY, bboxMinY, mapContext.getCoordinateReferenceSystem());

    /* Add all found features */
    if (features != null && features.size() > 0) {
      log.debug("Parsing found " + features.size() + " features.");
      String styleString = wfsLayer.getStyle();

      // TODO: sld styles should be stored in the database
      if (styleString == null || "".equals(styleString)) {
        styleString =
            SLDStore.getSLD(
                wfsLayer
                    .getWmsName()); // MapLayerServiceNoDbImpl.getSldStyle(wfsLayer.getWmsName());
      }

      Style style = SLD.styles(createSLDStyle(styleString))[0];
      mapContext.addLayer(features, style);
    } else {
      log.debug("Parsing found no features.");
    }

    BufferedImage image = renderImageFromFeatures(flowModel, mapContext, bounds);
    /*image.getGraphics().setColor(new Color(1f, 0, 0));
    image.getGraphics().drawRect(1, 1, image.getWidth()-1, image.getHeight()-1);*/
    flowModel.put("image", image);
  }
Beispiel #5
0
  /**
   * This method connects to the shapefile; retrieves information about its features; creates a map
   * frame to display the shapefile and adds a custom feature selection tool to the toolbar of the
   * map frame.
   */
  public void displayShapefile(File file) throws Exception {
    FileDataStore store = FileDataStoreFinder.getDataStore(file);
    featureSource = store.getFeatureSource();
    setGeometry();

    /*
     * Create the JMapFrame and set it to display the shapefile's features
     * with a default line and colour style
     */
    MapContext map = new DefaultMapContext();
    map.setTitle("Feature selection tool example");
    Style style = createDefaultStyle();
    map.addLayer(featureSource, style);
    mapFrame = new JMapFrame(map);
    mapFrame.enableToolBar(true);
    mapFrame.enableStatusBar(true);

    /*
     * Before making the map frame visible we add a new button to its
     * toolbar for our custom feature selection tool
     */
    JToolBar toolBar = mapFrame.getToolBar();
    JButton btn = new JButton("Select");
    toolBar.addSeparator();
    toolBar.add(btn);

    /*
     * When the user clicks the button we want to enable
     * our custom feature selection tool. Since the only
     * mouse action we are intersted in is 'clicked', and
     * we are not creating control icons or cursors here,
     * we can just create our tool as an anonymous sub-class
     * of CursorTool.
     */
    btn.addActionListener(
        new ActionListener() {

          public void actionPerformed(ActionEvent e) {
            mapFrame
                .getMapPane()
                .setCursorTool(
                    new CursorTool() {

                      @Override
                      public void onMouseClicked(MapMouseEvent ev) {
                        selectFeatures(ev);
                      }
                    });
          }
        });

    /** Finally, we display the map frame. When it is closed this application will exit. */
    mapFrame.setSize(600, 600);
    mapFrame.setVisible(true);
  }
  public MapContext buildContext() {
    RandomStyleFactory RANDOM_STYLE_FACTORY = new RandomStyleFactory();

    MapContext context = null;
    MapLayer layer;

    try {
      context = new DefaultMapContext(DefaultGeographicCRS.WGS84);
      DataStore store =
          DataStoreFinder.getDataStore(
              new SingletonMap(
                  "url",
                  Demo_ContextTree.class.getResource(
                      "/org/geotools/gui/swing/demo/shape/test_polygon.shp")));
      FeatureSource<SimpleFeatureType, SimpleFeature> fs =
          store.getFeatureSource(store.getTypeNames()[0]);
      Style style = RANDOM_STYLE_FACTORY.createRandomVectorStyle(fs);
      layer = new DefaultMapLayer(fs, style);
      layer.setTitle("demo_polygon.shp");
      context.addLayer(layer);

      store =
          DataStoreFinder.getDataStore(
              new SingletonMap(
                  "url",
                  Demo_ContextTree.class.getResource(
                      "/org/geotools/gui/swing/demo/shape/test_ligne.shp")));
      fs = store.getFeatureSource(store.getTypeNames()[0]);
      style = RANDOM_STYLE_FACTORY.createRandomVectorStyle(fs);
      layer = new DefaultMapLayer(fs, style);
      layer.setTitle("demo_line.shp");
      context.addLayer(layer);

      store =
          DataStoreFinder.getDataStore(
              new SingletonMap(
                  "url",
                  Demo_ContextTree.class.getResource(
                      "/org/geotools/gui/swing/demo/shape/test_point.shp")));
      fs = store.getFeatureSource(store.getTypeNames()[0]);
      style = RANDOM_STYLE_FACTORY.createRandomVectorStyle(fs);
      layer = new DefaultMapLayer(fs, style);
      layer.setTitle("demo_point.shp");
      context.addLayer(layer);
      context.setTitle("DemoContext");
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return context;
  }
 public void testPolyLabeling() throws Exception {
   FeatureCollection collection = createPolyFeatureCollection();
   Style style = loadStyle("PolyStyle.sld");
   assertNotNull(style);
   MapContext map = new DefaultMapContext(DefaultGeographicCRS.WGS84);
   map.addLayer(collection, style);
   StreamingRenderer renderer = new StreamingRenderer();
   renderer.setContext(map);
   ReferencedEnvelope env = map.getLayerBounds();
   int boundary = 10;
   env =
       new ReferencedEnvelope(
           env.getMinX() - boundary,
           env.getMaxX() + boundary,
           env.getMinY() - boundary,
           env.getMaxY() + boundary,
           null);
   RendererBaseTest.showRender("testPolyLabeling", renderer, timout, env);
 }
Beispiel #8
0
  public void run() {
    Display display = Display.getCurrent();
    Shell shell = new Shell(display);
    File openFile = JFileImageChooser.showOpenFile(shell);

    if (openFile != null && openFile.exists()) {
      AbstractGridFormat format = GridFormatFinder.findFormat(openFile);
      AbstractGridCoverage2DReader tiffReader = format.getReader(openFile);
      StyleFactoryImpl sf = new StyleFactoryImpl();
      RasterSymbolizer symbolizer = sf.getDefaultRasterSymbolizer();
      Style defaultStyle = SLD.wrapSymbolizers(symbolizer);

      MapContext mapContext = mapPane.getMapContext();
      MapLayer layer = new MapLayer(tiffReader, defaultStyle);
      layer.setTitle(openFile.getName());
      mapContext.addLayer(layer);
      mapPane.redraw();
    }
  }
  @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);
  }