Example #1
0
  public void saveEdits(int numRows)
      throws ReadDriverException, InitializeWriterException, StopWriterVisitorException {
    if (limit == -1 || numRows == 0 || (numRows % limit) != 0) {
      return;
    }
    ies.endComplexRow(PluginServices.getText(this, "expression"));
    if ((layer != null) && layer.getSource() instanceof VectorialEditableAdapter) {
      VectorialEditableAdapter vea = (VectorialEditableAdapter) layer.getSource();
      ISpatialWriter spatialWriter = (ISpatialWriter) vea.getDriver();
      vea.cleanSelectableDatasource();
      // We want that the recordset of the layer shows the changes of the fields
      layer.setRecordset(vea.getRecordset());
      ILayerDefinition lyrDef = EditionUtilities.createLayerDefinition(layer);
      spatialWriter.initialize(lyrDef);
      vea.saveEdits(spatialWriter, EditionEvent.ALPHANUMERIC);
      vea.getCommandRecord().clearAll();
    } else {
      if (ies instanceof IWriteable) {
        IWriteable w = (IWriteable) ies;
        IWriter writer = w.getWriter();
        if (writer == null) {
        } else {
          ITableDefinition tableDef = ies.getTableDefinition();
          writer.initialize(tableDef);

          ies.saveEdits(writer, EditionEvent.ALPHANUMERIC);
          ies.getSelection().clear();
        }
      }
      ies.getCommandRecord().clearAll();
    }
    ies.startComplexRow();
  }
 /**
  * Writer to create dbf file
  *
  * @param writer
  * @param feature - fill with the corresponding rows
  * @param index - fill file position
  */
 private void write(IWriter writer, IFeature feature, int index) {
   DefaultRowEdited edRow = new DefaultRowEdited(feature, DefaultRowEdited.STATUS_ADDED, index);
   try {
     writer.process(edRow);
   } catch (VisitorException e) {
     logger.error("Error en la generación del fichero dbf");
   }
 }
