Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extTableImport / src / org / gvsig / tableImport / addgeominfo / process / AddGeometricInfoProcess.java @ 31234

History | View | Annotate | Download (39.9 KB)

1
package org.gvsig.tableImport.addgeominfo.process;
2

    
3
/* gvSIG. Geographic Information System of the Valencian Government
4
 *
5
 * Copyright (C) 2007-2008 Infrastructures and Transports Department
6
 * of the Valencian Government (CIT)
7
 *
8
 * This program is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU General Public License
10
 * as published by the Free Software Foundation; either version 2
11
 * of the License, or (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21
 * MA  02110-1301, USA.
22
 *
23
 */
24

    
25
import java.awt.Component;
26
import java.awt.Shape;
27
import java.awt.event.MouseAdapter;
28
import java.awt.event.MouseEvent;
29
import java.sql.Types;
30
import java.util.ArrayList;
31
import java.util.Arrays;
32

    
33
import javax.swing.JButton;
34
import javax.swing.JOptionPane;
35

    
36
import org.apache.log4j.Logger;
37
import org.gvsig.gui.beans.buttonspanel.ButtonsPanel;
38
import org.gvsig.gui.beans.incrementabletask.IncrementableProcess;
39
import org.gvsig.gui.beans.incrementabletask.IncrementableTask;
40
import org.gvsig.tableImport.addgeominfo.GeomInfo;
41

    
42
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
43
import com.hardcode.gdbms.engine.values.Value;
44
import com.hardcode.gdbms.engine.values.ValueFactory;
45
import com.iver.andami.PluginServices;
46
import com.iver.andami.messages.NotificationManager;
47
import com.iver.andami.ui.mdiManager.IWindow;
48
import com.iver.cit.gvsig.CADExtension;
49
import com.iver.cit.gvsig.EditionManager;
50
import com.iver.cit.gvsig.EditionUtilities;
51
import com.iver.cit.gvsig.ProjectExtension;
52
import com.iver.cit.gvsig.exceptions.table.CancelEditingTableException;
53
import com.iver.cit.gvsig.fmap.MapControl;
54
import com.iver.cit.gvsig.fmap.core.DefaultFeature;
55
import com.iver.cit.gvsig.fmap.core.FMultiPoint2D;
56
import com.iver.cit.gvsig.fmap.core.FMultipoint3D;
57
import com.iver.cit.gvsig.fmap.core.FPoint2D;
58
import com.iver.cit.gvsig.fmap.core.FPoint3D;
59
import com.iver.cit.gvsig.fmap.core.FShape;
60
import com.iver.cit.gvsig.fmap.core.GeometryUtilities;
61
import com.iver.cit.gvsig.fmap.core.IGeometry;
62
import com.iver.cit.gvsig.fmap.drivers.FieldDescription;
63
import com.iver.cit.gvsig.fmap.drivers.ILayerDefinition;
64
import com.iver.cit.gvsig.fmap.drivers.shp.IndexedShpDriver;
65
import com.iver.cit.gvsig.fmap.edition.DefaultRowEdited;
66
import com.iver.cit.gvsig.fmap.edition.EditionEvent;
67
import com.iver.cit.gvsig.fmap.edition.ISpatialWriter;
68
import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter;
69
import com.iver.cit.gvsig.fmap.edition.rules.IRule;
70
import com.iver.cit.gvsig.fmap.edition.rules.RulePolygon;
71
import com.iver.cit.gvsig.fmap.layers.FLyrAnnotation;
72
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
73
import com.iver.cit.gvsig.fmap.rendering.ILegend;
74
import com.iver.cit.gvsig.fmap.rendering.IVectorLegend;
75
import com.iver.cit.gvsig.gui.cad.CADToolAdapter;
76
import com.iver.cit.gvsig.layers.VectorialLayerEdited;
77
import com.iver.cit.gvsig.project.Project;
78
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
79
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
80
import com.iver.cit.gvsig.project.documents.table.gui.Table;
81
import com.iver.cit.gvsig.project.documents.view.gui.View;
82
import com.iver.cit.gvsig.project.documents.view.legend.CreateSpatialIndexMonitorableTask;
83

    
84
/**
85
 * Process that adds the selected geometric information.</a>.
86
 *
87
 * @author Pablo Piqueras Bartolom? (pablo.piqueras@iver.es)
88
 */
