/**
   * Returns a mapgraphics layer by its class.
   *
   * @param theClass the class of the mapgraphics.
   * @return the layer or null, if none was found (not visible or not existing).
   */
  public static ILayer getMapgraphicLayerByClass(Class<?> theClass) {

    try {
      List<IResolve> mapgraphics =
          CatalogPlugin.getDefault().getLocalCatalog().find(MapGraphicService.SERVICE_URL, null);
      List<IResolve> members = mapgraphics.get(0).members(null);
      for (IResolve resolve : members) {
        if (resolve.canResolve(theClass)) {
          IGeoResource resolve2 = resolve.resolve(IGeoResource.class, null);
          String resName = resolve2.getInfo(new NullProgressMonitor()).getName();

          List<ILayer> mapLayers = ApplicationGIS.getActiveMap().getMapLayers();
          for (ILayer layer : mapLayers) {
            if (layer.getName().trim().equals(resName.trim())) {
              return layer;
            }
          }
        }
      }
    } catch (IOException e) {
      JGrassPlugin.log(
          "JGrassPlugin problem: eu.hydrologis.udig.catalog.utils#JGrassCatalogUtilities#getMapgraphicLayerByClass",
          e); //$NON-NLS-1$
      e.printStackTrace();
      return null;
    }
    return null;
  }
 @Override
 public CoordinateReferenceSystem getCrs() {
   ILayer processingRegionMapGraphic = OmsBoxPlugin.getDefault().getProcessingRegionMapGraphic();
   if (processingRegionMapGraphic != null) {
     processingRegionMapGraphic.getCRS();
   }
   return null;
 }
  /**
   * This example shows how to obtain a color.
   *
   * @param g
   * @param monitor
   * @throws RenderException
   */
  public void render(Graphics2D g, IProgressMonitor monitor) throws RenderException {
    if (monitor == null) monitor = new NullProgressMonitor();

    CsvReader reader = null;
    try {
      ILayer layer = getContext().getLayer();
      IGeoResource resource = layer.findGeoResource(CSV.class);
      if (resource == null) return;
      ReferencedEnvelope bounds = getRenderBounds();
      monitor.subTask("connecting");
      CSV csv = resource.resolve(CSV.class, null);
      // LOOK UP STYLE
      IStyleBlackboard style = layer.getStyleBlackboard();
      Color color = (Color) style.get(ColorStyle.ID);

      // DATA TO WORLD
      CoordinateReferenceSystem dataCRS = layer.getCRS();
      CoordinateReferenceSystem worldCRS = context.getCRS();
      MathTransform dataToWorld = CRS.findMathTransform(dataCRS, worldCRS, false);

      // DRAW FILE
      monitor.beginTask("csv render", csv.getSize());
      reader = csv.reader();
      reader.readHeaders();
      int nameIndex = reader.getIndex("name");
      Coordinate worldLocation = new Coordinate();
      while (reader.readRecord()) {
        Point point = CSV.getPoint(reader);
        Coordinate dataLocation = point.getCoordinate();
        try {
          JTS.transform(dataLocation, worldLocation, dataToWorld);
        } catch (TransformException e) {
          continue;
        }
        if (bounds != null && !bounds.contains(worldLocation)) {
          continue; // optimize!
        }
        java.awt.Point p = getContext().worldToPixel(worldLocation);

        g.setColor(color);
        g.fillRect(p.x - 2, p.y - 2, 6, 6);

        g.setColor(Color.BLACK);
        String name = reader.get(nameIndex);
        g.drawString(name, p.x + 15, p.y + 15);
        monitor.worked(1);
        if (monitor.isCanceled()) break;
      }
    } catch (IOException e) {
      throw new RenderException(e); // rethrow any exceptions encountered
    } catch (FactoryException e) {
      throw new RenderException(e); // rethrow any exceptions encountered
    } finally {
      if (reader != null) reader.close();
      monitor.done();
    }
  }
  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;
  }
