@SuppressWarnings("unchecked")
 private FeatureStore<SimpleFeatureType, SimpleFeature> getResource(ILayer editLayer)
     throws IOException {
   FeatureStore<SimpleFeatureType, SimpleFeature> store =
       editLayer.getResource(FeatureStore.class, null);
   return store;
 }
Esempio n. 2
0
  public void rollback(IProgressMonitor monitor) throws Exception {
    editBlackboard.removeGeometries(Collections.singleton(first));

    EditGeom newGeom =
        editBlackboard.newGeom(
            oldshape.getEditGeom().getFeatureIDRef().get(), oldshape.getEditGeom().getShapeType());

    for (int i = 0; i < oldshape.getNumCoords(); i++) {
      editBlackboard.addCoordinate(oldshape.getCoord(i), newGeom.getShell());
    }

    if (currentShapeSet) setCurrentShape(newGeom.getShell());

    FeatureStore<SimpleFeatureType, SimpleFeature> store =
        layer.getResource(FeatureStore.class, new SubProgressMonitor(monitor, 1));

    FilterFactory factory = CommonFactoryFinder.getFilterFactory(GeoTools.getDefaultHints());
    Set<FeatureId> ids = new HashSet<FeatureId>();
    for (FeatureId id : newFids) {
      ids.add(id);
    }
    Id filter = factory.id(ids);

    store.removeFeatures(filter);
    Geometry oldType = (Geometry) oldFeature.getDefaultGeometry();
    GeometryDescriptor newType = store.getSchema().getGeometryDescriptor();
    store.modifyFeatures(
        newType, oldType, factory.id(FeatureUtils.stringToId(factory, oldFeature.getID())));
    oldFeature.setDefaultGeometry(oldGeometry);
    newFids.clear();
  }
  private List<Layer> getWMSLayers() throws IOException {
    List<Layer> layers = new ArrayList<Layer>();

    for (ILayer iLayer : getLayers()) {
      Layer layer = iLayer.getResource(Layer.class, null);
      layers.add(layer);
    }

    return layers;
  }