89
public class AddGeometricInfoProcess extends IncrementableProcess {
90

    
91
        private boolean                                 layerWasBeingEdited = false;
92

    
93
        private View                                 view                                 = null;
94
        private FLyrVect                         layer                                 = null;
95
        private Object[]                         fields                                 = null;
96
        private ProjectTable                 layerProjectTable         = null;
97
        private VectorialEditableAdapter vea                         = null;
98

    
99
        /**
100
         * Creates a new <p>GeoVisorImportProcess</p>.
101
         *
102
         * @param title of the progress dialog
103
         * @param label the label that explains the process
104
         * @param view the view where the layer is added
105
         * @param layer the vector layer
106
         * @param fields fields to add
107
         */
108
        public AddGeometricInfoProcess(String title, String label, View view, FLyrVect layer, Object[] fields) {
109
                super(title);
110

    
111
                this.label = label;
112
                this.view = view;
113
                this.layer = layer;
114
                this.fields = fields;
115
                this.isPausable = true;
116
        }
117

    
118
        /**
119
         * Sets the object that will display the evolution of this loading process as a progress dialog.
120
         *
121
         * @param iTask the object that will display the evolution of this loading process
122
         */
123
        public void setIncrementableTask(IncrementableTask iTask) {
124
                this.iTask = iTask;
125
                iTask.setAskCancel(true);
126
                iTask.getButtonsPanel().addAccept();
127
                iTask.getButtonsPanel().setEnabled(ButtonsPanel.BUTTON_ACCEPT, false);
128

    
129
                JButton jButton = iTask.getButtonsPanel().getButton(ButtonsPanel.BUTTON_ACCEPT);
130
                jButton.addMouseListener(new MouseAdapter() {
131
                        /*
132
                         * (non-Javadoc)
133
                         * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
134
                         */
135
                        public void mouseClicked(MouseEvent e) {
136
                                processFinalize();
137
                        }
138
                });
139
        }
140

    
141
        /**
142
         * <p>Gets the project table of the active layer.</p>
143
         *
144
         * @return the project table of the active layer, or <code>null</code> if there wasn't any
145
         */
146
        public ProjectTable getLayerProjectTable() {
147
                return layerProjectTable;
148
        }
149

    
150
        /**
151
         * <p>Gets the vectorial editable adapter of the active layer.</p>
152
         *
153
         * @return the vectorial editable adapter of the active layer
154
         */
155
        public VectorialEditableAdapter getVea() {
156
                return vea;
157
        }
158

    
159
        /*
160
         * (non-Javadoc)
161
         * @see java.lang.Runnable#run()
162
         */
163
        public void run() {
164
                String text = null;
165

    
166
                try {
167
                        process();
168
                        while (! ended) {
169
                                t0 += 500;
170
                Thread.currentThread().sleep(150);
171
                        }
172
                } catch (Exception ie) {
173
                        if (! cancelProcess.isCanceled()) {
174
                                Logger.getLogger(IncrementableProcess.class).error(ie);
175
                                label = PluginServices.getText(null, "Process_failed");
176
                                iTask.getProgressPanel().setLabel(label);
177
                                text = PluginServices.getText(null, "Failed_the_process_Shouldnt_work_with_the_layer");
178
                        }
179
                        else {
180
                                label = PluginServices.getText(null, "Process_canceled");
181
                                iTask.getProgressPanel().setLabel(label);
182
                                text = PluginServices.getText(null, "Process_canceled");
183
                        }
184
                }
185
                finally {
186
                        iTask.setAskCancel(false);
187
                        iTask.getButtonsPanel().setEnabled(ButtonsPanel.BUTTON_ACCEPT, true);
188
                        iTask.getButtonsPanel().setEnabled(ButtonsPanel.BUTTON_CANCEL, false);
189

    
190
                        if (text != null) {
191
                                log.addLine(PluginServices.getText(null, "Percent") + ": " + getPercent());
192
                                log.addLine(text);
193

    
194
                                if (cancelProcess.isCanceled())
195
                                        JOptionPane.showMessageDialog(iTask.getButtonsPanel(), text, PluginServices.getText(this, "Information"), JOptionPane.INFORMATION_MESSAGE);
196
                                else
197
                                        JOptionPane.showMessageDialog(iTask.getButtonsPanel(), text, PluginServices.getText(this, "Error"), JOptionPane.ERROR_MESSAGE);
198
                        }
199

    
200
                        if (percentage == 100) {
201
                                label = PluginServices.getText(null, "Process_finished");
202
                                iTask.getProgressPanel().setLabel(label);
203
//                                iTask.getProgressPanel().setPercent(100); // Forces setting the progress bar at 100 %
204
                        }
205

    
206
                        // Ends this process
207
                        ended = true;
208

    
209
                        // Ends the progress panel
210
                        iTask.stop();
211
                }
212
        }
213

    
214
        /**
215
         * Importation process.
216
         *
217
         * @throws InterruptedException if fails the process
218
         */
219
        public void process() throws InterruptedException {
220

    
221
                MapControl mapControl = null;
222
                String previousTool_ID = null;
223
                short n_fields_added = 0;
224

    
225
                percentage = 5;
226

    
227
                if (cancelProcess.isCanceled()) {
228
                        throw new InterruptedException();
229
                }
230

    
231
                try {
232
                        mapControl = view.getMapControl();
233

    
234
                        // Saves the current tool
235
                        previousTool_ID = mapControl.getCurrentTool();
236

    
237
                        layerWasBeingEdited = layer.isEditing();
238
                }
239
                catch(Exception e) {
240
                        NotificationManager.showMessageError(PluginServices.getText(null, "Failed_the_process"), e);
241
                        throw new InterruptedException();
242
                }
243
                layer.setWaitTodraw(true);
244
                CADExtension cad_extension = null;
245
                VectorialEditableAdapter vea = null;
246
                EditionManager editionManager = null;
247

    
248
                try {
249
                        /* 3- Starts layer in edition */
250
                        if (cancelProcess.isCanceled()) {
251
                                throw new InterruptedException();
252
                        }
253

    
254
                        log.addLine(PluginServices.getText(null, "Starting_the_layer_in_edition_mode"));
255
                        percentage = 12;
256

    
257
                        if (cancelProcess.isCanceled()) {
258
                                throw new InterruptedException();
259
                        }
260

    
261
                        editionManager = CADExtension.getEditionManager();
262
                        editionManager.setMapControl(mapControl);
263

    
264
                        layer.addLayerListener(editionManager);
265

    
266
                        ILegend legendOriginal = layer.getLegend();
267

    
268
                        if (! layer.isWritable()) {
269
                                JOptionPane.showMessageDialog((Component) PluginServices.getMDIManager().getActiveWindow(),
270
                                        PluginServices.getText(this, "this_layer_is_not_self_editable"),
271
                                        PluginServices.getText(this, "warning_title"),
272
                                        JOptionPane.WARNING_MESSAGE);
273

    
274
                                throw new InterruptedException();
275
                        }
276

    
277
                        /* 3.1- Sets the cad tool adapter if wasn't added */
278
                        if (cancelProcess.isCanceled()) {
279
                                throw new InterruptedException();
280
                        }
281

    
282
                        CADToolAdapter cta = CADExtension.getCADToolAdapter();
283
                        if (! mapControl.getNamesMapTools().containsKey("cadtooladapter")) {
284
                                mapControl.addMapTool("cadtooladapter", cta);
285
                        }
286

    
287
                        layer.setEditing(true);
288
                        percentage = 20;
289
                        if (cancelProcess.isCanceled()) {
290
                                throw new InterruptedException();
291
                        }
292

    
293
                        vea = (VectorialEditableAdapter) layer.getSource();
294

    
295
                        vea.getRules().clear();
296
                        if (vea.getShapeType() == FShape.POLYGON) {
297
                                IRule rulePol = new RulePolygon();
298
                                vea.getRules().add(rulePol);
299
                        }
300

    
301
                        if (! (layer.getSource().getDriver() instanceof IndexedShpDriver)) {
302
                                VectorialLayerEdited vle=(VectorialLayerEdited)editionManager.getLayerEdited(layer);
303
                                vle.setLegend(legendOriginal);
304
                        }
305

    
306
                        vea.getCommandRecord().addCommandListener(mapControl);
307

    
308
                        /* 3.2- If exits any layer associated, changes its model by the VectorialEditableAdapter's one */
309
                        if (cancelProcess.isCanceled()) {
310
                                throw new InterruptedException();
311
                        }
312

    
313
                        ProjectExtension pe = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class);
314
                        percentage = 25;
315

    
316
                        ProjectTable pt = pe.getProject().getTable(layer);
317
                        if (pt != null){
318
                                pt.setModel(vea);
319

    
320
                                /* 3.3- If there is any view with the table associated to this vector layer -> updates the table */
321
                                // This step is executed after finishing the process, to avoid problems with Swing threads
322
                        }
323

    
324
                        /* 3.4- Repaints the view */
325
                        if (cancelProcess.isCanceled()) {
326
                                throw new InterruptedException();
327
                        }
328

    
329
//                        mapControl.drawMap(false);
330

    
331
                        percentage = 33;
332

    
333
                        GeomInfo field;
334
                        AddedFieldInfo addedField = null;
335
                        int i, j;
336
                        String operationName = PluginServices.getText(null, "setGeomInfo_");
337
                        IGeometry geometry = null;
338
                        Value value = null;
339
                        Value[] values;
340
                        ArrayList list;
341
                        short inc = 0;
342
                        double c_value;
343

    
344
                        mapControl.getMapContext().beginAtomicEvent();
345
                        vea.startComplexRow();
346
                        try{
347

    
348
                        /* 4- For each field selected */
349
                        if (fields.length > 0)
350
                                inc = (short) ((75 - 33) / fields.length);
351

    
352
                        for (i = 0; i < fields.length; i++) {
353

    
354
                                if (cancelProcess.isCanceled()) {
355
                                        throw new InterruptedException();
356
                                }
357

    
358
                                field = (GeomInfo) fields[i];
359

    
360
                                /* 4.1- If its required -> creates a new field */
361
                                if (field.isNewColumn()) {
362
                                        addedField = addField(vea, field);
363

    
364
                                        /* 4.1.1- If didn't added the field */
365
                                        if (addedField.getColumn() == -1)
366
                                                continue;
367
                                }
368
                                else {
369
                                        /* 4.2- Else -> Validates the properties of the selected field (if can add the data -> fails that subtask) */
370
                                        /* 4.2.1- Finds the column of the field */
371

    
372
                                        if (cancelProcess.isCanceled()) {
373
                                                throw new InterruptedException();
374
                                        }
375

    
376
                                        FieldDescription[] fieldDescriptions = vea.getFieldsDescription();
377

    
378
                                        for (j = 0; j < fieldDescriptions.length; j++) {
379
                                                if (cancelProcess.isCanceled()) {
380
                                                        throw new InterruptedException();
381
                                                }
382

    
383
                                                if (fieldDescriptions[j].getFieldName().compareTo(field.getName()) == 0) {
384
                                                        addedField = new AddedFieldInfo(j, fieldDescriptions[j]);
385
                                                        break;
386
                                                }
387
                                        }
388

    
389
                                        if (addedField == null) {
390
                                                log.addLine(PluginServices.getText(this, "Error") + ": " + PluginServices.getText(this, "Couldnt_find_column") + " \"" + field.getName() + "\"");
391
                                        }
392
                                        else  {
393
                                                /* 4.2.2- Validates if the properties of the column are compatible with the data to add, otherwise doesn't add the information */
394
                                                if (cancelProcess.isCanceled()) {
395
                                                        throw new InterruptedException();
396
                                                }
397

    
398
                                                switch (addedField.getFieldAdded().getFieldType()) {
399
                                                        case Types.DOUBLE:
400
                                                                if ( (addedField.getFieldAdded().getFieldLength() < 13) || (addedField.getFieldAdded().getFieldDecimalCount() < 1) ) {
401
                                                                        log.addLine(PluginServices.getText(this, "Warning") + ": " + PluginServices.getText(this, "Incompatible_data_type_in_column_wont_modify_that_column") + " \"" + field.getName() + "\"");
402
                                                                        continue;
403
                                                                }
404
                                                                break;
405
                                                        case Types.BIGINT:
406
                                                                if ( addedField.getFieldAdded().getFieldLength() < 13) {
407
                                                                        log.addLine(PluginServices.getText(this, "Warning") + ": " + PluginServices.getText(this, "Incompatible_data_type_in_column_wont_modify_that_column") + " \"" + field.getName() + "\"");
408
                                                                        continue;
409
                                                                }
410
                                                                break;
411
                                                        default:
412
                                                                log.addLine(PluginServices.getText(this, "Warning") + ": " + PluginServices.getText(this, "Incompatible_data_type_in_column_wont_modify_that_column") + " \"" + field.getName() + "\"");
413
                                                                continue;
414
                                                }
415
                                                if (! ((addedField.getFieldAdded().getFieldType() == Types.DOUBLE) && (addedField.getFieldAdded().getFieldLength() > 0))) {
416
                                                        log.addLine(PluginServices.getText(this, "Warning") + ": " + PluginServices.getText(this, "Incompatible_data_type_in_column_wont_modify_that_column") + " \"" + field.getName() + "\"");
417
                                                        break;
418
                                                }
419
                                        }
420
                                }
421

    
422
                                /* 5- Calculates the information and adds it to the selected field */
423
                                if (cancelProcess.isCanceled()) {
424
                                        throw new InterruptedException();
425
                                }
426
                                vea.start();
427
                                switch(field.getShapeType()) {
428
                                        case FShape.NULL:
429
                                                break;
430
                                        case FShape.POINT:
431
                                                /* 5.1- For each geometry: calculates the new geometric information and sets to the new field */
432
                                                for (j = 0; j < vea.getRowCount(); j ++) {
433
                                                        if (cancelProcess.isCanceled()) {
434
                                                                throw new InterruptedException();
435
                                                        }
436

    
437
//                                                        vea.start();
438
                                                        geometry = (IGeometry) vea.getShape(j);
439
//                                                        vea.stop();
440

    
441
                                                        Shape shape = null;
442

    
443
                                                        if (geometry != null) {
444
                                                                shape = geometry.getInternalShape();
445
                                                        }
446
                                                        else {
447
                                                                log.addLine(PluginServices.getText(this, "Warning") + ": " + PluginServices.getText(this, "unassigned_geometry_at_row") + j);
448
                                                                continue;
449
                                                        }
450

    
451
                                                        if (shape == null) {
452
                                                                log.addLine(PluginServices.getText(this, "Warning") + ": " + PluginServices.getText(this, "geometry_without_internal_shape_at_row") + j);
453
                                                                continue;
454
                                                        }
455
                                                        else {
456
                                                                /* 5.2- Enables the edition of the row */
457
                                                                if (cancelProcess.isCanceled()) {
458
                                                                        throw new InterruptedException();
459
                                                                }
460

    
461
                                                                //vea.startComplexRow();
462
                                                                DefaultRowEdited row = (DefaultRowEdited) vea.getRow(j);
463
                                                                DefaultFeature feature = (DefaultFeature) row.getLinkedRow().cloneRow();
464

    
465
                                                                /* 5.3- Gets the feature of each row */
466
                                                                values = feature.getAttributes();
467
                                                                list = new ArrayList(Arrays.asList(values));
468

    
469
                                                                /* 5.4- Calculates the geometric information for that geometry / feature */
470
                                                                if (cancelProcess.isCanceled()) {
471
//                                                                        vea.endComplexRow(operationName);
472
                                                                        throw new InterruptedException();
473
                                                                }
474

    
475
                                                                if (shape instanceof FPoint2D) {
476
                                                                        FPoint2D point = (FPoint2D)shape;
477

    
478
                                                                        switch (field.getGeomSubType()) {
479
                                                                                case GeomInfo.X:
480
                                                                                        /* X */
481
                                                                                        value = ValueFactory.createValueByType(Double.toString(point.getX()), Types.DOUBLE);
482
                                                                                        break;
483
                                                                                case GeomInfo.Y:
484
                                                                                        /* Y */
485
                                                                                        value = ValueFactory.createValueByType(Double.toString(point.getY()), Types.DOUBLE);
486
                                                                                        break;
487
                                                                                case GeomInfo.Z:
488
                                                                                case GeomInfo.UNDEFINED:
489
                                                                                default:
490
                                                                                        value = ValueFactory.createValue(0.0d);
491
                                                                                        break;
492
                                                                        }
493
                                                                }
494
                                                                else { // instance of FPoint3D
495
                                                                        FPoint3D point = (FPoint3D)shape;
496

    
497
                                                                        switch (field.getGeomSubType()) {
498
                                                                        case GeomInfo.X:
499
                                                                                /* X */
500
                                                                                value = ValueFactory.createValueByType(Double.toString(point.getX()), Types.DOUBLE);
501
                                                                                break;
502
                                                                        case GeomInfo.Y:
503
                                                                                /* Y */
504
                                                                                value = ValueFactory.createValueByType(Double.toString(point.getY()), Types.DOUBLE);
505
                                                                                break;
506
                                                                        case GeomInfo.Z:
507
                                                                                /* Z */
508
                                                                                value = ValueFactory.createValueByType(Double.toString(point.getZs()[0]), Types.DOUBLE);
509
                                                                                break;
510
                                                                        case GeomInfo.UNDEFINED:
511
                                                                        default:
512
                                                                                value = value = ValueFactory.createValue(0.0d);
513
                                                                                break;
514
                                                                        }
515
                                                                }
516

    
517
                                                                /* 5.5- Sets the new value */
518
                                                                if (cancelProcess.isCanceled()) {
519
//                                                                        vea.endComplexRow(operationName);
520
                                                                        throw new InterruptedException();
521
                                                                }
522

    
523
                                                                list.remove(addedField.getColumn());
524
                                                                list.add(addedField.getColumn(), value);
525
                                                                feature.setAttributes((Value[])list.toArray(new Value[0]));
526

    
527
                                                                vea.modifyRow(row.getIndex(), feature, operationName, EditionEvent.ALPHANUMERIC);
528

    
529
                                                                /* 5.6- Disables the edition of the row */
530
//                                                                vea.endComplexRow(operationName);
531

    
532
                                                                /* 5.7- Increments the counter of the fields added */
533
                                                                n_fields_added ++;
534
                                                        }
535
                                                }
536
                                                break;
537
                                        case FShape.LINE:
538
                                                /* 5.1- For each geometry: calculates the new geometric information and sets to the new field */
539
                                                for (j = 0; j < vea.getRowCount(); j ++) {
540
                                                        if (cancelProcess.isCanceled()) {
541
                                                                throw new InterruptedException();
542
                                                        }
543

    
544
//                                                        vea.start();
545
                                                        geometry = (IGeometry) vea.getShape(j);
546
//                                                        vea.stop();
547

    
548
                                                        Shape shape = null;
549

    
550
                                                        if (geometry != null) {
551
                                                                shape = geometry.getInternalShape();
552
                                                        }
553
                                                        else {
554
                                                                log.addLine(PluginServices.getText(this, "Warning") + ": " + PluginServices.getText(this, "unassigned_geometry_at_row") + j);
555
                                                                continue;
556
                                                        }
557

    
558
                                                        if (shape == null) {
559
                                                                log.addLine(PluginServices.getText(this, "Warning") + ": " + PluginServices.getText(this, "geometry_without_internal_shape_at_row") + j);
560
                                                                continue;
561
                                                        }
562
                                                        else {
563
                                                                try {
564
                                                                        c_value = GeometryUtilities.getLength(layer.getMapContext().getViewPort(), geometry);
565
                                                                }
566
                                                                catch (Exception e) {
567
                                                                        NotificationManager.showMessageError(PluginServices.getText(null, "Failed_calculating_perimeter_of_geometry"), e);
568

    
569
                                                                        percentage += inc;
570
                                                                        continue;
571
                                                                }
572

    
573
                                                                /* 5.2- Enables the edition of the row */
574
                                                                if (cancelProcess.isCanceled()) {
575
                                                                        throw new InterruptedException();
576
                                                                }
577

    
578
//                                                                vea.startComplexRow();
579
                                                                DefaultRowEdited row = (DefaultRowEdited) vea.getRow(j);
580
                                                                DefaultFeature feature = (DefaultFeature) row.getLinkedRow().cloneRow();
581

    
582
                                                                /* 5.3- Gets the feature of each row */
583
                                                                if (cancelProcess.isCanceled()) {
584
//                                                                        vea.endComplexRow(operationName);
585
                                                                        throw new InterruptedException();
586
                                                                }
587

    
588
                                                                values = feature.getAttributes();
589
                                                                list = new ArrayList(Arrays.asList(values));
590

    
591
                                                                /* 5.4- Calculates the geometric information for that geometry / feature */
592
                                                                /* LENGTH */
593
                                                                value = ValueFactory.createValueByType(Double.toString(c_value), Types.DOUBLE);
594

    
595
                                                                /* 5.5- Sets the new value */
596
                                                                if (cancelProcess.isCanceled()) {
597
//                                                                        vea.endComplexRow(operationName);
598
                                                                        throw new InterruptedException();
599
                                                                }
600

    
601
                                                                list.remove(addedField.getColumn());
602
                                                                list.add(addedField.getColumn(), value);
603
                                                                feature.setAttributes((Value[])list.toArray(new Value[0]));
604

    
605
                                                                vea.modifyRow(row.getIndex(), feature, operationName, EditionEvent.ALPHANUMERIC);
606

    
607
                                                                /* 5.6- Disables the edition of the row */
608
//                                                                vea.endComplexRow(operationName);
609

    
610
                                                                /* 5.7- Increments the counter of the fields added */
611
                                                                n_fields_added ++;
612
                                                        }
613
                                                }
614
                                                break;
615
                                        case FShape.POLYGON:
616
                                                /* 5.1- For each geometry: calculates the new geometric information and sets to the new field */
617
                                                for (j = 0; j < vea.getRowCount(); j ++) {
618
                                                        if (cancelProcess.isCanceled()) {
619
                                                                throw new InterruptedException();
620
                                                        }
621

    
622

    
623
                                                        geometry = (IGeometry) vea.getShape(j);
624
//                                                        vea.stop();
625

    
626
                                                        Shape shape = null;
627

    
628
                                                        if (geometry != null) {
629
                                                                shape = geometry.getInternalShape();
630
                                                        }
631
                                                        else {
632
                                                                log.addLine(PluginServices.getText(this, "Warning") + ": " + PluginServices.getText(this, "unassigned_geometry_at_row") + j);
633
                                                                continue;
634
                                                        }
635

    
636
                                                        if (shape == null) {
637
                                                                log.addLine(PluginServices.getText(this, "Warning") + ": " + PluginServices.getText(this, "geometry_without_internal_shape_at_row") + j);
638
                                                                continue;
639
                                                        }
640
                                                        else {
641
                                                                /* 5.2- Enables the edition of the row */
642
                                                                if (cancelProcess.isCanceled()) {
643
                                                                        throw new InterruptedException();
644
                                                                }
645

    
646
//                                                                vea.startComplexRow();
647
                                                                DefaultRowEdited row = (DefaultRowEdited) vea.getRow(j);
648
                                                                DefaultFeature feature = (DefaultFeature) row.getLinkedRow().cloneRow();
649

    
650
                                                                /* 5.3- Gets the feature of each row */
651
                                                                if (cancelProcess.isCanceled()) {
652
//                                                                        vea.endComplexRow(operationName);
653
                                                                        throw new InterruptedException();
654
                                                                }
655

    
656
                                                                values = feature.getAttributes();
657
                                                                list = new ArrayList(Arrays.asList(values));
658

    
659
                                                                /* 5.4- Calculates the geometric information for that geometry / feature */
660
                                                                switch (field.getGeomSubType()) {
661
                                                                        case GeomInfo.PERIMETER:
662
                                                                                /* PERIMETER */
663
                                                                                try {
664
                                                                                        c_value = GeometryUtilities.getLength(layer.getMapContext().getViewPort(), geometry);
665
                                                                                }
666
                                                                                catch (Exception e) {
667
                                                                                        NotificationManager.showMessageError(PluginServices.getText(null, "Failed_calculating_perimeter_of_geometry"), e);
668
                                                                                        percentage += inc;
669
                                                                                        continue;
670
                                                                                }
671

    
672
                                                                                value = ValueFactory.createValueByType(Double.toString(c_value), Types.DOUBLE);
673
                                                                                break;
674
                                                                        case GeomInfo.AREA:
675
                                                                                /* AREA */
676
                                                                                try {
677
                                                                                        c_value = GeometryUtilities.getArea(layer, geometry);
678
                                                                                }
679
                                                                                catch (Exception e) {
680
                                                                                        NotificationManager.showMessageError(PluginServices.getText(null, "Failed_calculating_area_of_geometry"), e);
681

    
682
                                                                                        percentage += inc;
683
                                                                                        continue;
684
                                                                                }
685

    
686
                                                                                value = ValueFactory.createValueByType(Double.toString(c_value), Types.DOUBLE);
687
                                                                                break;
688
                                                                        case GeomInfo.UNDEFINED:
689
                                                                                // Do nothing
690
                                                                                break;
691
                                                                }
692

    
693
                                                                /* 5.5- Sets the new value */
694
                                                                if (cancelProcess.isCanceled()) {
695
//                                                                        vea.endComplexRow(operationName);
696
                                                                        throw new InterruptedException();
697
                                                                }
698

    
699
                                                                list.remove(addedField.getColumn());
700
                                                                list.add(addedField.getColumn(), value);
701
                                                                feature.setAttributes((Value[])list.toArray(new Value[0]));
702

    
703
                                                                vea.modifyRow(row.getIndex(), feature, operationName, EditionEvent.ALPHANUMERIC);
704

    
705
                                                                /* 5.6- Disables the edition of the row */
706
//                                                                vea.endComplexRow(operationName);
707

    
708
                                                                /* 5.7- Increments the counter of the fields added */
709
                                                                n_fields_added ++;
710
                                                        }
711
                                                }
712
                                                break;
713
                                        case FShape.TEXT:
714
                                                break;
715
                                        case FShape.MULTI: // Other types
716
                                                break;
717
                                        case FShape.MULTIPOINT:
718
                                                /* 5.1- For each geometry: calculates the new geometric information and sets to the new field */
719
                                                for (j = 0; j < vea.getRowCount(); j ++) {
720
                                                        if (cancelProcess.isCanceled()) {
721
//                                                                vea.endComplexRow(operationName);
722
                                                                throw new InterruptedException();
723
                                                        }
724

    
725
//                                                        vea.start();
726
                                                        geometry = (IGeometry) vea.getShape(j);
727
//                                                        vea.stop();
728

    
729
                                                        Shape shape = null;
730

    
731
                                                        if (geometry != null) {
732
                                                                shape = geometry.getInternalShape();
733
                                                        }
734
                                                        else {
735
                                                                log.addLine(PluginServices.getText(this, "Warning") + ": " + PluginServices.getText(this, "unassigned_geometry_at_row") + j);
736
                                                                continue;
737
                                                        }
738

    
739
                                                        if (shape == null) {
740
                                                                log.addLine(PluginServices.getText(this, "Warning") + ": " + PluginServices.getText(this, "geometry_without_internal_shape_at_row") + j);
741
                                                                continue;
742
                                                        }
743
                                                        else {
744
                                                                /* 5.2- Enables the edition of the row */
745
                                                                if (cancelProcess.isCanceled()) {
746
//                                                                        vea.endComplexRow(operationName);
747
                                                                }
748

    
749
//                                                                vea.startComplexRow();
750
                                                                DefaultRowEdited row = (DefaultRowEdited) vea.getRow(j);
751
                                                                DefaultFeature feature = (DefaultFeature) row.getLinkedRow().cloneRow();
752

    
753
                                                                /* 5.3- Gets the feature of each row */
754
                                                                if (cancelProcess.isCanceled()) {
755
//                                                                        vea.endComplexRow(operationName);
756
                                                                        throw new InterruptedException();
757
                                                                }
758

    
759
                                                                values = feature.getAttributes();
760
                                                                list = new ArrayList(Arrays.asList(values));
761

    
762
                                                                /* 5.4- Calculates the geometric information for that geometry / feature */
763
                                                                /* NUMBER OF POINTS */
764
                                                                if (shape instanceof FMultiPoint2D) {
765
                                                                        value = ValueFactory.createValueByType(Integer.toString(((FMultiPoint2D)shape).getNumPoints()), Types.BIGINT);
766
                                                                }
767
                                                                else {
768
                                                                        if (shape instanceof FMultipoint3D) {
769
                                                                                value = ValueFactory.createValueByType(Integer.toString(((FMultipoint3D)shape).getNumPoints()), Types.BIGINT);
770
                                                                        }
771
                                                                        else
772
                                                                                continue;
773
                                                                }
774

    
775
                                                                /* 5.5- Sets the new value */
776
                                                                if (cancelProcess.isCanceled()) {
777
//                                                                        vea.endComplexRow(operationName);
778
                                                                        throw new InterruptedException();
779
                                                                }
780

    
781
                                                                list.remove(addedField.getColumn());
782
                                                                list.add(addedField.getColumn(), value);
783
                                                                feature.setAttributes((Value[])list.toArray(new Value[0]));
784

    
785
                                                                vea.modifyRow(row.getIndex(), feature, operationName, EditionEvent.ALPHANUMERIC);
786

    
787
                                                                /* 5.6- Disables the edition of the row */
788
//                                                                vea.endComplexRow(operationName);
789

    
790
                                                                /* 5.7- Increments the counter of the fields added */
791
                                                                n_fields_added ++;
792
                                                        }
793
                                                }
794
                                                break;
795
                                        case FShape.CIRCLE:
796
                                                break;
797
                                        case FShape.ARC:
798
                                                break;
799
                                        case FShape.ELLIPSE:
800
                                                break;
801
                                        case FShape.Z:
802
                                                break;
803
                                        default : // UNDEFINED
804
                                }
805
                                vea.stop();
806
                                percentage += inc;
807
                        }
808
                    }finally{
809
                            vea.endComplexRow(operationName);
810
                            mapControl.getMapContext().endAtomicEvent();
811
                    }
812

    
813
                        /* 6- Stops layer in edition */
814
                        if (cancelProcess.isCanceled()) {
815
                                throw new InterruptedException();
816
                        }
817

    
818
                        percentage = 75;
819
                        log.addLine(PluginServices.getText(null, "Stopping_the_layer_of_edition_mode"));
820
                        mapControl.getCanceldraw().setCanceled(true);
821

    
822
                        VectorialLayerEdited lyrEd = (VectorialLayerEdited)        editionManager.getActiveLayerEdited();
823
                        if (lyrEd != null)
824
                                lyrEd.clearSelection(true);
825
                        try {
826
                                layer.getRecordset().removeSelectionListener(lyrEd);
827
                        } catch (ReadDriverException e) {
828
                                NotificationManager.addError("Remove Selection Listener",e);
829
                        }
830
//                        if (pt != null){
831
//                                pt.createAlias();
832
//
833
//                        }
834

    
835
                        percentage = 80;
836

    
837
                        // Can't cancel next subtasks
838
                        iTask.getButtonsPanel().getButton(ButtonsPanel.BUTTON_CANCEL).setEnabled(false);
839

    
840
                        if (cancelProcess.isCanceled()) {
841
                                throw new InterruptedException();
842
                        }
843

    
844
                        /* 6.1- Saves the layer */
845
                        /* This part can't be cancelled */
846
                        if (layer.isWritable()) {
847
                                try {
848
                                        saveLayer(layer);
849
                                }
850
                                catch (Exception e) {
851
                                        log.addLine(PluginServices.getText(null, "Failed_saving_the_layer"));
852
                                        throw e;
853
                                }
854

    
855
                                percentage = 90;
856

    
857
                                /* 6.2- Only finish the edition mode if wasn't being edited */
858
                                vea.getCommandRecord().removeCommandListener(mapControl);
859
                                layer.setEditing(false);
860
                                if (layer.isSpatiallyIndexed()) {
861
                            if (layer.getISpatialIndex() != null) {
862
                                                PluginServices.cancelableBackgroundExecution(new CreateSpatialIndexMonitorableTask((FLyrVect)layer));
863
                        }
864
                                }
865

    
866
                                /* 6.3- If has ended successfully the editing */
867
                                layer.removeLayerListener(editionManager);
868
                                if (layer instanceof FLyrAnnotation) {
869
                                        FLyrAnnotation lva = (FLyrAnnotation)layer;
870
                            lva.setMapping(lva.getMapping());
871
                                }
872

    
873
                                /* 6.4.a- If layer was being edited, restores it to that state */
874
                                if (layerWasBeingEdited) {
875

    
876
                                        // Restores the previous tool
877
                                        mapControl.setTool(previousTool_ID);
878
                                        percentage = 91;
879

    
880
                                        view.hideConsole();
881
                                        percentage = 93;
882

    
883
                                        mapControl.drawMap(false);
884
                                        percentage = 96;
885
                                        CADExtension.clearView();
886

    
887
                                        startLayerInEdition(mapControl, cad_extension, editionManager, vea, layer);
888
                                }
889
                                else {
890
                                        /* 6.4.b- Restores the previous tool */
891
                                        mapControl.setTool(previousTool_ID);
892
                                        percentage = 91;
893

    
894
                                        view.hideConsole();
895

    
896
                                        percentage = 98;
897
                                        CADExtension.clearView();
898
                                }
899

    
900
                                percentage = 100;
901
                                log.addLine(PluginServices.getText(null, "Process_finished_successfully"));
902
                                layer.setWaitTodraw(false);
903
                                mapControl.drawMap(false);
904
                                return;
905
                        }
906

    
907
                        // Shouldn't execute this code!
908
                        // This code can't be cancelled
909
                        cancelEdition(layer);
910
                        vea.getCommandRecord().removeCommandListener(mapControl);
911
                        if (!(layer.getSource().getDriver() instanceof IndexedShpDriver)){
912
                                VectorialLayerEdited vle=(VectorialLayerEdited)CADExtension.getEditionManager().getLayerEdited(layer);
913
                                layer.setLegend((IVectorLegend)vle.getLegend());
914
                        }
915

    
916
                        layer.setEditing(false);
917

    
918
                        /* 6.5- If layer was being edited, restores it to that state */
919
                        if (layerWasBeingEdited) {
920
                                startLayerInEdition(mapControl, cad_extension, editionManager, vea, layer);
921
                        }
922

    
923
//                        PluginServices.getMainFrame().enableControls();
924
                        percentage = 100;
925
                        log.addLine(PluginServices.getText(null, "Process_finished_successfully"));
926
                        layer.setWaitTodraw(false);
927
                        mapControl.drawMap(false);
928
                        return;
929
                }
930
                catch (Exception e) {
931
                        if (! cancelProcess.isCanceled())
932
                                PluginServices.getLogger().error(PluginServices.getText(null, "Exception_adding_geometric_info"), e);
933

    
934
                        try {
935
                                try {
936
                                        // Removes the fields added
937
                                        while (n_fields_added >= 0) {
938
                                                vea.undo();
939
                                                n_fields_added --;
940
                                        }
941
                                }
942
                                catch (Exception ex) {
943
                                        PluginServices.getLogger().error(ex);
944
                                        log.addLine(PluginServices.getText(null, "Failed_restoring_layer_fields_should_remove_and_add_the_layer_to_have_consistent_data"));
945
                                        JOptionPane.showMessageDialog(iTask.getProgressPanel(), PluginServices.getText(null, "Failed_restoring_layer_fields_should_remove_and_add_the_layer_to_have_consistent_data"), PluginServices.getText(null, "Error"), JOptionPane.ERROR_MESSAGE);
946
                                }
947

    
948
                                // Emergency restore
949
                                // This code can't be cancelled
950
                                // Only finish the edition mode if wasn't being edited
951
                                cancelEdition(layer);
952
                                layer.setEditing(false);
953

    
954
                                mapControl.setTool(previousTool_ID);
955
                                view.hideConsole();
956

    
957
                                CADExtension.clearView();
958

    
959
                                // If layer was being edited, restores it to that state
960
                                if (layerWasBeingEdited) {
961
                                        startLayerInEdition(mapControl, cad_extension, editionManager, vea, layer);
962
                                }
963
                                layer.setWaitTodraw(false);
964
                                mapControl.drawMap(false);
965
//                                PluginServices.getMainFrame().enableControls();
966
                        }
967
                        catch (Exception ex) {
968
                                NotificationManager.showMessageError(PluginServices.getText(null, "Failed_restoring_layer_in_edition_mode"), ex);
969
                                log.addLine(PluginServices.getText(null, "Failed_restoring_layer_in_edition_mode"));
970
                        }
971
                        throw new InterruptedException();
972
                }
973

    
974
        }