Beispiel #5
0
 public void refreshMap() {
   IMap activeMap = ApplicationGIS.getActiveMap();
   RenderedImage image = activeMap.getRenderManager().getImage();
   if (image == null) {
     return;
   }
   List<ILayer> mapLayers = activeMap.getMapLayers();
   for (ILayer iLayer : mapLayers) {
     iLayer.refresh(null);
   }
 }
  @SuppressWarnings("unchecked")
  private void setFilter(WebMapServer wms, GetMapRequest request) {
    Filter mapFilter = null;

    Map<ILayer, Filter> filters = new HashMap<ILayer, Filter>();
    List<ILayer> layers = getContext().getLayers();
    for (ILayer layer : layers) {
      Object layerFilter =
          layer.getStyleBlackboard().get(ProjectBlackboardConstants.LAYER__DATA_QUERY);
      Filter filter;
      if (layerFilter instanceof Query) {
        filter = (Filter) ((Query) layerFilter).getFilter();
      } else if (layerFilter instanceof Filter) {
        filter = (Filter) layerFilter;
      } else {
        filter = mapFilter;
      }
      if (filter != null && filter != Filter.INCLUDE) {
        filters.put(layer, filter);
      }
    }

    if (filters.isEmpty()) return;

    StringBuilder builder = new StringBuilder();
    HashMap hashMap = new HashMap();
    for (Map.Entry<ILayer, Filter> entry : filters.entrySet()) {
      if (entry.getValue() == null) builder.append('(');
      try {
        StringWriter writer = new StringWriter();
        DocumentWriter.writeDocument(entry.getValue(), FilterSchema.getInstance(), writer, hashMap);
        builder.append(writer.toString());
      } catch (OperationNotSupportedException e) {
        WMSPlugin.log(
            "Error writing filter for layer: " + entry.getKey().getID(), e); // $NON-NLS-1$
        builder.append("<Filter/>"); // $NON-NLS-1$
      } catch (IOException e) {
        // SHOULDN'T Happen I don't think...
        assert false;
        WMSPlugin.log(
            "Error writing filter for layer: " + entry.getKey().getID(), e); // $NON-NLS-1$
        builder.append("<Filter/>"); // $NON-NLS-1$
      }
      builder.append(')');
    }

    try {
      String encode = URLEncoder.encode(builder.toString(), "UTF-8"); // $NON-NLS-1$
      request.setVendorSpecificParameter("filter", encode); // $NON-NLS-1$
    } catch (UnsupportedEncodingException e) {
      // better not happen!
      throw (RuntimeException) new RuntimeException().initCause(e);
    }
  }
  /** if the layer deleted is the current source layer, changes the units option to map units */
  @Override
  protected final void removedLayerActions(ILayer layer) {

    super.removedLayerActions(layer);

    ILayer sourceLayer = getSourceLayer();

    if (sourceLayer.equals(layer)) {

      this.currentUnits = null;
      setSelectionUnitOption(this.radioMapUnits);
    }

    populate();
  }
  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();
  }
 /**
  * Create new instance
  *
  * @param blackboard blackboard to add selected features
  * @param layer layer used to obtain features. Must have a FeatureStore resource.
  * @param filter filter used to select features
  */
 public SelectFeaturesInFilterCommand(EditBlackboard blackboard, ILayer layer, Filter filter) {
   if (!layer.hasResource(FeatureStore.class))
     throw new IllegalArgumentException("Layer must have a FeatureStore resource"); // $NON-NLS-1$
   this.filter = filter;
   this.layer = layer;
   this.bb = blackboard;
 }
 private GridStyle getStyle(ILayer layer) {
   GridStyle gridStyle = (GridStyle) layer.getStyleBlackboard().get(GridStyle.ID);
   if (gridStyle == null) {
     return GridStyle.DEFAULT_STYLE;
   }
   return gridStyle;
 }
 @SuppressWarnings("unchecked")
 private FeatureStore<SimpleFeatureType, SimpleFeature> getResource(ILayer editLayer)
     throws IOException {
   FeatureStore<SimpleFeatureType, SimpleFeature> store =
       editLayer.getResource(FeatureStore.class, null);
   return store;
 }
  /** Changes the count of features selected of the selected layer */
  @Override
  protected void changedFilterSelectionActions(final ILayer layer, final Filter newFilter) {

    if (layer.equals(this.currentFirstLayer)) {

      this.featuresInFirstLayer =
          presentSelectedFeaturesSum(
              this.currentFirstLayer, newFilter, this.cLabelFeaturesInFirstLayer);
    }
    if (layer.equals(this.currentSecondLayer)) {

      this.featuresInSecondLayer =
          presentSelectedFeaturesSum(
              this.currentSecondLayer, newFilter, this.cLabelFeaturesInSecondLayer);
    }
  }
  /**
   * Creates A geometry filter for the given layer.
   *
   * @param boundingBox in the same crs as the viewport model.
   * @return a Geometry filter in the correct CRS or null if an exception occurs.
   */
  public Filter createBBoxFilter(
      ReferencedEnvelope boundingBox, ILayer layer, Class<? extends Filter> filterType) {
    FilterFactory2 factory = CommonFactoryFinder.getFilterFactory2(GeoTools.getDefaultHints());
    if (!layer.hasResource(FeatureSource.class)) return Filter.EXCLUDE;
    try {

      SimpleFeatureType schema = layer.getSchema();
      Name geom = getGeometryAttDescriptor(schema).getName();

      Filter bboxFilter = factory.bbox(factory.property(geom), boundingBox);

      return bboxFilter;
    } catch (Exception e) {
      ProjectPlugin.getPlugin().log(e);
      return Filter.EXCLUDE;
    }
  }
 @Override
 public ReferencedEnvelope getExtent() {
   ILayer processingRegionLayer = OmsBoxPlugin.getDefault().getProcessingRegionMapGraphic();
   if (processingRegionLayer != null) {
     IStyleBlackboard blackboard = processingRegionLayer.getStyleBlackboard();
     ProcessingRegionStyle style =
         (ProcessingRegionStyle) blackboard.get(ProcessingRegionStyleContent.ID);
     if (style == null) {
       style = ProcessingRegionStyleContent.createDefault();
     }
     ProcessingRegion processinRegion =
         new ProcessingRegion(
             style.west, style.east, style.south, style.north, style.rows, style.cols);
     ReferencedEnvelope envelope = new ReferencedEnvelope(processinRegion.getEnvelope(), getCrs());
     return envelope;
   }
   return null;
 }
  private double[] screenClosest(int x, int y, ILayer layer) {
    double[] gridSize = getStyle(layer).getGridSize();

    double newx = Math.round(x / gridSize[0]) * gridSize[0];
    double newy = Math.round(y / gridSize[1]) * gridSize[1];

    Coordinate result = layer.getMap().getViewportModel().pixelToWorld((int) newx, (int) newy);
    return new double[] {result.x, result.y};
  }
  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$
  }
 private boolean mismatch(ILayer graticule, GraticuleStyle style) {
   String code;
   try {
     code = "EPSG:" + CRS.lookupEpsgCode(graticule.getCRS(), false); // $NON-NLS-1$
     return !code.equals(style.getCRS());
   } catch (FactoryException ex) {
     MapGraphicPlugin.log(Messages.GraticuleGraphic_Error, ex);
   }
   return true;
 }
  static void writeContext(IMap map, BufferedWriter out) throws IOException {
    writeHeader(map, out);
    writeGeneral(map, out);
    append(2, out, "<ResourceList>"); // $NON-NLS-1$
    for (ILayer layer : map.getMapLayers()) {
      try {
        if (layer.isType(Layer.class)) {
          writeLayer(layer, out);
        } else if (layer.isType(WFSDataStore.class)) {
          writeFeatureType(layer, out);
        } else {
          // n/a
        }

      } catch (IOException io) {
        // skip - unable to figure out details ...
      }
    }
    append(2, out, "</ResourceList>"); // $NON-NLS-1$
    append(0, out, "</OWSContext>"); // $NON-NLS-1$
  }
  public void run(IProgressMonitor monitor) throws Exception {

    final ILayer editLayer = handler.getEditLayer();
    final Point mouseLocation = position;

    final EditBlackboard layerBlackboard = handler.getEditBlackboard(editLayer);
    final boolean includeSegmentsInCurrent = true;
    final SnapBehaviour snapBehaviour = SnapBehaviour.CURRENT_LAYER;

    final CoordinateReferenceSystem mapCrs = handler.getContext().getCRS();
    final int snappingRadius = PreferenceUtil.instance().getSnappingRadius();

    final SnapSegmentFinder segmentFinder = new SnapSegmentFinder(mapCrs);
    List<LineSegment> linesList = new ArrayList<LineSegment>();
    LineSegment closestSnapSegment;
    closestSnapSegment =
        segmentFinder.getClosestSnapSegment(
            handler,
            layerBlackboard,
            mouseLocation,
            includeSegmentsInCurrent,
            snapBehaviour,
            snappingRadius);

    if (closestSnapSegment != null) {
      CoordinateReferenceSystem layerCrs = editLayer.getCRS();
      closestSnapSegment = GeoToolsUtils.reproject(closestSnapSegment, mapCrs, layerCrs);
    }
    linesList.add(closestSnapSegment);
    if (this.mapMouseEvent.isShiftDown()) {
      this.segmentCopyContext.addSegments(linesList);
    } else {
      this.segmentCopyContext.setReferenceLineSegment(closestSnapSegment);
    }
    this.segmentCopyContext.setMode(PrecisionToolsMode.WAITING);

    System.out.println("\nSegment: " + closestSnapSegment.toString());
  }
  /**
   * Creates a query that requests the features in sourceLayer as dictated by filter. Query only
   * requests the attributes that can be mapped from sourceLayer to targetLayer.
   *
   * @param queryAttributes populates with a mapping of attributeTypeNames from targetLayer to
   *     sourcelayer
   * @return
   */
  @SuppressWarnings("unchecked")
  private Query createQuery(
      ILayer sourceLayer, Filter filter, Layer targetLayer, Map<String, String> queryAttributes) {
    SimpleFeatureType sourceSchema = sourceLayer.getSchema();
    SimpleFeatureType targetSchema = targetLayer.getSchema();
    // Maps type names to type names since we are ignoring case

    queryAttributes.putAll(FeatureUtils.createAttributeMapping(sourceSchema, targetSchema));
    Set<String> properties = new HashSet(queryAttributes.values());
    return new DefaultQuery(
        sourceSchema.getName().getLocalPart(),
        filter,
        properties.toArray(new String[properties.size()]));
  }
  private double[] worldClosest(int x1, int y1, ILayer layer) throws FactoryException {
    Coordinate coord = layer.getMap().getViewportModel().pixelToWorld(x1, y1);
    CoordinateReferenceSystem crs = layer.getMap().getViewportModel().getCRS();
    MathTransform mt = CRS.findMathTransform(DefaultGeographicCRS.WGS84, crs);

    double[] gridSize = getStyle(layer).getGridSize();
    try {

      if (!mt.isIdentity()) {
        double tx = gridSize[0] / 2.0;
        double ty = gridSize[1] / 2.0;
        double[] toTransform = new double[] {-tx, -ty, tx, ty};
        double[] dest = new double[4];
        mt.transform(toTransform, 0, dest, 0, 2);
        gridSize = new double[] {Math.abs(dest[2] - dest[0]), Math.abs(dest[3] - dest[1])};
      }
    } catch (Exception e) {
      MapGraphicPlugin.log("", e); // $NON-NLS-1$
    }
    double newx = Math.round(coord.x / gridSize[0]) * gridSize[0];
    double newy = Math.round(coord.y / gridSize[1]) * gridSize[1];
    return new double[] {newx, newy};
  }
  private MathTransform createMathTransform(ILayer sourceLayer, ILayer targetLayer) {
    MathTransform temp;
    try {
      CoordinateReferenceSystem targetCRS = targetLayer.getCRS();
      CoordinateReferenceSystem sourceCRS = sourceLayer.getCRS();
      if (targetCRS.equals(sourceCRS)) temp = null;
      else temp = CRS.findMathTransform(sourceCRS, targetCRS, true);
      if (temp == null || temp.isIdentity()) temp = null;
    } catch (FactoryException e1) {
      ProjectPlugin.log("", e1); // $NON-NLS-1$
      temp = null;
    }

    if (temp == null) {
      try {
        return CRS.findMathTransform(DefaultGeographicCRS.WGS84, DefaultGeographicCRS.WGS84);
      } catch (Exception e) {
        ProjectPlugin.log("", e); // $NON-NLS-1$
        return null;
      }
    }
    return temp;
  }
