Statistics
| Revision:

root / branches / v2_0_0_prep / extensions / extEditing / src / org / gvsig / editing / ExportTo.java @ 31496

History | View | Annotate | Download (28.9 KB)

1
package org.gvsig.editing;
2

    
3
import java.awt.Component;
4
import java.io.File;
5

    
6
import javax.swing.JComponent;
7
import javax.swing.JFileChooser;
8
import javax.swing.JOptionPane;
9

    
10
import org.gvsig.andami.PluginServices;
11
import org.gvsig.andami.messages.NotificationManager;
12
import org.gvsig.andami.plugins.Extension;
13
import org.gvsig.app.project.documents.view.ViewDocument;
14
import org.gvsig.app.project.documents.view.gui.DefaultViewPanel;
15
import org.gvsig.fmap.dal.DALLocator;
16
import org.gvsig.fmap.dal.DataManager;
17
import org.gvsig.fmap.dal.exception.DataException;
18
import org.gvsig.fmap.dal.exception.ReadException;
19
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
20
import org.gvsig.fmap.dal.feature.DisposableIterator;
21
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
22
import org.gvsig.fmap.dal.feature.EditableFeatureType;
23
import org.gvsig.fmap.dal.feature.Feature;
24
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
25
import org.gvsig.fmap.dal.feature.FeatureQuery;
26
import org.gvsig.fmap.dal.feature.FeatureSelection;
27
import org.gvsig.fmap.dal.feature.FeatureSet;
28
import org.gvsig.fmap.dal.feature.FeatureStore;
29
import org.gvsig.fmap.dal.feature.FeatureType;
30
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
31
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemServerExplorer;
32
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemServerExplorerParameters;
33
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemStoreParameters;
34
import org.gvsig.fmap.dal.store.dxf.DXFStoreParameters;
35
import org.gvsig.fmap.dal.store.shp.SHPNewStoreParameters;
36
import org.gvsig.fmap.geom.Geometry;
37
import org.gvsig.fmap.mapcontext.MapContext;
38
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
39
import org.gvsig.fmap.mapcontext.layers.FLayer;
40
import org.gvsig.fmap.mapcontext.layers.FLayers;
41
import org.gvsig.fmap.mapcontext.layers.LayerFactory;
42
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
43
import org.gvsig.tools.dispose.DisposeUtils;
44
import org.gvsig.tools.evaluator.AbstractEvaluator;
45
import org.gvsig.tools.evaluator.Evaluator;
46
import org.gvsig.tools.evaluator.EvaluatorData;
47
import org.gvsig.tools.evaluator.EvaluatorException;
48
import org.gvsig.utils.PostProcessSupport;
49
import org.gvsig.utils.SimpleFileFilter;
50

    
51

    
52
public class ExportTo extends Extension {
53
        private String lastPath = null;
54
//        private class WriterTask extends AbstractMonitorableTask
55
//        {
56
//                FLyrVect lyrVect;
57
//                IWriter writer;
58
//                int rowCount;
59
//                ReadableVectorial va;
60
//                SelectableDataSource sds;
61
//                FBitSet bitSet;
62
//                MapContext mapContext;
63
//                VectorialDriver reader;
64
//
65
//                public WriterTask(MapContext mapContext, FLyrVect lyr, IWriter writer, Driver reader) throws ReadDriverException
66
//                {
67
//                        this.mapContext = mapContext;
68
//                        this.lyrVect = lyr;
69
//                        this.writer = writer;
70
//                        this.reader = (VectorialDriver) reader;
71
//
72
//                        setInitialStep(0);
73
//                        setDeterminatedProcess(true);
74
//                        setStatusMessage(PluginServices.getText(this, "exportando_features"));
75
//
76
//                        va = lyrVect.getSource();
77
//                        sds = lyrVect.getRecordset();
78
//
79
//                        bitSet = sds.getSelection();
80
//
81
//                        if (bitSet.cardinality() == 0)
82
//                                rowCount = va.getShapeCount();
83
//                        else
84
//                                rowCount = bitSet.cardinality();
85
//
86
//                        setFinalStep(rowCount);
87
//
88
//                }
89
//                public void run() throws Exception {
90
//                        va.start();
91
//                        ICoordTrans ct = lyrVect.getCoordTrans();
92
//                        DriverAttributes attr = va.getDriverAttributes();
93
//                        boolean bMustClone = false;
94
//                        if (attr != null) {
95
//                                if (attr.isLoadedInMemory()) {
96
//                                        bMustClone = attr.isLoadedInMemory();
97
//                                }
98
//                        }
99
//                        if (lyrVect instanceof FLyrAnnotation && lyrVect.getShapeType()!=FShape.POINT) {
100
//                                SHPLayerDefinition lyrDef=(SHPLayerDefinition)writer.getTableDefinition();
101
//                                lyrDef.setShapeType(FShape.POINT);
102
//                                writer.initialize(lyrDef);
103
//                        }
104
//
105
//                        // Creamos la tabla.
106
//                        writer.preProcess();
107
//
108
//                        if (bitSet.cardinality() == 0) {
109
//                                rowCount = va.getShapeCount();
110
//                                for (int i = 0; i < rowCount; i++) {
111
//                                        IGeometry geom = va.getShape(i);
112
//                                        if (geom == null) {
113
//                                                continue;
114
//                                        }
115
//                                        if (lyrVect instanceof FLyrAnnotation && geom.getGeometryType()!=FShape.POINT) {
116
//                                                Point2D p=FLabel.createLabelPoint((FShape)geom.getInternalShape());
117
//                                                geom=ShapeFactory.createPoint2D(p.getX(),p.getY());
118
//                                        }
119
//                                        if (ct != null) {
120
//                                                if (bMustClone)
121
//                                                        geom = geom.cloneGeometry();
122
//                                                geom.reProject(ct);
123
//                                        }
124
//                                        reportStep();
125
//                                        setNote(PluginServices.getText(this, "exporting_") + i);
126
//                                        if (isCanceled())
127
//                                                break;
128
//
129
//                                        if (geom != null) {
130
//                                                Value[] values = sds.getRow(i);
131
//                                                IFeature feat = new DefaultFeature(geom, values, "" + i);
132
//                                                DefaultRowEdited edRow = new DefaultRowEdited(feat,
133
//                                                                DefaultRowEdited.STATUS_ADDED, i);
134
//                                                writer.process(edRow);
135
//                                        }
136
//                                }
137
//                        } else {
138
//                                int counter = 0;
139
//                                for (int i = bitSet.nextSetBit(0); i >= 0; i = bitSet
140
//                                                .nextSetBit(i + 1)) {
141
//                                        IGeometry geom = va.getShape(i);
142
//                                        if (geom == null) {
143
//                                                continue;
144
//                                        }
145
//                                        if (lyrVect instanceof FLyrAnnotation && geom.getGeometryType()!=FShape.POINT) {
146
//                                                Point2D p=FLabel.createLabelPoint((FShape)geom.getInternalShape());
147
//                                                geom=ShapeFactory.createPoint2D(p.getX(),p.getY());
148
//                                        }
149
//                                        if (ct != null) {
150
//                                                if (bMustClone)
151
//                                                        geom = geom.cloneGeometry();
152
//                                                geom.reProject(ct);
153
//                                        }
154
//                                        reportStep();
155
//                                        setNote(PluginServices.getText(this, "exporting_") + counter);
156
//                                        if (isCanceled())
157
//                                                break;
158
//
159
//                                        if (geom != null) {
160
//                                                Value[] values = sds.getRow(i);
161
//                                                IFeature feat = new DefaultFeature(geom, values, "" + i);
162
//                                                DefaultRowEdited edRow = new DefaultRowEdited(feat,
163
//                                                                DefaultRowEdited.STATUS_ADDED, i);
164
//
165
//                                                writer.process(edRow);
166
//                                        }
167
//                                }
168
//
169
//                        }
170
//
171
//                        writer.postProcess();
172
//                        va.stop();
173
//                        if (reader != null){
174
//                                int res = JOptionPane.showConfirmDialog(
175
//                                        (JComponent) PluginServices.getMDIManager().getActiveWindow()
176
//                                        , PluginServices.getText(this, "insertar_en_la_vista_la_capa_creada"),
177
//                                        PluginServices.getText(this,"insertar_capa"),
178
//                                        JOptionPane.YES_NO_OPTION);
179
//
180
//                                if (res == JOptionPane.YES_OPTION)
181
//                                {
182
//                                        PostProcessSupport.executeCalls();
183
//                                        ILayerDefinition lyrDef = (ILayerDefinition) writer.getTableDefinition();
184
//                                        FLayer newLayer = LayerFactory.createLayer(
185
//                                                        lyrDef.getName(), reader, mapContext.getProjection());
186
//                                        mapContext.getLayers().addLayer(newLayer);
187
//                                }
188
//                        }
189
//
190
//                }
191
//                /* (non-Javadoc)
192
//                 * @see com.iver.utiles.swing.threads.IMonitorableTask#finished()
193
//                 */
194
//                public void finished() {
195
//                        // TODO Auto-generated method stub
196
//
197
//                }
198
//
199
//        }
200
//        private class MultiWriterTask extends AbstractMonitorableTask{
201
//                Vector tasks=new Vector();
202
//                public void addTask(WriterTask wt) {
203
//                        tasks.add(wt);
204
//                }
205
//                public void run() throws Exception {
206
//                        for (int i = 0; i < tasks.size(); i++) {
207
//                                ((WriterTask)tasks.get(i)).run();
208
//                        }
209
//                        tasks.clear();
210
//                }
211
//                /* (non-Javadoc)
212
//                 * @see com.iver.utiles.swing.threads.IMonitorableTask#finished()
213
//                 */
214
//                public void finished() {
215
//                        // TODO Auto-generated method stub
216
//
217
//                }
218
//
219
//
220
//        }
221
        /**
222
         * @see org.gvsig.andami.plugins.IExtension#initialize()
223
         */
224
        public void initialize() {
225
        }
226

    
227
        /**
228
         * @see org.gvsig.andami.plugins.IExtension#execute(java.lang.String)
229
         */
230
        public void execute(String actionCommand) {
231
                org.gvsig.andami.ui.mdiManager.IWindow f = PluginServices.getMDIManager()
232
                                .getActiveWindow();
233

    
234
                if (f instanceof DefaultViewPanel) {
235
                        DefaultViewPanel vista = (DefaultViewPanel) f;
236
                        ViewDocument model = vista.getModel();
237
                        MapContext mapa = model.getMapContext();
238
                        FLayers layers = mapa.getLayers();
239
                        FLayer[] actives = layers.getActives();
240
                        try {
241
                                // NOTA: SI HAY UNA SELECCI?N, SOLO SE SALVAN LOS SELECCIONADOS
242
                                for (int i = 0; i < actives.length; i++) {
243
                                        if (actives[i] instanceof FLyrVect) {
244
                                                FLyrVect lv = (FLyrVect) actives[i];
245
//                                                saveToDXF(mapa,lv);
246

    
247

    
248

    
249
                                                /////////
250

    
251
                                                long numSelec = ((FeatureSelection)lv.getFeatureStore().getSelection()).getSize();
252
                                                if (numSelec > 0) {
253
                                                        int resp = JOptionPane.showConfirmDialog(
254
                                                                        (Component) PluginServices.getMainFrame(),
255
                                                                        PluginServices.getText(this,"se_van_a_guardar_") + numSelec
256
                                                                                        + PluginServices.getText(this,"features_desea_continuar"),
257
                                                                        PluginServices.getText(this,"export_to"), JOptionPane.YES_NO_OPTION);
258
                                                        if (resp != JOptionPane.YES_OPTION) {
259
                                                                continue;
260
                                                        }
261
                                                } // if numSelec > 0
262
                                                if (actionCommand.equals("SHP")) {
263
                                                        saveToSHP(mapa, lv);
264
                                                }
265
                                                if (actionCommand.equals("DXF")) {
266
                                                        saveToDXF(mapa, lv);
267
                                                }
268
//                                                if (actionCommand.equals("POSTGIS")) {
269
//                                                        saveToPostGIS(mapa, lv);
270
//                                                }
271
//                                                if (actionCommand.equals("GML")) {
272
//                                                        saveToGml(mapa, lv);
273
//                                                }
274
                                        } // actives[i]
275
                                } // for
276
                        } catch (Exception e) {
277
                                NotificationManager.showMessageError(e.getMessage(),e);
278
                        }
279
                }
280
        }
281

    
282
//        public void saveToPostGIS(MapContext mapContext, FLyrVect layer){
283
//                try {
284
//                        String tableName = JOptionPane.showInputDialog(PluginServices
285
//                                        .getText(this, "intro_tablename"));
286
//                        if (tableName == null)
287
//                                return;
288
//                        tableName = tableName.toLowerCase();
289
//                        DlgConnection dlg = new DlgConnection();
290
//                        dlg.setModal(true);
291
//                        dlg.setVisible(true);
292
//                        ConnectionSettings cs = dlg.getConnSettings();
293
//                        if (cs == null)
294
//                                return;
295
//                        IConnection conex = ConnectionFactory.createConnection(cs
296
//                                        .getConnectionString(), cs.getUser(), cs.getPassw());
297
//
298
//
299
//                        DBLayerDefinition originalDef = null;
300
//                        if (layer.getSource().getDriver() instanceof IVectorialDatabaseDriver) {
301
//                                originalDef=((IVectorialDatabaseDriver) layer.getSource().getDriver()).getLyrDef();
302
//                        }
303
//
304
//
305
//                        DBLayerDefinition dbLayerDef = new DBLayerDefinition();
306
//                        // Fjp:
307
//                        // Cambio: En Postgis, el nombre de cat?logo est? siempre vac?o. Es algo heredado de Oracle, que no se usa.
308
//                        // dbLayerDef.setCatalogName(cs.getDb());
309
//                        dbLayerDef.setCatalogName("");
310
//
311
//                        // A?adimos el schema dentro del layer definition para poder tenerlo en cuenta.
312
//                        dbLayerDef.setSchema(cs.getSchema());
313
//
314
//                        dbLayerDef.setTableName(tableName);
315
//                        dbLayerDef.setName(tableName);
316
//                        dbLayerDef.setShapeType(layer.getShapeType());
317
//                        SelectableDataSource sds = layer.getRecordset();
318
//
319
//                        FieldDescription[] fieldsDescrip = sds.getFieldsDescription();
320
//                        dbLayerDef.setFieldsDesc(fieldsDescrip);
321
//                // Creamos el driver. OJO: Hay que a?adir el campo ID a la
322
//                // definici?n de campos.
323
//
324
//                        if (originalDef != null){
325
//                                dbLayerDef.setFieldID(originalDef.getFieldID());
326
//                                dbLayerDef.setFieldGeometry(originalDef.getFieldGeometry());
327
//
328
//                        }else{
329
//                                // Search for id field name
330
//                                int index=0;
331
//                                String fieldName="gid";
332
//                                while (findFileByName(fieldsDescrip,fieldName) != -1){
333
//                                        index++;
334
//                                        fieldName="gid"+index;
335
//                                }
336
//                                dbLayerDef.setFieldID(fieldName);
337
//
338
//                                // search for geom field name
339
//                                index=0;
340
//                                fieldName="the_geom";
341
//                                while (findFileByName(fieldsDescrip,fieldName) != -1){
342
//                                        index++;
343
//                                        fieldName="the_geom"+index;
344
//                                }
345
//                                dbLayerDef.setFieldGeometry(fieldName);
346
//
347
//                        }
348
//
349
//                        // if id field dosen't exist we add it
350
//                        if (findFileByName(fieldsDescrip,dbLayerDef.getFieldID()) == -1)
351
//                        {
352
//                        int numFieldsAnt = fieldsDescrip.length;
353
//                        FieldDescription[] newFields = new FieldDescription[dbLayerDef.getFieldsDesc().length + 1];
354
//                    for (int i=0; i < numFieldsAnt; i++)
355
//                    {
356
//                            newFields[i] = fieldsDescrip[i];
357
//                    }
358
//                    newFields[numFieldsAnt] = new FieldDescription();
359
//                    newFields[numFieldsAnt].setFieldDecimalCount(0);
360
//                    newFields[numFieldsAnt].setFieldType(Types.INTEGER);
361
//                    newFields[numFieldsAnt].setFieldLength(7);
362
//                    newFields[numFieldsAnt].setFieldName("gid");
363
//                    dbLayerDef.setFieldsDesc(newFields);
364
//
365
//                }
366
//
367
//
368
//                        dbLayerDef.setWhereClause("");
369
//                        String strSRID = layer.getProjection().getAbrev();
370
//                        dbLayerDef.setSRID_EPSG(strSRID);
371
//                        dbLayerDef.setConnection(conex);
372
//
373
//                        PostGISWriter writer=(PostGISWriter)LayerFactory.getWM().getWriter("PostGIS Writer");
374
//                        writer.setWriteAll(true);
375
//                        writer.setCreateTable(true);
376
//                        writer.initialize(dbLayerDef);
377
//                        PostGisDriver postGISDriver=new PostGisDriver();
378
//                        postGISDriver.setLyrDef(dbLayerDef);
379
//                        postGISDriver.open();
380
//                        PostProcessSupport.clearList();
381
//                        Object[] params = new Object[2];
382
//                        params[0] = conex;
383
//                        params[1] = dbLayerDef;
384
//                        PostProcessSupport.addToPostProcess(postGISDriver, "setData",
385
//                                        params, 1);
386
//
387
//                        writeFeatures(mapContext, layer, writer, postGISDriver);
388
//
389
//                } catch (DriverLoadException e) {
390
//                        NotificationManager.addError(e.getMessage(),e);
391
//                } catch (DBException e) {
392
//                        NotificationManager.addError(e.getMessage(),e);
393
//                } catch (InitializeWriterException e) {
394
//                        NotificationManager.addError(e.getMessage(),e);
395
//                } catch (ReadDriverException e) {
396
//                        NotificationManager.addError(e.getMessage(),e);
397
//                }
398
//
399
//        }
400

    
401
        /**
402
         * Lanza un thread en background que escribe las features. Cuando termina, pregunta al usuario si quiere
403
         * a?adir la nueva capa a la vista. Para eso necesita un driver de lectura ya configurado.
404
         * @param mapContext
405
         * @param layer
406
         * @param writer
407
         * @param reader
408
         */
409
//        private void writeFeatures(MapContext mapContext, FLyrVect layer, IWriter writer, Driver reader) throws ReadDriverException
410
//        {
411
//                PluginServices.cancelableBackgroundExecution(new WriterTask(mapContext, layer, writer, reader));
412
//        }
413
//        private void writeMultiFeatures(MapContext mapContext, FLyrVect layers, IWriter[] writers, Driver[] readers) throws ReadDriverException{
414
//                MultiWriterTask mwt=new MultiWriterTask();
415
//                for (int i=0;i<writers.length;i++) {
416
//                        mwt.addTask(new WriterTask(mapContext, layers, writers[i], readers[i]));
417
//                }
418
//                PluginServices.cancelableBackgroundExecution(mwt);
419
//        }
420
        /**
421
         * @param layer
422
         *            FLyrVect to obtain features. If selection, only selected
423
         *            features will be precessed.
424
         * @param writer
425
         *            (Must be already initialized)
426
         * @throws DataException
427
         * @throws ReadException
428
         * @throws ProcessWriterException
429
         * @throws ExpansionFileReadException
430
         * @throws EditionException
431
         */
432
//        public void writeFeaturesNoThread(FLyrVect layer, IWriter writer) throws ReadDriverException, VisitorException, ExpansionFileReadException{
433
//                ReadableVectorial va = layer.getSource();
434
//                SelectableDataSource sds = layer.getRecordset();
435
//
436
//                // Creamos la tabla.
437
//                writer.preProcess();
438
//
439
//                int rowCount;
440
//                FBitSet bitSet = layer.getRecordset().getSelection();
441
//
442
//                if (bitSet.cardinality() == 0)
443
//                        rowCount = va.getShapeCount();
444
//                else
445
//                        rowCount = bitSet.cardinality();
446
//
447
//                ProgressMonitor progress = new ProgressMonitor(
448
//                                (JComponent) PluginServices.getMDIManager().getActiveWindow(),
449
//                                PluginServices.getText(this, "exportando_features"),
450
//                                PluginServices.getText(this, "exportando_features"), 0,
451
//                                rowCount);
452
//
453
//                progress.setMillisToDecideToPopup(200);
454
//                progress.setMillisToPopup(500);
455
//
456
//                if (bitSet.cardinality() == 0) {
457
//                        rowCount = va.getShapeCount();
458
//                        for (int i = 0; i < rowCount; i++) {
459
//                                IGeometry geom = va.getShape(i);
460
//
461
//                                progress.setProgress(i);
462
//                                if (progress.isCanceled())
463
//                                        break;
464
//
465
//                                if (geom != null) {
466
//                                        Value[] values = sds.getRow(i);
467
//                                        IFeature feat = new DefaultFeature(geom, values, "" + i);
468
//                                        DefaultRowEdited edRow = new DefaultRowEdited(feat,
469
//                                                        IRowEdited.STATUS_ADDED, i);
470
//                                        writer.process(edRow);
471
//                                }
472
//                        }
473
//                } else {
474
//                        int counter = 0;
475
//                        for (int i = bitSet.nextSetBit(0); i >= 0; i = bitSet
476
//                                        .nextSetBit(i + 1)) {
477
//                                IGeometry geom = va.getShape(i);
478
//
479
//                                progress.setProgress(counter++);
480
//                                if (progress.isCanceled())
481
//                                        break;
482
//
483
//                                if (geom != null) {
484
//                                        Value[] values = sds.getRow(i);
485
//                                        IFeature feat = new DefaultFeature(geom, values, "" + i);
486
//                                        DefaultRowEdited edRow = new DefaultRowEdited(feat,
487
//                                                        IRowEdited.STATUS_ADDED, i);
488
//
489
//                                        writer.process(edRow);
490
//                                }
491
//                        }
492
//
493
//                }
494
//
495
//                writer.postProcess();
496
//                progress.close();
497
//        }
498

    
499

    
500

    
501
        public void saveToDXF(MapContext mapContext, FLyrVect lv)
502
                        throws DataException, ValidateDataParametersException {
503
                JFileChooser jfc = new JFileChooser(lastPath);
504
                SimpleFileFilter filterShp = new SimpleFileFilter("dxf",
505
                                PluginServices.getText(this, "dxf_files"));
506
                jfc.setFileFilter(filterShp);
507
                if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
508
                        File newFile = jfc.getSelectedFile();
509
                        String path = newFile.getAbsolutePath();
510
                        if( newFile.exists()){
511
                                int resp = JOptionPane.showConfirmDialog(
512
                                                (Component) PluginServices.getMainFrame(),PluginServices.getText(this,"fichero_ya_existe_seguro_desea_guardarlo"),
513
                                                PluginServices.getText(this,"guardar"), JOptionPane.YES_NO_OPTION);
514
                                if (resp != JOptionPane.YES_OPTION) {
515
                                        return;
516
                                }
517
                        }
518
                        if (!(path.toLowerCase().endsWith(".dxf"))){
519
                                path = path + ".dxf";
520
                        }
521
                        newFile = new File(path);
522

    
523
                        DataManager datamanager=DALLocator.getDataManager();
524

    
525
                        FilesystemServerExplorerParameters explorerParams=(FilesystemServerExplorerParameters) datamanager.createServerExplorerParameters(FilesystemServerExplorer.NAME);
526
                        explorerParams.setRoot(newFile.getParent());
527

    
528
                        FilesystemServerExplorer explorer=(FilesystemServerExplorer) datamanager.createServerExplorer(explorerParams);
529

    
530
                        NewFeatureStoreParameters newParams = (NewFeatureStoreParameters) explorer.getAddParameters(newFile);
531
                        ((DXFStoreParameters)newParams).setSRS(mapContext.getProjection());
532

    
533
                        lv.getFeatureStore().export(explorer, newParams);
534

    
535
                        openLayer(newParams, newFile.getName(), mapContext);
536
                }
537
        }