975

    
976
        /**
977
         * <p>Adds a new field as a new column in a vector layer data source.</p>
978
         *
979
         * @param vea adapter of a vector layer that allows edit the layer
980
         * @param geomInfo information about the new field to add
981
         *
982
         * @return information about the field added
983
         */
984
        private AddedFieldInfo addField(VectorialEditableAdapter vea, GeomInfo geomInfo) {
985
                try {
986
                        FieldDescription fD = null;
987

    
988
                        if (geomInfo.getShapeType() == FShape.MULTIPOINT)
989
                                fD = GeomInfo.getFieldDescription(geomInfo, Types.BIGINT, 13, (short) 0);
990
                        else
991
                                fD = GeomInfo.getFieldDescription(geomInfo, Types.DOUBLE, 13, (short) 6);
992

    
993
                        DefaultRowEdited row = (DefaultRowEdited) vea.getRow(0);
994
                        int column = row.getAttributes().length;
995

    
996
                        vea.addField(fD);
997
                        log.addLine(fD.getFieldName() + ": " + PluginServices.getText(null, "field_added_successfully"));
998
                        return new AddedFieldInfo(column, fD);
999
                }
1000
                catch (Exception e) {
1001
                        NotificationManager.showMessageError(PluginServices.getText(null, "Failed_creting_new_field") + " \"" + geomInfo.getName() + "\"", e);
1002
                        log.addLine(PluginServices.getText(null, "Failed_creting_new_field") + " \"" + geomInfo.getName() + "\"");
1003
                        return new AddedFieldInfo(-1, null);
1004
                }
1005
        }
