Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extCAD / src / com / iver / cit / gvsig / ExportTo.java @ 33292

History | View | Annotate | Download (28.4 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
                                                reportStep();
177
                                                continue;
178
                                        }
179
                                        if (lyrVect instanceof FLyrAnnotation && geom.getGeometryType()!=FShape.POINT) {
180
                                                Point2D p=FLabel.createLabelPoint((FShape)geom.getInternalShape());
181
                                                geom=ShapeFactory.createPoint2D(p.getX(),p.getY());
182
                                        }
183
                                        if (isCanceled())
184
                                                break;
185
                                        if (ct != null) {
186
                                                if (bMustClone)
187
                                                        geom = geom.cloneGeometry();
188
                                                geom.reProject(ct);
189
                                        }
190
                                        reportStep();
191
                                        setNote(PluginServices.getText(this, "exporting_") + i);
192
                                        if (isCanceled())
193
                                                break;
194

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

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

    
236
                                                writer.process(edRow);
237
                                        }
238
                                }
239

    
240
                        }
241

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

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

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

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

    
295

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

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

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

    
348
                }
349
        }
350

    
351
        public void saveToPostGIS(MapContext mapContext, FLyrVect layer){
352
                try {
353
                        String tableName = null;
354
                        boolean tableNameNotFilled = true;
355

    
356
                        // show the input tableName dialog until user cancel or enter a valid identifier
357
                        do {
358
                                tableName = JOptionPane.showInputDialog(PluginServices.getText(this, "intro_tablename"));
359
                                if (tableName == null) {
360
                                        return;
361
                                }
362
                                tableNameNotFilled = (tableName.trim().length() == 0);
363
                                if (tableNameNotFilled) {
364
                                        JOptionPane.showMessageDialog(null,
365
                                                        PluginServices.getText(this,"intro_tablename_blank"),
366
                                                        PluginServices.getText(this,"warning"),
367
                                                        JOptionPane.WARNING_MESSAGE);
368
                                }
369
                        } while (tableNameNotFilled);
370

    
371
                        CharSequence seq = "\\/=.:,;??*{}?$%&()@#|!?";
372
                        for (int i = 0; i < seq.length(); i++) {
373
                                char c = seq.charAt(i);
374
                                if(tableName != null && tableName.indexOf(c) != -1) {
375
                                        NotificationManager.showMessageInfo(PluginServices.getText(this, "wrong_characters"), null);
376
                                        break;
377
                                }
378
                        }
379

    
380
                        DlgConnection dlg = new DlgConnection(new String[]{"PostGIS JDBC Driver"});
381
                        dlg.setModal(true);
382
                        dlg.setVisible(true);
383
                        ConnectionSettings cs = dlg.getConnSettings();
384
                        if (cs == null)
385
                                return;
386
                        IConnection conex = ConnectionFactory.createConnection(cs
387
                                        .getConnectionString(), cs.getUser(), cs.getPassw());
388

    
389

    
390
                        DBLayerDefinition originalDef = null;
391
                        if (layer.getSource().getDriver() instanceof IVectorialDatabaseDriver) {
392
                                originalDef=((IVectorialDatabaseDriver) layer.getSource().getDriver()).getLyrDef();
393
                        }
394

    
395

    
396
                        DBLayerDefinition dbLayerDef = new DBLayerDefinition();
397
                        // Fjp:
398
                        // Cambio: En Postgis, el nombre de cat?logo est? siempre vac?o. Es algo heredado de Oracle, que no se usa.
399
                        // dbLayerDef.setCatalogName(cs.getDb());
400
                        dbLayerDef.setCatalogName("");
401

    
402
                        // A?adimos el schema dentro del layer definition para poder tenerlo en cuenta.
403
                        dbLayerDef.setSchema(cs.getSchema());
404

    
405
                        dbLayerDef.setTableName(tableName);
406
                        dbLayerDef.setName(tableName);
407
                        dbLayerDef.setShapeType(layer.getShapeType());
408
                        SelectableDataSource sds = layer.getRecordset();
409

    
410
                        FieldDescription[] fieldsDescrip = sds.getFieldsDescription();
411
                        dbLayerDef.setFieldsDesc(fieldsDescrip);
412
                        // Creamos el driver. OJO: Hay que a?adir el campo ID a la
413
                        // definici?n de campos.
414

    
415
                        if (originalDef != null){
416
                                dbLayerDef.setFieldID(originalDef.getFieldID());
417
                                dbLayerDef.setFieldGeometry(originalDef.getFieldGeometry());
418

    
419
                        }else{
420
                                // Search for id field name
421
                                int index=0;
422
                                String fieldName="gid";
423
                                while (findFileByName(fieldsDescrip,fieldName) != -1){
424
                                        index++;
425
                                        fieldName= "gid" + index;
426
                                }
427
                                dbLayerDef.setFieldID(fieldName);
428

    
429
                                // search for geom field name
430
                                index=0;
431
                                fieldName="the_geom";
432
                                while (findFileByName(fieldsDescrip,fieldName) != -1){
433
                                        index++;
434
                                        fieldName = "the_geom" + index;
435
                                }
436
                                dbLayerDef.setFieldGeometry(fieldName);
437

    
438
                        }
439

    
440
                        // if id field dosen't exist we add it
441
                        if (findFileByName(fieldsDescrip,dbLayerDef.getFieldID()) == -1)
442
                        {
443
                                int numFieldsAnt = fieldsDescrip.length;
444
                                FieldDescription[] newFields = new FieldDescription[dbLayerDef.getFieldsDesc().length + 1];
445
                                for (int i=0; i < numFieldsAnt; i++)
446
                                {
447
                                        newFields[i] = fieldsDescrip[i];
448
                                }
449
                                newFields[numFieldsAnt] = new FieldDescription();
450
                                newFields[numFieldsAnt].setFieldDecimalCount(0);
451
                                newFields[numFieldsAnt].setFieldType(Types.INTEGER);
452
                                newFields[numFieldsAnt].setFieldLength(7);
453
                                newFields[numFieldsAnt].setFieldName(dbLayerDef.getFieldID());
454
                                dbLayerDef.setFieldsDesc(newFields);
455

    
456
                        }
457

    
458
                        // all fields to lowerCase
459
                        FieldDescription field;
460
                        for (int i=0;i<dbLayerDef.getFieldsDesc().length;i++){
461
                                field = dbLayerDef.getFieldsDesc()[i];
462
                                field.setFieldName(field.getFieldName().toLowerCase());
463
                        }
464
                        dbLayerDef.setFieldID(dbLayerDef.getFieldID().toLowerCase());
465
                        dbLayerDef.setFieldGeometry(dbLayerDef.getFieldGeometry().toLowerCase());
466

    
467
                        dbLayerDef.setWhereClause("");
468
                        String strSRID = layer.getProjection().getAbrev();
469
                        dbLayerDef.setSRID_EPSG(strSRID);
470
                        dbLayerDef.setConnection(conex);
471

    
472
                        PostGISWriter writer=(PostGISWriter)LayerFactory.getWM().getWriter("PostGIS Writer");
473
                        writer.setWriteAll(true);
474
                        writer.setCreateTable(true);
475
                        writer.initialize(dbLayerDef);
476
                        PostGisDriver postGISDriver=new PostGisDriver();
477
                        postGISDriver.setLyrDef(dbLayerDef);
478
                        postGISDriver.open();
479
                        PostProcessSupport.clearList();
480
                        Object[] params = new Object[2];
481
                        params[0] = conex;
482
                        params[1] = dbLayerDef;
483
                        PostProcessSupport.addToPostProcess(postGISDriver, "setData",
484
                                        params, 1);
485

    
486
                        writeFeatures(mapContext, layer, writer, postGISDriver);
487

    
488
                } catch (DriverLoadException e) {
489
                        NotificationManager.addError(e.getMessage(),e);
490
                } catch (DBException e) {
491
                        NotificationManager.showMessageError(e.getLocalizedMessage(),e);
492
                } catch (InitializeWriterException e) {
493
                        NotificationManager.showMessageError(e.getMessage(),e);
494
                } catch (ReadDriverException e) {
495
                        NotificationManager.addError(e.getMessage(),e);
496
                }
497

    
498
        }