538

    
539
        class GeometryTypeEvaluator extends AbstractEvaluator{
540
                private FeatureType featureType=null;
541
                private int type=0;
542
                private FeatureSelection selection;
543
                private boolean hasSelection=false;
544

    
545
                public GeometryTypeEvaluator(FeatureType ft, int t, FeatureSelection selection) {
546
                        featureType=ft;
547
                        type=t;
548
                        this.selection=selection;
549
                        hasSelection=selection.getSelectedCount()>0;
550
                        this.getFieldsInfo().addFieldValue(
551
                                        ft.getDefaultGeometryAttributeName());
552
                }
553
                public Object evaluate(EvaluatorData data) throws EvaluatorException {
554
                        if (hasSelection){
555
                                if (!selection.isSelected((Feature)data)){
556
                                        return false;
557
                                }
558
                        }
559
                        Geometry geometry=(Geometry) data.getDataValue(featureType.getDefaultGeometryAttributeName());
560
                        return new Boolean(geometry.getType()==type);
561
                }
562

    
563
                public String getName() {
564
                        return "GeometryTypeEvaluator";
565
                }
566

    
567
        }
568

    
569
        public void saveToSHP(MapContext mapContext, FLyrVect lv)
570
                        throws DataException, ValidateDataParametersException {
571
                JFileChooser jfc = new JFileChooser(lastPath);
572
                SimpleFileFilter filterShp = new SimpleFileFilter("shp",
573
                                PluginServices.getText(this, "shp_files"));
574
                jfc.setFileFilter(filterShp);
575
                if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
576
                        File newFile = jfc.getSelectedFile();
577
                        String path = newFile.getAbsolutePath();
578
                        if( newFile.exists()){
579
                                int resp = JOptionPane.showConfirmDialog(
580
                                                (Component) PluginServices.getMainFrame(),PluginServices.getText(this,"fichero_ya_existe_seguro_desea_guardarlo"),
581
                                                PluginServices.getText(this,"guardar"), JOptionPane.YES_NO_OPTION);
582
                                if (resp != JOptionPane.YES_OPTION) {
583
                                        return;
584
                                }
585
                        }
586
                        if (!(path.toLowerCase().endsWith(".shp"))){
587
                                path = path + ".shp";
588
                        }
589
                        newFile = new File(path);
590

    
591
                        DataManager datamanager=DALLocator.getDataManager();
592

    
593
                        FilesystemServerExplorerParameters explorerParams=(FilesystemServerExplorerParameters) datamanager.createServerExplorerParameters(FilesystemServerExplorer.NAME);
594
                        explorerParams.setRoot(newFile.getParent());
595

    
596
                        FilesystemServerExplorer explorer=(FilesystemServerExplorer) datamanager.createServerExplorer(explorerParams);
597

    
598
                        NewFeatureStoreParameters newParams = (NewFeatureStoreParameters) explorer.getAddParameters(newFile);
599

    
600

    
601
                        FeatureStore store=lv.getFeatureStore();
602
                        FeatureQuery featureQuery = store.createFeatureQuery();
603
                        ((SHPNewStoreParameters) newParams).setSRS(mapContext.getProjection());
604

    
605
                        FeatureSet set = null;
606
                        Evaluator evaluator;
607
                        if (lv.getShapeType()==Geometry.TYPES.GEOMETRY){
608
                                String pathFile =
609
                                                ((FilesystemStoreParameters) newParams).getFile()
610
                                                                .getAbsolutePath();
611
                                String withoutShp = pathFile.replaceAll("\\.shp", "");
612
                                try {
613
                                        //POINT
614
                                        evaluator=new GeometryTypeEvaluator(store.getDefaultFeatureType(),Geometry.TYPES.POINT,store.getFeatureSelection());
615
                                        featureQuery.setFilter(evaluator);
616
                                        set=store.getFeatureSet(featureQuery);
617
                                        ((SHPNewStoreParameters) newParams).setSHPFile(new File(withoutShp + "_point" + ".shp"));
618
                                        ((SHPNewStoreParameters) newParams).setDBFFile(new File(withoutShp + "_point" + ".dbf"));
619
                                        ((SHPNewStoreParameters) newParams).setSHXFile(new File(withoutShp + "_point" + ".shx"));
620
                                        export(explorer, newParams, set, store,Geometry.TYPES.POINT);
621
                                        openLayer(newParams,((SHPNewStoreParameters) newParams).getFile().getName(),mapContext);
622
                                } finally {
623
                                        DisposeUtils.dispose(set);
624
                                }
625
        
626
                                try {
627
                                        //CURVE
628
                                        evaluator=new GeometryTypeEvaluator(store.getDefaultFeatureType(),Geometry.TYPES.CURVE,store.getFeatureSelection());
629
                                        featureQuery.setFilter(evaluator);
630
                                        set=store.getFeatureSet(featureQuery);
631
                                        ((SHPNewStoreParameters) newParams).setSHPFile(new File(withoutShp + "_curve" + ".shp"));
632
                                        ((SHPNewStoreParameters) newParams).setDBFFile(new File(withoutShp + "_curve" + ".dbf"));
633
                                        ((SHPNewStoreParameters) newParams).setSHXFile(new File(withoutShp + "_curve" + ".shx"));
634
                                        export(explorer, newParams, set, lv.getFeatureStore(),Geometry.TYPES.CURVE);
635
                                        openLayer(newParams,((SHPNewStoreParameters) newParams).getFile().getName(),mapContext);
636
                                } finally {
637
                                        DisposeUtils.dispose(set);
638
                                }
639
        
640
                                try {
641
                                        //SURFACE
642
                                        evaluator=new GeometryTypeEvaluator(store.getDefaultFeatureType(),Geometry.TYPES.SURFACE,store.getFeatureSelection());
643
                                        featureQuery.setFilter(evaluator);
644
                                        set=store.getFeatureSet(featureQuery);
645
                                        ((SHPNewStoreParameters) newParams).setSHPFile(new File(withoutShp + "_surface" + ".shp"));
646
                                        ((SHPNewStoreParameters) newParams).setDBFFile(new File(withoutShp + "_surface" + ".dbf"));
647
                                        ((SHPNewStoreParameters) newParams).setSHXFile(new File(withoutShp + "_surface" + ".shx"));
648
                                        export(explorer, newParams, set, lv.getFeatureStore(),Geometry.TYPES.SURFACE);
649
                                        openLayer(newParams,((SHPNewStoreParameters) newParams).getFile().getName(),mapContext);
650
                                } finally {
651
                                        DisposeUtils.dispose(set);
652
                                }
653
                        }else{
654
                                store.export(explorer, newParams);
655
                                openLayer(newParams,newFile.getName(),mapContext);
656
                        }
657
                }