1006

    
1007
        /**
1008
         * <p>Information about the field added.</p>
1009
         *
1010
         * @author Pablo Piqueras Bartolom? (pablo.piqueras@iver.es)
1011
         */
1012
        private class AddedFieldInfo {
1013
                /**
1014
                 * Column index in the data source, where was added.
1015
                 */
1016
                private int column;
1017

    
1018
                /**
1019
                 * Field added.
1020
                 */
1021
                private FieldDescription fieldAdded;
1022

    
1023
                /**
1024
                 * <p>Creates a new <code>AddedFieldInfo</code>.</p>
1025
                 *
1026
                 * @param column the column index in the data source, where was added
1027
                 * @param fieldAdded the field added
1028
                 */
1029
                public AddedFieldInfo(int column, FieldDescription fieldAdded) {
1030
                        super();
1031
                        this.column = column;
1032
                        this.fieldAdded = fieldAdded;
1033
                }
1034

    
1035
                /**
1036
                 * <p>Gets the column index in the data source, where was added.</p>
1037
                 *
1038
                 * @return the column index in the data source, where was added
1039
                 */
1040
                public int getColumn() {
1041
                        return column;
1042
                }
1043

    
1044
                /**
1045
                 * <p>Gets the field added.</p>
1046
                 *
1047
                 * @return the field added
1048
                 */
1049
                public FieldDescription getFieldAdded() {
1050
                        return fieldAdded;
1051
                }
1052
        }
