/**
   * Rellena los registros del dbf.
   *
   * @param sds DOCUMENT ME!
   */
  private void createdbf(SelectableDataSource sds, BitSet bitset) {
    int i = 0;

    // for (int i = 0; i < fgs.length; i++) {
    try {
      if (sds == null) {
        for (int j = 0; j < geometries.length; j++) {
          enteros[0] = ValueFactory.createValue((double) i);
          dbfWrite.write(enteros);
          i++;
        }
      } else {
        for (int j = bitset.nextSetBit(0); j >= 0; j = bitset.nextSetBit(j + 1)) {
          for (int r = 0; r < sds.getFieldCount(); r++) {
            record[r] = sds.getFieldValue(j, r);
          }

          dbfWrite.write(record);
        }
      }
    } catch (IOException e1) {
      e1.printStackTrace();
    } catch (ReadDriverException e) {
      e.printStackTrace();
    }
  }
  private Map loadValuesFromSource(
      SelectableDataSource source, String keyFieldName, ArrayList fieldsPositions)
      throws ReadDriverException {
    HashMap values = new HashMap();
    int row, i;
    Value[] rowValues;
    Value key;
    int keyPos = source.getFieldIndexByName(keyFieldName);
    long rowCount = source.getRowCount();
    for (row = 0; row < rowCount; row++) {
      key = source.getFieldValue(row, keyPos);
      if (values.containsKey(key)) {
        continue;
      }
      rowValues = new Value[fieldsPositions.size()];

      for (i = 0; i < fieldsPositions.size(); i++) {
        rowValues[i] = source.getFieldValue(row, ((Integer) fieldsPositions.get(i)).intValue());
      }

      values.put(key, rowValues);
    }

    return values;
  }
  /**
   * DOCUMENT ME!
   *
   * @param mapContext DOCUMENT ME!
   * @param layer DOCUMENT ME!
   * @param duplicate DOCUMENT ME!
   * @throws ReadDriverException
   * @throws EditionException DOCUMENT ME!
   * @throws DriverIOException DOCUMENT ME!
   */
  public void saveToShp(MapContext mapContext, Annotation_Layer layer, String duplicate)
      throws ReadDriverException {
    try {
      JFileChooser jfc = new JFileChooser();
      SimpleFileFilter filterShp =
          new SimpleFileFilter("shp", PluginServices.getText(this, "shp_files"));
      jfc.setFileFilter(filterShp);

      if (jfc.showSaveDialog((Component) PluginServices.getMainFrame())
          == JFileChooser.APPROVE_OPTION) {
        File newFile = jfc.getSelectedFile();
        String path = newFile.getAbsolutePath();

        if (newFile.exists()) {
          int resp =
              JOptionPane.showConfirmDialog(
                  (Component) PluginServices.getMainFrame(),
                  PluginServices.getText(this, "fichero_ya_existe_seguro_desea_guardarlo"),
                  PluginServices.getText(this, "guardar"),
                  JOptionPane.YES_NO_OPTION);

          if (resp != JOptionPane.YES_OPTION) {
            return;
          }
        }

        if (!(path.toLowerCase().endsWith(".shp"))) {
          path = path + ".shp";
        }

        newFile = new File(path);

        SelectableDataSource sds = layer.getRecordset();
        FieldDescription[] fieldsDescrip = sds.getFieldsDescription();

        ShpWriter writer = (ShpWriter) LayerFactory.getWM().getWriter("Shape Writer");
        Driver driver = null;

        SHPLayerDefinition lyrDefPoint = new SHPLayerDefinition();
        lyrDefPoint.setFieldsDesc(fieldsDescrip);

        File filePoints = new File(path);
        lyrDefPoint.setFile(filePoints);
        lyrDefPoint.setName(filePoints.getName());
        lyrDefPoint.setShapeType(FShape.POINT);
        writer.setFile(filePoints);
        writer.initialize(lyrDefPoint);
        driver = getOpenAnnotationDriver(filePoints);
        writeFeatures(mapContext, layer, writer, driver, duplicate);
      }
    } catch (InitializeWriterException e) {
      throw new ReadDriverException(layerAnnotation.getName(), e);
    } catch (DriverLoadException e) {
      throw new ReadDriverException(layerAnnotation.getName(), e);
    } catch (IOException e) {
      throw new ReadDriverException(layerAnnotation.getName(), e);
    }
  }
  /**
   * Inicializa.
   *
   * @param sds Capa.
   */
  public void create(SelectableDataSource sds, BitSet bitset) {
    // if (layer instanceof AlphanumericData) {
    try {
      if (sds == null) {
        DbaseFileHeaderNIO myHeader = DbaseFileHeaderNIO.createNewDbaseHeader();
        myHeader.setNumRecords(geometries.length);
        dbfWrite = new DbaseFileWriterNIO(myHeader, (FileChannel) getWriteChannel(dbfPath));
        enteros = new Value[1];
      } else {
        // VectorialFileAdapter
        // vfa=(VectorialFileAdapter)((SingleLayer)lv).getSource();
        DbaseFileHeaderNIO myHeader;

        myHeader = DbaseFileHeaderNIO.createDbaseHeader(sds);

        myHeader.setNumRecords(geometries.length);
        dbfWrite = new DbaseFileWriterNIO(myHeader, (FileChannel) getWriteChannel(dbfPath));
        record = new Object[sds.getFieldCount()];
      }

      createdbf(sds, bitset);
      System.out.println("Acabado DBF");
    } catch (IOException e) {
      e.printStackTrace();

      // /} catch (DriverException e1) {
      // e1.printStackTrace();
    } catch (ReadDriverException e2) {
      e2.printStackTrace();
    }

    // return true;
    // }
    // return false;
  }
  @Override
  public void export(MapContext mapContext, FLyrVect layer) {
    try {
      JFileChooser jfc = new JFileChooser(lastPath);
      SimpleFileFilter filterShp =
          new SimpleFileFilter("dxf", PluginServices.getText(this, "dxf_files"));
      jfc.setFileFilter(filterShp);
      if (jfc.showSaveDialog((Component) PluginServices.getMainFrame())
          == JFileChooser.APPROVE_OPTION) {
        File newFile = jfc.getSelectedFile();
        String path = newFile.getAbsolutePath();
        if (!(path.toLowerCase().endsWith(".dxf"))) {
          path = path + ".dxf";
        }
        newFile = new File(path);

        DxfWriter writer = (DxfWriter) LayerFactory.getWM().getWriter("DXF Writer");
        SHPLayerDefinition lyrDef = new SHPLayerDefinition();
        SelectableDataSource sds = layer.getRecordset();
        FieldDescription[] fieldsDescrip = sds.getFieldsDescription();
        lyrDef.setFieldsDesc(fieldsDescrip);
        lyrDef.setFile(newFile);
        lyrDef.setName(newFile.getName());
        lyrDef.setShapeType(layer.getShapeType());
        writer.setFile(newFile);
        writer.initialize(lyrDef);
        writer.setProjection(layer.getProjection());
        DxfFieldsMapping fieldsMapping = new DxfFieldsMapping();
        // TODO: Recuperar aqu� los campos del cuadro de di�logo.
        writer.setFieldMapping(fieldsMapping);
        DXFMemoryDriver dxfDriver = new DXFMemoryDriver();
        dxfDriver.open(newFile);
        writeFeatures(mapContext, layer, writer, dxfDriver);
        String fileName = newFile.getAbsolutePath();
        lastPath = fileName.substring(0, fileName.lastIndexOf(File.separatorChar));
      }

    } catch (ReadDriverException e) {
      NotificationManager.addError(e.getMessage(), e);
    } catch (InitializeWriterException e) {
      NotificationManager.addError(e.getMessage(), e);
    } catch (DriverLoadException e) {
      NotificationManager.addError(e.getMessage(), e);
    }
  }
