Statistics
| Revision:

root / trunk / extensions / extCAD / src / com / iver / cit / gvsig / ExportTo.java @ 31488

History | View | Annotate | Download (28.1 KB)

1
package com.iver.cit.gvsig;
2

    
3
import java.awt.Component;
4
import java.awt.geom.Point2D;
5
import java.io.File;
6
import java.io.IOException;
7
import java.nio.charset.Charset;
8
import java.sql.Types;
9
import java.util.HashMap;
10
import java.util.Vector;
11
import java.util.prefs.Preferences;
12

    
13
import javax.swing.JComponent;
14
import javax.swing.JFileChooser;
15
import javax.swing.JOptionPane;
16
import javax.swing.ProgressMonitor;
17

    
18
import org.cresques.cts.ICoordTrans;
19

    
20
import com.hardcode.driverManager.Driver;
21
import com.hardcode.driverManager.DriverLoadException;
22
import com.hardcode.gdbms.driver.exceptions.FileNotFoundDriverException;
23
import com.hardcode.gdbms.driver.exceptions.InitializeWriterException;
24
import com.hardcode.gdbms.driver.exceptions.OpenDriverException;
25
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
26
import com.hardcode.gdbms.engine.data.driver.DriverException;
27
import com.hardcode.gdbms.engine.values.Value;
28
import com.iver.andami.PluginServices;
29
import com.iver.andami.messages.NotificationManager;
30
import com.iver.andami.plugins.Extension;
31
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException;
32
import com.iver.cit.gvsig.exceptions.visitors.VisitorException;
33
import com.iver.cit.gvsig.fmap.MapContext;
34
import com.iver.cit.gvsig.fmap.core.DefaultFeature;
35
import com.iver.cit.gvsig.fmap.core.FShape;
36
import com.iver.cit.gvsig.fmap.core.IFeature;
37
import com.iver.cit.gvsig.fmap.core.IGeometry;
38
import com.iver.cit.gvsig.fmap.core.ShapeFactory;
39
import com.iver.cit.gvsig.fmap.core.v02.FLabel;
40
import com.iver.cit.gvsig.fmap.drivers.ConnectionFactory;
41
import com.iver.cit.gvsig.fmap.drivers.DBException;
42
import com.iver.cit.gvsig.fmap.drivers.DBLayerDefinition;
43
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
44
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
45
import com.iver.cit.gvsig.fmap.drivers.FieldDescription;
46
import com.iver.cit.gvsig.fmap.drivers.IConnection;
47
import com.iver.cit.gvsig.fmap.drivers.ILayerDefinition;
48
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
49
import com.iver.cit.gvsig.fmap.drivers.SHPLayerDefinition;
50
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
51
import com.iver.cit.gvsig.fmap.drivers.dbf.DbaseFile;
52
import com.iver.cit.gvsig.fmap.drivers.dxf.DXFMemoryDriver;
53
import com.iver.cit.gvsig.fmap.drivers.jdbc.postgis.PostGISWriter;
54
import com.iver.cit.gvsig.fmap.drivers.jdbc.postgis.PostGisDriver;
55
import com.iver.cit.gvsig.fmap.drivers.shp.IndexedShpDriver;
56
import com.iver.cit.gvsig.fmap.edition.DefaultRowEdited;
57
import com.iver.cit.gvsig.fmap.edition.IRowEdited;
58
import com.iver.cit.gvsig.fmap.edition.IWriter;
59
import com.iver.cit.gvsig.fmap.edition.writers.dxf.DxfFieldsMapping;
60
import com.iver.cit.gvsig.fmap.edition.writers.dxf.DxfWriter;
61
import com.iver.cit.gvsig.fmap.edition.writers.shp.ShpWriter;
62
import com.iver.cit.gvsig.fmap.layers.FBitSet;
63
import com.iver.cit.gvsig.fmap.layers.FLayer;
64
import com.iver.cit.gvsig.fmap.layers.FLayers;
65
import com.iver.cit.gvsig.fmap.layers.FLyrAnnotation;
66
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
67
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
68
import com.iver.cit.gvsig.fmap.layers.ReadableVectorial;
69
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
70
import com.iver.cit.gvsig.fmap.layers.VectorialFileAdapter;
71
import com.iver.cit.gvsig.project.documents.view.IProjectView;
72
import com.iver.cit.gvsig.project.documents.view.gui.View;
73
import com.iver.cit.gvsig.vectorialdb.ConnectionSettings;
74
import com.iver.cit.gvsig.vectorialdb.DlgConnection;
75
import com.iver.utiles.PostProcessSupport;
76
import com.iver.utiles.SimpleFileFilter;
77
import com.iver.utiles.swing.threads.AbstractMonitorableTask;
78

    
79
public class ExportTo extends Extension {
80
        private String lastPath = null;
81
        private static HashMap<FLyrVect, EndExportToCommand> exportedLayers =
82
                new HashMap<FLyrVect, EndExportToCommand>();
83
        private static Preferences prefs = Preferences.userRoot().node( "gvSIG.encoding.dbf" );
84
        
85
        /**
86
         * This method is used to add a layer that is exported
87
         * to other format and its edition has to be finished
88
         * at the end of this process.
89
         * @param layer
90
         */
91
        public static void addLayerToStopEdition(FLyrVect layer, EndExportToCommand command){
92
                exportedLayers.put(layer, command);
93
        }
94

    
95
        public static void executeCommand(FLyrVect layer) throws Exception{
96
                if (exportedLayers.containsKey(layer)){
97
                        EndExportToCommand command = exportedLayers.get(layer);
98
                        command.execute();
99
                        exportedLayers.remove(layer);
100
                }
101
        }
102

    
103
        private class WriterTask extends AbstractMonitorableTask
104
        {
105
                FLyrVect lyrVect;
106
                IWriter writer;
107
                int rowCount;
108
                ReadableVectorial va;
109
                SelectableDataSource sds;
110
                FBitSet bitSet;
111
                MapContext mapContext;
112
                VectorialDriver reader;
113

    
114
                public WriterTask(MapContext mapContext, FLyrVect lyr, IWriter writer, Driver reader) throws ReadDriverException
115
                {
116
                        this.mapContext = mapContext;
117
                        this.lyrVect = lyr;
118
                        this.writer = writer;
119
                        this.reader = (VectorialDriver) reader;
120

    
121
                        setInitialStep(0);
122
                        setDeterminatedProcess(true);
123
                        setStatusMessage(PluginServices.getText(this, "exportando_features"));
124

    
125
                        va = lyrVect.getSource();
126
                        sds = lyrVect.getRecordset();
127

    
128
                        bitSet = sds.getSelection();
129

    
130
                        if (bitSet.cardinality() == 0)
131
                                rowCount = va.getShapeCount();
132
                        else
133
                                rowCount = bitSet.cardinality();
134

    
135
                        setFinalStep(rowCount);
136

    
137
                }
138
                public void run() throws Exception {
139
                        lyrVect.setWaitTodraw(true);
140
                        va.start();
141
                        ICoordTrans ct = lyrVect.getCoordTrans();
142
                        DriverAttributes attr = va.getDriverAttributes();
143
                        boolean bMustClone = false;
144
                        if (attr != null) {
145
                                if (attr.isLoadedInMemory()) {
146
                                        bMustClone = attr.isLoadedInMemory();
147
                                }
148
                        }
149
                        if (lyrVect instanceof FLyrAnnotation && lyrVect.getShapeType()!=FShape.POINT) {
150
                                SHPLayerDefinition lyrDef=(SHPLayerDefinition)writer.getTableDefinition();
151
                                lyrDef.setShapeType(FShape.POINT);
152
                                writer.initialize(lyrDef);
153
                        }
154
                        
155
                         if(writer instanceof ShpWriter) {
156
                                 String charSetName = prefs.get("dbf_encoding", DbaseFile.getDefaultCharset().toString());
157
                                 if(lyrVect.getSource() instanceof VectorialFileAdapter) {
158
                                         ((ShpWriter)writer).loadDbfEncoding(((VectorialFileAdapter)lyrVect.getSource()).getFile().getAbsolutePath(), Charset.forName(charSetName));
159
                                 } else {
160
                                                Object s = lyrVect.getProperty("DBFFile");
161
                                                if(s != null && s instanceof String)
162
                                                        ((ShpWriter)writer).loadDbfEncoding((String)s, Charset.forName(charSetName));
163
                                 }
164
                         }
165
                        
166
                        // Creamos la tabla.
167
                        writer.preProcess();
168

    
169
                        if (bitSet.cardinality() == 0) {
170
                                rowCount = va.getShapeCount();
171
                                for (int i = 0; i < rowCount; i++) {
172
                                        if (isCanceled())
173
                                                break;
174
                                        IGeometry geom = va.getShape(i);
175
                                        if (geom == null) {
176
                                                continue;
177
                                        }
178
                                        if (lyrVect instanceof FLyrAnnotation && geom.getGeometryType()!=FShape.POINT) {
179
                                                Point2D p=FLabel.createLabelPoint((FShape)geom.getInternalShape());
180
                                                geom=ShapeFactory.createPoint2D(p.getX(),p.getY());
181
                                        }
182
                                        if (isCanceled())
183
                                                break;
184
                                        if (ct != null) {
185
                                                if (bMustClone)
186
                                                        geom = geom.cloneGeometry();
187
                                                geom.reProject(ct);
188
                                        }
189
                                        reportStep();
190
                                        setNote(PluginServices.getText(this, "exporting_") + i);
191
                                        if (isCanceled())
192
                                                break;
193

    
194
                                        if (geom != null) {
195
                                                Value[] values = sds.getRow(i);
196
                                                IFeature feat = new DefaultFeature(geom, values, "" + i);
197
                                                DefaultRowEdited edRow = new DefaultRowEdited(feat,
198
                                                                DefaultRowEdited.STATUS_ADDED, i);
199
                                                writer.process(edRow);
200
                                        }
201
                                }
202
                        } else {
203
                                int counter = 0;
204
                                for (int i = bitSet.nextSetBit(0); i >= 0; i = bitSet
205
                                                .nextSetBit(i + 1)) {
206
                                        if (isCanceled())
207
                                                break;
208
                                        IGeometry geom = va.getShape(i);
209
                                        if (geom == null) {
210
                                                continue;
211
                                        }
212
                                        if (lyrVect instanceof FLyrAnnotation && geom.getGeometryType()!=FShape.POINT) {
213
                                                Point2D p=FLabel.createLabelPoint((FShape)geom.getInternalShape());
214
                                                geom=ShapeFactory.createPoint2D(p.getX(),p.getY());
215
                                        }
216
                                        if (isCanceled())
217
                                                break;
218
                                        if (ct != null) {
219
                                                if (bMustClone)
220
                                                        geom = geom.cloneGeometry();
221
                                                geom.reProject(ct);
222
                                        }
223
                                        reportStep();
224
                                        setNote(PluginServices.getText(this, "exporting_") + counter);
225
                                        if (isCanceled())
226
                                                break;
227

    
228
                                        if (geom != null) {
229
                                                Value[] values = sds.getRow(i);
230
                                                IFeature feat = new DefaultFeature(geom, values, "" + i);
231
                                                DefaultRowEdited edRow = new DefaultRowEdited(feat,
232
                                                                DefaultRowEdited.STATUS_ADDED, i);
233

    
234
                                                writer.process(edRow);
235
                                        }
236
                                }
237

    
238
                        }
239

    
240
                        writer.postProcess();
241
                        va.stop();
242
                        if (reader != null && !isCanceled()){
243
                                int res = JOptionPane.showConfirmDialog(
244
                                        (JComponent) PluginServices.getMDIManager().getActiveWindow()
245
                                        , PluginServices.getText(this, "insertar_en_la_vista_la_capa_creada"),
246
                                        PluginServices.getText(this,"insertar_capa"),
247
                                        JOptionPane.YES_NO_OPTION);
248

    
249
                                if (res == JOptionPane.YES_OPTION)
250
                                {
251
                                        PostProcessSupport.executeCalls();
252
                                        ILayerDefinition lyrDef = (ILayerDefinition) writer.getTableDefinition();
253
                                        FLayer newLayer = LayerFactory.createLayer(
254
                                                        lyrDef.getName(), reader, mapContext.getProjection());
255
                                        mapContext.getLayers().addLayer(newLayer);
256
                                }
257
                        }
258
                        lyrVect.setWaitTodraw(false);
259

    
260
                }
261
                /* (non-Javadoc)
262
                 * @see com.iver.utiles.swing.threads.IMonitorableTask#finished()
263
                 */
264
                public void finished() {
265
                        try {
266
                                executeCommand(lyrVect);
267
                        } catch (Exception e) {
268
                                NotificationManager.addError(e);
269
                        }
270
                }
271

    
272
        }
273
        private class MultiWriterTask extends AbstractMonitorableTask{
274
                Vector tasks=new Vector();
275
                public void addTask(WriterTask wt) {
276
                        tasks.add(wt);
277
                }
278
                public void run() throws Exception {
279
                        for (int i = 0; i < tasks.size(); i++) {
280
                                ((WriterTask)tasks.get(i)).run();
281
                        }
282
                }
283
                /* (non-Javadoc)
284
                 * @see com.iver.utiles.swing.threads.IMonitorableTask#finished()
285
                 */
286
                public void finished() {
287
                        for (int i = 0; i < tasks.size(); i++) {
288
                                ((WriterTask)tasks.get(i)).finished();
289
                        }
290
                        tasks.clear();
291
                }
292

    
293

    
294
        }
295
        /**
296
         * @see com.iver.andami.plugins.IExtension#initialize()
297
         */
298
        public void initialize() {
299
        }
300

    
301
        /**
302
         * @see com.iver.andami.plugins.IExtension#execute(java.lang.String)
303
         */
304
        public void execute(String actionCommand) {
305
                com.iver.andami.ui.mdiManager.IWindow f = PluginServices.getMDIManager()
306
                                .getActiveWindow();
307

    
308
                if (f instanceof View) {
309
                        View vista = (View) f;
310
                        IProjectView model = vista.getModel();
311
                        MapContext mapa = model.getMapContext();
312
                        FLayers layers = mapa.getLayers();
313
                        FLayer[] actives = layers.getActives();
314
                        try {
315
                                // NOTA: SI HAY UNA SELECCI?N, SOLO SE SALVAN LOS SELECCIONADOS
316
                                for (int i = 0; i < actives.length; i++) {
317
                                        if (actives[i] instanceof FLyrVect) {
318
                                                FLyrVect lv = (FLyrVect) actives[i];
319
                                                int numSelec = lv.getRecordset().getSelection()
320
                                                                .cardinality();
321
                                                if (numSelec > 0) {
322
                                                        int resp = JOptionPane.showConfirmDialog(
323
                                                                        (Component) PluginServices.getMainFrame(),
324
                                                                        PluginServices.getText(this,"se_van_a_guardar_") + numSelec
325
                                                                                        + PluginServices.getText(this,"features_desea_continuar"),
326
                                                                        PluginServices.getText(this,"export_to"), JOptionPane.YES_NO_OPTION);
327
                                                        if (resp != JOptionPane.YES_OPTION) {
328
                                                                continue;
329
                                                        }
330
                                                } // if numSelec > 0
331
                                                if (actionCommand.equals("SHP")) {
332
                                                        saveToShp(mapa, lv);
333
                                                }
334
                                                if (actionCommand.equals("DXF")) {
335
                                                        saveToDxf(mapa, lv);
336
                                                }
337
                                                if (actionCommand.equals("POSTGIS")) {
338
                                                        saveToPostGIS(mapa, lv);
339
                                                }
340
                                        } // actives[i]
341
                                } // for
342
                        } catch (ReadDriverException e) {
343
                                NotificationManager.showMessageError(e.getMessage(),e);
344
                        }
345

    
346
                }
347
        }
348

    
349
        public void saveToPostGIS(MapContext mapContext, FLyrVect layer){
350
                try {
351
                        String tableName = JOptionPane.showInputDialog(PluginServices
352
                                        .getText(this, "intro_tablename"));
353
                        
354
                        CharSequence seq = "\\/=.:,;??*{}?$%&()@#|!?";
355
                        for (int i = 0; i < seq.length(); i++) {
356
                                char c = seq.charAt(i);
357
                                if(tableName != null && tableName.indexOf(c) != -1) {
358
                                        NotificationManager.showMessageInfo(PluginServices.getText(this, "wrong_characters"), null);
359
                                        break;
360
                                }
361
                        } 
362
                
363
                        if (tableName == null)
364
                                return;
365
                        tableName = tableName.toLowerCase();
366

    
367
                        DlgConnection dlg = new DlgConnection(new String[]{"PostGIS JDBC Driver"});
368
                        dlg.setModal(true);
369
                        dlg.setVisible(true);
370
                        ConnectionSettings cs = dlg.getConnSettings();
371
                        if (cs == null)
372
                                return;
373
                        IConnection conex = ConnectionFactory.createConnection(cs
374
                                        .getConnectionString(), cs.getUser(), cs.getPassw());
375

    
376

    
377
                        DBLayerDefinition originalDef = null;
378
                        if (layer.getSource().getDriver() instanceof IVectorialDatabaseDriver) {
379
                                originalDef=((IVectorialDatabaseDriver) layer.getSource().getDriver()).getLyrDef();
380
                        }
381

    
382

    
383
                        DBLayerDefinition dbLayerDef = new DBLayerDefinition();
384
                        // Fjp:
385
                        // Cambio: En Postgis, el nombre de cat?logo est? siempre vac?o. Es algo heredado de Oracle, que no se usa.
386
                        // dbLayerDef.setCatalogName(cs.getDb());
387
                        dbLayerDef.setCatalogName("");
388

    
389
                        // A?adimos el schema dentro del layer definition para poder tenerlo en cuenta.
390
                        dbLayerDef.setSchema(cs.getSchema());
391

    
392
                        dbLayerDef.setTableName(tableName);
393
                        dbLayerDef.setName(tableName);
394
                        dbLayerDef.setShapeType(layer.getShapeType());
395
                        SelectableDataSource sds = layer.getRecordset();
396

    
397
                        FieldDescription[] fieldsDescrip = sds.getFieldsDescription();
398
                        dbLayerDef.setFieldsDesc(fieldsDescrip);
399
                // Creamos el driver. OJO: Hay que a?adir el campo ID a la
400
                // definici?n de campos.
401

    
402
                        if (originalDef != null){
403
                                dbLayerDef.setFieldID(originalDef.getFieldID());
404
                                dbLayerDef.setFieldGeometry(originalDef.getFieldGeometry());
405

    
406
                        }else{
407
                                // Search for id field name
408
                                int index=0;
409
                                String fieldName="gid";
410
                                while (findFileByName(fieldsDescrip,fieldName) != -1){
411
                                        index++;
412
                                        fieldName="gid"+index;
413
                                }
414
                                dbLayerDef.setFieldID(fieldName);
415

    
416
                                // search for geom field name
417
                                index=0;
418
                                fieldName="the_geom";
419
                                while (findFileByName(fieldsDescrip,fieldName) != -1){
420
                                        index++;
421
                                        fieldName="the_geom"+index;
422
                                }
423
                                dbLayerDef.setFieldGeometry(fieldName);
424

    
425
                        }
426

    
427
                        // if id field dosen't exist we add it
428
                        if (findFileByName(fieldsDescrip,dbLayerDef.getFieldID()) == -1)
429
                        {
430
                        int numFieldsAnt = fieldsDescrip.length;
431
                        FieldDescription[] newFields = new FieldDescription[dbLayerDef.getFieldsDesc().length + 1];
432
                    for (int i=0; i < numFieldsAnt; i++)
433
                    {
434
                            newFields[i] = fieldsDescrip[i];
435
                    }
436
                    newFields[numFieldsAnt] = new FieldDescription();
437
                    newFields[numFieldsAnt].setFieldDecimalCount(0);
438
                    newFields[numFieldsAnt].setFieldType(Types.INTEGER);
439
                    newFields[numFieldsAnt].setFieldLength(7);
440
                    newFields[numFieldsAnt].setFieldName("gid");
441
                    dbLayerDef.setFieldsDesc(newFields);
442

    
443
                }
444

    
445
                        // all fields to lowerCase
446
                        FieldDescription field;
447
                        for (int i=0;i<dbLayerDef.getFieldsDesc().length;i++){
448
                                field = dbLayerDef.getFieldsDesc()[i];
449
                                field.setFieldName(field.getFieldName().toLowerCase());
450
                        }
451
                        dbLayerDef.setFieldID(dbLayerDef.getFieldID().toLowerCase());
452
                        dbLayerDef.setFieldGeometry(dbLayerDef.getFieldGeometry().toLowerCase());
453

    
454
                        dbLayerDef.setWhereClause("");
455
                        String strSRID = layer.getProjection().getAbrev();
456
                        dbLayerDef.setSRID_EPSG(strSRID);
457
                        dbLayerDef.setConnection(conex);
458

    
459
                        PostGISWriter writer=(PostGISWriter)LayerFactory.getWM().getWriter("PostGIS Writer");
460
                        writer.setWriteAll(true);
461
                        writer.setCreateTable(true);
462
                        writer.initialize(dbLayerDef);
463
                        PostGisDriver postGISDriver=new PostGisDriver();
464
                        postGISDriver.setLyrDef(dbLayerDef);
465
                        postGISDriver.open();
466
                        PostProcessSupport.clearList();
467
                        Object[] params = new Object[2];
468
                        params[0] = conex;
469
                        params[1] = dbLayerDef;
470
                        PostProcessSupport.addToPostProcess(postGISDriver, "setData",
471
                                        params, 1);
472

    
473
                        writeFeatures(mapContext, layer, writer, postGISDriver);
474

    
475
                } catch (DriverLoadException e) {
476
                        NotificationManager.addError(e.getMessage(),e);
477
                } catch (DBException e) {
478
                        NotificationManager.showMessageError(e.getLocalizedMessage(),e);
479
                } catch (InitializeWriterException e) {
480
                        NotificationManager.showMessageError(e.getMessage(),e);
481
                } catch (ReadDriverException e) {
482
                        NotificationManager.addError(e.getMessage(),e);
483
                }
484

    
485
        }
486

    
487
        /**
488
         * Lanza un thread en background que escribe las features. Cuando termina, pregunta al usuario si quiere
489
         * a?adir la nueva capa a la vista. Para eso necesita un driver de lectura ya configurado.
490
         * @param mapContext
491
         * @param layer
492
         * @param writer
493
         * @param reader
494
         * @throws ReadDriverException
495
         * @throws DriverException
496
         * @throws DriverIOException
497
         */
498
        private void writeFeatures(MapContext mapContext, FLyrVect layer, IWriter writer, Driver reader) throws ReadDriverException
499
        {
500
                PluginServices.cancelableBackgroundExecution(new WriterTask(mapContext, layer, writer, reader));
501
        }
502
        private void writeMultiFeatures(MapContext mapContext, FLyrVect layers, IWriter[] writers, Driver[] readers) throws ReadDriverException{
503
                MultiWriterTask mwt=new MultiWriterTask();
504
                for (int i=0;i<writers.length;i++) {
505
                        mwt.addTask(new WriterTask(mapContext, layers, writers[i], readers[i]));
506
                }
507
                PluginServices.cancelableBackgroundExecution(mwt);
508
        }
509
        /**
510
         * @param layer
511
         *            FLyrVect to obtain features. If selection, only selected
512
         *            features will be precessed.
513
         * @param writer
514
         *            (Must be already initialized)
515
         * @throws ReadDriverException
516
         * @throws ProcessWriterException
517
         * @throws ExpansionFileReadException
518
         * @throws EditionException
519
         * @throws DriverException
520
         * @throws DriverIOException
521
         * @throws com.hardcode.gdbms.engine.data.driver.DriverException
522
         */
523
        public void writeFeaturesNoThread(FLyrVect layer, IWriter writer) throws ReadDriverException, VisitorException, ExpansionFileReadException{
524
                ReadableVectorial va = layer.getSource();
525
                SelectableDataSource sds = layer.getRecordset();
526

    
527
                // Creamos la tabla.
528
                writer.preProcess();
529

    
530
                int rowCount;
531
                FBitSet bitSet = layer.getRecordset().getSelection();
532

    
533
                if (bitSet.cardinality() == 0)
534
                        rowCount = va.getShapeCount();
535
                else
536
                        rowCount = bitSet.cardinality();
537

    
538
                ProgressMonitor progress = new ProgressMonitor(
539
                                (JComponent) PluginServices.getMDIManager().getActiveWindow(),
540
                                PluginServices.getText(this, "exportando_features"),
541
                                PluginServices.getText(this, "exportando_features"), 0,
542
                                rowCount);
543

    
544
                progress.setMillisToDecideToPopup(200);
545
                progress.setMillisToPopup(500);
546

    
547
                if (bitSet.cardinality() == 0) {
548
                        rowCount = va.getShapeCount();
549
                        for (int i = 0; i < rowCount; i++) {
550
                                IGeometry geom = va.getShape(i);
551

    
552
                                progress.setProgress(i);
553
                                if (progress.isCanceled())
554
                                        break;
555

    
556
                                if (geom != null) {
557
                                        Value[] values = sds.getRow(i);
558
                                        IFeature feat = new DefaultFeature(geom, values, "" + i);
559
                                        DefaultRowEdited edRow = new DefaultRowEdited(feat,
560
                                                        IRowEdited.STATUS_ADDED, i);
561
                                        writer.process(edRow);
562
                                }
563
                        }
564
                } else {
565
                        int counter = 0;
566
                        for (int i = bitSet.nextSetBit(0); i >= 0; i = bitSet
567
                                        .nextSetBit(i + 1)) {
568
                                IGeometry geom = va.getShape(i);
569

    
570
                                progress.setProgress(counter++);
571
                                if (progress.isCanceled())
572
                                        break;
573

    
574
                                if (geom != null) {
575
                                        Value[] values = sds.getRow(i);
576
                                        IFeature feat = new DefaultFeature(geom, values, "" + i);
577
                                        DefaultRowEdited edRow = new DefaultRowEdited(feat,
578
                                                        IRowEdited.STATUS_ADDED, i);
579

    
580
                                        writer.process(edRow);
581
                                }
582
                        }
583

    
584
                }
585

    
586
                writer.postProcess();
587
                progress.close();
588
        }
589

    
590
        public void saveToDxf(MapContext mapContext, FLyrVect layer)  {
591
                try {
592
                        JFileChooser jfc = new JFileChooser(lastPath);
593
                        SimpleFileFilter filterShp = new SimpleFileFilter("dxf",
594
                                        PluginServices.getText(this, "dxf_files"));
595
                        jfc.setFileFilter(filterShp);
596
                        if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
597
                                File newFile = jfc.getSelectedFile();
598
                                String path = newFile.getAbsolutePath();
599
                                if (!(path.toLowerCase().endsWith(".dxf"))) {
600
                                        path = path + ".dxf";
601
                                }
602
                                newFile = new File(path);
603

    
604
                                DxfWriter writer = (DxfWriter) LayerFactory.getWM().getWriter(
605
                                                "DXF Writer");
606
                                SHPLayerDefinition lyrDef = new SHPLayerDefinition();
607
                                SelectableDataSource sds = layer.getRecordset();
608
                                FieldDescription[] fieldsDescrip = sds.getFieldsDescription();
609
                                lyrDef.setFieldsDesc(fieldsDescrip);
610
                                lyrDef.setFile(newFile);
611
                                lyrDef.setName(newFile.getName());
612
                                lyrDef.setShapeType(layer.getShapeType());
613
                                writer.setFile(newFile);
614
                                writer.initialize(lyrDef);
615
                                writer.setProjection(layer.getProjection());
616
                                DxfFieldsMapping fieldsMapping = new DxfFieldsMapping();
617
                                // TODO: Recuperar aqu? los campos del cuadro de di?logo.
618
                                writer.setFieldMapping(fieldsMapping);
619
                                DXFMemoryDriver dxfDriver=new DXFMemoryDriver();
620
                                dxfDriver.open(newFile);
621
                                writeFeatures(mapContext, layer, writer, dxfDriver);
622
                                String fileName = newFile.getAbsolutePath();
623
                                lastPath  = fileName.substring(0, fileName.lastIndexOf(File.separatorChar));
624
                        }
625

    
626
                } catch (ReadDriverException e) {
627
                        NotificationManager.addError(e.getMessage(),e);
628
                } catch (InitializeWriterException e) {
629
                        NotificationManager.addError(e.getMessage(),e);
630
                } catch (DriverLoadException e) {
631
                        NotificationManager.addError(e.getMessage(),e);
632
                }
633

    
634
        }