Esempio n. 4
0
  public void run(IProgressMonitor monitor) throws Exception {
    editBlackboard.startBatchingEvents();

    oldshape = shapeProvider.get(new SubProgressMonitor(monitor, 1));
    oldFeature = featureProvider.get(new SubProgressMonitor(monitor, 1));
    oldGeometry = (Geometry) oldFeature.getDefaultGeometry();
    layer = layerProvider.get(new SubProgressMonitor(monitor, 1));

    editBlackboard.removeGeometries(Collections.singleton(oldshape.getEditGeom()));
    ShapeType shapeType = oldshape.getEditGeom().getShapeType();
    EditGeom current =
        editBlackboard.newGeom(oldshape.getEditGeom().getFeatureIDRef().get(), shapeType);
    first = current;

    final Set<EditGeom> addedGeoms = new HashSet<EditGeom>();
    for (int i = 0; i < oldshape.getNumPoints(); i++) {
      addCoords(current.getShell(), i);
      if (current.getShell().getNumPoints() > 1
          && i < oldshape.getNumPoints() - 1
          && points.contains(oldshape.getPoint(i))) {

        current =
            editBlackboard.newGeom(
                "newFeature" + System.currentTimeMillis(), shapeType); // $NON-NLS-1$
        List<Coordinate> coords = oldshape.getCoordsAt(i);
        editBlackboard.addCoordinate(coords.get(coords.size() - 1), current.getShell());
        addedGeoms.add(current);
      }
    }

    editBlackboard.removeGeometries(addedGeoms);

    if (getCurrentShape() == oldshape) {
      currentShapeSet = true;
      setCurrentShape(first.getShell());
    }

    final FeatureStore<SimpleFeatureType, SimpleFeature> store =
        layer.getResource(FeatureStore.class, new SubProgressMonitor(monitor, 1));

    modifyOldFeature(store);

    createAndAddFeatures(addedGeoms, store);

    editBlackboard.fireBatchedEvents();
  }
  private static void writeFeatureType(ILayer layer, BufferedWriter out) throws IOException {
    WFSDataStore wfs = (WFSDataStore) layer.getResource(WFSDataStore.class, null);
    SimpleFeatureType type = layer.getSchema();
    String typeName = type.getName().getLocalPart();

    int hidden = layer.isVisible() ? 1 : 0;
    ServiceInfo serviceInfo = wfs.getInfo();
    String title = serviceInfo.getTitle();
    String version = "1.0.0"; // only known entry at this time //$NON-NLS-1$
    URI source = serviceInfo.getSource();
    String get = source == null ? "" : source.toString();

    ResourceInfo resourceInfo = wfs.getFeatureSource(typeName).getInfo();
    append(4, out, "<SimpleFeatureType hidden=\"" + hidden + "\">"); // $NON-NLS-1$ //$NON-NLS-2$
    append(
        6,
        out,
        "<Server service=\"OGC:WFS\" title=\""
            + title
            + "\" version=\""
            + version
            + "\">"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    append(
        8,
        out,
        "<OnlineResource method=\"GET\" xlink:href=\""
            + get
            + "\" xlink:type=\"simple\"/>"); //$NON-NLS-1$ //$NON-NLS-2$
    append(6, out, "</Server>"); // $NON-NLS-1$
    append(6, out, "<Name>" + typeName + "</Name>"); // $NON-NLS-1$ //$NON-NLS-2$
    append(6, out, "<Title>" + resourceInfo.getTitle() + "</Title>"); // $NON-NLS-1$ //$NON-NLS-2$
    // if( !Double.isNaN( layer.getMinScaleDenominator() ))
    //        append( 6, out,
    // "<sld:MinScaleDenominator>"+layer.getMinScaleDenominator()+"</sld:MinScaleDenominator>");
    // if( !Double.isNaN( layer.getMaxScaleDenominator() ))
    //        append( 6, out,
    // "<sld:MinScaleDenominator>"+layer.getMaxScaleDenominator()+"</sld:MinScaleDenominator>");
    String SRS = "EPSG:4326";
    CoordinateReferenceSystem crs = resourceInfo.getCRS();
    // TODO: anyone knows how to get the urn for the crs object?
    append(6, out, "<SRS>" + SRS + "</SRS>"); // $NON-NLS-1$ //$NON-NLS-2$
    append(4, out, "</SimpleFeatureType>"); // $NON-NLS-1$
  }
Esempio n. 6
0
  public static List<SimpleFeature> fromFeatureLayer(String mapName) throws IOException {

    ILayer selectedLayer = ApplicationGIS.getActiveMap().getEditManager().getSelectedLayer();
    FeatureSource<SimpleFeatureType, SimpleFeature> featureSource =
        selectedLayer.getResource(FeatureSource.class, new NullProgressMonitor());
    FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection = null;
    Filter filter = selectedLayer.getFilter();
    if (filter.equals(Filter.EXCLUDE)) {
      featureCollection = featureSource.getFeatures();
    } else {
      featureCollection = featureSource.getFeatures(filter);
    }

    List<SimpleFeature> featuresList = new ArrayList<SimpleFeature>();
    FeatureIterator<SimpleFeature> featureIterator = featureCollection.features();
    while (featureIterator.hasNext()) {
      SimpleFeature feature = featureIterator.next();
      featuresList.add(feature);
    }
    featureCollection.close(featureIterator);

    return featuresList;
  }
  public void run(IProgressMonitor monitor) throws Exception {
    monitor.beginTask(Messages.AddFeaturesCommand_taskMessage, 10);
    monitor.worked(1);

    FeatureStore<SimpleFeatureType, SimpleFeature> store =
        layer.getResource(FeatureStore.class, new SubProgressMonitor(monitor, 2));
    String geomAttributeName = layer.getSchema().getGeometryDescriptor().getLocalName();
    String[] desiredProperties = new String[] {geomAttributeName};
    Query query = new DefaultQuery(layer.getSchema().getTypeName(), filter, desiredProperties);
    FeatureCollection<SimpleFeatureType, SimpleFeature> features = store.getFeatures(query);

    FeatureIterator<SimpleFeature> iter = features.features();
    try {
      commands = new ArrayList<UndoableMapCommand>();
      while (iter.hasNext()) {
        SimpleFeature feature = iter.next();
        commands.add(new SelectFeatureCommand(bb, feature));
      }

      float index = 0;
      float inc = (float) 7 / commands.size();
      for (UndoableMapCommand command : commands) {
        command.setMap(getMap());
        index += inc;
        SubProgressMonitor subProgressMonitor = new SubProgressMonitor(monitor, (int) index);
        command.run(subProgressMonitor);
        subProgressMonitor.done();
        if (index > 1) {
          index = 0;
        }
      }
    } finally {
      features.close(iter);
    }

    monitor.done();
  }
  public synchronized void render(
      Graphics2D destination, ReferencedEnvelope bounds, IProgressMonitor monitor)
      throws RenderException {

    int endLayerStatus = ILayer.DONE;
    try {
      if (bounds == null || bounds.isNull()) {
        bounds = getContext().getImageBounds();
      }

      if (monitor.isCanceled()) return;

      getContext().setStatus(ILayer.WAIT);

      WebMapServer wms = getWMS();

      GetMapRequest request = wms.createGetMapRequest();

      // put in default exception format we understand as a client
      // (if suppoted by the server)
      WMSCapabilities capabilities = wms.getCapabilities();
      if (capabilities
          .getRequest()
          .getGetMap()
          .getFormats()
          .contains(GetMapRequest.EXCEPTION_XML)) {
        request.setExceptions(GetMapRequest.EXCEPTION_XML);
      }
      setImageFormat(wms, request);

      if (monitor.isCanceled()) return;

      double currScale = getContext().getViewportModel().getScaleDenominator();
      List<ILayer> layers = getLayers();
      for (int i = layers.size() - 1; i >= 0; i--) {
        ILayer ilayer = layers.get(i);
        Layer layer;
        double minScale = 0;
        double maxScale = Double.MAX_VALUE;
        layer = ilayer.getResource(org.geotools.data.ows.Layer.class, null);
        // check if there are min/max scale rules
        StyleBlackboard sb = (StyleBlackboard) ilayer.getStyleBlackboard();
        Style style = (Style) sb.lookup(Style.class);
        if (style != null) {
          Rule rule = style.getFeatureTypeStyles()[0].getRules()[0];
          minScale = rule.getMinScaleDenominator();
          maxScale = rule.getMaxScaleDenominator();
        }

        if (currScale >= minScale && currScale <= maxScale) {
          // check for a wms style
          StyleImpl wmsStyle =
              (StyleImpl) ilayer.getStyleBlackboard().get(WMSStyleContent.WMSSTYLE);
          if (wmsStyle != null) {
            request.addLayer(layer, wmsStyle);
          } else {
            request.addLayer(layer);
          }
        }
      }

      if (monitor.isCanceled()) return;

      List<Layer> wmsLayers = getWMSLayers();
      if (wmsLayers == null || wmsLayers.isEmpty()) {
        endLayerStatus = ILayer.WARNING;
        return;
      }

      // figure out request CRS
      String requestCRScode = findRequestCRS(wmsLayers, getViewportCRS(), getContext().getMap());
      // TODO: make findRequestCRS more efficient (we are running CRS.decode at *least* twice)
      CoordinateReferenceSystem requestCRS = CRS.decode(requestCRScode);

      // figure out viewport
      //            ReferencedEnvelope viewport;
      //            Envelope viewportBBox = getViewportBBox();
      //            CoordinateReferenceSystem viewportCRS = getViewportCRS();
      //            if (viewportBBox == null) {
      //                // change viewport to world
      //                viewportBBox = new Envelope(-180, 180, -90, 90);
      //                if (!DefaultGeographicCRS.WGS84.equals(viewportCRS)) { // reproject
      //                    viewport = new ReferencedEnvelope(viewportBBox,
      // DefaultGeographicCRS.WGS84);
      //                    viewportBBox = viewport.transform(viewportCRS, true);
      //                }
      //            }

      ReferencedEnvelope requestBBox = null;
      Envelope backprojectedBBox = null; // request bbox projected to the viewport crs
      //            viewport = new ReferencedEnvelope(viewportBBox, viewportCRS);
      //            requestBBox = calculateRequestBBox(wmsLayers, viewport, requestCRS);

      requestBBox = calculateRequestBBox(wmsLayers, bounds, requestCRS, capabilities.getVersion());

      // check that a request is needed (not out of a bounds, invalid, etc)
      if (requestBBox == NILL_BOX) {
        endLayerStatus = ILayer.WARNING;
        return;
      }
      assert requestBBox.getCoordinateReferenceSystem().equals(requestCRS);

      if (requestBBox.getCoordinateReferenceSystem().equals(getViewportCRS())) {
        backprojectedBBox = (Envelope) requestBBox;
      } else {
        backprojectedBBox = (Envelope) requestBBox.transform(getViewportCRS(), true);
      }

      if (WMSPlugin.isDebugging(Trace.RENDER)) {
        WMSPlugin.trace("Viewport CRS: " + getViewportCRS().getName()); // $NON-NLS-1$
        WMSPlugin.trace("Request CRS: " + requestCRS.getName()); // $NON-NLS-1$
        WMSPlugin.trace("Context Image bounds: " + getContext().getImageBounds()); // $NON-NLS-1$
        WMSPlugin.trace("Request BBox  bounds: " + requestBBox); // $NON-NLS-1$
        WMSPlugin.trace("Backprojected request bounds: " + backprojectedBBox); // $NON-NLS-1$
      }

      Service wmsService = capabilities.getService();
      Dimension maxDimensions = new Dimension(wmsService.getMaxWidth(), wmsService.getMaxHeight());
      //            Dimension imageDimensions =
      // calculateImageDimensions(getContext().getMapDisplay()
      //                    .getDisplaySize(), maxDimensions, getViewportBBox(), backprojectedBBox);
      Dimension imageDimensions =
          calculateImageDimensions(
              getContext().getImageSize(), maxDimensions, bounds, backprojectedBBox);
      if (imageDimensions.height < 1 || imageDimensions.width < 1) {
        endLayerStatus = ILayer.WARNING;
        return;
      }
      request.setDimensions(
          imageDimensions.width + "", imageDimensions.height + ""); // $NON-NLS-1$ //$NON-NLS-2$
      // epsg could be under identifiers or authority.
      Set<ReferenceIdentifier> identifiers = requestCRS.getIdentifiers();
      String srs = identifiers.isEmpty() ? EPSG_4326 : identifiers.iterator().next().toString();
      request.setSRS(srs); // EPSG_4326
      request.setBBox(requestBBox);
      // request.setBBox(requestBBox.getMinX() + "," + requestBBox.getMinY()+ "," +
      // requestBBox.getMaxX()+ "," + requestBBox.getMaxY());

      if (monitor.isCanceled()) return;

      setFilter(wms, request);

      // request.setProperty("DACS_ACS", null);
      BufferedImage image = readImage(wms, request, monitor);

      if (monitor.isCanceled()) return;

      if (image == null) {
        Exception e = new RuntimeException(Messages.BasicWMSRenderer2_unable_to_decode_image);
        throw wrapException(e);
      }

      // backprojectedBBox or viewportBBox
      renderGridCoverage(destination, backprojectedBBox, imageDimensions, requestBBox, image);

    } catch (Exception e) {
      if (e instanceof RenderException) throw (RenderException) e;
      throw new RenderException(e);
    } finally {
      getContext().setStatus(endLayerStatus);
      if (endLayerStatus == ILayer.DONE) {
        // clear the status message (rendering was successful)
        getContext().setStatusMessage(null);
      }
    }
  }
  private static void writeLayer(ILayer layer, BufferedWriter out) throws IOException {
    Layer wmsLayer = layer.getResource(Layer.class, null);
    WebMapServer wms = layer.getResource(WebMapServer.class, null);
    WMSCapabilities caps = wms.getCapabilities();
    String version = caps.getVersion();

    String title = wms.getCapabilities().getService().getTitle();
    int hidden = layer.isVisible() ? 1 : 0;
    int info = layer.isApplicable("info") ? 1 : 0; // $NON-NLS-1$
    String get = caps.getRequest().getGetCapabilities().getGet().toExternalForm();
    System.out.println(get);
    if (get.endsWith("&")) get = get.substring(0, get.length() - 1); // $NON-NLS-1$
    append(
        4,
        out,
        "<Layer hidden=\""
            + hidden
            + "\" queryable=\""
            + info
            + "\">"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    append(
        6,
        out,
        "<Server service=\"OGC:WMS\" title=\""
            + title
            + "\" version=\""
            + version
            + "\">"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    append(
        8,
        out,
        "<OnlineResource method=\"GET\" xlink:href=\""
            + get
            + "\" xlink:type=\"simple\"/>"); //$NON-NLS-1$ //$NON-NLS-2$
    append(6, out, "</Server>"); // $NON-NLS-1$
    append(6, out, "<Name>" + wmsLayer.getName() + "</Name>"); // $NON-NLS-1$ //$NON-NLS-2$
    append(6, out, "<Title>" + wmsLayer.getTitle() + "</Title>"); // $NON-NLS-1$ //$NON-NLS-2$
    if (!Double.isNaN(wmsLayer.getScaleHintMin()))
      append(
          6,
          out,
          "<sld:MinScaleDenominator>"
              + wmsLayer.getScaleHintMin()
              + "</sld:MinScaleDenominator>"); //$NON-NLS-1$ //$NON-NLS-2$
    if (!Double.isNaN(wmsLayer.getScaleHintMax()))
      append(
          6,
          out,
          "<sld:MaxScaleDenominator>"
              + wmsLayer.getScaleHintMax()
              + "</sld:MaxScaleDenominator>"); //$NON-NLS-1$ //$NON-NLS-2$
    for (String srs : (Set<String>) wmsLayer.getSrs()) {
      append(6, out, "<SRS>" + srs + "</SRS>"); // $NON-NLS-1$ //$NON-NLS-2$
    }
    append(6, out, "<FormatList>"); // $NON-NLS-1$

    boolean first = true; // TODO: look up preferences?
    for (String format : caps.getRequest().getGetMap().getFormats()) {
      if (first) {
        append(
            8, out, "<Format current=\"1\">" + format + "</Format>"); // $NON-NLS-1$ //$NON-NLS-2$
        first = false;
      }
      append(8, out, "<Format>" + format + "</Format>"); // $NON-NLS-1$ //$NON-NLS-2$
    }
    append(6, out, "</FormatList>"); // $NON-NLS-1$

    first = true; // TODO: look up on styleblackboard?
    append(6, out, "<StyleList>"); // $NON-NLS-1$
    Object styles = wmsLayer.getStyles();
    List list;
    if (styles instanceof String) list = Collections.singletonList(styles);
    else if (styles instanceof List) list = (List) styles;
    else list = Collections.emptyList();
    for (Iterator<Object> iter = list.iterator(); iter.hasNext(); ) {
      Object next = iter.next();
      if (next instanceof String) {
        String style = (String) next;
        first = writeStyle(style, style, first, out);
      } else if (next instanceof StyleImpl) {
        StyleImpl style = (StyleImpl) next;
        writeStyle(style.getName(), style.getTitle().toString(), first, out);
      }
    }
    append(6, out, "</StyleList>"); // $NON-NLS-1$
    append(4, out, "</Layer>"); // $NON-NLS-1$
  }
  /**
   * @see
   *     net.refractions.udig.project.ui.tool.AbstractTool#mousePressed(net.refractions.udig.project.render.displayAdapter.MapMouseEvent)
   */
  public void mousePressed(MapMouseEvent e) {
    // validate the mouse click (only left mouse clicks should work for dragging)
    if (!validModifierButtonCombo(e)) {
      return;
    }

    // set the active objects and also force a redraw of
    // the composed map image before panning so that we can
    // remove the placemarker being dragged
    List<ILayer> mapLayers = getContext().getMap().getMapLayers();
    Iterator<ILayer> iterator = mapLayers.iterator();
    while (iterator.hasNext()) {
      ILayer layer = iterator.next();
      GeoReferenceMapGraphic mapGraphic;
      try {
        mapGraphic = layer.getResource(GeoReferenceMapGraphic.class, null);
        if (mapGraphic != null) {
          activeMapGraphic = mapGraphic;
          GlassPane glass = getContext().getViewportPane().getGlass();
          if (glass instanceof GeoReferenceGlassPane) {
            activeGlassPane = (GeoReferenceGlassPane) glass;
          }
          layer.refresh(null); // refresh to ensure the selected graphic disappears
          break;
        }
      } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }
    }

    // determine if the user clicked on a placemarker or not. If multiple
    // placemarkers are clicked on, choose the closest one to the click
    draggingPlaceMarker = null;
    if (activeMapGraphic != null) {
      Point point = e.getPoint();
      List<PlaceMarker> imageMarkers = activeMapGraphic.getImageMarkers();
      List<PlaceMarker> basemapMarkers = activeMapGraphic.getBasemapMarkers();
      if (imageMarkers == null || imageMarkers.size() < 1) {
        return;
      }
      double currentdistance = PlaceMarker.DRAWING_SIZE + 1;
      for (PlaceMarker marker : imageMarkers) {
        Point markerPoint = marker.getPoint();
        if (markerPoint != null) {
          double distance = point.distance(markerPoint.x, markerPoint.y);
          if (distance <= PlaceMarker.DRAWING_SIZE && distance < currentdistance) {
            draggingPlaceMarker = marker;
            currentdistance = distance;
          }
        }
      }

      // check basemap markers if we haven't matched one yet
      if (draggingPlaceMarker == null && basemapMarkers != null) {
        for (PlaceMarker marker : basemapMarkers) {
          // compare the map coordinate not the screen point since
          // the screen point could be out of whack if the user
          // panned/zoomed the map
          Coordinate markerCoord = marker.getCoord();
          if (markerCoord != null) {
            Point markerPoint = getContext().worldToPixel(markerCoord);
            if (markerPoint != null) {
              double distance = point.distance(markerPoint.x, markerPoint.y);
              if (distance <= PlaceMarker.DRAWING_SIZE && distance < currentdistance) {
                draggingPlaceMarker = marker;
                currentdistance = distance;
              }
            }
          }
        }
      }
    }

    // did we find a marker?
    if (draggingPlaceMarker == null) {
      return;
    }

    // marker found, set dragging vars
    dragging = true;
    draggingPlaceMarker.setDragging(true);
    mouseStart = e.getPoint();
    if (activeGlassPane != null && draggingPlaceMarker != null) {
      Point point = null;
      if (draggingPlaceMarker.isBasemapMarker() && draggingPlaceMarker.getCoord() != null) {
        point = getContext().worldToPixel(draggingPlaceMarker.getCoord());
      } else {
        point = draggingPlaceMarker.getPoint();
      }
      activeGlassPane.startDraggingMarker(draggingPlaceMarker, point.x, point.y);
    }
  }
  @SuppressWarnings("unchecked")
  private void copyFeatures(
      ILayer sourceLayer, Filter filter, final Layer targetLayer, final IProgressMonitor monitor) {
    monitor.beginTask(Messages.CopyFeaturesCommand_name, 104);
    final int[] worked = new int[] {-3};
    monitor.worked(1);
    try {
      SubProgressMonitor subProgressMonitor = new SubProgressMonitor(monitor, 2);
      FeatureStore<SimpleFeatureType, SimpleFeature> destination =
          targetLayer.getResource(FeatureStore.class, subProgressMonitor);
      subProgressMonitor.done();
      worked[0] += 2;
      subProgressMonitor = new SubProgressMonitor(monitor, 2);
      FeatureSource<SimpleFeatureType, SimpleFeature> source =
          sourceLayer.getResource(FeatureSource.class, subProgressMonitor);
      subProgressMonitor.done();
      worked[0] += 2;
      // If no FeatureStore then features can't be copied
      // If no FeatureSource then features can't be copied
      if (destination == null || source == null) {
        targetLayer.setFilter(filter);
        return;
      }

      // Create a query that will get the attributes that are compatible
      // what is compatible? Do the attribute names and types have to be the same or
      // just the types.
      // Executive decision:
      // Match both name and type, the rest must be customized.
      final HashMap<String, String> attributeMap = new HashMap<String, String>();
      Query query = createQuery(sourceLayer, filter, targetLayer, attributeMap);
      if (attributeMap.isEmpty()) {
        targetLayer.setFilter(filter);
        return;
      }
      MathTransform mt = createMathTransform(sourceLayer, targetLayer);
      FeatureCollection<SimpleFeatureType, SimpleFeature> features = source.getFeatures(query);
      SimpleFeatureType schema = targetLayer.getSchema();

      CopyFeatureCollection c =
          new CopyFeatureCollection(
              schema,
              features,
              monitor,
              worked,
              mt,
              attributeMap,
              targetLayer.layerToMapTransform());
      Envelope env = c.env;
      targetLayer.eSetDeliver(false);
      try {
        List<FeatureId> fids = destination.addFeatures(c);

        displayCopiedFeatures(env);

        FilterFactory filterFactory =
            CommonFactoryFinder.getFilterFactory(GeoTools.getDefaultHints());
        addedFeaturesFilter = filterFactory.id(new HashSet(fids));
      } finally {
        targetLayer.eSetDeliver(true);
      }
      getMap().getRenderManager().refresh(targetLayer, env);
    } catch (IOException e) {
      throw (RuntimeException) new RuntimeException().initCause(e);
    } finally {
      monitor.done();
    }
  }
  public boolean canAddLayer(ILayer layer) {

    if (!layer.hasResource(Layer.class)) return false;

    try {
      if (!layer
          .findGeoResource(Layer.class)
          .parent(ProgressManager.instance().get())
          .equals(getRenderContext().getGeoResource().parent(ProgressManager.instance().get())))
        return false;
    } catch (IOException e2) {
      return false;
    }

    double opacity = Double.NaN;

    ICompositeRenderContext context1 = (ICompositeRenderContext) context;

    IRenderContext[] contexts =
        context1.getContexts().toArray(new IRenderContext[context1.getContexts().size()]);
    Arrays.sort(contexts);
    List<Layer> owsLayers = new ArrayList<Layer>();
    IService currentService;
    try {
      owsLayers.add(layer.getResource(Layer.class, new NullProgressMonitor()));
      currentService = layer.getResource(IService.class, null);
    } catch (IOException e1) {
      WMSPlugin.log("", e1); // $NON-NLS-1$
      return false;
    }
    for (IRenderContext renderContext : contexts) {
      ILayer previousLayer = renderContext.getLayer();

      try {
        owsLayers.add(previousLayer.getResource(Layer.class, new NullProgressMonitor()));
        IService previousService = previousLayer.getResource(IService.class, null);
        if (currentService != previousService) {
          return false;
        }
      } catch (IOException e) {
        WMSPlugin.log("Error while retrieving service.", e); // $NON-NLS-1$
        return false;
      }

      if (BasicWMSRenderer2.findRequestCRS(owsLayers, context.getCRS(), context.getMap()) == null)
        return false;

      Style style = (Style) previousLayer.getStyleBlackboard().get(SLDContent.ID);
      if (style != null) {
        opacity = SLDs.rasterOpacity(SLDs.rasterSymbolizer(style));
      }
    }

    Style style = (Style) layer.getStyleBlackboard().get(SLDContent.ID);
    if (style == null && Double.isNaN(opacity)) {
      return true;
    }

    double result = SLDs.rasterOpacity(SLDs.rasterSymbolizer(style));

    if (result == opacity) {
      return true;
    }
    return false;
  }