Exemple #6
0
 private void init() {
   try {
     sds = ies.getRecordset();
     fieldDescriptors = sds.getFieldsDescription();
     fieldDescriptor = fieldDescriptors[selectedIndex];
     interpreter.declareBean("sds", sds, SelectableDataSource.class);
     indexRow = new Index();
     interpreter.declareBean("indexRow", indexRow, Index.class);
   } catch (BSFException e) {
     e.printStackTrace();
   } catch (ReadDriverException e) {
     e.printStackTrace();
   }
 }
  /** DOCUMENT ME! */
  public void performAction() {
    myWizardComponents.getFinishButton().setEnabled(false);

    Annotation_FieldSelect panel1 = (Annotation_FieldSelect) myWizardComponents.getWizardPanel(0);
    Annotation_ConfigureLabel panel2 =
        (Annotation_ConfigureLabel) myWizardComponents.getWizardPanel(1);

    SelectableDataSource source;
    Annotation_Mapping mapping = new Annotation_Mapping();

    try {
      source = this.layerAnnotation.getRecordset();

      mapping.setColumnText(source.getFieldIndexByName(panel1.getField()));

      if (!panel2.getAngleFieldName().equals(ConfigureLabel.TEXT_FOR_DEFAULT_VALUE)) {
        mapping.setColumnRotate(source.getFieldIndexByName(panel2.getAngleFieldName()));
      }

      if (!panel2.getColorFieldName().equals(ConfigureLabel.TEXT_FOR_DEFAULT_VALUE)) {
        mapping.setColumnColor(source.getFieldIndexByName(panel2.getColorFieldName()));
      }

      if (!panel2.getSizeFieldName().equals(ConfigureLabel.TEXT_FOR_DEFAULT_VALUE)) {
        mapping.setColumnHeight(source.getFieldIndexByName(panel2.getSizeFieldName()));
      }

      if (!panel2.getFontFieldName().equals(ConfigureLabel.TEXT_FOR_DEFAULT_VALUE)) {
        mapping.setColumnTypeFont(source.getFieldIndexByName(panel2.getFontFieldName()));
      }
    } catch (ReadDriverException e) {
      NotificationManager.addError(e);
    }

    try {
      this.layerAnnotation.setMapping(mapping);
      // AttrInTableLabelingStrategy labeling = new
      // AttrInTableLabelingStrategy();
      ((Annotation_Legend) layerAnnotation.getLegend())
          .setUnits(panel2.getCmbUnits().getSelectedUnitIndex());
      // this.layerAnnotation.setLabelingStrategy(labeling);
      // ((FSymbol)
      // this.layerAnnotation.getLegend().getDefaultSymbol()).setFontSizeInPixels(panel2.sizeUnitsInPixels());
      saveToShp(map, this.layerAnnotation, panel1.getDuplicate());
    } catch (LegendLayerException e) {
      NotificationManager.addError(e);
    } catch (ReadDriverException e) {
      NotificationManager.addError(e);
    }

    this.myWizardComponents.getCancelAction().performAction();
  }
  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();
      }
    }
  }