499

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

    
540
                // Creamos la tabla.
541
                writer.preProcess();
542

    
543
                int rowCount;
544
                FBitSet bitSet = layer.getRecordset().getSelection();
545

    
546
                if (bitSet.cardinality() == 0)
547
                        rowCount = va.getShapeCount();
548
                else
549
                        rowCount = bitSet.cardinality();
550

    
551
                ProgressMonitor progress = new ProgressMonitor(
552
                                (JComponent) PluginServices.getMDIManager().getActiveWindow(),
553
                                PluginServices.getText(this, "exportando_features"),
554
                                PluginServices.getText(this, "exportando_features"), 0,
555
                                rowCount);
556

    
557
                progress.setMillisToDecideToPopup(200);
558
                progress.setMillisToPopup(500);
559

    
560
                if (bitSet.cardinality() == 0) {
561
                        rowCount = va.getShapeCount();
562
                        for (int i = 0; i < rowCount; i++) {
563
                                IGeometry geom = va.getShape(i);
564

    
565
                                progress.setProgress(i);
566
                                if (progress.isCanceled())
567
                                        break;
568

    
569
                                if (geom != null) {
570
                                        Value[] values = sds.getRow(i);
571
                                        IFeature feat = new DefaultFeature(geom, values, "" + i);
572
                                        DefaultRowEdited edRow = new DefaultRowEdited(feat,
573
                                                        IRowEdited.STATUS_ADDED, i);
574
                                        writer.process(edRow);
575
                                }
576
                        }
577
                } else {
578
                        int counter = 0;
579
                        for (int i = bitSet.nextSetBit(0); i >= 0; i = bitSet
580
                        .nextSetBit(i + 1)) {
581
                                IGeometry geom = va.getShape(i);
582

    
583
                                progress.setProgress(counter++);
584
                                if (progress.isCanceled())
585
                                        break;
586

    
587
                                if (geom != null) {
588
                                        Value[] values = sds.getRow(i);
589
                                        IFeature feat = new DefaultFeature(geom, values, "" + i);
590
                                        DefaultRowEdited edRow = new DefaultRowEdited(feat,
591
                                                        IRowEdited.STATUS_ADDED, i);
592

    
593
                                        writer.process(edRow);
594
                                }
595
                        }
596

    
597
                }