Example #3
0
  /** @see com.iver.andami.plugins.IExtension#isEnabled() */
  public boolean isEnabled() {
    IWindow v = PluginServices.getMDIManager().getActiveWindow();
    if (!(v instanceof Table)) {
      return false;
    }
    IEditableSource ies = ((Table) v).getModel().getModelo();
    if (!(ies instanceof IWriteable)) {
      return false;
    }
    IWriter writer = ((IWriteable) ies).getWriter();
    if (writer == null) {
      return false;
    }
    if (!writer.canAlterTable()) {
      return false;
    }

    return true;
  }
  /**
   * Creating dbf format file with the statistics
   *
   * @param valores - Pairs String name (key) + Double value
   * @param endFile - File to write the information
   */
  private void exportToDBFFile(List<MyObjectStatistics> valores, File endFile) {

    try {
      FileDriver driver = null;
      try {
        driver = (FileDriver) LayerFactory.getDM().getDriver("gdbms dbf driver");
      } catch (DriverLoadException e1) {
        logger.error("Error Creando el driver dbf");
      }

      try {
        if (!endFile.exists()) {
          try {
            driver.createSource(
                endFile.getAbsolutePath(), new String[] {"0"}, new int[] {Types.DOUBLE});
          } catch (ReadDriverException e) {
            logger.error("Error en createSource");
          }
          endFile.createNewFile();
        }

        try {
          driver.open(endFile);
        } catch (OpenDriverException e) {
          logger.error("Error abriendo el fichero de destino");
        }
      } catch (IOException e) {
        try {
          throw new Exception("Error creando el fichero de destino", e);
        } catch (Exception e1) {
          logger.error("Error creando el fichero de destino");
        }
      }

      IWriter writer = ((IWriteable) driver).getWriter();
      ITableDefinition orgDef = new TableDefinition();
      try {
        // Preparing the total rows in the new dbf file, in this case
        // two rows : Name Value
        FieldDescription[] fields = new FieldDescription[2];
        fields[0] = new FieldDescription();
        fields[0].setFieldType(Types.VARCHAR);
        fields[0].setFieldName(PluginServices.getText(this, "Nombre"));
        fields[0].setFieldLength(50);
        fields[1] = new FieldDescription();
        fields[1].setFieldType(Types.DOUBLE);
        fields[1].setFieldName(PluginServices.getText(this, "Valor"));
        fields[1].setFieldLength(50);
        fields[1].setFieldDecimalCount(25);
        fields[1].setFieldLength(100);
        orgDef.setFieldsDesc(fields);
        writer.initialize(orgDef);
      } catch (InitializeWriterException e) {
        logger.error("Error en la inicialización del writer");
      }
      try {
        writer.preProcess();
      } catch (StartWriterVisitorException e) {
        logger.error("Error en el preProcess del writer");
      }
      try {
        int index = 0;
        Value[] value = new Value[2];
        IFeature feat = null;

        Iterator<MyObjectStatistics> iterador = valores.listIterator();

        while (iterador.hasNext()) {
          MyObjectStatistics data = (MyObjectStatistics) iterador.next();
          value[0] = ValueFactory.createValue(data.getKey());
          value[1] = ValueFactory.createValue(data.getValue());
          feat = new DefaultFeature(null, value, "" + index++);
          write(writer, feat, index);
        }
      } catch (Exception e) {
        logger.error("Error en el write");
      }
      try {
        writer.postProcess(); // Operation finished
        JOptionPane.showMessageDialog(
            null,
            PluginServices.getText(this, "fichero_creado_en") + " " + endFile.getAbsolutePath(),
            PluginServices.getText(this, "fichero_creado_en_formato") + " dbf",
            JOptionPane.INFORMATION_MESSAGE); // Informing the user
      } catch (StopWriterVisitorException e) {
        logger.error("Error en el postProcess del writer");
      }
    } catch (Exception e) { // Informing the user
      logger.error("Error exportando a formato dbf");
      JOptionPane.showMessageDialog(
          null,
          PluginServices.getText(this, "Error_exportando_las_estadisticas")
              + " "
              + endFile.getAbsolutePath(),
          PluginServices.getText(this, "Error"),
          JOptionPane.ERROR_MESSAGE);
    }
  }