1053

    
1054
        /**
1055
         * <p>Starts layer in edition mode.</p>
1056
         *
1057
         * @param mapControl the <code>MapControl</code> object that contains the layer
1058
         * @param cad_extension extension that allows edit a layer
1059
         * @param editionManager manager for editing layers
1060
         * @param vea adapter of the editable vector layers
1061
         * @param layer the layer to start in edition mode
1062
         *
1063
         * @throws Exception any exception produced starting in edition the layer
1064
         */
1065
        private void startLayerInEdition(MapControl mapControl, CADExtension cad_extension, EditionManager editionManager, VectorialEditableAdapter vea, FLyrVect layer) throws Exception {
1066
                log.addLine(PluginServices.getText(null, "Starting_the_layer_in_edition_mode"));
1067
                editionManager = CADExtension.getEditionManager();
1068
                editionManager.setMapControl(mapControl);
1069

    
1070
                layer.addLayerListener(editionManager);
1071

    
1072
                ILegend legendOriginal = layer.getLegend();
1073

    
1074
                if (! layer.isWritable()) {
1075
                        JOptionPane.showMessageDialog((Component) PluginServices.getMDIManager().getActiveWindow(),
1076
                                PluginServices.getText(this, "this_layer_is_not_self_editable"),
1077
                                PluginServices.getText(this, "warning_title"),
1078
                                JOptionPane.WARNING_MESSAGE);
1079

    
1080
                        throw new InterruptedException();
1081
                }
1082

    
1083
                /* N.1- Sets the cad tool adapter if wasn't added */
1084
                CADToolAdapter cta = CADExtension.getCADToolAdapter();
1085
                if (! mapControl.getNamesMapTools().containsKey("cadtooladapter")) {
1086
                        mapControl.addMapTool("cadtooladapter", cta);
1087
                }
1088

    
1089
                layer.setEditing(true);
1090
                vea = (VectorialEditableAdapter) layer.getSource();
1091

    
1092
                vea.getRules().clear();
1093
                if (vea.getShapeType() == FShape.POLYGON) {
1094
                        IRule rulePol = new RulePolygon();
1095
                        vea.getRules().add(rulePol);
1096
                }
1097

    
1098
                if (! (layer.getSource().getDriver() instanceof IndexedShpDriver)) {
1099
                        VectorialLayerEdited vle=(VectorialLayerEdited)editionManager.getLayerEdited(layer);
1100
                        vle.setLegend(legendOriginal);
1101
                }
1102

    
1103
                vea.getCommandRecord().addCommandListener(mapControl);
1104

    
1105
                /* N.2- If exits any layer associated, changes its model by the VectorialEditableAdapter's one */
1106
                ProjectExtension pe = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class);
