public void enteredFromLeft(Map dataMap) {
    if (!Constants.APLICACION.isLogged()) {
      Constants.APLICACION.login();
    }
    if (!Constants.APLICACION.isLogged()) {
      wizardContext.cancelWizard();
      return;
    }

    try {
      jbInit();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #2
0
  public boolean execute(PlugInContext context) throws Exception {
    reportNothingToUndoYet(context);

    // limpiamos lo que haya podido quedar de ejecuciones anteriores
    emptyBlackboard();

    WizardDialog d =
        new WizardDialog(
            GeopistaUtil.getFrame(context.getWorkbenchGuiComponent()),
            Constants.APLICACION.getI18nString("ExtractDialogGestionar"),
            context.getErrorHandler());
    d.init(
        new WizardPanel[] {
          new MobileModifyPanel01("MobileModifyPanel01", null, context),
        });

    d.setSize(520, 650);
    d.setLocation(10, 20);
    d.setVisible(true);

    if (!d.wasFinishPressed()) {
      LayerManager layerManager = context.getLayerManager();
      if (layerManager != null) {
        Layer graticuleLayer = layerManager.getLayer(GraticuleCreatorEngine.getGraticuleName());
        // si existe una cuadrícula la borramos
        if (graticuleLayer != null) {
          layerManager.remove(graticuleLayer);
        }
      }
      return false;
    }

    return true;
  }
예제 #3
0
  /*
   * Se ejecuta una vez finalizado el interfaz despues de pasar por todas las pantallas.
   * (non-Javadoc)
   * @see com.vividsolutions.jump.workbench.plugin.ThreadedPlugIn#run(com.vividsolutions.jump.task.TaskMonitor, com.vividsolutions.jump.workbench.plugin.PlugInContext)
   */
  public void run(TaskMonitor monitor, PlugInContext context) throws Exception {
    try {
      monitor.report(
          I18N.get(
              PluginMobileExtracti18n, MobilePluginI18NResource.MobileModifyPanel01_deletingProy));

      ExtractionProject eProject =
          (ExtractionProject) blackboard.get(MobileModifyPanel01.SELECTED_EXTRACT_PROJECT);

      // guardamos la informacion en base de datos
      final String sUrlPrefix =
          Constants.APLICACION.getString(UserPreferenceConstants.LOCALGIS_SERVER_URL);
      AdministradorCartografiaClient administradorCartografiaClient =
          new AdministradorCartografiaClient(
              sUrlPrefix
                  + WebAppConstants.GEOPISTA_WEBAPP_NAME
                  + ServletConstants.ADMINISTRADOR_CARTOGRAFIA_SERVLET_NAME);
      administradorCartografiaClient.deleteExtractProject(eProject);

      // Borramos los datos subidos al servidor.
      httpDeleteProject(Constants.URL_DELETE_SERVER, eProject);

      String dirBase =
          UserPreferenceStore.getUserPreference(
              UserPreferenceConstants.PREFERENCES_DATA_PATH_KEY,
              UserPreferenceConstants.DEFAULT_DATA_PATH,
              true);
      dirBase += File.separator + "maps";

      String projectName = eProject.getNombreProyecto();
      String idProyecto = eProject.getIdProyecto();

      String dirMapName = projectName + "." + idProyecto;
      File dirBaseMake = new File(dirBase, dirMapName);
      if (dirBaseMake.exists()) {
        MobileUtils.deleteDir(dirBaseMake);
        logger.info("Borrando fichero local:" + dirBaseMake);
      }

    } finally {
      // borramos la cuadrícula
      LayerManager layerManager = context.getLayerManager();
      Layer graticuleLayer = layerManager.getLayer(GraticuleCreatorEngine.getGraticuleName());
      if (graticuleLayer != null) {
        layerManager.remove(graticuleLayer);
      }
    }
  }
public class MobileAssignCellsPanel02 extends JPanel implements WizardPanel {
  public static final String MOBILE_USERS_GRATICULES = "MOBILE_USERS_GRATICULES";
  private Blackboard blackboard = Constants.APLICACION.getBlackboard();
  private String localId = null;
  private WizardContext wizardContext;
  private PlugInContext context;
  private List<JComboBox> jComboList;

  /** @return null to turn the Next button into a Finish button */
  private String nextID = null;

  private JScrollPane jPaneInternal;
  private String[] arrayNombresUsuarios; // array de usuarios de los combos
  private JComboBox jcomboSelecAll;
  private List<Usuario>
      listaUsuariosPermisos; // lista de usuarios con permiso de lectura sobre las capas extraídas

  public MobileAssignCellsPanel02(String id, String nextId, PlugInContext context) {
    this.nextID = nextId;
    this.localId = id;
    this.context = context;
    this.arrayNombresUsuarios = null;
    this.listaUsuariosPermisos = null;
  }

  public void enteredFromLeft(Map dataMap) {
    if (!Constants.APLICACION.isLogged()) {
      Constants.APLICACION.login();
    }
    if (!Constants.APLICACION.isLogged()) {
      wizardContext.cancelWizard();
      return;
    }

    try {
      jbInit();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private void jbInit() throws Exception {
    this.removeAll();

    // creamos y centramos la cuadrícula con los valores pasados
    //    	crearCentrarCuadricula(context, (Double)
    // blackboard.get(GraticuleCreatorPlugIn.CELL_SIDE_LENGTH_X),
    //    			(Double) blackboard.get(GraticuleCreatorPlugIn.CELL_SIDE_LENGTH_Y),
    //    			(Integer) blackboard.get(GraticuleCreatorPlugIn.LAYER_HEIGHT_IN_CELLS),
    //    			(Integer) blackboard.get(GraticuleCreatorPlugIn.LAYER_WIDTH_IN_CELLS),
    //    			(Coordinate) blackboard.get(GraticuleCreatorPlugIn.SOUTHWEST_CORNER_OF_LEFT_LAYER));

    this.setLayout(new GridBagLayout());
    java.awt.GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
    gridBagConstraints1.gridx = 0;
    gridBagConstraints1.gridy = 1;
    gridBagConstraints1.weightx = 1.0;
    gridBagConstraints1.weighty = 1.0;
    gridBagConstraints1.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints1.ipadx = -21;
    gridBagConstraints1.ipady = 141;
    java.awt.GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
    gridBagConstraints2.gridx = 0;
    gridBagConstraints2.gridy = 0;
    gridBagConstraints2.insets = new java.awt.Insets(5, 5, 5, 5);
    this.add(getGraticuleCells(), gridBagConstraints1);
    this.add(getPanelButtonAllUser(), gridBagConstraints2);
  }

  /**
   * 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 Component getPanelButtonAllUser() {
    JPanel jpanelAll = new JPanel();
    jcomboSelecAll = new JComboBox(arrayNombresUsuarios);
    JButton jButtonSelecAll =
        new JButton(
            I18N.get(
                MobileAssignCellsPlugin.PluginMobileExtracti18n,
                MobilePluginI18NResource.MobileAssignCellsPanel02_asignTodas));
    jButtonSelecAll.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            int selectIndex = jcomboSelecAll.getSelectedIndex();
            for (int i = 0; i < jComboList.size(); i++) {
              jComboList.get(i).setSelectedIndex(selectIndex);
            }
          }
        });

    // añadimos al panel final
    jpanelAll.add(jButtonSelecAll);
    jpanelAll.add(jcomboSelecAll);

    return jpanelAll;
  }

  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;
  }

  /**
   * Selecciona un elemento del combo en caso de existir
   *
   * @param jcombo
   * @param listaUsuariosPermisos2
   * @param idUser
   */
  private void seleccionaUsuarioComboCelda(JComboBox jcombo, String idUser) {
    Usuario u = null;
    // buscamos en la lista de usuarios con permisos reales sobre las capas extraídas
    for (int i = 0; i < listaUsuariosPermisos.size(); i++) {
      u = listaUsuariosPermisos.get(i);
      if (u.getId().equals(idUser)) {
        jcombo.setSelectedIndex(i + 1);
      }
    }
  }

  /** Called when the user presses Next on this panel */
  public void exitingToRight() throws Exception {
    /** guardamos las celdas que tienen usuario asignado * */
    JComboBox jCombo = null;
    String idCelda;
    String idSelectedUsuario;
    HashMap<String, String> celdasUsuarios =
        new HashMap<String, String>(); // lista de usuarios asignados a la celda que es índice
    int selectedIndex;
    for (int i = 0; i < jComboList.size(); i++) {
      jCombo = jComboList.get(i);
      idCelda = jCombo.getName();
      selectedIndex = jCombo.getSelectedIndex();
      idSelectedUsuario = ComboItemGraticuleListener.SIN_ASIGNAR;
      if (selectedIndex > 0) {
        idSelectedUsuario = listaUsuariosPermisos.get(selectedIndex - 1).getId();
      }
      celdasUsuarios.put(idCelda, idSelectedUsuario);
    }

    // añadimos al clipboard el map generado
    blackboard.put(MOBILE_USERS_GRATICULES, celdasUsuarios);
  }

  /**
   * Tip: Delegate to an InputChangedFirer.
   *
   * @param listener a party to notify when the input changes (usually the WizardDialog, which needs
   *     to know when to update the enabled state of the buttons.
   */
  public void add(InputChangedListener listener) {}

  public void remove(InputChangedListener listener) {}

  public String getTitle() {
    return this.getName();
  }

  public String getID() {
    return localId;
  }

  public String getInstructions() {
    return I18N.get(
        MobileAssignCellsPlugin.PluginMobileExtracti18n,
        MobilePluginI18NResource.MobileAssignCellsPanel02_asignUser);
  }

  public boolean isInputValid() {
    JComboBox jCombo = null;
    // si existe algún usuario seleccionado
    for (int i = 0; i < jComboList.size(); i++) {
      jCombo = jComboList.get(i);
      if (jCombo.getSelectedIndex() != 0) {
        return true;
      }
    }
    return false;
  }

  public void setWizardContext(WizardContext wd) {
    wizardContext = wd;
  }

  public void setNextID(String nextID) {
    this.nextID = nextID;
  }

  public String getNextID() {
    return nextID;
  }

  /* (non-Javadoc)
   * @see com.geopista.ui.wizard.WizardPanel#exiting()
   */
  public void exiting() {}
} //  @jve:decl-index=0:visual-constraint="10,10"
  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;
  }
예제 #6
0
public class MobileExtractPanel03 extends JPanel implements WizardPanel {
  private static Logger log = Logger.getLogger(MobileExtractPanel03.class);
  private static final String GEOMETRY_ATR = "geometry";
  private Blackboard blackboard = Constants.APLICACION.getBlackboard();
  private String localId = null;
  private WizardContext wizardContext;
  private PlugInContext context;
  private JButton jButtonGraticule;
  // capas desconectadas con permiso de modificación
  private JTree writeableAtributesTree;
  private NamedVector[] writeableRootNodes;
  public static final String MOBILE_WRITEABLE_LAYERS_ATRIB = "MOBILE_WRITEABLE_LAYERS_ATRIB";
  private JScrollPane writeableLayerScrollPane = null;
  // capas desconectadas con permiso de lectura
  private JTree readableAtributesTree;
  private NamedVector[] readableRootNodes;
  public static final String MOBILE_READABLE_LAYERS_ATRIB = "MOBILE_READABLE_LAYERS_ATRIB";
  private JScrollPane readableLayerScrollPane = null;

  public static final String MOBILE_PROJECT_NAME = "MOBILE_PROJECT_NAME";

  /** @return null to turn the Next button into a Finish button */
  private String nextID = null;

  private boolean bCuadriculaCreada;

  public MobileExtractPanel03(String id, String nextId, PlugInContext context) {
    this.nextID = nextId;
    this.localId = id;
    this.context = context;
    writeableAtributesTree = null;
    readableAtributesTree = null;
    bCuadriculaCreada = false;
  }

  public void enteredFromLeft(Map dataMap) {
    if (!Constants.APLICACION.isLogged()) {
      Constants.APLICACION.login();
    }
    if (!Constants.APLICACION.isLogged()) {
      wizardContext.cancelWizard();
      return;
    }

    writeableLayerScrollPane = null;
    readableLayerScrollPane = null;

    try {
      jbInit();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private void jbInit() throws Exception {
    this.removeAll();
    this.setLayout(new GridBagLayout());
    java.awt.GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
    gridBagConstraints1.gridx = 0;
    gridBagConstraints1.gridy = 1;
    gridBagConstraints1.weightx = 1.0;
    gridBagConstraints1.weighty = 1.0;
    gridBagConstraints1.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints1.ipadx = -21;
    gridBagConstraints1.ipady = 141;
    gridBagConstraints1.insets = new java.awt.Insets(5, 5, 5, 5);
    java.awt.GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
    gridBagConstraints2.gridx = 0;
    gridBagConstraints2.gridy = 2;
    gridBagConstraints2.insets = new java.awt.Insets(5, 5, 5, 5);
    java.awt.GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
    gridBagConstraints3.gridx = 0;
    gridBagConstraints3.gridy = 3;
    gridBagConstraints3.weightx = 1.0;
    gridBagConstraints3.weighty = 1.0;
    gridBagConstraints3.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints3.ipadx = -21;
    gridBagConstraints3.ipady = 141;
    gridBagConstraints3.insets = new java.awt.Insets(5, 5, 5, 5);

    java.awt.GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
    gridBagConstraints4.gridx = 0;
    gridBagConstraints4.gridy = 0;

    String projectName = (String) blackboard.get(MOBILE_PROJECT_NAME);
    JLabel extractionProjectNameLabel = new JLabel(projectName);

    this.add(extractionProjectNameLabel, gridBagConstraints4);

    this.add(getWriteableLayerScrollPane(), gridBagConstraints1);
    this.add(getReadableLayerScrollPane(), gridBagConstraints3);
    this.add(getGraticuleButton(), gridBagConstraints2);
  }

  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;
  }

  /**
   * 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);
    }
  }

  /**
   * This method initializes availableLayerScrollPane
   *
   * @return javax.swing.JScrollPane
   */
  private JScrollPane getWriteableLayerScrollPane() {
    if (writeableLayerScrollPane == null) {
      writeableLayerScrollPane = new JScrollPane();
      writeableAtributesTree = getWriteableLayerTree();
      writeableLayerScrollPane.setViewportView(writeableAtributesTree);
      writeableLayerScrollPane.setHorizontalScrollBarPolicy(
          javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    }
    return writeableLayerScrollPane;
  }
  /**
   * Retorna un árbol con las capas seleccionadas y sus atributos
   *
   * @return javax.swing.JList
   */
  private JTree getWriteableLayerTree() {
    ArrayList<GeopistaLayer> extractLayers =
        (ArrayList<GeopistaLayer>) blackboard.get(MobileExtractPanel01.MOBILE_WRITEABLE_LAYERS);
    writeableRootNodes = getRootLayerNodes(extractLayers);
    Vector rootVector =
        new NamedVector(
            I18N.get(
                MobileExtractPlugin.PluginMobileExtracti18n,
                MobilePluginI18NResource.MobileExtractPanel03_capasEdit),
            writeableRootNodes);
    JTree tree = new JTree(rootVector);
    tree.setFont(new Font(tree.getFont().getName(), Font.BOLD, tree.getFont().getSize()));
    CheckBoxNodeRenderer renderer = new CheckBoxNodeRenderer(Color.BLUE);
    tree.setCellRenderer(renderer);
    tree.setCellEditor(new CheckBoxNodeEditor(tree));
    tree.setEditable(true);

    //		DefaultMutableTreeNode root = new DefaultMutableTreeNode("Capas");
    //	    JTree tree = new JTree(root);
    //	    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
    //	    DefaultMutableTreeNode chosen = null;
    //	    if(extractLayers!=null){
    //			for (int i = 0; i < extractLayers.size(); i++) {
    //				geopistaLayer = extractLayers.get(i);
    //				chosen = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
    //				if (chosen == null){
    //					chosen = root;
    //				}
    //				model.insertNodeInto(getTreeNodeFromLayer(geopistaLayer), chosen, 0);
    //			}
    //	    }

    return tree;
  }

  /**
   * This method initializes availableLayerScrollPane
   *
   * @return javax.swing.JScrollPane
   */
  private JScrollPane getReadableLayerScrollPane() {
    if (readableLayerScrollPane == null) {
      readableLayerScrollPane = new JScrollPane();
      readableAtributesTree = getReadableLayerTree();
      readableLayerScrollPane.setViewportView(readableAtributesTree);
      readableLayerScrollPane.setHorizontalScrollBarPolicy(
          javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    }
    return readableLayerScrollPane;
  }
  /**
   * Retorna un árbol con las capas seleccionadas y sus atributos
   *
   * @return javax.swing.JList
   */
  private JTree getReadableLayerTree() {
    ArrayList<GeopistaLayer> extractLayers =
        (ArrayList<GeopistaLayer>) blackboard.get(MobileExtractPanel01.MOBILE_READABLE_LAYERS);
    readableRootNodes = getRootLayerNodes(extractLayers);
    Vector rootVector =
        new NamedVector(
            I18N.get(
                MobileExtractPlugin.PluginMobileExtracti18n,
                MobilePluginI18NResource.MobileExtractPanel03_capasLect),
            readableRootNodes);
    JTree tree = new JTree(rootVector);
    // tree.setFont(new Font(tree.getFont().getName(), Font.BOLD, tree.getFont().getSize()));
    CheckBoxNodeRenderer renderer = new CheckBoxNodeRenderer(Color.RED);
    tree.setCellRenderer(renderer);
    tree.setCellEditor(new CheckBoxNodeEditor(tree));
    tree.setEditable(true);
    return tree;
  }

  /**
   * Añade todos los atributos de las capas seleccionadas
   *
   * @param extractLayers
   * @return
   */
  private NamedVector[] getRootLayerNodes(ArrayList<GeopistaLayer> extractLayers) {
    NamedVector[] returnVector = null;
    if (extractLayers != null) {
      GeopistaLayer geopistaLayer = null;
      String layerSystemId;
      EIELFilesUtils eielFilesUtils;
      String layerName;
      returnVector = new NamedVector[extractLayers.size()];
      // capas
      for (int i = 0; i < extractLayers.size(); i++) {
        geopistaLayer = extractLayers.get(i);
        layerSystemId = geopistaLayer.getSystemId();
        eielFilesUtils = new EIELFilesUtils(layerSystemId);
        layerName = geopistaLayer.getName();

        // buscamos el identificador de cada capa
        GeopistaSchema featureGeoSchema =
            (GeopistaSchema) geopistaLayer.getFeatureCollectionWrapper().getFeatureSchema();
        // atributos
        NamedVector namedVector = new NamedVector(layerName);
        Column columnByAttribute = null;
        String colName = null;
        for (int j = 0; j < featureGeoSchema.getAttributeCount(); j++) {
          columnByAttribute = featureGeoSchema.getColumnByAttribute(j);
          colName = columnByAttribute.getName();
          if (colName.toLowerCase().equals(GEOMETRY_ATR)) { // no lo mostramos
            continue;
          }
          // CAMBIAR: COMPROBAR SI SE DEBE SELECCIONAR id SI ES TIPO EIEL
          else if (colName.toLowerCase().equals(Constants.FIELD_ID)) { // lo ponemos al principio
            namedVector.add(0, new CheckBoxNode(featureGeoSchema.getAttributeName(j), true, false));
          } else if (colName.toLowerCase().equals(Constants.FIELD_ID_MUNICIPIO)) {
            namedVector.add(1, new CheckBoxNode(featureGeoSchema.getAttributeName(j), true, false));
          }
          // caso especial para licencias
          // la referencia castastral será el atributo clave para localizar la licencia
          else if (colName.toLowerCase().contains(Constants.CLAVE_METAINFO)
              && Utils.isInArray(Constants.TIPOS_LICENCIAS, layerSystemId)) {
            namedVector.add(new CheckBoxNode(featureGeoSchema.getAttributeName(j), true, false));
          }
          // caso especial para inventario de patrimonio
          else if (colName.toLowerCase().equals(Constants.NUM_BIENES_ID)
              && Utils.isInArray(Constants.TIPOS_INVENTARIO, layerSystemId)) {
            namedVector.add(new CheckBoxNode(featureGeoSchema.getAttributeName(j), true, false));
          }
          // caso especial para EIEL
          else if (Utils.isInArray(Constants.TIPOS_EIEL, layerSystemId)) {
            if (isPkFieldEIEL(eielFilesUtils, layerSystemId, colName))
              namedVector.add(new CheckBoxNode(featureGeoSchema.getAttributeName(j), true, false));
            else
              namedVector.add(new CheckBoxNode(featureGeoSchema.getAttributeName(j), false, true));
          } else { // simplemente lo añadimos
            // if(!(licUtils.isInArray(Constants.TIPOS_LICENCIAS, layerSystemId) ||
            // licUtils.isInArray(Constants.TIPOS_INVENTARIO, layerSystemId))){
            if (!Utils.isInArray(Constants.TIPOS_LICENCIAS, layerSystemId)) {
              namedVector.add(new CheckBoxNode(featureGeoSchema.getAttributeName(j), false, true));
            }
          }
        }
        returnVector[i] = namedVector;
      }
    }

    return returnVector;
  }

  private boolean isPkFieldEIEL(
      EIELFilesUtils eielFilesUtils, String layerSystemId, String colName) {
    Iterator it = eielFilesUtils.getEIELLayerBean(layerSystemId).getRelacionFields().iterator();
    while (it.hasNext()) {
      LCGCampoCapaTablaEIEL lcgCampoCapa = (LCGCampoCapaTablaEIEL) it.next();
      if (lcgCampoCapa.getCampoBD().equals(colName.toLowerCase())) {
        return true;
      }
    }
    return false;
  }

  //	/**
  //	 * Obtiene un nodo del árbol compuesto por el nombre de la capa y sus atributos
  //	 * @param layer
  //	 * @return
  //	 */
  //	private DefaultMutableTreeNode getTreeNodeFromLayer(GeopistaLayer layer) {
  //	    DefaultMutableTreeNode r = new DefaultMutableTreeNode(layer.getName());
  //	    FeatureSchema featureSchema = layer.getFeatureCollectionWrapper().getFeatureSchema();
  //
  //	    for (int i = 1; i < featureSchema.getAttributeCount(); i++){
  //	      r.add((MutableTreeNode) new CheckBoxNode(featureSchema.getAttributeName(i), false));
  //	    }
  //
  //	    return r;
  //	}

  /** Called when the user presses Next on this panel */
  public void exitingToRight() throws Exception {
    // Recorremos el árbol y guardamos una lista con las capas y sus atributos seleccionados
    Map<String, List<String>> tablaCapasAtributosEscritura = new HashMap<String, List<String>>();
    if (writeableRootNodes.length > 0) {
      tablaCapasAtributosEscritura = getLayersAtributesList(writeableAtributesTree);
    }
    // guardamos los atributos seleccionados de escritura
    blackboard.put(MOBILE_WRITEABLE_LAYERS_ATRIB, tablaCapasAtributosEscritura);
    Map<String, List<String>> tablaCapasAtributosLectura = new HashMap<String, List<String>>();
    if (readableRootNodes.length > 0) {
      tablaCapasAtributosLectura = getLayersAtributesList(readableAtributesTree);
    }
    // guardamos los atributos seleccionados de escritura
    blackboard.put(MOBILE_READABLE_LAYERS_ATRIB, tablaCapasAtributosLectura);
  }

  /**
   * Obtiene los nodos seleccionados de un jtree creando una hash de Capas/Atributos
   *
   * @param jtreeAtributes
   * @return
   */
  private Map<String, List<String>> getLayersAtributesList(JTree jtreeAtributes) {
    Map<String, List<String>> tablaCapasAtributos = new HashMap<String, List<String>>();
    List<String> listaAtr = null;
    String nombreCapa = null;
    String nombreAtributo = null;
    DefaultTreeModel model = (DefaultTreeModel) jtreeAtributes.getModel();
    DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
    DefaultMutableTreeNode chosen = (DefaultMutableTreeNode) root.getFirstChild();
    DefaultMutableTreeNode leaf = null;
    CheckBoxNode checkNode = null;
    for (int i = 0; i < root.getChildCount(); i++) {
      nombreCapa = chosen.toString();
      leaf = chosen.getFirstLeaf();
      for (int j = 0; j < chosen.getLeafCount(); j++) {
        checkNode = (CheckBoxNode) leaf.getUserObject();
        nombreAtributo = checkNode.getText();
        // testeamos si el atributo está seleccionado
        if (checkNode.isSelected()) {
          if (tablaCapasAtributos.containsKey(nombreCapa)) {
            listaAtr = tablaCapasAtributos.get(nombreCapa);
          } else {
            listaAtr = new ArrayList<String>();
          }
          listaAtr.add(nombreAtributo);
          tablaCapasAtributos.put(nombreCapa, listaAtr);
        }
        leaf = leaf.getNextLeaf();
      }
      // si no hay ningun atributo seleccionado guardamos unicamente la capa
      if (!tablaCapasAtributos.containsKey(nombreCapa)) {
        tablaCapasAtributos.put(nombreCapa, null);
      }
      chosen = chosen.getNextSibling();
    }

    return tablaCapasAtributos;
  }

  /**
   * Tip: Delegate to an InputChangedFirer.
   *
   * @param listener a party to notify when the input changes (usually the WizardDialog, which needs
   *     to know when to update the enabled state of the buttons.
   */
  public void add(InputChangedListener listener) {}

  public void remove(InputChangedListener listener) {}

  public String getTitle() {
    return this.getName();
  }

  public String getID() {
    return localId;
  }

  public String getInstructions() {
    return I18N.get(
        MobileExtractPlugin.PluginMobileExtracti18n,
        MobilePluginI18NResource.MobileExtractPanel03_selecAtrib);
  }

  public boolean isInputValid() {
    LayerManager layerManager = context.getLayerManager();
    Layer graticuleLayer = layerManager.getLayer(GraticuleCreatorEngine.getGraticuleName());
    if (graticuleLayer == null) {
      return false;
    }
    return true;
  }

  public void setWizardContext(WizardContext wd) {
    wizardContext = wd;
  }

  public void setNextID(String nextID) {
    this.nextID = nextID;
  }

  public String getNextID() {
    return nextID;
  }

  /* (non-Javadoc)
   * @see com.geopista.ui.wizard.WizardPanel#exiting()
   */
  public void exiting() {}
} //  @jve:decl-index=0:visual-constraint="10,10"
예제 #7
0
public class MobileModifyPlugin extends GeopistaAbstractSaveMapPlugIn {

  private static final Log logger = LogFactory.getLog(MobileModifyPlugin.class);
  private Blackboard blackboard = Constants.APLICACION.getBlackboard();
  public static final String PluginMobileExtracti18n = "PluginMobileExtracti18n";

  /** Inicialización del plugin para cargarlo desde el fichero workbench.properties */
  public void initialize(PlugInContext context) throws Exception {
    // para internacionalización
    Locale currentLocale = I18N.getLocaleAsObject();
    ResourceBundle bundle =
        ResourceBundle.getBundle(
            "com.geopista.ui.plugin.mobile.language.PluginMobileExtracti18n", currentLocale);
    I18N.plugInsResourceBundle.put(PluginMobileExtracti18n, bundle);

    FeatureInstaller featureInstaller = new FeatureInstaller(context.getWorkbenchContext());

    EnableCheckFactory checkFactory = context.getCheckFactory();
    featureInstaller.addMainMenuItem(
        this,
        new String[] {"Tools", MobilePluginI18NResource.GEOPISTAConfiguration_proyectMovil},
        I18N.get(PluginMobileExtracti18n, MobilePluginI18NResource.MobileModifyPlugin_text),
        false,
        null,
        new MultiEnableCheck()
            .add(checkFactory.createWindowWithLayerNamePanelMustBeActiveCheck())
            .add(checkFactory.createAdminUserCheck()));

    ((WorkbenchGuiComponent) context.getWorkbenchContext().getIWorkbench().getGuiComponent())
        .getToolBar("Movilidad")
        .addPlugIn(
            this.getIcon(),
            this,
            createEnableCheck(context.getWorkbenchContext()),
            context.getWorkbenchContext());
  }

  public String getName() {
    return I18N.get(PluginMobileExtracti18n, MobilePluginI18NResource.MobileModifyPlugin_text);
  }

  public ImageIcon getIcon() {
    return IconLoader.icon("/com/geopista/ui/images/movilidad_borrar.png");
  }

  public static MultiEnableCheck createEnableCheck(WorkbenchContext workbenchContext) {
    EnableCheckFactory checkFactory = new EnableCheckFactory(workbenchContext);
    return new MultiEnableCheck()
        .add(checkFactory.createWindowWithLayerNamePanelMustBeActiveCheck());
  }

  public boolean execute(PlugInContext context) throws Exception {
    reportNothingToUndoYet(context);

    // limpiamos lo que haya podido quedar de ejecuciones anteriores
    emptyBlackboard();

    WizardDialog d =
        new WizardDialog(
            GeopistaUtil.getFrame(context.getWorkbenchGuiComponent()),
            Constants.APLICACION.getI18nString("ExtractDialogGestionar"),
            context.getErrorHandler());
    d.init(
        new WizardPanel[] {
          new MobileModifyPanel01("MobileModifyPanel01", null, context),
        });

    d.setSize(520, 650);
    d.setLocation(10, 20);
    d.setVisible(true);

    if (!d.wasFinishPressed()) {
      LayerManager layerManager = context.getLayerManager();
      if (layerManager != null) {
        Layer graticuleLayer = layerManager.getLayer(GraticuleCreatorEngine.getGraticuleName());
        // si existe una cuadrícula la borramos
        if (graticuleLayer != null) {
          layerManager.remove(graticuleLayer);
        }
      }
      return false;
    }

    return true;
  }

  /** Borra lo que haya utilizado del blackboard en sus anteriores ejecuciones */
  private void emptyBlackboard() {
    blackboard.remove(MobileModifyPanel01.SELECTED_EXTRACT_PROJECT);
  }

  /*
   * Se ejecuta una vez finalizado el interfaz despues de pasar por todas las pantallas.
   * (non-Javadoc)
   * @see com.vividsolutions.jump.workbench.plugin.ThreadedPlugIn#run(com.vividsolutions.jump.task.TaskMonitor, com.vividsolutions.jump.workbench.plugin.PlugInContext)
   */
  public void run(TaskMonitor monitor, PlugInContext context) throws Exception {
    try {
      monitor.report(
          I18N.get(
              PluginMobileExtracti18n, MobilePluginI18NResource.MobileModifyPanel01_deletingProy));

      ExtractionProject eProject =
          (ExtractionProject) blackboard.get(MobileModifyPanel01.SELECTED_EXTRACT_PROJECT);

      // guardamos la informacion en base de datos
      final String sUrlPrefix =
          Constants.APLICACION.getString(UserPreferenceConstants.LOCALGIS_SERVER_URL);
      AdministradorCartografiaClient administradorCartografiaClient =
          new AdministradorCartografiaClient(
              sUrlPrefix
                  + WebAppConstants.GEOPISTA_WEBAPP_NAME
                  + ServletConstants.ADMINISTRADOR_CARTOGRAFIA_SERVLET_NAME);
      administradorCartografiaClient.deleteExtractProject(eProject);

      // Borramos los datos subidos al servidor.
      httpDeleteProject(Constants.URL_DELETE_SERVER, eProject);

      String dirBase =
          UserPreferenceStore.getUserPreference(
              UserPreferenceConstants.PREFERENCES_DATA_PATH_KEY,
              UserPreferenceConstants.DEFAULT_DATA_PATH,
              true);
      dirBase += File.separator + "maps";

      String projectName = eProject.getNombreProyecto();
      String idProyecto = eProject.getIdProyecto();

      String dirMapName = projectName + "." + idProyecto;
      File dirBaseMake = new File(dirBase, dirMapName);
      if (dirBaseMake.exists()) {
        MobileUtils.deleteDir(dirBaseMake);
        logger.info("Borrando fichero local:" + dirBaseMake);
      }

    } finally {
      // borramos la cuadrícula
      LayerManager layerManager = context.getLayerManager();
      Layer graticuleLayer = layerManager.getLayer(GraticuleCreatorEngine.getGraticuleName());
      if (graticuleLayer != null) {
        layerManager.remove(graticuleLayer);
      }
    }
  }

  private void httpDeleteProject(String url, ExtractionProject eProject) throws Exception {
    PostMethod method = null;
    try {
      HttpClient client = new HttpClient();
      client.getParams().setParameter("http.connection.timeout", new Integer(8000));
      method = new PostMethod(url);
      method.addParameter("PROJECT_ID", eProject.getIdProyecto());
      method.addParameter("PROJECT_NAME", eProject.getNombreProyecto());

      int statusCode1 = client.executeMethod(method);
      logger.info("statusLine>>> " + method.getStatusLine() + " || statusCode>>> " + statusCode1);

    } catch (Exception e) {
      logger.error("No se ha podido eliminar el proyecto. " + e, e);
      throw e;
    } finally {
      if (method != null) method.releaseConnection();
    }
  }
}