658
        }
659

    
660

    
661
        private void openLayer(NewFeatureStoreParameters newParams, String name, MapContext mapContext) throws ReadException {
662
                int res = JOptionPane.showConfirmDialog(
663
                                (JComponent) PluginServices.getMDIManager().getActiveWindow()
664
                                , PluginServices.getText(this, "insertar_en_la_vista_la_capa_creada"),
665
                                PluginServices.getText(this,"insertar_capa"),
666
                                JOptionPane.YES_NO_OPTION);
667

    
668
                if (res == JOptionPane.YES_OPTION){
669
                        PostProcessSupport.executeCalls();
670
                        LayerFactory layerFactory=LayerFactory.getInstance();
671
                        try {
672
                                FLayer newLayer = layerFactory.getInstance().createLayer(
673
                                                name,newParams);
674

    
675
                                mapContext.getLayers().addLayer(newLayer);
676
                        } catch (LoadLayerException e) {
677
                                throw new ReadException("Load layer",e);
678
                        }
679
                }
680

    
681
        }
682

    
683
        private void export(FilesystemServerExplorer explorer,
684
                        NewFeatureStoreParameters params, FeatureSet set, FeatureStore featureStore, int geometryType) {
685
//                if (this.getFeatureTypes().size() != 1) {
686
//                        throw new NotYetImplemented(
687
//                                        "export whith more than one type not yet implemented");
688
//                }
689
//                FeatureSelection featureSelection=(FeatureSelection)getSelection();
690
                DisposableIterator it1 = null;
691
                try {
692
                        EditableFeatureType type = featureStore.getDefaultFeatureType().getEditable();
693
                        FeatureAttributeDescriptor fad=(FeatureAttributeDescriptor)type.get(type.getDefaultGeometryAttributeName());
694
                        type.remove(fad.getName());
695
                        EditableFeatureAttributeDescriptor efad=type.add(fad.getName(), fad.getDataType(), fad.getSize());
696
                        efad.setDefaultValue(fad.getDefaultValue());
697
                        efad.setGeometryType(geometryType);
698
                        efad.setPrecision(fad.getPrecision());
699
                        type.setDefaultGeometryAttributeName(fad.getName());
700
//                        if (params.getDefaultFeatureType() == null
701
//                                        || params.getDefaultFeatureType().size() == 0) {
702
                                params.setDefaultFeatureType(type);
703
//                        }
704
                        explorer.add(params, true);
705

    
706
                        DataManager manager = DALLocator.getDataManager();
707
                        FeatureStore target = (FeatureStore) manager
708
                                        .createStore(params);
709
                        FeatureType targetType = target.getDefaultFeatureType();
710

    
711
                        target.edit(FeatureStore.MODE_APPEND);
712
//                        FeatureSet features=null;
713
//                        if (featureSelection.getSize()>0){
714
//                                features = this.getFeatureSelection();
715
//                        }else{
716
//                                features = this.getFeatureSet();
717
//                        }
718
                        it1 = set.iterator();
719
                        while (it1.hasNext()) {
720
                                Feature feature = (Feature) it1.next();
721
                                target.insert(target.createNewFeature(targetType, feature));
722
                        }
723
                        target.finishEditing();
724
                        target.dispose();
725
                } catch (Exception e) {
726
                        NotificationManager.showMessageError(e.getLocalizedMessage(),e);
727
                } finally {
728
                        DisposeUtils.dispose(it1);
729
                }
730

    
731
        }