Example #5
0
  public void doImportField(ImportFieldParams params) throws Exception {

    if (!params.isValid()) {
      // TODO: ver que excepcion a lanzar
      throw new Exception("invalid Paramenters: " + params.getValidationMsg());
    }

    IEditableSource edSource = null;
    IEditableSource edSourceToImport = params.getTableToImport().getModelo();

    SelectableDataSource rsSourceToImport = edSourceToImport.getRecordset();

    ArrayList fieldsToImport = new ArrayList();
    ArrayList fieldsToImport_des = new ArrayList();
    ArrayList fieldsToImport_pos = new ArrayList();
    Iterator iter;
    Map values;
    int i;

    try {
      rsSourceToImport.start();

      // Cargamos la lista con los campos que vamos a importar
      iter = params.getFieldsToImport().iterator();
      FielToImport fieldToImport;
      while (iter.hasNext()) {
        fieldToImport = (FielToImport) iter.next();
        if (fieldToImport.toImport) {
          fieldsToImport.add(fieldToImport);
        }
      }

      // Cargamos la lista de la definicio de capos desde la
      // tabla a importar
      iter = fieldsToImport.iterator();
      FieldDescription[] toImportAllFieldsDescription = edSourceToImport.getFieldsDescription();
      FieldDescription tmpFieldDesc, newFieldDesc;

      while (iter.hasNext()) {
        fieldToImport = (FielToImport) iter.next();
        for (i = 0; i < toImportAllFieldsDescription.length; i++) {
          tmpFieldDesc = toImportAllFieldsDescription[i];
          if (tmpFieldDesc.getFieldName().equals(fieldToImport.originalFieldName)) {
            newFieldDesc = tmpFieldDesc.cloneField();
            newFieldDesc.setFieldLength(tmpFieldDesc.getFieldLength());
            newFieldDesc.setFieldName(fieldToImport.fieldNameToUse);
            newFieldDesc.setDefaultValue(tmpFieldDesc.getDefaultValue());
            newFieldDesc.setFieldAlias(fieldToImport.fieldNameToUse);
            newFieldDesc.setFieldType(tmpFieldDesc.getFieldType());
            fieldsToImport_des.add(newFieldDesc);
            fieldsToImport_pos.add(new Integer(i));
          }
        }
      }

      // Cagamos los valores en un hash
      values =
          this.loadValuesFromSource(
              rsSourceToImport, params.getTableToImportField(), fieldsToImport_pos);
    } catch (Exception e) {
      throw e;
    } finally {

      rsSourceToImport.stop();
      rsSourceToImport = null;
      edSourceToImport = null;
    }

    FLyrVect layer = null;

    boolean changeEditing = false;
    // Ponemos en edicion si no lo esta
    if (params.getTable().getAssociatedTable() instanceof FLyrVect) {
      // Viene de una capa
      layer = (FLyrVect) params.getTable().getAssociatedTable();
      if (!layer.isEditing()) {
        layer.setEditing(true);
        changeEditing = true;
      }
      edSource = (VectorialEditableAdapter) layer.getSource();
    } else {
      // es una tabla normal
      edSource = params.getTable().getModelo();
      if (!edSource.isEditing()) {
        edSource.startEdition(EditionEvent.ALPHANUMERIC);
        changeEditing = true;
      }
    }

    edSource.startComplexRow();

    int originalFieldsCount = edSource.getRecordset().getFieldCount();
    int finalFieldsCount = originalFieldsCount + fieldsToImport.size();
    // Añadimos los campos
    iter = fieldsToImport_des.iterator();
    while (iter.hasNext()) {
      ((EditableAdapter) edSource).addField((FieldDescription) iter.next());
    }

    // Recorremos la fuente y vamos actualizando
    int rowCount = edSource.getRowCount();
    IRowEdited originalRow;
    IRow newRow;
    IRowEdited newRowEdited;
    Value[] finalValues;
    Value[] originalValues;
    Value[] valuesToUse;
    Value key;
    int column;
    int srcKeyPos = edSource.getRecordset().getFieldIndexByName(params.getTableField());
    for (i = 0; i < rowCount; i++) {
      originalRow = edSource.getRow(i);

      key = originalRow.getAttribute(srcKeyPos);
      valuesToUse = (Value[]) values.get(key);
      if (valuesToUse == null) {
        continue;
      }
      newRow = originalRow.getLinkedRow().cloneRow();
      originalValues = newRow.getAttributes();
      finalValues = new Value[finalFieldsCount];
      System.arraycopy(originalValues, 0, finalValues, 0, originalFieldsCount);
      for (column = 0; column < valuesToUse.length; column++) {
        finalValues[column + originalFieldsCount] = valuesToUse[column];
      }
      newRow.setAttributes(finalValues);
      newRowEdited = new DefaultRowEdited(newRow, IRowEdited.STATUS_MODIFIED, i);
      edSource.modifyRow(
          newRowEdited.getIndex(), newRowEdited.getLinkedRow(), "", EditionEvent.ALPHANUMERIC);
    }

    edSource.endComplexRow("Import fields");
    if (changeEditing) {
      if (layer == null) {
        IWriter writer = ((IWriteable) edSource).getWriter();
        writer.initialize(edSource.getTableDefinition());
        edSource.stopEdition(writer, EditionEvent.ALPHANUMERIC);
        edSource.getSelection().clear();

      } else {
        layer.setRecordset(edSource.getRecordset());
        ISpatialWriter spatialWriter =
            (ISpatialWriter) ((VectorialEditableAdapter) edSource).getWriter();
        ILayerDefinition lyrDef = EditionUtilities.createLayerDefinition(layer);
        spatialWriter.initialize(lyrDef);
        edSource.stopEdition(spatialWriter, EditionEvent.ALPHANUMERIC);
        layer.setEditing(false);
        edSource.getSelection().clear();
      }
    }
  }