1107

    
1108
                ProjectTable pt = pe.getProject().getTable(layer);
1109
                this.layerProjectTable = pt;
1110

    
1111
                if (pt != null){
1112
                        pt.setModel(vea);
1113

    
1114
                        /* N.3- If there is any view with the table associated to this vector layer -> updates the table */
1115
                        // This step is executed after finishing the process, to avoid problems with Swing threads
1116
//                           com.iver.andami.ui.mdiManager.IWindow[] views = PluginServices.getMDIManager().getAllWindows();
1117
//
1118
//                        for (int i = 0 ; i < views.length ; i++) {
1119
//                                if (views[i] instanceof Table) {
1120
//                                        Table table = (Table)views[i];
1121
//                                        ProjectTable model = table.getModel();
1122
//
1123
//                                        if (model.equals(pt)) {
1124
//                                                table.setModel(pt);
1125
//                                                vea.getCommandRecord().addCommandListener(table);
1126
//                                        }
1127
//                                }
1128
//                        }
1129
                }
1130

    
1131
                /* N.4- Repaints the view */
1132
                mapControl.drawMap(false);
1133
        }
1134

    
1135
        /**
1136
         * <p>Saves and stops the edition of a vector layer.</p>
1137
         *
1138
         * @param layer the vector layer to save
1139
         *
1140
         * @throws Exception if fails saving the layer
1141
         */