598

    
599
                writer.postProcess();
600
                progress.close();
601
        }
602

    
603
        public void saveToDxf(MapContext mapContext, FLyrVect layer)  {
604
                try {
605
                        JFileChooser jfc = new JFileChooser(lastPath);
606
                        SimpleFileFilter filterShp = new SimpleFileFilter("dxf",
607
                                        PluginServices.getText(this, "dxf_files"));
608
                        jfc.setFileFilter(filterShp);
609
                        if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
610
                                File newFile = jfc.getSelectedFile();
611
                                String path = newFile.getAbsolutePath();
612
                                if (!(path.toLowerCase().endsWith(".dxf"))) {
613
                                        path = path + ".dxf";
614
                                }
615
                                newFile = new File(path);
616

    
617
                                DxfWriter writer = (DxfWriter) LayerFactory.getWM().getWriter(
618
                                "DXF Writer");
619
                                SHPLayerDefinition lyrDef = new SHPLayerDefinition();
620
                                SelectableDataSource sds = layer.getRecordset();
621
                                FieldDescription[] fieldsDescrip = sds.getFieldsDescription();
622
                                lyrDef.setFieldsDesc(fieldsDescrip);
623
                                lyrDef.setFile(newFile);
624
                                lyrDef.setName(newFile.getName());
625
                                lyrDef.setShapeType(layer.getShapeType());
626
                                writer.setFile(newFile);
627
                                writer.initialize(lyrDef);
628
                                writer.setProjection(layer.getProjection());
629
                                DxfFieldsMapping fieldsMapping = new DxfFieldsMapping();
630
                                // TODO: Recuperar aqu? los campos del cuadro de di?logo.
631
                                writer.setFieldMapping(fieldsMapping);
632
                                DXFMemoryDriver dxfDriver=new DXFMemoryDriver();
633
                                dxfDriver.open(newFile);
634
                                writeFeatures(mapContext, layer, writer, dxfDriver);
635
                                String fileName = newFile.getAbsolutePath();
636
                                lastPath  = fileName.substring(0, fileName.lastIndexOf(File.separatorChar));
637
                        }
638

    
639
                } catch (ReadDriverException e) {
640
                        NotificationManager.addError(e.getMessage(),e);
641
                } catch (InitializeWriterException e) {
642
                        NotificationManager.addError(e.getMessage(),e);
643
                } catch (DriverLoadException e) {
644
                        NotificationManager.addError(e.getMessage(),e);
645
                }
