Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extTableExport / src / org / gvsig / tableExport / ExportTableToFileExtension.java @ 28456

History | View | Annotate | Download (7.31 KB)

1
package org.gvsig.tableExport;
2

    
3

    
4
import java.awt.Component;
5
import java.io.File;
6
import java.io.IOException;
7
import java.sql.Types;
8
import java.util.Iterator;
9

    
10
import javax.swing.JFileChooser;
11
import javax.swing.JOptionPane;
12

    
13
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
14
import com.hardcode.gdbms.engine.data.driver.DriverException;
15
import com.hardcode.gdbms.engine.data.driver.FileDriver;
16
import com.hardcode.gdbms.engine.values.Value;
17
import com.iver.andami.PluginServices;
18
import com.iver.andami.messages.NotificationManager;
19
import com.iver.andami.plugins.Extension;
20
import com.iver.andami.ui.mdiManager.IWindow;
21
import com.iver.cit.gvsig.fmap.core.DefaultFeature;
22
import com.iver.cit.gvsig.fmap.core.IFeature;
23
import com.iver.cit.gvsig.fmap.drivers.ITableDefinition;
24
import com.iver.cit.gvsig.fmap.edition.DefaultRowEdited;
25
import com.iver.cit.gvsig.fmap.edition.IWriteable;
26
import com.iver.cit.gvsig.fmap.edition.IWriter;
27
import com.iver.cit.gvsig.fmap.layers.FBitSet;
28
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
29
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
30
import com.iver.cit.gvsig.project.documents.table.gui.Table;
31
import com.iver.utiles.GenericFileFilter;
32

    
33

    
34
/**
35
 * Extensi?n que permite exportar una tabla a cualquier
36
 * driver de fichero que soporte escritura.
37
 *
38
 * @author jmvivo
39
 */
40
public class ExportTableToFileExtension extends Extension {
41
    /**
42
     * @see com.iver.andami.plugins.IExtension#initialize()
43
     */
44
    public void initialize() {
45
    }
46

    
47
    /**
48
     * @param actionCommand Debe de estar compuesto por tres par?mentros
49
     *                      separados por '|' d?nde el primero es el nombre
50
     *                      del driver, el segundo la extensi?n de los ficheros
51
     *                      y el tercero el nombre del tipo. Ejemplo:<br>
52
     *  "gdbms dbf driver|dbf|dbf file"
53
     *
54
     * @see com.iver.andami.plugins.IExtension#execute(java.lang.String)
55
     */
56
    public void execute(String actionCommand) {
57
            IWindow v = PluginServices.getMDIManager().getActiveWindow();
58
            Table table = (Table) v;
59

    
60
            String[] params=actionCommand.split("[|]");
61

    
62
            if (params.length != 3){
63
                    NotificationManager.showMessageError("Parametros no validos: "+actionCommand, null);
64
                    return;
65

    
66
            }
67

    
68

    
69
            try {
70
                    exportToFile(table,params[0],params[1],params[2]);
71
            } catch (Exception e) {
72
                    NotificationManager.showMessageError("error_en_el_proceso", e);
73
            }
74

    
75
    }
76

    
77
        public void exportToFile(Table table, String driverName,String fileExtension,String fileDescription) throws Exception{
78
                FileDriver driver = (FileDriver)LayerFactory.getDM().getDriver(driverName);
79
                if (driver == null){
80
                        throw new Exception("Driver '"+driverName+"' Not Found");
81
                }
82
                File file = this.askForFileName(fileExtension,fileDescription);
83
                if (file == null){
84
                        return;
85
                }
86
                exportToFile(table,driver,file);
87
        }
88

    
89
        public void exportToFile(Table table, FileDriver driver,String fileExtension,String fileDescription) throws Exception{
90
                File file = this.askForFileName(fileExtension,fileDescription);
91
                exportToFile(table,driver,file);
92
        }
93

    
94
        public void exportToFile(Table table, FileDriver driver,File file) throws Exception{
95
                SelectableDataSource source;
96
                ITableDefinition orgDef;
97
                try {
98
                        source = table.getModel().getModelo().getRecordset();
99
                        source.start();
100
                        orgDef = table.getModel().getModelo().getTableDefinition();
101
                } catch (Exception e) {
102
                        throw new Exception("Error preparando la fuente", e); // TODO intenacionalizacion??
103
                }
104

    
105

    
106
                try {
107
                        if (!file.exists()){
108

    
109
                                //Builds a valid empty dbf file. We need it for call to the method Driver.open
110
                                driver.createSource(file.getAbsolutePath(),new String[] {"0"},new int[] {Types.INTEGER} );
111
                                file.createNewFile();
112

    
113
                        }
114

    
115
                        driver.open(file);
116
                } catch (IOException e) {
117
                        throw new Exception("Error preparando el fichero destino", e); // TODO intenacionalizacion??
118
                }
119

    
120
                IWriter writer = ((IWriteable)driver).getWriter();
121
                try {
122
                        writer.initialize(orgDef);
123
                        writer.preProcess();
124
                        SourceIterator iter = new SourceIterator(source);
125
                        IFeature feature;
126
                        int i=0;
127
                        while (iter.hasNext()){
128
                                 feature = iter.nextFeature();
129

    
130
                                 DefaultRowEdited edRow = new DefaultRowEdited(feature,
131
                                                 DefaultRowEdited.STATUS_ADDED, i);
132
                                 writer.process(edRow);
133
                                 i++;
134

    
135
                        }
136
                        writer.postProcess();
137

    
138

    
139
                } catch (Exception e) {
140
                        throw new Exception("Error generando fichero", e); // TODO intenacionalizacion??
141

    
142
                }
143

    
144
                try {
145
                        source.stop();
146
                        driver.close();
147
                } catch (Exception e) {
148
                        throw new Exception("Error cerrando ficheros", e); // TODO intenacionalizacion??
149
                }
150

    
151

    
152
        }
153

    
154
        private File askForFileName(String ext,String extDescription){
155
                JFileChooser jfc = new JFileChooser();
156
                jfc.addChoosableFileFilter(new GenericFileFilter(ext,
157
                                extDescription));
158
                if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
159
                        File file=jfc.getSelectedFile();
160
                        if (file==null){
161
                                return null;
162
                        }
163
                        if (file.exists()){
164
                                int resp = JOptionPane.showConfirmDialog(
165
                                                (Component) PluginServices.getMainFrame(),PluginServices.getText(this,"fichero_ya_existe_seguro_desea_guardarlo"),
166
                                                PluginServices.getText(this,"guardar"), JOptionPane.YES_NO_OPTION);
167
                                if (resp != JOptionPane.YES_OPTION) {
168
                                        return null;
169
                                }
170
                        }
171
                        String name = file.getAbsolutePath();
172
                        if (!name.toLowerCase().endsWith("." +ext.toLowerCase())){
173
                                file = new File(name + "."+ext);
174
                        }
175
                        return file;
176
                } else{
177
                        return null;
178
                }
179

    
180
        }