Exemple #9
0
  /**
   * Evaluate the expression.
   *
   * @throws ReadDriverException
   * @throws BSFException
   */
  public boolean evalExpression(String expression) throws ReadDriverException, BSFException {
    long rowCount = sds.getRowCount();
    byte[] expressionBytes;
    String encoding = System.getProperty("file.encoding");
    try {
      expressionBytes = expression.getBytes(encoding);
      expression = new String(expressionBytes, "ISO-8859-1");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    expression = expression.replaceAll("\\[", "field(\"").replaceAll("\\]", "\")");

    interpreter.declareBean("ee", this, EvalExpression.class);
    interpreter.exec(
        ExpressionFieldExtension.JYTHON,
        null,
        -1,
        -1,
        "def expression():\n" + "  return " + expression + "");
    if (rowCount > 0) {
      try {
        interpreter.exec(
            ExpressionFieldExtension.JYTHON,
            null,
            -1,
            -1,
            "def isCorrect():\n" + "    ee.isCorrectValue(expression())\n");
        interpreter.exec(ExpressionFieldExtension.JYTHON, null, -1, -1, "isCorrect()");
      } catch (BSFException ee) {
        String message = ee.getMessage();
        if (message.length() > 200) {
          message = message.substring(0, 200);
        }
        int option =
            JOptionPane.showConfirmDialog(
                (Component) PluginServices.getMainFrame(),
                PluginServices.getText(this, "error_expression")
                    + "\n"
                    + message
                    + "\n"
                    + PluginServices.getText(this, "continue?"));
        if (option != JOptionPane.OK_OPTION) {
          return false;
        }
      }
    }
    ies.startComplexRow();

    ArrayList exceptions = new ArrayList();
    interpreter.declareBean("exceptions", exceptions, ArrayList.class);
    FBitSet selection = sds.getSelection();
    if (selection.cardinality() > 0) {
      interpreter.declareBean("selection", selection, FBitSet.class);
      interpreter.exec(
          ExpressionFieldExtension.JYTHON,
          null,
          -1,
          -1,
          "def p():\n"
              + "  i=selection.nextSetBit(0)\n"
              + "  while i >=0:\n"
              + "    indexRow.set(i)\n"
              + "    obj=expression()\n"
              + "    ee.setValue(obj,i)\n"
              + "    ee.saveEdits(i)\n"
              + "    i=selection.nextSetBit(i+1)\n");
    } else {
      interpreter.exec(
          ExpressionFieldExtension.JYTHON,
          null,
          -1,
          -1,
          "def p():\n"
              + "  for i in xrange("
              + rowCount
              + "):\n"
              + "    indexRow.set(i)\n"
              +
              //						"    print i , expression() , repr (expression())\n" +
              "    ee.setValue(expression(),i)\n"
              + "    ee.saveEdits(i)\n");
    }
    try {
      interpreter.eval(ExpressionFieldExtension.JYTHON, null, -1, -1, "p()");
    } catch (BSFException ee) {

      JOptionPane.showMessageDialog(
          (Component) PluginServices.getMainFrame(),
          PluginServices.getText(this, "evaluate_expression_with_errors")
              + " "
              + (rowCount - indexRow.get())
              + "\n"
              + ee.getMessage());
    }

    ies.endComplexRow(PluginServices.getText(this, "expression"));

    return true;
  }