732
        /**
733
         * This method saves a layer to GML
734
         * @param mapContext
735
         * @param layer
736
         * @throws EditionException
737
         * @throws DriverIOException
738
         */
739
//        public void saveToGml(MapContext mapContext, FLyrVect layer)  {
740
//                try {
741
//                        JFileChooser jfc = new JFileChooser();
742
//                        SimpleFileFilter filterShp = new SimpleFileFilter("gml",
743
//                                        PluginServices.getText(this, "gml_files"));
744
//                        jfc.setFileFilter(filterShp);
745
//                        if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
746
//                                File newFile = jfc.getSelectedFile();
747
//                                String path = newFile.getAbsolutePath();
748
//                                if (!(path.toLowerCase().endsWith(".gml"))) {
749
//                                        path = path + ".gml";
750
//                                }
751
//                                newFile = new File(path);
752
//
753
//                                GMLWriter writer = (GMLWriter)LayerFactory.getWM().getWriter("GML Writer");
754
//
755
//                                SHPLayerDefinition lyrDef = new SHPLayerDefinition();
756
//                                SelectableDataSource sds = layer.getRecordset();
757
//                                FieldDescription[] fieldsDescrip = sds.getFieldsDescription();
758
//                                lyrDef.setFieldsDesc(fieldsDescrip);
759
//                                lyrDef.setName(newFile.getName());
760
//                                lyrDef.setShapeType(layer.getShapeType());
761
//
762
//                                writer.setFile(newFile);
763
//                                writer.setSchema(lyrDef);
764
//                                writer.setBoundedBy(layer.getFullExtent(),layer.getProjection());
765
//                                writer.initialize(lyrDef);
766
//                                GMLDriver gmlDriver=new GMLDriver();
767
//                                gmlDriver.open(newFile);
768
//                                writeFeatures(mapContext, layer, writer, gmlDriver);
769
//                        }
770
//
771
//                } catch (SchemaEditionException e) {
772
//                        NotificationManager.addError(e.getMessage(),e);
773
//                } catch (InitializeWriterException e) {
774
//                        NotificationManager.addError(e.getMessage(),e);
775
//                } catch (ReadDriverException e) {
776
//                        NotificationManager.addError(e.getMessage(),e);
777
//                } catch (DriverLoadException e) {
778
//                        NotificationManager.addError(e.getMessage(),e);
779
//                }
780
//
781
//        }
782
//        private IndexedShpDriver getOpenShpDriver(File fileShp) throws OpenDriverException {
783
//                IndexedShpDriver drv = new IndexedShpDriver();
784
//                if (!fileShp.exists()) {
785
//                        try {
786
//                                fileShp.createNewFile();
787
//                                File newFileSHX=new File(fileShp.getAbsolutePath().replaceAll("[.]shp",".shx"));
788
//                                newFileSHX.createNewFile();
789
//                                File newFileDBF=new File(fileShp.getAbsolutePath().replaceAll("[.]shp",".dbf"));
790
//                                newFileDBF.createNewFile();
791
//                        } catch (IOException e) {
792
//                                throw new FileNotFoundDriverException("SHP",e,fileShp.getAbsolutePath());
793
//                        }
794
//                }
795
//                drv.open(fileShp);
796
//                return drv;
797
//        }
798
        /**
799
         * @see org.gvsig.andami.plugins.IExtension#isEnabled()
800
         */
