Example #1
0
  public static void load(String mapname) {
    if (JGrassPlugin.getDefault() != null) {
      JGrassMapGeoResource addedMap =
          JGrassCatalogUtilities.addMapToCatalog(
              p_locationPath, p_mapsetName, mapname, JGrassConstants.GRASSBINARYRASTERMAP);
      if (addedMap == null)
        p_err.println("An error occurred while trying to add the map to the catalog.");

      IMap activeMap = ApplicationGIS.getActiveMap();
      ApplicationGIS.addLayersToMap(
          activeMap,
          Collections.singletonList((IGeoResource) addedMap),
          activeMap.getMapLayers().size());
    }
  }
  /**
   * 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 error.
  *
  * <p>Description ...
  *
  * @see org.geotools.validation.ValidationResults#error(org.geotools.feature.SimpleFeature,
  *     java.lang.String)
  * @param feature
  * @param message
  */
 public void error(SimpleFeature feature, String message) {
   // add the error to our list of failed features + failure messages
   if (message == null) message = ""; // $NON-NLS-1$
   failedFeatures.add(feature);
   failureMessages.add(feature.getID() + ": " + message); // $NON-NLS-1$
   // find the layer of the current feature
   IMap activeMap = ApplicationGIS.getActiveMap();
   List<ILayer> layers = new ArrayList<ILayer>();
   if (activeMap != ApplicationGIS.NO_MAP) {
     layers.addAll(activeMap.getMapLayers());
   }
   Layer layer = null;
   for (Iterator i = layers.listIterator(); i.hasNext(); ) {
     Layer thisLayer = (Layer) i.next();
     if (feature.getName().getLocalPart().equals(thisLayer.getName())) {
       layer = thisLayer;
       break;
     }
   }
   // add the error to the issues list
   FeatureIssue issue =
       new FeatureIssue(
           Priority.HIGH,
           message,
           layer,
           feature,
           Messages.GenericValidationResults_validationError);
   issues.add(issue);
 }