646

    
647
        }
648

    
649
        public void saveToShp(MapContext mapContext, FLyrVect layer) {
650
                try {
651
                        JFileChooser jfc = new JFileChooser();
652
                        SimpleFileFilter filterShp = new SimpleFileFilter("shp",
653
                                        PluginServices.getText(this, "shp_files"));
654
                        jfc.setFileFilter(filterShp);
655
                        if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
656
                                File newFile = jfc.getSelectedFile();
657
                                String path = newFile.getAbsolutePath();
658
                                if( newFile.exists()){
659
                                        int resp = JOptionPane.showConfirmDialog(
660
                                                        (Component) PluginServices.getMainFrame(),PluginServices.getText(this,"fichero_ya_existe_seguro_desea_guardarlo"),
661
                                                        PluginServices.getText(this,"guardar"), JOptionPane.YES_NO_OPTION);
662
                                        if (resp != JOptionPane.YES_OPTION) {
663
                                                return;
664
                                        }
665
                                }
666
                                if (!(path.toLowerCase().endsWith(".shp"))) {
667
                                        path = path + ".shp";
668
                                }
669
                                newFile = new File(path);
670

    
671

    
672

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

    
676
                                if (layer.getShapeType() == FShape.MULTI) // Exportamos a 3
677
                                        // ficheros
678
                                {
679
                                        ShpWriter writer1 = (ShpWriter) LayerFactory.getWM().getWriter(
680
                                        "Shape Writer");
681
                                        Driver[] drivers=new Driver[3];
682
                                        ShpWriter[] writers=new ShpWriter[3];
683

    
684
                                        // puntos
685
                                        String auxPoint = path.replaceFirst("\\.shp", "_points.shp");
686

    
687
                                        SHPLayerDefinition lyrDefPoint = new SHPLayerDefinition();
688
                                        lyrDefPoint.setFieldsDesc(fieldsDescrip);
689
                                        File filePoints = new File(auxPoint);
690
                                        lyrDefPoint.setFile(filePoints);
691
                                        lyrDefPoint.setName(filePoints.getName());
692
                                        lyrDefPoint.setShapeType(FShape.POINT);
693
                                        loadEnconding(layer, writer1);
694
                                        writer1.setFile(filePoints);
695
                                        writer1.initialize(lyrDefPoint);
696
                                        writers[0]=writer1;
697
                                        drivers[0]=getOpenShpDriver(filePoints);
698
                                        //drivers[0]=null;
699

    
700
                                        ShpWriter writer2 = (ShpWriter) LayerFactory.getWM().getWriter(
701
                                        "Shape Writer");
702
                                        // Lineas
703
                                        String auxLine = path.replaceFirst("\\.shp", "_line.shp");
704
                                        SHPLayerDefinition lyrDefLine = new SHPLayerDefinition();
705
                                        lyrDefLine.setFieldsDesc(fieldsDescrip);
706

    
707
                                        File fileLines = new File(auxLine);
708
                                        lyrDefLine.setFile(fileLines);
709
                                        lyrDefLine.setName(fileLines.getName());
710
                                        lyrDefLine.setShapeType(FShape.LINE);
711
                                        loadEnconding(layer, writer2);
712
                                        writer2.setFile(fileLines);
713
                                        writer2.initialize(lyrDefLine);
714
                                        writers[1]=writer2;
715
                                        drivers[1]=getOpenShpDriver(fileLines);
716
                                        //drivers[1]=null;
717

    
718
                                        ShpWriter writer3 = (ShpWriter) LayerFactory.getWM().getWriter(
719
                                        "Shape Writer");
720
                                        // Pol?gonos
721
                                        String auxPolygon = path.replaceFirst("\\.shp", "_polygons.shp");
722
                                        SHPLayerDefinition lyrDefPolygon = new SHPLayerDefinition();
723
                                        lyrDefPolygon.setFieldsDesc(fieldsDescrip);
724
                                        File filePolygons = new File(auxPolygon);
725
                                        lyrDefPolygon.setFile(filePolygons);
726
                                        lyrDefPolygon.setName(filePolygons.getName());
727
                                        lyrDefPolygon.setShapeType(FShape.POLYGON);
728
                                        loadEnconding(layer, writer3);
729
                                        writer3.setFile(filePolygons);
730
                                        writer3.initialize(lyrDefPolygon);
731
                                        writers[2]=writer3;
732
                                        drivers[2]=getOpenShpDriver(filePolygons);
733
                                        //drivers[2]=null;
734

    
735
                                        writeMultiFeatures(mapContext,layer, writers, drivers);
736
                                } else {
737
                                        ShpWriter writer = (ShpWriter) LayerFactory.getWM().getWriter(
738
                                        "Shape Writer");
739
                                        loadEnconding(layer, writer);
740
                                        IndexedShpDriver drv = getOpenShpDriver(newFile);
741
                                        SHPLayerDefinition lyrDef = new SHPLayerDefinition();
742
                                        lyrDef.setFieldsDesc(fieldsDescrip);
743
                                        lyrDef.setFile(newFile);
744
                                        lyrDef.setName(newFile.getName());
745
                                        lyrDef.setShapeType(layer.getTypeIntVectorLayer());
746
                                        writer.setFile(newFile);
747
                                        writer.initialize(lyrDef);
748
                                        // CODIGO PARA EXPORTAR UN SHP A UN CHARSET DETERMINADO
749
                                        // ES UTIL PARA QUE UN DBF SE VEA CORRECTAMENTE EN EXCEL, POR EJEMPLO
750
                                        //                                        Charset resul = (Charset) JOptionPane.showInputDialog((Component)PluginServices.getMDIManager().getActiveWindow(),
751
                                        //                                                                PluginServices.getText(ExportTo.class, "select_charset_for_writing"),
752
                                        //                                                                "Charset", JOptionPane.QUESTION_MESSAGE, null,
753
                                        //                                                                Charset.availableCharsets().values().toArray(),
754
                                        //                                                                writer.getCharsetForWriting().displayName());
755
                                        //                                        if (resul == null)
756
                                        //                                                return;
757
                                        //                                        Charset charset = resul;
758
                                        //                                        writer.setCharsetForWriting(charset);
759
                                        writeFeatures(mapContext, layer, writer, drv);
760

    
761
                                }
762
                        }
763
                } catch (InitializeWriterException e) {
764
                        NotificationManager.addError(e.getMessage(),e);
765
                } catch (OpenDriverException e) {
766
                        NotificationManager.addError(e.getMessage(),e);
767
                } catch (ReadDriverException e) {
768
                        NotificationManager.addError(e.getMessage(),e);
769
                } catch (DriverLoadException e) {
770
                        NotificationManager.addError(e.getMessage(),e);
771
                }
