public boolean execute(PlugInContext context) throws Exception {
    if (context.getLayerViewPanel() == null) {
      return false;
    }
    try {
      if (app.getBlackboard().get("temporalincidents") != null)
        app.getBlackboard().put("temporalincidents", new ArrayList<IdEdgeNetworkBean>());

      // JOptionPane.showMessageDialog(app.getMainFrame(),I18N.get("temporalIncidents","routeengine.temporalincidents.remove.removed"));
    } catch (Exception e) {
      context
          .getLayerViewPanel()
          .getContext()
          .warnUser(I18N.get("temporalIncidents", "routeengine.temporalincidents.remove.error"));
      return false;
    }
    JOptionPane.showMessageDialog(
        context.getWorkbenchFrame(),
        I18N.get("temporalIncidents", "routeengine.temporalincidents.remove.removed"));
    context
        .getLayerViewPanel()
        .getContext()
        .setStatusMessage(
            I18N.get("temporalIncidents", "routeengine.temporalincidents.remove.removed"));
    return true;
  }
  public boolean execute(final PlugInContext context) throws Exception {
    reportNothingToUndoYet(context);

    Collection features;
    Transferable transferable =
        GUIUtil.getContents(Toolkit.getDefaultToolkit().getSystemClipboard());

    if (transferable.isDataFlavorSupported(
        CollectionOfFeaturesTransferable.COLLECTION_OF_FEATURES_FLAVOR)) {
      features =
          (Collection)
              GUIUtil.getContents(Toolkit.getDefaultToolkit().getSystemClipboard())
                  .getTransferData(CollectionOfFeaturesTransferable.COLLECTION_OF_FEATURES_FLAVOR);
    } else {
      // Allow the user to paste features using WKT. [Jon Aquino]
      features =
          reader
              .read(
                  new StringReader((String) transferable.getTransferData(DataFlavor.stringFlavor)))
              .getFeatures();
    }

    final SelectionManager selectionManager = context.getLayerViewPanel().getSelectionManager();
    final Layer layer = context.getSelectedLayer(0);
    final Collection featureCopies =
        conform(features, layer.getFeatureCollectionWrapper().getFeatureSchema());
    Feature feature = ((Feature) featureCopies.iterator().next());
    Coordinate firstPoint = feature.getGeometry().getCoordinate();
    Coordinate cursorPt =
        context
            .getLayerViewPanel()
            .getViewport()
            .toModelCoordinate(context.getLayerViewPanel().getLastMouseLocation());
    Coordinate displacement = CoordUtil.subtract(cursorPt, firstPoint);
    moveAll(featureCopies, displacement);

    execute(
        new UndoableCommand(getName()) {
          public void execute() {
            layer.getFeatureCollectionWrapper().addAll(featureCopies);
            selectionManager.clear();
            selectionManager.getFeatureSelection().selectItems(layer, featureCopies);
          }

          public void unexecute() {
            layer.getFeatureCollectionWrapper().removeAll(featureCopies);
          }
        },
        context);

    return true;
  }
 /**
  * Ajusta el tamaño de la ventana al envelope pasado como parámetro
  *
  * @param ctx
  * @param newWrapperEnvelope
  * @param viewport
  */
 public static void resizeViewToEnvelope(
     PlugInContext ctx, Envelope newWrapperEnvelope, IViewport viewport) {
   // ajustamos las proporciones de la ventana a las de la feature
   JInternalFrame activeInternalFrame = ctx.getActiveInternalFrame();
   Dimension dimView = ((Dimension) ctx.getLayerViewPanel()).getSize();
   Double widthView = dimView.getWidth();
   Double heightView = dimView.getHeight();
   int widthDiff = (int) (activeInternalFrame.getWidth() - widthView);
   int heightDiff = (int) (activeInternalFrame.getHeight() - heightView);
   Integer newWidth =
       (int)
           ((newWrapperEnvelope.getWidth() / viewport.getEnvelopeInModelCoordinates().getWidth())
               * widthView);
   Integer newHeight =
       (int)
           ((newWrapperEnvelope.getHeight() / viewport.getEnvelopeInModelCoordinates().getHeight())
               * heightView);
   Dimension newDimensionView = new Dimension(newWidth + widthDiff, newHeight + heightDiff);
   activeInternalFrame.setSize(newDimensionView);
   // zoom al envelope actual
   try {
     viewport.zoom(newWrapperEnvelope);
   } catch (NoninvertibleTransformException e) {
     log.warn("No se ha podido alcanzar el zoom " + newWrapperEnvelope);
   }
 }
 protected void reportNothingToUndoYet() {
   context
       .getLayerViewPanel()
       .getLayerManager()
       .getUndoableEditReceiver()
       .reportNothingToUndoYet();
 }
  private void onZoomToRouteButtonDo() {
    if (this.pluginContext != null) {

      //			GeometryFactory geoFactory = new GeometryFactory();
      ArrayList<Geometry> geoArrayList = new ArrayList<Geometry>();
      if (this.infoRoutesStretchBeansCollection != null
          && !this.infoRoutesStretchBeansCollection.isEmpty()) {
        Iterator<InfoRouteStretchBean> it = this.infoRoutesStretchBeansCollection.iterator();
        while (it.hasNext()) {
          InfoRouteStretchBean actualStretchBean = it.next();
          if (actualStretchBean != null
              && actualStretchBean.getGeometries() != null
              && !actualStretchBean.getGeometries().isEmpty()) {
            geoArrayList.addAll(actualStretchBean.getGeometries());
          }
        }
      }
      //			GeometryCollection geoCollection = new GeometryCollection(geoArrayList.toArray(new
      // Geometry[geoArrayList.size()]), geoFactory);

      try {
        zoomToSelectedItemsPlugIn.zoom(geoArrayList, pluginContext.getLayerViewPanel());
      } catch (NoninvertibleTransformException e) {
        e.printStackTrace();
        ErrorDialog.show(
            null,
            "Error resaltar la ruta",
            I18N.get(
                "routedescription", "routeengine.route.description.error.route.not.zoom.message"),
            StringUtil.stackTrace(e));
      }
    }
  }
  private void onInfoRouteListMosueOver(Point point) {
    Object value = null;
    try {
      int pos = infoRouteJList.locationToIndex(point);
      value = ((DefaultListModel) infoRouteJList.getModel()).get(pos);

      if (value != null && value instanceof InfoRouteStretchBean) {
        InfoRouteStretchBean actualStretchBean = (InfoRouteStretchBean) value;
        ArrayList<Geometry> geoArrayList = new ArrayList<Geometry>();
        if (actualStretchBean != null
            && actualStretchBean.getGeometries() != null
            && !actualStretchBean.getGeometries().isEmpty()) {
          geoArrayList.addAll(actualStretchBean.getGeometries());
        }

        if (value instanceof TurnRouteStreetchBean) {
          GeometryFactory geoFactory = new GeometryFactory();
          if (((TurnRouteStreetchBean) value).getTurnNode() != null) {
            geoArrayList.add(
                geoFactory.createPoint(
                    ((XYNode) ((TurnRouteStreetchBean) value).getTurnNode()).getCoordinate()));
          }
        }

        GeometryFactory geoFactory = new GeometryFactory();
        GeometryCollection geoCollection =
            new GeometryCollection(
                geoArrayList.toArray(new Geometry[geoArrayList.size()]), geoFactory);

        pluginContext.getLayerViewPanel().flash(geoCollection);

        try {
          //					Component comp = getInfoListPanel().getComponentAt(point);
          //					 if (comp != null){
          //						comp.setBackground(Color.LIGHT_GRAY);
          //						 comp.setForeground(Color.RED);
          //					 }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }

    } catch (Exception ex) {
      ex.printStackTrace();
      ErrorDialog.show(
          null,
          "Error resaltar un tramo de la ruta.",
          I18N.get(
              "routedescription", "routeengine.route.description.error.route.not.zoom.message"),
          StringUtil.stackTrace(ex));
    }
  }
  /** @inheritDoc */
  public boolean execute(PlugInContext context) throws Exception {

    RasterImageLayer rLayer =
        (RasterImageLayer) LayerTools.getSelectedLayerable(context, RasterImageLayer.class);

    if (rLayer == null) {
      StandardPirolPlugIn.warnUser(context, PirolPlugInMessages.getString("no-layer-selected"));
      return this.finishExecution(context, false);
    }

    context.getLayerViewPanel().getViewport().zoom(rLayer.getEnvelope());

    return this.finishExecution(context, true);
  }
 public boolean execute(PlugInContext context) throws Exception {
   try {
     CursorTool circleTool =
         DrawConstrainedCircleTool.create((LayerNamePanelProxy) context.getActiveInternalFrame());
     context.getLayerViewPanel().setCurrentCursorTool(circleTool);
     return true;
   } catch (Exception e) {
     context.getWorkbenchFrame().warnUser(errorSeeOutputWindow);
     context.getWorkbenchFrame().getOutputFrame().createNewDocument();
     context
         .getWorkbenchFrame()
         .getOutputFrame()
         .addText("DrawConstrainedCircleTool Exception:" + e.toString());
     return false;
   }
 }
  /**
   * Crea una cuadrícula con los parámetros indicados y centra el mapa sobre la misma
   *
   * @param plugContext
   * @param cellSideLengthX
   * @param cellSideLengthY
   * @param layerHeightInCells
   * @param layerWidthInCells
   * @param southwestCornerOfLeftLayer
   * @throws NoninvertibleTransformException
   */
  public static void crearCentrarCuadricula(
      PlugInContext plugContext,
      double cellSideLengthX,
      double cellSideLengthY,
      int layerWidthInCells,
      int layerHeightInCells,
      Coordinate southwestCornerOfLeftLayer) {
    // creación de la última cuadrícula
    GraticuleCreatorEngine graticuleCreator = new GraticuleCreatorEngine();
    graticuleCreator.setCellSideLengthX(cellSideLengthX);
    graticuleCreator.setCellSideLengthY(cellSideLengthY);
    graticuleCreator.setLayerWidthInCells(layerWidthInCells);
    graticuleCreator.setLayerHeightInCells(layerHeightInCells);
    graticuleCreator.setSouthwestCornerOfLeftLayer(southwestCornerOfLeftLayer);
    //        graticuleCreator.setCellSideLengthX((Double)
    // blackboard.get(GraticuleCreatorPlugIn.CELL_SIDE_LENGTH_X));
    //        graticuleCreator.setCellSideLengthY((Double)
    // blackboard.get(GraticuleCreatorPlugIn.CELL_SIDE_LENGTH_Y));
    //        graticuleCreator.setLayerWidthInCells((Integer)
    // blackboard.get(GraticuleCreatorPlugIn.LAYER_WIDTH_IN_CELLS));
    //      graticuleCreator.setLayerHeightInCells((Integer)
    // blackboard.get(GraticuleCreatorPlugIn.LAYER_HEIGHT_IN_CELLS));
    //        graticuleCreator.setSouthwestCornerOfLeftLayer((Coordinate)
    // blackboard.get(GraticuleCreatorPlugIn.SOUTHWEST_CORNER_OF_LEFT_LAYER));
    graticuleCreator.execute(plugContext);

    // centrado de la visión
    double minX = graticuleCreator.getSouthwestCornerOfLeftLayer().x;
    double minY = graticuleCreator.getSouthwestCornerOfLeftLayer().y;
    double maxX =
        minX + graticuleCreator.getLayerWidthInCells() * graticuleCreator.getCellSideLengthX();
    double maxY =
        minY + graticuleCreator.getLayerHeightInCells() * graticuleCreator.getCellSideLengthY();
    Envelope modelEnvelope = new Envelope(minX, maxX, minY, maxY);
    try {
      plugContext.getLayerViewPanel().getViewport().zoom(modelEnvelope);
    } catch (NoninvertibleTransformException e) {
      e.printStackTrace();
    }
  }
  private void onInfoRouteListeMouseClicked() {
    Object value = null;
    try {

      value = infoRouteJList.getSelectedValue();

      ArrayList<Geometry> geoArrayList = new ArrayList<Geometry>();

      if (value != null && value instanceof InfoRouteStretchBean) {
        InfoRouteStretchBean actualStretchBean = (InfoRouteStretchBean) value;

        if (actualStretchBean != null
            && actualStretchBean.getGeometries() != null
            && !actualStretchBean.getGeometries().isEmpty()) {
          geoArrayList.addAll(actualStretchBean.getGeometries());
        }

        if (value instanceof TurnRouteStreetchBean) {
          GeometryFactory geoFactory = new GeometryFactory();
          if (((TurnRouteStreetchBean) value).getTurnNode() != null) {
            geoArrayList.add(
                geoFactory.createPoint(
                    ((XYNode) ((TurnRouteStreetchBean) value).getTurnNode()).getCoordinate()));
          }
        }

        zoomToSelectedItemsPlugIn.zoom(geoArrayList, pluginContext.getLayerViewPanel());
      }

    } catch (Exception ex) {
      ex.printStackTrace();
      ErrorDialog.show(
          null,
          "Error resaltar un tramo de la ruta.",
          I18N.get(
              "routedescription", "routeengine.route.description.error.route.not.zoom.message"),
          StringUtil.stackTrace(ex));
    }
  }
  public boolean execute(PlugInContext context) throws Exception {
    // Don't make this plug-in undoable -- it's a lot of data to store in memory [Jon Aquino]
    context.getLayerManager().getUndoableEditReceiver().reportIrreversibleChange();

    CoordinateSystem destination =
        (CoordinateSystem)
            JOptionPane.showInputDialog(
                (Component) context.getWorkbenchGuiComponent(),
                AppContext.getApplicationContext().getI18nString("SelectCoordinateReferenceSystem"),
                AppContext.getApplicationContext().getI18nString("CoordinateReferenceSystem"),
                JOptionPane.PLAIN_MESSAGE,
                null,
                new ArrayList(
                        CoordinateSystemRegistry.instance(
                                context.getWorkbenchContext().getBlackboard())
                            .getCoordinateSystems())
                    .toArray(),
                context.getLayerManager().getCoordinateSystem());

    if (destination == null) {
      return false;
    }

    if (context.getLayerManager().getCoordinateSystem() == destination) {
      return true;
    }

    if (Reprojector.instance()
        .wouldChangeValues(context.getLayerManager().getCoordinateSystem(), destination)) {
      // Two-phase commit [Jon Aquino]
      ArrayList transactions = new ArrayList();

      for (Iterator i = context.getLayerManager().iterator(); i.hasNext(); ) {
        Layer layer = (Layer) i.next();
        EditTransaction transaction =
            new EditTransaction(
                layer.getFeatureCollectionWrapper().getFeatures(),
                getName(),
                layer,
                isRollingBackInvalidEdits(context),
                false,
                context.getLayerViewPanel());

        for (int j = 0; j < transaction.size(); j++) {
          Reprojector.instance()
              .reproject(
                  transaction.getGeometry(j),
                  context.getLayerManager().getCoordinateSystem(),
                  destination);
        }

        transactions.add(transaction);
      }

      EditTransaction.commit(transactions);
    }
    // cambia

    for (Iterator i = context.getLayerManager().iterator(); i.hasNext(); ) {
      Layer layer = (Layer) i.next();
      layer.getFeatureCollectionWrapper().getFeatureSchema().setCoordinateSystem(destination);
      DataSourceQuery dsq = layer.getDataSourceQuery();
      if (dsq != null)
        dsq.getDataSource()
            .getProperties()
            .put(DataSource.COORDINATE_SYSTEM_KEY, destination.getName());
    }

    context.getLayerManager().setCoordinateSystem(destination);

    if (context.getLayerViewPanel() != null) {
      context.getLayerViewPanel().getViewport().zoomToFullExtent();
    }

    return true;
  }
  private JScrollPane getGraticuleCells() {
    // sacamos las cuadrículas de la rejilla
    LayerManager layerManager = context.getLayerManager();
    Layer graticuleLayer = layerManager.getLayer(GraticuleCreatorEngine.getGraticuleName());
    if (graticuleLayer != null) {
      FeatureCollectionWrapper fCollWrapper = graticuleLayer.getFeatureCollectionWrapper();
      List featList = fCollWrapper.getFeatures();
      jComboList = new ArrayList<JComboBox>();
      Feature feature = null;
      Integer cellId = null;
      JPanel jPaneCells = new JPanel();
      int cols = featList.size() / 2;
      if (featList.size() % 2 != 0) {
        cols++;
      }
      jPaneCells.setLayout(new GridLayout(cols, 2));

      //	        //capas extraídas
      //	        ArrayList<GeopistaLayer> writeableLayers = (ArrayList<GeopistaLayer>)
      // blackboard.get(MobileExtractPanel01.MOBILE_WRITEABLE_LAYERS);
      //	        ArrayList<GeopistaLayer> readableLayers = (ArrayList<GeopistaLayer>)
      // blackboard.get(MobileExtractPanel01.MOBILE_READABLE_LAYERS);
      //	        ArrayList<String> listLayersId = new ArrayList<String>();
      //	        GeopistaLayer geopistaLayer = null;
      //	        for(int i=0; i<writeableLayers.size(); i++){
      //	        	geopistaLayer = writeableLayers.get(i);
      //	        	listLayersId.add(String.valueOf(geopistaLayer.getId_LayerDataBase()));
      //	        }
      //	        for(int i=0; i<readableLayers.size(); i++){
      //	        	geopistaLayer = readableLayers.get(i);
      //	        	listLayersId.add(String.valueOf(geopistaLayer.getId_LayerDataBase()));
      //	        }

      // obtenemos el proyecto de extracción seleccionado de la pantalla anterior
      ExtractionProject eProject =
          (ExtractionProject) blackboard.get(MobileAssignCellsPanel01.SELECTED_EXTRACT_PROJECT);

      JPanel auxPanel = null;
      arrayNombresUsuarios = null;
      listaUsuariosPermisos = null;
      HashMap<String, String> usuariosAsignados = null;
      final String sUrlPrefix = Constants.APLICACION.getString("geopista.conexion.servidorurl");
      try {
        // añadimos los usuarios a los combos
        AdministradorCartografiaClient administradorCartografiaClient =
            new AdministradorCartografiaClient(
                sUrlPrefix
                    + WebAppConstants.GEOPISTA_WEBAPP_NAME
                    + ServletConstants.ADMINISTRADOR_CARTOGRAFIA_SERVLET_NAME);
        ListaUsuarios usersRealList =
            (ListaUsuarios)
                administradorCartografiaClient.getUsersPermLayers(
                    eProject.getIdExtractLayersList());
        // usuarios ya asignados
        usuariosAsignados =
            administradorCartografiaClient.getAssignCellsExtractProject(eProject.getIdProyecto());
        // usuarios con permisos sobre las capas
        Hashtable<String, Usuario> usuariosReales =
            (Hashtable<String, Usuario>) usersRealList.gethUsuarios();
        Set<String> keySetUsers = usuariosReales.keySet();
        arrayNombresUsuarios = new String[keySetUsers.size() + 1];
        arrayNombresUsuarios[0] = ComboItemGraticuleListener.SIN_ASIGNAR;
        listaUsuariosPermisos = new ArrayList<Usuario>();
        String userKey = null;
        Usuario usuario = null;
        int k = 1;
        for (Iterator iterator = keySetUsers.iterator(); iterator.hasNext(); ) {
          userKey = (String) iterator.next();
          usuario = usuariosReales.get(userKey);
          arrayNombresUsuarios[k] = usuario.getName();
          listaUsuariosPermisos.add(usuario);
          k++;
        }
      } catch (Exception e) {
        e.printStackTrace();
      }

      JComboBox jcombo = null;
      ILayerViewPanel layerViewPanel = (ILayerViewPanel) context.getLayerViewPanel();
      JLabel jLabelCelda = null;
      String cellIdStr = null;
      Map<Layer, HashSet<Feature>> visibleLayerToFeaturesInFenceMap = null;
      graticuleLayer.setVisible(false); // para quitar la cuadrícula de la intersección
      // añadimos el identificador de cada una al panel
      for (int i = 0; i < featList.size(); i++) {
        feature = (Feature) featList.get(i);
        visibleLayerToFeaturesInFenceMap =
            layerViewPanel.visibleLayerToFeaturesInFenceMap(feature.getGeometry());
        cellId = (Integer) feature.getAttribute(GraticuleCreatorEngine.ATR_CELL_ID);
        auxPanel = new JPanel();
        jLabelCelda =
            new JLabel(
                I18N.get(
                        MobileAssignCellsPlugin.PluginMobileExtracti18n,
                        MobilePluginI18NResource.MobileAssignCellsPanel02_celda)
                    + cellId);
        jcombo = new JComboBox(arrayNombresUsuarios);
        cellIdStr = String.valueOf(cellId);
        jcombo.setName(cellIdStr);

        // celdas con features o sin ellas
        if (visibleLayerToFeaturesInFenceMap == null
            || visibleLayerToFeaturesInFenceMap.size() == 0) {
          jLabelCelda.setEnabled(false);
          jcombo.setEnabled(false);
        } else {
          jLabelCelda.setForeground(Color.RED);
          jcombo.addItemListener(
              new ComboItemGraticuleListener(
                  layerViewPanel, graticuleLayer, feature, jLabelCelda, wizardContext));
          jComboList.add(jcombo);
        }

        auxPanel.add(jLabelCelda);
        auxPanel.add(jcombo);
        jPaneCells.add(auxPanel);
      }
      graticuleLayer.setVisible(true);

      // seleccionamos los usuario asignados en los combos
      if (usuariosAsignados != null && usuariosAsignados.size() != 0) {
        for (int i = 0; i < jComboList.size(); i++) {
          jcombo = jComboList.get(i);
          cellIdStr = jcombo.getName();
          if (usuariosAsignados.containsKey(cellIdStr)) {
            seleccionaUsuarioComboCelda(jcombo, usuariosAsignados.get(cellIdStr));
          }
        }
      }

      jPaneInternal = new JScrollPane();
      jPaneInternal.setViewportView(jPaneCells);
      jPaneInternal.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    }

    return jPaneInternal;
  }
Beispiel #13
0
  public boolean execute(PlugInContext context) throws Exception {
    if (context.getLayerViewPanel() == null) return false;
    this.networkMgr = NetworkModuleUtilWorkbench.getNetworkManager(context);
    configProperties = new CalcRutaConfigFileReaderWriter();
    if (configProperties.getRedesNames() == null) {
      context
          .getLayerViewPanel()
          .getContext()
          .warnUser(
              I18N.get("calcruta", "routeengine.calcularruta.errormessage.emptyconfiguration"));
      return false;
    }
    this.context = context;
    nodesInfo = new HashMap<Integer, VirtualNodeInfo>();
    configuatorNetworks = new HashMap<String, Network>();

    nodesFeatureCol = AddNewLayerPlugIn.createBlankFeatureCollection();
    nodesFeatureCol.getFeatureSchema().addAttribute("nodeId", AttributeType.INTEGER);

    if (context.getLayerManager().getLayer("Puntos para TSP") != null) {
      context.getLayerManager().remove(sourcePointLayer);
    }

    sourcePointLayer = context.addLayer("Puntos TSP", "Puntos para TSP", nodesFeatureCol);

    //		LabelStyle labelStyle = new LabelStyle();
    //		labelStyle.setAttribute("nodeId");
    //		labelStyle.setColor(Color.black);
    //		labelStyle.setScaling(false);
    //		labelStyle.setEnabled(true);
    //		sourcePointLayer.addStyle(labelStyle);

    if (networkMgr == null) {
      context.getLayerViewPanel().getContext().warnUser("Error en el NetworkManager.");
      return false;
    }

    if (networkMgr.getNetworks().isEmpty()) {
      context
          .getLayerViewPanel()
          .getContext()
          .warnUser("No hay redes cargadas en el NetworkManager");
      return false;
    }

    if (configProperties.getRedesNames().length <= 0) {
      context
          .getLayerViewPanel()
          .getContext()
          .warnUser("Error en la configuracion. Inicie el configurador de rutas");
    }

    String redes[] = configProperties.getRedesNames();
    for (int i = 0; i < redes.length; i++) {
      configuatorNetworks.put(
          redes[i], ((LocalGISNetworkManager) networkMgr).getAllNetworks().get(redes[i]));
    }
    for (int m = 0; m < configuatorNetworks.values().size(); m++) {
      if (configuatorNetworks.values().toArray()[m] == null) {
        context
            .getLayerViewPanel()
            .getContext()
            .warnUser("Error en la configuracion. Inicie el configurador de rutas");
        return false;
      }
    }

    ToolboxDialog toolbox = new ToolboxDialog(context.getWorkbenchContext());
    //		toolbox.add();
    //
    //		RouteEngineDrawPointTool.createCursor(IconLoader.icon("bandera.gif").getImage());
    context
        .getLayerViewPanel()
        .setCurrentCursorTool(RouteEngineTSPDrawPointTool.create(toolbox.getContext()));

    return false;
  }
  /**
   * @param context
   * @throws IOException
   */
  private void saveTrafficRegulationInformation(PlugInContext context, TaskMonitor monitor)
      throws IOException {

    String netName = "";
    if (getSelectedLayer().getSystemId().startsWith("Arcos-")) {
      String[] a = getSelectedLayer().getSystemId().split("-");
      netName = a[1];
      System.out.println(a.length);
      for (int i = 2; i < a.length; i++) {
        netName = netName + "-" + a[i];
      }
    } else {
      netName = getSelectedLayer().getSystemId();
    }

    ArrayList<GeopistaFeature> listaFeatures = this.getSelectedsArrayListStreetFeature();
    ArrayList<Integer> listaEdgeIds = this.getSelectedsArrayListEdgesIds();

    for (int i = 0; i < listaFeatures.size(); i++) {

      monitor.report("Modificando Direccion tramo " + i + " de " + listaEdgeIds.size());

      Edge selectedEdge = searchEdgeByIdAndNetworkName(context, netName, listaEdgeIds.get(i));

      if (selectedEdge instanceof LocalGISStreetDynamicEdge) {
        // Se actualiza el StreetEdge
        ((LocalGISStreetDynamicEdge) selectedEdge).setTrafficRegulation(getTrafficRegualtion());

        RouteArrowLineStyle line =
            new RouteArrowLineStyle.BiDirect(
                (Viewport) context.getLayerViewPanel().getViewport(),
                (Graphics2D) ((LayerViewPanel) context.getLayerViewPanel()).getGraphics());
        if (this.getSelectedLayer().getStyle(RouteArrowLineStyle.class) != null) {
          getSelectedLayer().removeStyle(getSelectedLayer().getStyle(RouteArrowLineStyle.class));
        }
        getSelectedLayer().addStyle(line);

        GeopistaFeature feat = listaFeatures.get(i);

        if (feat != null) {
          // se actualiza el valor de la feature
          feat.setAttribute(
              I18N.get(
                  "regulacionTrafico",
                  "routeengine.trafficregulation.trafficregulationattributename"),
              getTrafficRegualtion().toString());
          //					this.paintBidirectTrafiicRegulation(getTrafficRegualtion());

          if (feat.getSchema().hasAttribute("pintadaRegulacionTrafico")
              && feat.getAttribute("pintadaRegulacionTrafico") != null
              && feat.getAttribute("pintadaRegulacionTrafico") instanceof Integer) {
            try {
              feat.setAttribute("pintadaRegulacionTrafico", 1);
            } catch (Exception e) {
            }
          }
        }

        context.getLayerViewPanel().repaint();
      }
      NetworkManager nManager = NetworkModuleUtilWorkbench.getNetworkManager(context);
      Network actualNetwork = nManager.getNetwork(netName);

      // intentamos insercion en la base de datos de la velocidad de la v�a
      Category categoryLayer = context.getLayerManager().getCategory(getSelectedLayer());
      if (!categoryLayer.getName().equals("")) {
        if (actualNetwork.getGraph() instanceof DynamicGraph
            && ((DynamicGraph) actualNetwork.getGraph()).getMemoryManager()
                instanceof SpatialAllInMemoryExternalSourceMemoryManager) {
          RouteConnectionFactory routeConnection = new GeopistaRouteConnectionFactoryImpl();
          LocalGISNetworkDAO lnDAO = new LocalGISNetworkDAO();
          Connection connection = null;
          try {
            connection = routeConnection.getConnection();
            lnDAO.updateStreetData(netName, (LocalGISStreetDynamicEdge) selectedEdge, connection);
          } catch (SQLException e) {
            e.printStackTrace();
          } catch (Exception e) {
            e.printStackTrace();
          } finally {
            ConnectionUtilities.closeConnection(connection);
          }
        }
      }
    }
  }
  private JButton getGraticuleButton() {
    jButtonGraticule =
        new JButton(
            I18N.get(
                MobileExtractPlugin.PluginMobileExtracti18n,
                MobilePluginI18NResource.MobileExtractPanel03_crearCuadricula));

    LayerManager layerManager = context.getLayerManager();
    Layer graticuleLayer = layerManager.getLayer(GraticuleCreatorEngine.getGraticuleName());

    // si ya existe una capa cuadrícula significa que se trata de un fichero importado previamente a
    // ejecutar el asistente
    if (graticuleLayer != null) {
      jButtonGraticule.setEnabled(false);

      if (bCuadriculaCreada == true) {
        // solo ejecutamos este código una vez
        return jButtonGraticule;
      }

      FeatureCollectionWrapper graticuleCollectionWrapper =
          graticuleLayer.getFeatureCollectionWrapper();
      FeatureSchema featureSchema = graticuleCollectionWrapper.getFeatureSchema();

      // cuadriculas visionadas
      IViewport viewport = (IViewport) context.getLayerViewPanel().getViewport();
      Envelope viewEnvelope = viewport.getEnvelopeInModelCoordinates();
      List<Feature> graticuleFeatures = graticuleCollectionWrapper.query(viewEnvelope);
      // ordenamos por distancia al origen las features
      List<SortedFeature> sortedGraticuleFeatures = new ArrayList<SortedFeature>();
      Feature feature = null;
      SortedFeature sortFeat = null;
      for (Iterator iterator = graticuleFeatures.iterator(); iterator.hasNext(); ) {
        feature = (Feature) iterator.next();
        sortFeat = new SortedFeature(feature);
        sortedGraticuleFeatures.add(sortFeat);
      }
      Collections.sort(sortedGraticuleFeatures);

      // borramos el resto de cuadrículas
      graticuleCollectionWrapper.clear();
      graticuleCollectionWrapper.addAll(graticuleFeatures);
      Envelope newWrapperEnvelope = graticuleCollectionWrapper.getEnvelope();

      // zoom al envelope actual
      try {
        viewport.zoom(newWrapperEnvelope);
      } catch (NoninvertibleTransformException e) {
        log.warn("No se ha podido alcanzar el zoom " + newWrapperEnvelope);
      }

      // ajustamos la ventana al envelope de la cuadrícula
      resizeViewToEnvelope(context, newWrapperEnvelope, viewport);

      // guardamos las propiedades gráficas de la extracción
      Envelope featEnvelope =
          sortedGraticuleFeatures.get(0).getFeature().getGeometry().getEnvelopeInternal();
      Double featWidth = featEnvelope.getWidth();
      Double featHeight = featEnvelope.getHeight();
      Double minX = newWrapperEnvelope.getMinX();
      Double minY = newWrapperEnvelope.getMinY();
      Coordinate coordCorner = new Coordinate(minX, minY);
      blackboard.put(GraticuleCreatorPlugIn.SOUTHWEST_CORNER_OF_LEFT_LAYER, coordCorner);
      blackboard.put(GraticuleCreatorPlugIn.CELL_SIDE_LENGTH_X, featWidth);
      blackboard.put(GraticuleCreatorPlugIn.CELL_SIDE_LENGTH_Y, featHeight);
      Integer numCeldasAncho = (int) (newWrapperEnvelope.getWidth() / featWidth);
      Integer numCeldasAlto = (int) (newWrapperEnvelope.getHeight() / featHeight);
      blackboard.put(GraticuleCreatorPlugIn.LAYER_WIDTH_IN_CELLS, numCeldasAncho);
      blackboard.put(GraticuleCreatorPlugIn.LAYER_HEIGHT_IN_CELLS, numCeldasAlto);

      // creamos celdas para los espacios en blanco
      if (sortedGraticuleFeatures.size() < numCeldasAncho * numCeldasAlto) {
        Double curMinX = minX;
        Double curMinY = minY;
        Double fMinX = 0.0;
        GeometryFactory geoFact = new GeometryFactory();
        Feature newFeature = null;
        for (int i = 0; i < sortedGraticuleFeatures.size(); i++) {
          sortFeat = sortedGraticuleFeatures.get(i);
          feature = sortFeat.getFeature();
          fMinX = feature.getGeometry().getEnvelopeInternal().getMinX();
          if (curMinX.doubleValue() != fMinX.doubleValue()) {
            // creamos la feature
            newFeature = (Feature) feature.clone();
            Coordinate[] coordArray = {
              new Coordinate(curMinX, curMinY),
              new Coordinate(curMinX + featWidth, curMinY),
              new Coordinate(curMinX + featWidth, curMinY + featHeight),
              new Coordinate(curMinX, curMinY + featHeight),
              new Coordinate(curMinX, curMinY)
            };

            newFeature.setGeometry(
                geoFact.createPolygon(geoFact.createLinearRing(coordArray), null));
            sortedGraticuleFeatures.add(i, new SortedFeature(newFeature));
            graticuleCollectionWrapper.add(newFeature);
          }
          // para lo último
          else if ((i == sortedGraticuleFeatures.size() - 1)
              && ((minX + (featWidth * numCeldasAncho)) != (fMinX + featWidth))) {
            curMinX = fMinX + featWidth;
            newFeature = (Feature) feature.clone();
            Coordinate[] coordArray = {
              new Coordinate(curMinX, curMinY),
              new Coordinate(curMinX + featWidth, curMinY),
              new Coordinate(curMinX + featWidth, curMinY + featHeight),
              new Coordinate(curMinX, curMinY + featHeight),
              new Coordinate(curMinX, curMinY)
            };

            newFeature.setGeometry(
                geoFact.createPolygon(geoFact.createLinearRing(coordArray), null));
            sortedGraticuleFeatures.add(
                sortedGraticuleFeatures.size(), new SortedFeature(newFeature));
            graticuleCollectionWrapper.add(newFeature);
            continue;
          }

          if (((i + 1) % numCeldasAncho) != 0) {
            curMinX = curMinX + featWidth;
          } else { // ultima celda de cada fila
            curMinX = minX;
            curMinY += featHeight;
          }
        }
      }

      // añadimos el atributo cellid
      featureSchema.addAttribute(GraticuleCreatorEngine.ATR_CELL_ID, AttributeType.INTEGER);
      int k = 1;
      Object[] featAttribs = null;
      Object[] newFeatAttribs = null;
      for (Iterator iterator = sortedGraticuleFeatures.iterator(); iterator.hasNext(); k++) {
        feature = ((SortedFeature) iterator.next()).getFeature();
        featAttribs = feature.getAttributes();
        newFeatAttribs = new Object[featAttribs.length + 1];
        for (int i = 0; i < featAttribs.length; i++) {
          newFeatAttribs[i] = featAttribs[i];
        }
        newFeatAttribs[newFeatAttribs.length - 1] = k;
        feature.setAttributes(newFeatAttribs);
      }
      // pintamos el atributo en la capa
      LabelStyle labelStyle = graticuleLayer.getLabelStyle();
      labelStyle.setColor(Color.RED);
      labelStyle.setHeight(labelStyle.getHeight() * 4);
      labelStyle.setAttribute(GraticuleCreatorEngine.ATR_CELL_ID);
      labelStyle.setEnabled(true);

      // evitamos que se modifiquen las cuadrículas
      graticuleLayer.setEditable(false);
      graticuleLayer.fireAppearanceChanged();

      bCuadriculaCreada = true;
    }
    // llamada al graticulePlugin
    else {
      jButtonGraticule.addActionListener(
          new ActionListener() {

            public void actionPerformed(ActionEvent e) {
              GraticuleCreatorPlugIn graticulePlugin = new GraticuleCreatorPlugIn();
              try {
                graticulePlugin.execute(context);
              } catch (Exception e1) {
                e1.printStackTrace();
              }
              wizardContext.inputChanged(); // indicamos que ya se puede habilitar el boton
            }
          });
    }

    return jButtonGraticule;
  }
  public boolean execute(PlugInContext context) throws Exception {
    LineString a = null;
    List capasVisibles =
        context.getWorkbenchContext().getLayerNamePanel().getLayerManager().getVisibleLayers(true);

    context.getLayerViewPanel().getLayerManager().getVisibleLayers(true);
    context.getLayerNamePanel().getLayerManager().getVisibleLayers(false);

    Iterator capasVisiblesIter = capasVisibles.iterator();
    boolean cancelWhile = false;

    final LockManager lockManager =
        (LockManager)
            context
                .getActiveTaskComponent()
                .getLayerViewPanel()
                .getBlackboard()
                .get(LockManager.LOCK_MANAGER_KEY);

    while (capasVisiblesIter.hasNext()) {
      Layer capaActual = (Layer) capasVisiblesIter.next();
      Collection featuresSeleccionadas =
          context
              .getWorkbenchContext()
              .getLayerViewPanel()
              .getSelectionManager()
              .getFeaturesWithSelectedItems(capaActual);

      // Almacenamos en este ArrayList el resultado de la operacion de
      // bloqueo

      Iterator featuresSeleccionadasIter = featuresSeleccionadas.iterator();
      while (featuresSeleccionadasIter.hasNext()) {
        if (cancelWhile == true) {
          if (JOptionPane.showConfirmDialog(
                  (Component) context.getWorkbenchGuiComponent(),
                  aplicacion.getI18nString("GeopistaFeatureSchemaPlugIn.RestoFeatures"),
                  aplicacion.getI18nString("GeopistaFeatureSchemaPlugIn.EditarMultiplesEntidades"),
                  JOptionPane.YES_NO_OPTION)
              == JOptionPane.NO_OPTION) return false;
          else cancelWhile = false;
        }

        localFeature = (Feature) featuresSeleccionadasIter.next();
        String systemId = ((GeopistaFeature) localFeature).getSystemId();
        final ArrayList lockResultaArrayList = new ArrayList();
        // capa de sistema. La feature debe bloquearse
        if (capaActual instanceof GeopistaLayer
            && !((GeopistaLayer) capaActual).isLocal()
            && !((GeopistaLayer) capaActual).isExtracted()
            && capaActual.isEditable()
            && systemId != null
            && !((GeopistaFeature) localFeature).isTempID()
            && !systemId.equals("")) {

          final TaskMonitorDialog progressDialog =
              new TaskMonitorDialog(aplicacion.getMainFrame(), context.getErrorHandler());

          progressDialog.setTitle(aplicacion.getI18nString("LockFeatures"));
          progressDialog.addComponentListener(
              new ComponentAdapter() {
                public void componentShown(ComponentEvent e) {

                  // Wait for the dialog to appear before starting the
                  // task. Otherwise
                  // the task might possibly finish before the dialog
                  // appeared and the
                  // dialog would never close. [Jon Aquino]
                  new Thread(
                          new Runnable() {
                            public void run() {

                              try {

                                Integer lockID =
                                    lockManager.lockFeature(localFeature, progressDialog);
                                lockResultaArrayList.add(lockID);
                              } catch (Exception e) {

                              } finally {
                                progressDialog.setVisible(false);
                              }
                            }
                          })
                      .start();
                }
              });
          GUIUtil.centreOnWindow(progressDialog);
          progressDialog.setVisible(true);
        }

        FeatureDialog featureDialog =
            new FeatureDialog(
                GeopistaFunctionUtils.getFrame(context.getWorkbenchGuiComponent()),
                "Atributos",
                true,
                localFeature,
                context.getWorkbenchContext().getLayerViewPanel(),
                capaActual);

        Integer tempLockID = null;
        Iterator lockResultaArrayListIter = lockResultaArrayList.iterator();
        if (lockResultaArrayListIter.hasNext()) {
          tempLockID = (Integer) lockResultaArrayListIter.next();
        }
        final Integer lockID = tempLockID;

        try {

          ImageIcon icon = IconLoader.icon("logo_geopista.png");

          featureDialog.setSideBarImage(null);
        } catch (NullPointerException e) {
          e.printStackTrace();
        }

        if (capaActual instanceof GeopistaLayer) {
          String extendedForm = ((GeopistaLayer) capaActual).getFieldExtendedForm();
          if (extendedForm == null) extendedForm = "";
          if (!extendedForm.equals("")) {

            featureDialog.setExtendedForm(extendedForm);
          }
        }

        featureDialog.buildDialog();
        if ((capaActual instanceof GeopistaLayer
                && (((GeopistaLayer) capaActual).isLocal()
                    || ((GeopistaLayer) capaActual).isExtracted())
                && !capaActual.isEditable())
            || (lockID == null
                && capaActual instanceof GeopistaLayer
                && !((GeopistaLayer) capaActual).isLocal()
                && !((GeopistaLayer) capaActual).isExtracted()
                && !capaActual.isEditable()
                && systemId != null
                && !((GeopistaFeature) localFeature).isTempID()
                && !systemId.equals(""))) {
          featureDialog.setLock();
        }
        featureDialog.setVisible(true);

        // solo para GeopistaLayer

        if (featureDialog.wasOKPressed()) {
          if (capaActual.isEditable()) {

            if (capaActual instanceof GeopistaLayer
                && !((GeopistaLayer) capaActual).isLocal()
                && lockID == null) continue;
            // obtenemos la feature con los cambios introducidos por
            // el usuario
            clonefeature = featureDialog.getModifiedFeature();
            // Actualiza los parámetros
            execute(
                new UndoableCommand(getName()) {

                  public void execute() {

                    localFeature.setAttributes(clonefeature.getAttributes());
                  }

                  public void unexecute() {
                    ((GeopistaFeature) clonefeature).setFireDirtyEvents(false);
                    clonefeature.setAttributes(localFeature.getAttributes());
                    ((GeopistaFeature) clonefeature).setFireDirtyEvents(true);
                  }
                },
                context);
          }

        } else {
          // el usuario ha pedido cancelar la edición
          cancelWhile = true;
        }

        if (lockID != null) {
          final TaskMonitorDialog progressDialogFinal =
              new TaskMonitorDialog(aplicacion.getMainFrame(), context.getErrorHandler());

          progressDialogFinal.setTitle(aplicacion.getI18nString("UnlockFeatures"));
          progressDialogFinal.addComponentListener(
              new ComponentAdapter() {
                public void componentShown(ComponentEvent e) {

                  // Wait for the dialog to appear before starting
                  // the
                  // task. Otherwise
                  // the task might possibly finish before the
                  // dialog
                  // appeared and the
                  // dialog would never close. [Jon Aquino]
                  new Thread(
                          new Runnable() {
                            public void run() {

                              try {

                                lockManager.unlockFeaturesByLockId(lockID, progressDialogFinal);
                              } catch (Exception e) {

                              } finally {
                                progressDialogFinal.setVisible(false);
                              }
                            }
                          })
                      .start();
                }
              });
          GUIUtil.centreOnWindow(progressDialogFinal);
          progressDialogFinal.setVisible(true);
        }
      }
    }

    return false;
  }
  public boolean execute(PlugInContext context) throws Exception {
    reportNothingToUndoYet(context);
    context.getLayerViewPanel().getViewport().zoomToFullExtent();

    return true;
  }