Example #4
0
  /**
   * Creates a new default local {@link DatabaseConnectionProperties} and adds it to the list.
   *
   * @param databaseFolder the folder into which to create the database or <code>null</code>.
   * @param databaseName the name for the new database or <code>null</code>.
   * @return the properties for the new created database definition.
   */
  public DatabaseConnectionProperties createNewLocalDatabaseDefinition(
      String databaseFolder, String databaseName) {
    DatabaseConnectionProperties defaultProperties =
        new H2ConnectionFactory().createDefaultProperties();

    String projectName = databaseName;
    if (projectName == null) {
      IProject activeProject = ApplicationGIS.getActiveProject();
      if (activeProject != null) {
        projectName = activeProject.getName();
      }
    }
    if (projectName == null) {
      projectName = Messages.H2ConnectionFactory__default_db;
    }
    if (projectName != null && projectName.length() != 0) {
      defaultProperties.put(DatabaseConnectionProperties.TITLE, projectName);
      defaultProperties.put(DatabaseConnectionProperties.DESCRIPTION, projectName);
    }
    if (databaseFolder != null) {
      defaultProperties.put(DatabaseConnectionProperties.PATH, databaseFolder);
    }
    DatabasePlugin.getDefault().checkSameNameDbconnection(defaultProperties);

    availableDatabaseConnectionProperties.add(defaultProperties);
    relayout();

    setDatabaseSelected(defaultProperties);
    return defaultProperties;
  }
  /**
   * Find a resource from its url and add it to the map
   *
   * @param url the resources url
   * @param progressMonitor
   * @param addPosition the position into which to put it, 0 is most lower
   * @param map the map to which to add the resource to
   */
  public static void addResourceFromUrlToMap(
      URL url, IProgressMonitor progressMonitor, int addPosition, IMap map) {

    synchronized (url) {
      ICatalog catalog = CatalogPlugin.getDefault().getLocalCatalog();
      // first search the local catalog.
      List<IResolve> matches = catalog.find(url, new SubProgressMonitor(progressMonitor, 2));

      for (IResolve resolve : matches) {
        List<IResolve> members = null;
        try {
          List<IGeoResource> geoResources = new ArrayList<IGeoResource>();
          members = resolve.members(progressMonitor);
          if (members.size() < 1 && resolve.canResolve(IGeoResource.class)) {
            // if it is a map, it has no members
            geoResources.add(resolve.resolve(IGeoResource.class, progressMonitor));
          } else if (members.get(0).canResolve(IGeoResource.class)) {
            for (IResolve tmp : members) {
              IGeoResource finalResolve = tmp.resolve(IGeoResource.class, progressMonitor);
              geoResources.add(finalResolve);
            }
          }
          List<? extends ILayer> addedLayers =
              ApplicationGIS.addLayersToMap(map, geoResources, addPosition);
          if (addedLayers.size() == 0) {
            System.out.println("strange");
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
Example #6
0
  /**
   * Must go places!
   *
   * @param selection
   */
  public void showLocation(Object selection) {
    // selection should be an Feture (of some sort)
    SimpleFeature feature = (SimpleFeature) selection;
    Geometry geom = (Geometry) feature.getDefaultGeometry();
    Point point = geom.getCentroid();

    IMap imap = ApplicationGIS.getActiveMap();
    if (imap == ApplicationGIS.NO_MAP) return;

    CoordinateReferenceSystem world = imap.getViewportModel().getCRS();
    CoordinateReferenceSystem wsg84 = DefaultGeographicCRS.WGS84;

    double buffer = 0.01; // how much of the wgs84 world to see
    Envelope view = point.buffer(buffer).getEnvelopeInternal();

    MathTransform transform;
    try {
      transform = CRS.findMathTransform(wsg84, world, true); // relaxed
    } catch (FactoryException e) {
      return; // no go
    }
    Envelope areaOfInterest;
    try {
      areaOfInterest = JTS.transform(view, null, transform, 10);
    } catch (TransformException e) {
      return; // no go
    }

    // NavigationCommandFactory navigate = NavigationCommandFactory.getInstance();

    NavCommand show = new SetViewportBBoxCommand(areaOfInterest, world);
    imap.sendCommandASync(show);
  }
Example #7
0
 public boolean select(Viewer arg0, Object arg1, Object arg2) {
   String name = ((DatabaseConnectionProperties) arg2).getTitle();
   String projectName = ApplicationGIS.getActiveProject().getName();
   if (name.matches("(?i).*" + projectName + ".*")) { // $NON-NLS-1$ //$NON-NLS-2$
     return true;
   }
   return false;
 }
  public boolean isTrue(Object object, String value) {
    IMap map = ApplicationGIS.getActiveMap();
    if (map == ApplicationGIS.NO_MAP || map.getMapLayers().size() == 0) return false;
    PrimitiveShape shape = (PrimitiveShape) map.getBlackboard().get(EditToolHandler.CURRENT_SHAPE);
    if (shape == null) return false;

    return shape.getEditGeom() != null
        && shape.getEditGeom().getShapeType().toString().equalsIgnoreCase(value.trim());
  }
  /**
   * double scaleDenom = page1.isCustomScale() ? page1.getCustomScale() :
   * map.getViewportModel().getScaleDenominator();
   *
   * @param mapWithRasterLayersOnly a map with only raster layers
   * @param mapBoundsInTemplate a rectangle indicating the coordinates of the top left, width and
   *     height (where the coordinate system has (0,0) in the top left.
   * @param doc the PDF document object
   */
  private void writeRasterLayersOnlyToDocument(
      Map mapWithRasterLayersOnly,
      org.eclipse.swt.graphics.Rectangle mapBoundsInTemplate,
      Document doc,
      Dimension pageSize,
      double currentViewportScaleDenom) {

    // set dimensions of the raster image to be the same ratio as
    // the required map bounds within the page, but scaled up so
    // we can achieve a higher DPI when we later insert the image
    // into the page (90 refers to the default DPI)
    int w = mapBoundsInTemplate.width * page1.getDpi() / 90;
    int h = mapBoundsInTemplate.height * page1.getDpi() / 90;

    BufferedImage imageOfRastersOnly = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = imageOfRastersOnly.createGraphics();

    // define a DrawMapParameter object with a custom BoundsStrategy if a custom scale is set
    DrawMapParameter drawMapParameter = null;

    double scaleDenom =
        (page1.getScaleOption() == ExportPDFWizardPage1.CUSTOM_MAP_SCALE)
            ? page1.getCustomScale()
            : currentViewportScaleDenom;

    drawMapParameter =
        new DrawMapParameter(
            g,
            new java.awt.Dimension(w, h),
            mapWithRasterLayersOnly,
            new BoundsStrategy(scaleDenom),
            page1.getDpi(),
            SelectionStyle.EXCLUSIVE_ALL,
            null);

    try {

      // draw the map (at a high resolution as specified above)
      ApplicationGIS.drawMap(drawMapParameter);
      Image img = Image.getInstance(bufferedImage2ByteArray(imageOfRastersOnly));

      // scale the image down to fit into the page
      img.scaleAbsolute(mapBoundsInTemplate.width, mapBoundsInTemplate.height);

      // set the location of the image
      int left = mapBoundsInTemplate.x;
      int bottom = pageSize.height - mapBoundsInTemplate.height - mapBoundsInTemplate.y;
      img.setAbsolutePosition(left, bottom); // (0,0) is bottom left in the PDF coordinate system

      doc.add(img);
      addWhiteMapBorder(img, doc);

    } catch (Exception e) {
      // TODO: fail gracefully.
    }
  }
Example #10
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);
   }
 }
  private void checkStyle() {
    IMap activeMap = ApplicationGIS.getActiveMap();

    IBlackboard styleBlackboard = activeMap.getBlackboard();
    if (style == null) {
      style = (RasterLegendStyle) styleBlackboard.get(RasterLegendStyleContent.ID);
    }
    if (style == null) {
      style = RasterLegendStyleContent.createDefault();
      styleBlackboard.put(RasterLegendStyleContent.ID, style);
      // styleBlackboard.setSelected(new String[]{RasterLegendStyleContent.ID});
    }
  }
Example #12
0
  /** Creates a new default remote {@link DatabaseConnectionProperties} and adds it to the list. */
  public void createNewRemoteDatabaseDefinition() {
    DatabaseConnectionProperties defaultProperties =
        new PostgresConnectionFactory().createDefaultProperties();
    String projectName = ApplicationGIS.getActiveProject().getName();
    if (projectName != null && projectName.length() != 0) {
      defaultProperties.put(DatabaseConnectionProperties.TITLE, projectName);
      defaultProperties.put(DatabaseConnectionProperties.DESCRIPTION, projectName);
    }

    DatabasePlugin.getDefault().checkSameNameDbconnection(defaultProperties);

    availableDatabaseConnectionProperties.add(defaultProperties);
    relayout();
  }
  public void addPages() {
    super.addPages();

    if (ApplicationGIS.getActiveMap() == ApplicationGIS.NO_MAP) {
      return; // no pages no go!
    }
    page =
        new MapExportPage(
            Messages.ContextExportWizard_page_name,
            Messages.ContextExportWizard_page_title,
            ContextPlugin.getImageDescriptor(
                "icons/wizban/import_owscontext_wiz_gif")); //$NON-NLS-1$
    addPage(page);
  }
  private void updateBlackboard() {
    IMap activeMap = ApplicationGIS.getActiveMap();
    IBlackboard styleBlackboard = activeMap.getBlackboard();
    style = (RasterLegendStyle) styleBlackboard.get(RasterLegendStyleContent.ID);

    if (style == null) {
      style = RasterLegendStyleContent.createDefault();
      styleBlackboard.put(RasterLegendStyleContent.ID, style);
      // styleBlackboard.setSelected(new String[]{RasterLegendStyleContent.ID});
    }

    RGB bg = backgroundColour.getColorValue();
    try {
      int bAlpha = Integer.parseInt(backgroundAlphaText.getText());
      style.backgroundColor = new Color(bg.red, bg.green, bg.blue, bAlpha);
    } catch (Exception e) {
      style.backgroundColor = new Color(bg.red, bg.green, bg.blue);
    }
    bg = foregroundColor.getColorValue();
    try {
      int fAlpha = Integer.parseInt(forgroundAlphaText.getText());
      style.foregroundColor = new Color(bg.red, bg.green, bg.blue, fAlpha);
    } catch (Exception e) {
      style.foregroundColor = new Color(bg.red, bg.green, bg.blue);
    }
    bg = fontColour.getColorValue();
    style.fontColor = new Color(bg.red, bg.green, bg.blue);

    style.titleString = titleText.getText();
    style.xPos = Integer.parseInt(xposText.getText());
    style.yPos = Integer.parseInt(yposText.getText());
    style.legendHeight = Integer.parseInt(legHeightText.getText());
    style.legendWidth = Integer.parseInt(legWidthText.getText());
    style.boxWidth = Integer.parseInt(boxWidthText.getText());
    style.isRoundedRectangle = isroundedButton.getSelection();

    styleBlackboard.put(RasterLegendStyleContent.ID, style);
  }
 /**
  * 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);
 }
Example #16
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;
  }
  /**
   * Creates a page based on the template selected in the wizard **Note: this function may swap the
   * width and height if the template prefers different page orientation.
   *
   * @return a page
   */
  protected Page makePage(Rectangle pageSize, Document doc, Template template) {

    Map mapOnlyRasterLayers = null;
    Map mapNoRasterLayers = null;

    // **Note: the iText API doesn't render rasters at a high enough resolution if
    // they are written to the PDF via graphics2d.  To work around this problem, I
    // create two copies of the map: one with only the raster layers, and one with
    // everything else.
    // The "everything else" map gets drawn by a graphics2d.  The other layer must be
    // rasterized and inserted into the PDF via iText's API.

    // make one copy of the map with no raster layers
    mapNoRasterLayers = (Map) ApplicationGIS.copyMap(map);
    List<Layer> layersNoRasters = mapNoRasterLayers.getLayersInternal();
    List<Layer> toRemove = new ArrayList<Layer>();
    for (Layer layer : layersNoRasters) {
      for (IGeoResource resource : layer.getGeoResources()) {
        if (resource.canResolve(GridCoverageReader.class)) {
          toRemove.add(layer);
        }
      }
    }
    layersNoRasters.removeAll(toRemove);

    // adjust scale
    double currentViewportScaleDenom = map.getViewportModel().getScaleDenominator();
    if (currentViewportScaleDenom == -1)
      throw new IllegalStateException(
          "no scale denominator is available from the viewport model"); //$NON-NLS-1$

    if (page1.getScaleOption() == PrintWizardPage1.CUSTOM_MAP_SCALE) {
      float customScale = page1.getCustomScale();
      template.setMapScaleHint(customScale);
    } else if (page1.getScaleOption() == PrintWizardPage1.CURRENT_MAP_SCALE) {
      template.setMapScaleHint(currentViewportScaleDenom);
    } else if (page1.getScaleOption() == PrintWizardPage1.ZOOM_TO_SELECTION) {
      template.setZoomToSelectionHint(true);
      template.setMapScaleHint(currentViewportScaleDenom);
    }

    // 3. make the page itself
    Page page = ModelFactory.eINSTANCE.createPage();
    page.setSize(new Dimension((int) pageSize.getWidth(), (int) pageSize.getHeight()));

    // page name stuff not required, because this page will just get discarded
    MessageFormat formatter =
        new MessageFormat(Messages.CreatePageAction_newPageName, Locale.getDefault());
    if (page.getName() == null || page.getName().length() == 0) {
      page.setName(formatter.format(new Object[] {mapNoRasterLayers.getName()}));
    }

    template.init(page, mapNoRasterLayers);

    if (page1.getRasterEnabled()) {
      // make another copy with only raster layers
      mapOnlyRasterLayers = (Map) ApplicationGIS.copyMap(map);
      List<Layer> layersOnlyRasters = mapOnlyRasterLayers.getLayersInternal();
      List<Layer> toRemove2 = new ArrayList<Layer>();
      for (Layer layer : layersOnlyRasters) {
        for (IGeoResource resource : layer.getGeoResources()) {
          if (!resource.canResolve(GridCoverageReader.class)) {
            toRemove2.add(layer);
          }
        }
      }
      layersOnlyRasters.removeAll(toRemove2);

      // set bounds to match the other map
      SetViewportBBoxCommand cmdBbox =
          new SetViewportBBoxCommand(mapNoRasterLayers.getViewportModel().getBounds());
      mapOnlyRasterLayers.sendCommandSync(cmdBbox);

      if (layersNoRasters.size() > 0) {
        writeRasterLayersOnlyToDocument(
            mapOnlyRasterLayers,
            template.getMapBounds(),
            doc,
            page.getSize(), /*currentViewportScaleDenom*/
            mapNoRasterLayers.getViewportModel().getScaleDenominator());
      }
    }

    // copy the boxes from the template into the page
    Iterator<Box> iter = template.iterator();
    while (iter.hasNext()) {
      page.getBoxes().add(iter.next());
    }
    return page;

    // TODO Throw some sort of exception if the page can't be created

  }