635

    
636
        public void saveToShp(MapContext mapContext, FLyrVect layer) {
637
                try {
638
                        JFileChooser jfc = new JFileChooser();
639
                        SimpleFileFilter filterShp = new SimpleFileFilter("shp",
640
                                        PluginServices.getText(this, "shp_files"));
641
                        jfc.setFileFilter(filterShp);
642
                        if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
643
                                File newFile = jfc.getSelectedFile();
644
                                String path = newFile.getAbsolutePath();
645
                                if( newFile.exists()){
646
                                        int resp = JOptionPane.showConfirmDialog(
647
                                                        (Component) PluginServices.getMainFrame(),PluginServices.getText(this,"fichero_ya_existe_seguro_desea_guardarlo"),
648
                                                        PluginServices.getText(this,"guardar"), JOptionPane.YES_NO_OPTION);
649
                                        if (resp != JOptionPane.YES_OPTION) {
650
                                                return;
651
                                        }
652
                                }
653
                                if (!(path.toLowerCase().endsWith(".shp"))) {
654
                                        path = path + ".shp";
655
                                }
656
                                newFile = new File(path);
657

    
658

    
659

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

    
663
                                if (layer.getShapeType() == FShape.MULTI) // Exportamos a 3
664
                                // ficheros
665
                                {
666
                                        ShpWriter writer1 = (ShpWriter) LayerFactory.getWM().getWriter(
667
                                        "Shape Writer");
668
                                        Driver[] drivers=new Driver[3];
669
                                        ShpWriter[] writers=new ShpWriter[3];
670

    
671
                                        // puntos
672
                                        String auxPoint = path.replaceFirst("\\.shp", "_points.shp");
673

    
674
                                        SHPLayerDefinition lyrDefPoint = new SHPLayerDefinition();
675
                                        lyrDefPoint.setFieldsDesc(fieldsDescrip);
676
                                        File filePoints = new File(auxPoint);
677
                                        lyrDefPoint.setFile(filePoints);
678
                                        lyrDefPoint.setName(filePoints.getName());
679
                                        lyrDefPoint.setShapeType(FShape.POINT);
680
                                        loadEnconding(layer, writer1);
681
                                        writer1.setFile(filePoints);
682
                                        writer1.initialize(lyrDefPoint);
683
                                        writers[0]=writer1;
684
                                        drivers[0]=getOpenShpDriver(filePoints);
685
                                        //drivers[0]=null;
686

    
687
                                        ShpWriter writer2 = (ShpWriter) LayerFactory.getWM().getWriter(
688
                                        "Shape Writer");
689
                                        // Lineas
690
                                        String auxLine = path.replaceFirst("\\.shp", "_line.shp");
691
                                        SHPLayerDefinition lyrDefLine = new SHPLayerDefinition();
692
                                        lyrDefLine.setFieldsDesc(fieldsDescrip);
693

    
694
                                        File fileLines = new File(auxLine);
695
                                        lyrDefLine.setFile(fileLines);
696
                                        lyrDefLine.setName(fileLines.getName());
697
                                        lyrDefLine.setShapeType(FShape.LINE);
698
                                        loadEnconding(layer, writer2);
699
                                        writer2.setFile(fileLines);
700
                                        writer2.initialize(lyrDefLine);
701
                                        writers[1]=writer2;
702
                                        drivers[1]=getOpenShpDriver(fileLines);
703
                                        //drivers[1]=null;
704

    
705
                                        ShpWriter writer3 = (ShpWriter) LayerFactory.getWM().getWriter(
706
                                        "Shape Writer");
707
                                        // Pol?gonos
708
                                        String auxPolygon = path.replaceFirst("\\.shp", "_polygons.shp");
709
                                        SHPLayerDefinition lyrDefPolygon = new SHPLayerDefinition();
710
                                        lyrDefPolygon.setFieldsDesc(fieldsDescrip);
711
                                        File filePolygons = new File(auxPolygon);
712
                                        lyrDefPolygon.setFile(filePolygons);
713
                                        lyrDefPolygon.setName(filePolygons.getName());
714
                                        lyrDefPolygon.setShapeType(FShape.POLYGON);
715
                                        loadEnconding(layer, writer3);
716
                                        writer3.setFile(filePolygons);
717
                                        writer3.initialize(lyrDefPolygon);
718
                                        writers[2]=writer3;
719
                                        drivers[2]=getOpenShpDriver(filePolygons);
720
                                        //drivers[2]=null;
721

    
722
                                        writeMultiFeatures(mapContext,layer, writers, drivers);
723
                                } else {
724
                                        ShpWriter writer = (ShpWriter) LayerFactory.getWM().getWriter(
725
                                                "Shape Writer");
726
                                        loadEnconding(layer, writer);
727
                                        IndexedShpDriver drv = getOpenShpDriver(newFile);
728
                                        SHPLayerDefinition lyrDef = new SHPLayerDefinition();
729
                                        lyrDef.setFieldsDesc(fieldsDescrip);
730
                                        lyrDef.setFile(newFile);
731
                                        lyrDef.setName(newFile.getName());
732
                                        lyrDef.setShapeType(layer.getTypeIntVectorLayer());
733
                                        writer.setFile(newFile);
734
                                        writer.initialize(lyrDef);
735
                                        // CODIGO PARA EXPORTAR UN SHP A UN CHARSET DETERMINADO
736
                                        // ES UTIL PARA QUE UN DBF SE VEA CORRECTAMENTE EN EXCEL, POR EJEMPLO
737
//                                        Charset resul = (Charset) JOptionPane.showInputDialog((Component)PluginServices.getMDIManager().getActiveWindow(),
738
//                                                                PluginServices.getText(ExportTo.class, "select_charset_for_writing"),
739
//                                                                "Charset", JOptionPane.QUESTION_MESSAGE, null,
740
//                                                                Charset.availableCharsets().values().toArray(),
741
//                                                                writer.getCharsetForWriting().displayName());
742
//                                        if (resul == null)
743
//                                                return;
744
//                                        Charset charset = resul;
745
//                                        writer.setCharsetForWriting(charset);
746
                                        writeFeatures(mapContext, layer, writer, drv);
747

    
748
                                }
749
                        }
750
                } catch (InitializeWriterException e) {
751
                        NotificationManager.addError(e.getMessage(),e);
752
                } catch (OpenDriverException e) {
753
                        NotificationManager.addError(e.getMessage(),e);
754
                } catch (ReadDriverException e) {
755
                        NotificationManager.addError(e.getMessage(),e);
756
                } catch (DriverLoadException e) {
757
                        NotificationManager.addError(e.getMessage(),e);
758
                }