Beispiel #23
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;
  }
 /**
  * Override warning.
  *
  * <p>Description ...
  *
  * @see org.geotools.validation.ValidationResults#warning(org.geotools.feature.SimpleFeature,
  *     java.lang.String)
  * @param feature
  * @param message
  */
 public void warning(SimpleFeature feature, String message) {
   // add the warning to our list of warned features + warning messages
   warningFeatures.add(feature);
   warningMessages.add(feature.getID() + ": " + message); // $NON-NLS-1$
   // find the layer of the current feature
   List<ILayer> layers = ApplicationGIS.getActiveMap().getMapLayers();
   ILayer layer = null;
   for (Iterator i = layers.listIterator(); i.hasNext(); ) {
     layer = (ILayer) i.next();
     if (feature.getName().getLocalPart().equals(layer.getName())) {
       break;
     }
   }
   // add the error to the issues list
   FeatureIssue issue =
       new FeatureIssue(
           Priority.WARNING,
           message,
           layer,
           feature,
           Messages.GenericValidationResults_validationWarning);
   issues.add(issue);
 }
  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();
  }
  private Map<String, Tile> checkTooManyTiles(
      ILayer layer,
      WMTSource wmtSource,
      WMTLayerProperties layerProperties,
      WMTRenderJob renderJob,
      Map<String, Tile> tileList) {
    int tilesCount = tileList.size();

    if (tilesCount > WMTRenderJob.getTileLimitWarning()) {
      // too many tiles, let's use the recommended zoom-level (if it wasn't already used)
      Boolean selectionAutomatic = layerProperties.getSelectionAutomatic();

      if ((selectionAutomatic != null) && (selectionAutomatic == false)) {
        tileList.clear();
        tileList =
            wmtSource.cutExtentIntoTiles(
                renderJob, WMTRenderJob.getScaleFactor(), true, layerProperties);
        tilesCount = tileList.size();
      }

      // show a warning about this
      layer.setStatus(ILayer.WARNING);
      layer.setStatusMessage(Messages.Render_Warning_TooManyTiles);

      WMTPlugin.trace("[BasicWMTRender.render] Set WARNING_TOO_MANY_TILES"); // $NON-NLS-1$
    }

    if (tilesCount > WMTRenderJob.getTileLimitError()) {
      // this is just too much, cancel
      WMTPlugin.trace("[BasicWMTRender.render] Set ERROR_TOO_MANY_TILES"); // $NON-NLS-1$

      return Collections.emptyMap();
    }

    return tileList;
  }
  private WMTSource getWmtSourceFromLayer(ILayer layer) {
    IGeoResource resource = layer.findGeoResource(WMTSource.class);

    if (resource != null) {
      WMTSource wmtSource = null;
      try {
        wmtSource = resource.resolve(WMTSource.class, null);

        return wmtSource;
      } catch (Exception e) {
      }
    }

    return null;
  }