772

    
773
        }
774

    
775
        /**
776
         * Loads the dbf enconding
777
         * @param layer
778
         * @param writer
779
         */
780
        private void loadEnconding(FLyrVect layer, ShpWriter writer) {
781
                String charSetName = prefs.get("dbf_encoding", DbaseFile.getDefaultCharset().toString());
782
                if(layer.getSource() instanceof VectorialFileAdapter)
783
                        writer.loadDbfEncoding(((VectorialFileAdapter)layer.getSource()).getFile().getAbsolutePath(), Charset.forName(charSetName));
784
                else {
785
                        Object s = layer.getProperty("DBFFile");
786
                        if(s != null && s instanceof String)
787
                                writer.loadDbfEncoding((String)s, Charset.forName(charSetName));
788
                }
789
        }
790

    
791
        private IndexedShpDriver getOpenShpDriver(File fileShp) throws OpenDriverException {
792
                IndexedShpDriver drv = new IndexedShpDriver();
793
                if (!fileShp.exists()) {
794
                        try {
795
                                fileShp.createNewFile();
796
                                File newFileSHX=new File(fileShp.getAbsolutePath().replaceAll("[.]shp",".shx"));
797
                                newFileSHX.createNewFile();
798
                                File newFileDBF=new File(fileShp.getAbsolutePath().replaceAll("[.]shp",".dbf"));
799
                                newFileDBF.createNewFile();
800
                        } catch (IOException e) {
801
                                throw new FileNotFoundDriverException("SHP",e,fileShp.getAbsolutePath());
802
                        }
803
                }
804
                drv.open(fileShp);
805
                return drv;
806
        }