759

    
760
        }
761

    
762
        /**
763
         * Loads the dbf enconding
764
         * @param layer
765
         * @param writer
766
         */
767
        private void loadEnconding(FLyrVect layer, ShpWriter writer) {
768
                String charSetName = prefs.get("dbf_encoding", DbaseFile.getDefaultCharset().toString());
769
                if(layer.getSource() instanceof VectorialFileAdapter)
770
                        writer.loadDbfEncoding(((VectorialFileAdapter)layer.getSource()).getFile().getAbsolutePath(), Charset.forName(charSetName));
771
                else {
772
                        Object s = layer.getProperty("DBFFile");
773
                        if(s != null && s instanceof String)
774
                                writer.loadDbfEncoding((String)s, Charset.forName(charSetName));
775
                }
776
        }
777

    
778
        private IndexedShpDriver getOpenShpDriver(File fileShp) throws OpenDriverException {
779
                IndexedShpDriver drv = new IndexedShpDriver();
780
                if (!fileShp.exists()) {
781
                        try {
782
                                fileShp.createNewFile();
783
                                File newFileSHX=new File(fileShp.getAbsolutePath().replaceAll("[.]shp",".shx"));
784
                                newFileSHX.createNewFile();
785
                                File newFileDBF=new File(fileShp.getAbsolutePath().replaceAll("[.]shp",".dbf"));
786
                                newFileDBF.createNewFile();
787
                        } catch (IOException e) {
788
                                throw new FileNotFoundDriverException("SHP",e,fileShp.getAbsolutePath());
789
                        }
790
                }
791
                drv.open(fileShp);
792
                return drv;
793
        }