181

    
182

    
183
    /**
184
     * @see com.iver.andami.plugins.IExtension#isEnabled()
185
     */
186
    public boolean isEnabled() {
187
       return true;
188
    }
189

    
190
    /**
191
     * @see com.iver.andami.plugins.IExtension#isVisible()
192
     */
193
    public boolean isVisible() {
194
        IWindow v = PluginServices.getMDIManager().getActiveWindow();
195

    
196
        if (v == null) {
197
            return false;
198
        } else if (v instanceof Table) {
199
            return true;
200
        } else {
201
            return false;
202
        }
203
    }
204

    
205
    private class SourceIterator implements Iterator{
206
            private int index;
207
            private long count;
208
            private FBitSet selection = null;
209
            private SelectableDataSource source;
210

    
211
            public SourceIterator(SelectableDataSource source) throws DriverException, ReadDriverException{
212
                    this.source = source;
213
                    if (source.getSelection().cardinality()== 0){
214
                            this.selection = null;
215
                            this.index=0;
216
                            this.count = source.getRowCount();
217
                    } else{
218
                            this.selection = source.getSelection();
219
                            this.index=selection.nextSetBit(0);
220
                            this.count = selection.cardinality();
221
                    }
222

    
223
            }
224

    
225
                public void remove() {
226
                        throw new UnsupportedOperationException();
227
                }
228

    
229
                public boolean hasNext() {
230
                        if (this.selection == null)
231
                                return this.index < this.count;
232
                        return this.index >= 0;
233
                }
234

    
235
                public Object next() {
236
                        try {
237
                                return this.nextFeature();
238
                        } catch (DriverException e) {
239
                                throw new RuntimeException(e);
240
                        } catch (ReadDriverException e) {
241
                                throw new RuntimeException(e);
242
                        }
243
                }
244

    
245
                public IFeature nextFeature() throws DriverException, ReadDriverException {
246

    
247
                        Value[] values = this.source.getRow(this.index);
248
                        IFeature feat = new DefaultFeature(null, values, "" + this.index);
249
                        if (this.selection == null){
250
                                this.index++;
251
                        } else {
252
                                this.index = this.selection.nextSetBit(this.index + 1);
253
                        }
254
                        return feat;
255

    
256
                }
257

    
258
                public long count(){
259
                        return this.count;
260
                }
261

    
262
    }
263
}