801
        public boolean isEnabled() {
802
                int status = EditionUtilities.getEditionStatus();
803
                if (( status == EditionUtilities.EDITION_STATUS_ONE_VECTORIAL_LAYER_ACTIVE || status == EditionUtilities.EDITION_STATUS_ONE_VECTORIAL_LAYER_ACTIVE_AND_EDITABLE)
804
                                || (status == EditionUtilities.EDITION_STATUS_MULTIPLE_VECTORIAL_LAYER_ACTIVE)|| (status == EditionUtilities.EDITION_STATUS_MULTIPLE_VECTORIAL_LAYER_ACTIVE_AND_EDITABLE))
805
                {
806
                        return true;
807
                }
808
                return false;
809
        }
810

    
811
        /**
812
         * @see org.gvsig.andami.plugins.IExtension#isVisible()
813
         */
814
        public boolean isVisible() {
815
                org.gvsig.andami.ui.mdiManager.IWindow f = PluginServices.getMDIManager()
816
                                .getActiveWindow();
817

    
818
                if (f == null) {
819
                        return false;
820
                }
821

    
822
                if (f instanceof DefaultViewPanel) {
823
                        return true;
824
                }
825
                return false;
826
        }
827

    
828
//        private int findFileByName(FieldDescription[] fields, String fieldName){
829
//        for (int i=0; i < fields.length; i++)
830
//        {
831
//                FieldDescription f = fields[i];
832
//                if (f.getFieldName().equalsIgnoreCase(fieldName))
833
//                {
834
//                        return i;
835
//                }
836
//        }
837
//
838
//                return -1;
839
//
840
//        }
841

    
842
}