1142
        private void saveLayer(FLyrVect layer) throws Exception {
1143
                try {
1144
                        layer.setProperty("stoppingEditing", new Boolean(true));
1145
                        VectorialEditableAdapter vea = (VectorialEditableAdapter) layer.getSource();
1146

    
1147
                        ISpatialWriter writer = (ISpatialWriter) vea.getWriter();
1148
                        com.iver.andami.ui.mdiManager.IWindow[] views = PluginServices.getMDIManager().getAllWindows();
1149
                        for (int j = 0; j < views.length; j++) {
1150
                                if (views[j] instanceof Table) {
1151
                                        Table table = (Table) views[j];
1152
                                        if (table.getModel().getAssociatedTable() != null
1153
                                                        && table.getModel().getAssociatedTable().equals(layer)) {
1154
                                                table.stopEditingCell();
1155
                                        }
1156
                                }
1157
                        }
1158
                        vea.cleanSelectableDatasource();
1159
                        layer.setRecordset(vea.getRecordset());
1160

    
1161
                        // Queremos que el recordset del layer
1162
                        // refleje los cambios en los campos.
1163
                        ILayerDefinition lyrDef = EditionUtilities.createLayerDefinition(layer);
1164
                        String aux = "FIELDS:";
1165
                        FieldDescription[] flds = lyrDef.getFieldsDesc();
1166
                        for (int i=0; i < flds.length; i++)        {
1167
                                aux = aux + ", " + flds[i].getFieldAlias();
1168
                        }
1169

    
1170
                        System.err.println("Escribiendo la capa " + lyrDef.getName() + " con los campos " + aux);
1171
                        lyrDef.setShapeType(layer.getShapeType());
1172
                        writer.initialize(lyrDef);
1173
                        vea.stopEdition(writer, EditionEvent.GRAPHIC);
1174
                        layer.setProperty("stoppingEditing", new Boolean(false));
1175
                }
1176
                catch (Exception e) {
1177
                        log.addLine(PluginServices.getText(null, "Failed_saving_the_layer"));
1178
                        throw e;
1179
                }
1180
        }