794
        /**
795
         * @see com.iver.andami.plugins.IExtension#isEnabled()
796
         */
797
        public boolean isEnabled() {
798
                int status = EditionUtilities.getEditionStatus();
799
                if (( status == EditionUtilities.EDITION_STATUS_ONE_VECTORIAL_LAYER_ACTIVE || status == EditionUtilities.EDITION_STATUS_ONE_VECTORIAL_LAYER_ACTIVE_AND_EDITABLE)
800
                                || (status == EditionUtilities.EDITION_STATUS_MULTIPLE_VECTORIAL_LAYER_ACTIVE)|| (status == EditionUtilities.EDITION_STATUS_MULTIPLE_VECTORIAL_LAYER_ACTIVE_AND_EDITABLE))
801
                {
802
                        return true;
803
                }
804
                return false;
805
        }
806

    
807
        /**
808
         * @see com.iver.andami.plugins.IExtension#isVisible()
809
         */
810
        public boolean isVisible() {
811
                com.iver.andami.ui.mdiManager.IWindow f = PluginServices.getMDIManager()
812
                                .getActiveWindow();
813

    
814
                if (f == null) {
815
                        return false;
816
                }
817

    
818
                if (f instanceof View)
819
                        return true;
820
                return false;
821
        }
822

    
823
        private int findFileByName(FieldDescription[] fields, String fieldName){
824
        for (int i=0; i < fields.length; i++)
825
        {
826
                FieldDescription f = fields[i];
827
                if (f.getFieldName().equalsIgnoreCase(fieldName))
828
                {
829
                        return i;
830
                }
831
        }
832

    
833
                return -1;
834

    
835
        }
836

    
837
        /**
838
         * This class is used to execute a command at the end of a
839
         * export process.
840
         * @author jpiera
841
         *
842
         */
843
        public interface EndExportToCommand{
844
                public void execute() throws Exception;
845
        }
846

    
847
}