Beispiel #28
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();
  }
  /**
   * Traverses the FeatureCollection<SimpleFeatureType, SimpleFeature> <code>selection</code>
   * creating a buffered geometry on each SimpleFeature's default geometry and stores the result in
   * a new SimpleFeature on the <code>target</code> FeatureStore.
   *
   * <p>Note the buffer computation is made with a slightly {@link BufferOp modified version} of the
   * JTS <code>BufferOp</code> in order to allow the operation to be cancelled while inside the
   * buffer computation.
   *
   * @param params buffer parameters
   * @param selection source layer's selected features in its native CRS
   * @throws SOProcessException if {@link #createBufferedFeature(SimpleFeature, SimpleFeatureType,
   *     Geometry)} fails
   * @throws IOException if it is thrown while adding the resulting features to the target
   *     FeatureStore<SimpleFeatureType, SimpleFeature> or while commiting the transaction
   * @throws InterruptedException if the user cancelled the operation
   */
  private void performBuffer(
      IBufferParameters params, FeatureCollection<SimpleFeatureType, SimpleFeature> selection)
      throws SOProcessException, InterruptedException {

    assert selection != null;

    final int featureCount = selection.size();

    final ILayer sourceLayer = this.sourceLayer;

    final CoordinateReferenceSystem sourceCrs = LayerUtil.getCrs(sourceLayer);

    final CoordinateReferenceSystem mapCrs = MapUtil.getCRS(sourceLayer.getMap());

    final CoordinateReferenceSystem targetCrs =
        this.targetStore.getSchema().getDefaultGeometry().getCRS();

    final Unit sourceUnits = GeoToolsUtils.getDefaultCRSUnit(mapCrs);
    final Unit targetUnits = params.getUnitsOfMeasure();
    final int quadSegments = params.getQuadrantSegments().intValue();

    final Double width = params.getWidth().doubleValue();

    SimpleFeature sourceFeature = null;
    // the one to use if params.isMergeGeometry() == true
    Geometry mergedGeometry = null;

    FeatureIterator<SimpleFeature> iterator = null;

    try {
      int processingCount = 0;
      Geometry geometry;

      String subTaskName;

      iterator = selection.features();
      while (iterator.hasNext()) {

        processingCount++;
        subTaskName =
            MessageFormat.format(
                Messages.BufferProcess_subTask_BufferingFeatureN, processingCount, featureCount);

        getMonitor().subTask(subTaskName);

        checkCancelation();

        sourceFeature = iterator.next();

        geometry = (Geometry) sourceFeature.getDefaultGeometry();
        geometry = GeoToolsUtils.reproject(geometry, sourceCrs, mapCrs);
        geometry =
            makeBufferGeometry(
                geometry, width, sourceUnits, targetUnits, quadSegments, getMonitor());
        geometry = GeoToolsUtils.reproject(geometry, mapCrs, targetCrs);

        checkCancelation();

        if (params.isMergeGeometries()) {
          if (mergedGeometry == null) {
            mergedGeometry = geometry;
          } else {
            mergedGeometry = mergedGeometry.union(geometry);
          }
        } else {
          createAndStoreBufferedFeature(sourceFeature, geometry, this.targetStore);
        }
        getMonitor().worked(1);
      }
      checkCancelation();
      if (params.isMergeGeometries()) {
        createAndStoreBufferedFeature(null, mergedGeometry, this.targetStore);
      }

      getMonitor().subTask(Messages.BufferProcess_subtastCommittingTransaction);

    } catch (OperationNotFoundException e) {
      String message =
          MessageFormat.format(
              Messages.BufferProcess_failed_transforming, sourceFeature.getID(), e.getMessage());
      throw new SOProcessException(message, e);
    } catch (TransformException e) {
      String message =
          MessageFormat.format(
              Messages.BufferProcess_failed_transforming_feature_to_crs,
              sourceFeature.getID(),
              e.getMessage());
      throw new SOProcessException(message, e);
    } finally {

      if (iterator != null) iterator.close();

      getMonitor().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);
      }
    }
  }