1181

    
1182
        /**
1183
         * <p>Cancels the edition process without saving.</p>
1184
         *
1185
         * @param layer the layer being edited
1186
         *
1187
         * @throws Exception if fails canceling the layer
1188
         */
1189
        private void cancelEdition(FLyrVect layer) throws Exception {
1190
                try {
1191
                        layer.setProperty("stoppingEditing",new Boolean(true));
1192
                        com.iver.andami.ui.mdiManager.IWindow[] views = PluginServices.getMDIManager().getAllWindows();
1193
                        VectorialEditableAdapter vea = (VectorialEditableAdapter) layer.getSource();
1194
                        vea.cancelEdition(EditionEvent.GRAPHIC);
1195

    
1196
                        for (int j = 0; j < views.length; j++) {
1197
                                if (views[j] instanceof Table) {
1198
                                        Table table = (Table) views[j];
1199
                                        if ((table.getModel().getAssociatedTable() != null) && (table.getModel().getAssociatedTable().equals(layer))) {
1200
                                                // Avoid conflicts with the Swing threads
1201
                                            table.cancelEditingCell();
1202
                                        table.getModel().getModelo().cancelEdition(EditionEvent.ALPHANUMERIC);
1203
                                                //table.cancelEditing();
1204
                                        }
1205
                                }
1206
                        }
1207

    
1208
                        layer.setProperty("stoppingEditing", new Boolean(false));
1209
                }
1210
                catch (Exception e) {
1211
                        log.addLine(PluginServices.getText(null, "Failed_canceling_the_layer"));
1212
                        throw e;
1213
                }
1214
        }
1215
        protected void processFinalize() {
1216
                super.processFinalize();
1217
                ProjectExtension pe = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class);
1218
                Project project=pe.getProject();
1219
                ProjectTable pt = project.getTable(layer);
1220
                try {
1221
                        pt.createAlias();
1222
                } catch (ReadDriverException e1) {
1223
                        e1.printStackTrace();
1224
                }
1225
//                pt.recalculateColumnsFromAliases();
1226
                IWindow[] windows=PluginServices.getMDIManager().getAllWindows();
1227
                for (int i = 0; i < windows.length; i++) {
1228
                        if (windows[i] instanceof Table && ((Table)windows[i]).getModel().equals(pt)){
1229
                                try {
1230
                                        ((Table)windows[i]).cancelEditing();
1231
                                } catch (CancelEditingTableException e) {
1232
                                        e.printStackTrace();
1233
                                }
1234
                        }
1235
                }
1236
        }
1237
}