807
        /**
808
         * @see com.iver.andami.plugins.IExtension#isEnabled()
809
         */
810
        public boolean isEnabled() {
811
                int status = EditionUtilities.getEditionStatus();
812
                if (( status == EditionUtilities.EDITION_STATUS_ONE_VECTORIAL_LAYER_ACTIVE || status == EditionUtilities.EDITION_STATUS_ONE_VECTORIAL_LAYER_ACTIVE_AND_EDITABLE)
813
                                || (status == EditionUtilities.EDITION_STATUS_MULTIPLE_VECTORIAL_LAYER_ACTIVE)|| (status == EditionUtilities.EDITION_STATUS_MULTIPLE_VECTORIAL_LAYER_ACTIVE_AND_EDITABLE))
814
                {
815
                        return true;
816
                }
817
                return false;
818
        }
819

    
820
        /**
821
         * @see com.iver.andami.plugins.IExtension#isVisible()
822
         */
823
        public boolean isVisible() {
824
                com.iver.andami.ui.mdiManager.IWindow f = PluginServices.getMDIManager()
825
                .getActiveWindow();
826

    
827
                if (f == null) {
828
                        return false;
829
                }
830

    
831
                if (f instanceof View)
832
                        return true;
833
                return false;
834
        }
835

    
836
        private int findFileByName(FieldDescription[] fields, String fieldName){
837
                for (int i=0; i < fields.length; i++)
838
                {
839
                        FieldDescription f = fields[i];
840
                        if (f.getFieldName().equalsIgnoreCase(fieldName))
841
                        {
842
                                return i;
843
                        }
844
                }
845

    
846
                return -1;
847

    
848
        }
849

    
850
        /**
851
         * This class is used to execute a command at the end of a
852
         * export process.
853
         * @author jpiera
854
         *
855
         */
856
        public interface EndExportToCommand{
857
                public void execute() throws Exception;
858
        }
859

    
860
}