Statistics
| Revision:

root / trunk / extensions / extDerivedGeometries / src / es / iver / derivedGeom / process / AddDerivedGeometrySHPProcess.java @ 27865

History | View | Annotate | Download (33.9 KB)

1
package es.iver.derivedGeom.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.event.MouseAdapter;
27
import java.awt.event.MouseEvent;
28
import java.util.ArrayList;
29
import java.util.Arrays;
30

    
31
import javax.swing.JButton;
32
import javax.swing.JOptionPane;
33

    
34
import org.cresques.cts.IProjection;
35
import org.gvsig.gui.beans.buttonspanel.ButtonsPanel;
36
import org.gvsig.gui.beans.incrementabletask.IncrementableEvent;
37
import org.gvsig.gui.beans.incrementabletask.IncrementableProcess;
38
import org.gvsig.gui.beans.incrementabletask.IncrementableTask;
39
import org.gvsig.quickInfo.utils.geometries.GeometryUtilities;
40

    
41
import com.hardcode.gdbms.engine.values.Value;
42
import com.hardcode.gdbms.engine.values.ValueFactory;
43
import com.iver.andami.PluginServices;
44
import com.iver.andami.messages.NotificationManager;
45
import com.iver.cit.gvsig.CADExtension;
46
import com.iver.cit.gvsig.EditionManager;
47
import com.iver.cit.gvsig.EditionUtilities;
48
import com.iver.cit.gvsig.ProjectExtension;
49
import com.iver.cit.gvsig.fmap.MapControl;
50
import com.iver.cit.gvsig.fmap.core.DefaultFeature;
51
import com.iver.cit.gvsig.fmap.core.FPoint2D;
52
import com.iver.cit.gvsig.fmap.core.FShape;
53
import com.iver.cit.gvsig.fmap.core.IGeometry;
54
import com.iver.cit.gvsig.fmap.drivers.FieldDescription;
55
import com.iver.cit.gvsig.fmap.drivers.ILayerDefinition;
56
import com.iver.cit.gvsig.fmap.drivers.shp.IndexedShpDriver;
57
import com.iver.cit.gvsig.fmap.edition.EditionEvent;
58
import com.iver.cit.gvsig.fmap.edition.ISpatialWriter;
59
import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter;
60
import com.iver.cit.gvsig.fmap.edition.rules.IRule;
61
import com.iver.cit.gvsig.fmap.edition.rules.RulePolygon;
62
import com.iver.cit.gvsig.fmap.layers.FLyrAnnotation;
63
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
64
import com.iver.cit.gvsig.fmap.layers.VectorialAdapter;
65
import com.iver.cit.gvsig.fmap.rendering.ILegend;
66
import com.iver.cit.gvsig.gui.cad.CADToolAdapter;
67
import com.iver.cit.gvsig.layers.VectorialLayerEdited;
68
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
69
import com.iver.cit.gvsig.project.documents.table.gui.Table;
70
import com.iver.cit.gvsig.project.documents.view.legend.CreateSpatialIndexMonitorableTask;
71

    
72
import es.iver.derivedGeom.utils.LayerUtilities;
73

    
74

    
75

    
76
/**
77
 * Process that adds a layer with derivative geometries, according the configuration. 
78
 *
79
 * @author Pablo Piqueras Bartolom? (pablo.piqueras@iver.es)
80
 */
81
public class AddDerivedGeometrySHPProcess extends IncrementableProcess {
82
        private DerivedGeometryProcessParameters         parameters                = null;
83
        
84
        public AddDerivedGeometrySHPProcess(String title, String label, DerivedGeometryProcessParameters parameters) {
85
                super(title);
86

    
87
                this.label = label;
88
                this.parameters = parameters;
89
                this.isPausable = true;
90
        }
91

    
92
        /**
93
         * Sets the object that will display the evolution of this loading process as a progress dialog.
94
         * 
95
         * @param iTask the object that will display the evolution of this loading process
96
         */
97
        public void setIncrementableTask(IncrementableTask iTask) {
98
                this.iTask = iTask;
99
                iTask.setAskCancel(true);
100
                iTask.getButtonsPanel().addAccept();
101
                iTask.getButtonsPanel().setEnabled(ButtonsPanel.BUTTON_ACCEPT, false);
102

    
103
                JButton jButton = iTask.getButtonsPanel().getButton(ButtonsPanel.BUTTON_ACCEPT);
104
                jButton.addMouseListener(new MouseAdapter() {
105
                        /*
106
                         * (non-Javadoc)
107
                         * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
108
                         */
109
                        public void mouseClicked(MouseEvent e) {
110
                                processFinalize();
111
                        }
112
                });
113
        }
114

    
115
        /**
116
         * Importation process.
117
         * 
118
         * @throws InterruptedException if fails the process
119
         */
120
        public void process() throws InterruptedException {
121
                percentage = 5;
122

    
123
                FLyrVect layerAdded = null, sourceLayer = null;
124
                long numGeoms = 0;
125
                long numGeomsFailed = 0;
126
                MapControl mapControl = parameters.getMapControl();
127
                String previousTool_ID;
128
                
129
                try {
130
                        // Saves the current tool
131
                        previousTool_ID = mapControl.getCurrentTool();
132
                        
133
                        /* Creates the new layer */
134
                        if (parameters.getDestLayer() == null) {
135
                                try {
136
                                        mapControl.getMapContext().beginAtomicEvent();
137
        
138
                                        /* Copies the fields of the source layer */
139
                                        FieldDescription[] fieldDescriptions = parameters.getSourceLayer().getRecordset().getFieldsDescription();
140
                
141
                                        for (int i = 0; i < fieldDescriptions.length; i++) {                                
142
                                                fieldDescriptions[i] = fieldDescriptions[i].cloneField();
143
                                        }
144
        
145
                                        /* Creates the layer */
146
                                        layerAdded = LayerUtilities.createShapeLayer (
147
                                                        parameters.getMapControl().getMapContext(),
148
                                                        parameters.getDestinationFile(),
149
                                                        parameters.getDestinationLayerName(),
150
                                                        parameters.getDestinationLayerShapeType(),
151
                                                        parameters.getSourceLayer().getProjection(),
152
                                                        fieldDescriptions); // ?A cambiar?
153
                
154
                                        if (layerAdded == null)
155
                                                throw new InterruptedException();
156
                                        
157
                                        parameters.setDestLayer(layerAdded);
158
                                }
159
                                catch (Exception ex1) {
160
                                        if (! cancelProcess.isCanceled()) {
161
                                                NotificationManager.showMessageError(PluginServices.getText(null, "Failed_creating_the_new_layer"), ex1);
162
                                                log.addLine(PluginServices.getText(null, "Failed_creating_the_new_layer"));
163
                                        }
164
                
165
                                        throw new InterruptedException();
166
                                }
167
                                
168
                                try {
169
                                        log.addLine(PluginServices.getText(null, "Layer_created_successfully"));
170
                
171
                                        /* .- Adds the layer to TOC */
172
                                        mapControl.getMapContext().beginAtomicEvent();
173
                
174
                                        mapControl.getMapContext().getLayers().addLayer(layerAdded); //0, layerAdded); // 0 -> Adds the layer as the first in the TOC
175
                                log.addLine(PluginServices.getText(null, "Layer_added_to_TOC"));
176
                
177
                                mapControl.getMapContext().endAtomicEvent();
178
                                }
179
                                catch (Exception ex2) {
180
                                        if (! cancelProcess.isCanceled()) {
181
                                                NotificationManager.showMessageError(PluginServices.getText(null, "Failed_adding_the_layer_to_TOC"), ex2);
182
                                                log.addLine(PluginServices.getText(null, "Failed_adding_the_layer_to_TOC"));
183
                                        }
184
                
185
                                        throw new InterruptedException();
186
                                }
187
                        }
188
                        else {
189
                                layerAdded = parameters.getDestLayer();
190
                        }
191

    
192

    
193
                        try {
194
                                sourceLayer = parameters.getSourceLayer();
195
                                CADExtension cad_extension = null;
196
                                VectorialAdapter source_rv = (VectorialAdapter) sourceLayer.getSource();
197
                                VectorialEditableAdapter dest_rv = null;
198
                                EditionManager editionManager = null;
199

    
200
                                log.addLine(PluginServices.getText(null, "Source_layer") + " : " + sourceLayer.getName());
201
                                log.addLine(PluginServices.getText(null, "Output_layer") + " : " + parameters.getDestLayer().getName());
202
                                
203
                                /* 3- Starts layer in edition */
204
                                if (cancelProcess.isCanceled()) {
205
                                        throw new InterruptedException();
206
                                }
207

    
208
                                log.addLine(PluginServices.getText(null, "Starting_the_layer_in_edition_mode"));
209
//                                mapControl.getMapContext().clearAllCachingImageDrawnLayers();
210
                                percentage = 12;
211

    
212
                                if (cancelProcess.isCanceled()) {
213
                                        throw new InterruptedException();
214
                                }
215

    
216
                                cad_extension = (CADExtension) PluginServices.getExtension(CADExtension.class);
217
                                editionManager = cad_extension.getEditionManager();
218
                                editionManager.setMapControl(mapControl);
219

    
220
                                layerAdded.addLayerListener(editionManager);
221

    
222
                                ILegend legendOriginal = layerAdded.getLegend();
223

    
224
                                if (! layerAdded.isWritable()) {
225
                                        JOptionPane.showMessageDialog((Component) PluginServices.getMDIManager().getActiveWindow(),
226
                                                PluginServices.getText(this, "this_layer_is_not_self_editable"),
227
                                                PluginServices.getText(this, "warning_title"),
228
                                                JOptionPane.WARNING_MESSAGE);
229

    
230
                                        throw new InterruptedException();
231
                                }
232

    
233
                                /* 3.1- Sets the cad tool adapter if wasn't added */
234
                                if (cancelProcess.isCanceled()) {
235
                                        throw new InterruptedException();
236
                                }
237

    
238
                                CADToolAdapter cta = CADExtension.getCADToolAdapter();
239

    
240
                                if (! mapControl.getNamesMapTools().containsKey("cadtooladapter")) {
241
                                        mapControl.addMapTool("cadtooladapter", cta);
242
                                }
243

    
244
                                layerAdded.setEditing(true);
245
                                percentage = 20;
246
                                if (cancelProcess.isCanceled()) {
247
                                        throw new InterruptedException();
248
                                }
249

    
250
                                dest_rv = (VectorialEditableAdapter) layerAdded.getSource();
251

    
252
                                dest_rv.getRules().clear();
253

    
254
                                if (dest_rv.getShapeType() == FShape.POLYGON) {
255
                                        IRule rulePol = new RulePolygon();
256
                                        dest_rv.getRules().add(rulePol);
257
                                }
258

    
259
                                if (! (layerAdded.getSource().getDriver() instanceof IndexedShpDriver)) {
260
                                        VectorialLayerEdited vle=(VectorialLayerEdited)editionManager.getLayerEdited(layerAdded);
261
                                        vle.setLegend(legendOriginal);
262
                                }
263

    
264
                                dest_rv.getCommandRecord().addCommandListener(mapControl);
265

    
266
                                /* 3.2- If exits any layer associated, changes its model by the VectorialEditableAdapter's one */
267
                                if (cancelProcess.isCanceled()) {
268
                                        throw new InterruptedException();
269
                                }
270

    
271
                                ProjectExtension pe = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class);
272
                                percentage = 25;
273

    
274
                                ProjectTable dest_pt = pe.getProject().getTable(layerAdded);
275
                                if (dest_pt != null){
276
                                        dest_pt.setModel(dest_rv);
277

    
278
                                        /* 3.3- If there is any view with the table associated to this vector layer -> updates the table */
279
                                        // This step is executed after finishing the process, to avoid problems with Swing threads
280
                                }
281

    
282
                                /* 3.4- Repaints the view */
283
                                if (cancelProcess.isCanceled()) {
284
                                        throw new InterruptedException();
285
                                }
286

    
287
                                mapControl.drawMap(false);
288

    
289
                                percentage = 28;
290

    
291
                                String operationName;
292
                                IGeometry source_geometry = null, dest_geometry = null;
293
                                Value[] source_row_values;
294
                                IProjection tempProjection = null;
295
                                DefaultFeature newFeature;
296
                                String source_id;
297
                                final short LAYER_NOT_REPROJECTED = 0;
298
                                final short LAYER_REPROJECTED_TO_PLAIN_COORDINATES = 1;
299
                                final short LAYER_REPROJECTED_TO_GEOGRAPHIC_COORDINATES = 2;
300
                                short typeReprojection = LAYER_NOT_REPROJECTED;
301
                                long index;
302
                                short inc;
303

    
304
                                if (sourceLayer.getProjection().getAbrev().equals(mapControl.getViewPort().getProjection().getAbrev())) {
305
                                        /* 4.2.1- If the layer isn't projected -> Geographic coordinates (the default units are grades) */
306
                                        if (! sourceLayer.getProjection().isProjected()) {
307
                                                log.addLine(PluginServices.getText(null, "Incompatible_projection") + ": " + sourceLayer.getName());
308
                                                // UNSUPORTED
309
                                                new InterruptedException();
310
                                        }
311
                                        else {
312
                                        }
313

    
314
                                        typeReprojection = LAYER_NOT_REPROJECTED;
315
                                }
316
                                else {
317
                                        /* 4.2.1.1- If the layer isn't projected -> Geographic coordinates (the default units are grades) */
318
                                        /* 4.2.1.2- If the layer has been re-projected */
319
                                        if (! mapControl.getProjection().isProjected()) {
320
                                                // UNSUPORTED
321
                                                if (! sourceLayer.getProjection().isProjected()) {
322
                                                        log.addLine(PluginServices.getText(null, "Incompatible_projection") + ": " + sourceLayer.getName());
323
                                                        new InterruptedException();
324
                                                }
325

    
326
                                                typeReprojection = LAYER_REPROJECTED_TO_GEOGRAPHIC_COORDINATES;
327
                                        }
328
                                        else {
329
                                                typeReprojection = LAYER_REPROJECTED_TO_PLAIN_COORDINATES;
330
                                        }
331
                                        
332
                                        /* 4.3- Fixes a bug with the geoprocesses when the layer is reprojected */
333
                                        if (cancelProcess.isCanceled()) {
334
                                                throw new InterruptedException();
335
                                        }
336

    
337
                                        tempProjection = sourceLayer.getProjection();
338
                                        sourceLayer.setProjection(mapControl.getProjection());
339
                                        
340
                                }
341

    
342
                                percentage = 33;
343

    
344
                                /* 4- For each new geometry */
345
                                inc = (short) ((75 - 33) / parameters.getGeometryIndexes().length);
346
                                
347
                                switch(sourceLayer.getShapeType()) {
348
                                        case FShape.POINT:
349
                                                // The alphanumeric data will be lost
350
                                                numGeoms = parameters.getGeometryIndexes().length;
351
                                                
352
                                                long[] indexes;
353
                                                ArrayList points = new ArrayList();
354
                                                source_id = "";
355
                                        
356
                                                switch(parameters.getProcessID()) {
357
                                                        case DerivedGeometryProcessParameters.POINTS_TO_LINE_PROCESS_ID:
358
                                                                operationName = PluginServices.getText(this, "polyline_");
359

    
360
                                                                // For each new line, the the points
361
                                                                for (int i = 0; i < parameters.getGeometryIndexes().length; i++) {
362
                                                                        if (cancelProcess.isCanceled()) {
363
                                                                                throw new InterruptedException();
364
                                                                        }
365

    
366
                                                                        // Gets each geometry of the source
367
                                                                        try {
368
                                                                                indexes = parameters.getGeometryIndexes()[i];
369

    
370
                                                                                for (int j = 0; j < indexes.length; j++) {
371
                                                                                        if (cancelProcess.isCanceled()) {
372
                                                                                                throw new InterruptedException();
373
                                                                                        }
374

    
375
                                                                                        index = indexes[j];
376

    
377
                                                                                        source_rv.start();
378
                                                                                        source_id += " " + source_rv.getFeature((int)index).getID();
379
                                                                                        source_geometry = (IGeometry) source_rv.getShape((int)index);
380
                                                                                        source_rv.stop();
381

    
382
                                                                                        switch (typeReprojection) {
383
                                                                                                case LAYER_NOT_REPROJECTED:
384
                                                                                                        break;
385
                                                                                                case LAYER_REPROJECTED_TO_GEOGRAPHIC_COORDINATES: case LAYER_REPROJECTED_TO_PLAIN_COORDINATES:
386
                                                                                                        source_geometry.reProject(sourceLayer.getCoordTrans());
387
                                                                                                break;
388
                                                                                        }
389

    
390
                                                                                        points.add(source_geometry.getInternalShape());
391
                                                                                }
392
                                                                        }
393
                                                                        catch(Exception ex) {
394
                                                                                if (cancelProcess.isCanceled()) {
395
                                                                                        throw new InterruptedException();
396
                                                                                }
397

    
398
                                                                                NotificationManager.showMessageError(PluginServices.getText(null, "Failed_getting_geometry"), ex);
399
                                                                                log.addLine(PluginServices.getText(null, "Failed_getting_a_geometry_a_line_wont_be_created"));
400

    
401
                                                                                numGeomsFailed ++;
402
                                                                                points.clear();
403
                                                                                percentage += inc;
404

    
405
                                                                                continue;
406
                                                                        }
407

    
408
                                                                        /* Tries to create the new geometry */
409
                                                                        try {
410
                                                                                if (cancelProcess.isCanceled()) {
411
                                                                                        throw new InterruptedException();
412
                                                                                }
413

    
414
                                                                                dest_geometry = GeometryUtilities.getPolyLine2D((FPoint2D[])points.toArray(new FPoint2D[0]));
415

    
416
                                                                                // If has only one or two points the polygon couldn't be closed
417
                                                                                if (dest_geometry == null) {
418
                                                                                        try {
419
                                                                                                log.addLine(PluginServices.getText(null, "Impossible_convert_to_polyline") + " : " + Arrays.toString(indexes));
420
                                                                                        }
421
                                                                                        catch (Exception except) {
422
                                                                                                NotificationManager.showMessageError(PluginServices.getText(null, "Impossible_convert_to_polyline"), except);
423
                                                                                                log.addLine(PluginServices.getText(null, "Impossible_convert_to_polyline"));
424
                                                                                        }
425
                                                                                        numGeomsFailed ++;
426
                                                                                        points.clear();
427
                                                                                        percentage += inc;
428

    
429
                                                                                        continue;
430
                                                                                }
431
                                                                                
432
                                                                                /* Each geometry will only have one column, with a null value */
433
                                                                    Value[] values = new Value[1];
434
                                                                    values[0] = ValueFactory.createNullValue();
435
                                                                
436
                                                                                /* Creates the new row feature with the new geometry and the same alphanumeric values, and id */
437
                                                                                newFeature = new DefaultFeature(dest_geometry, values, source_id.trim());
438
                                                                        
439
                                                                    /* Adds the new row with the new polyline */
440
                                                                                dest_rv.startComplexRow();
441

    
442
                                                                                /* Adds the new feature */
443
                                                                                dest_rv.addRow(newFeature, operationName, EditionEvent.GRAPHIC);
444

    
445
                                                                                /* Disables the edition of the row */
446
                                                                                dest_rv.endComplexRow(operationName);
447

    
448
                                                                                /* Clears the points */
449
                                                                                points.clear();
450

    
451
                                                                                percentage += inc;
452
                                                                        }
453
                                                                        catch(Exception ex) {
454
                                                                                if (cancelProcess.isCanceled()) {
455
                                                                                        throw new InterruptedException();
456
                                                                                }
457

    
458
                                                                                NotificationManager.showMessageError(PluginServices.getText(null, "Failed_creating_geometry"), ex);
459
                                                                                log.addLine(PluginServices.getText(null, "Failed_creating_geometry_a_line_wont_be_created"));
460

    
461
                                                                                numGeomsFailed ++;
462
                                                                                points.clear();
463
                                                                                percentage += inc;
464

    
465
                                                                                continue;
466
                                                                        }
467
                                                                }
468
                                                                break;
469
                                                        case DerivedGeometryProcessParameters.POINTS_TO_POLYGON_PROCESS_ID:
470
                                                                operationName = PluginServices.getText(this, "polygon_");
471

    
472
                                                                // For each new line, the the points
473
                                                                for (int i = 0; i < parameters.getGeometryIndexes().length; i++) {
474
                                                                        if (cancelProcess.isCanceled()) {
475
                                                                                throw new InterruptedException();
476
                                                                        }
477

    
478
                                                                        // Gets each geometry of the source
479
                                                                        try {
480
                                                                                indexes = parameters.getGeometryIndexes()[i];
481

    
482
                                                                                for (int j = 0; j < indexes.length; j++) {
483
                                                                                        if (cancelProcess.isCanceled()) {
484
                                                                                                throw new InterruptedException();
485
                                                                                        }
486

    
487
                                                                                        index = indexes[j];
488

    
489
                                                                                        source_rv.start();
490
                                                                                        source_id += " " + source_rv.getFeature((int)index).getID();
491
                                                                                        source_geometry = (IGeometry) source_rv.getShape((int)index);
492
                                                                                        source_rv.stop();
493

    
494
                                                                                        switch (typeReprojection) {
495
                                                                                                case LAYER_NOT_REPROJECTED:
496
                                                                                                        break;
497
                                                                                                case LAYER_REPROJECTED_TO_GEOGRAPHIC_COORDINATES: case LAYER_REPROJECTED_TO_PLAIN_COORDINATES:
498
                                                                                                        source_geometry.reProject(sourceLayer.getCoordTrans());
499
                                                                                                break;
500
                                                                                        }
501

    
502
                                                                                        points.add(source_geometry.getInternalShape());
503
                                                                                }
504
                                                                        }
505
                                                                        catch(Exception ex) {
506
                                                                                if (cancelProcess.isCanceled()) {
507
                                                                                        throw new InterruptedException();
508
                                                                                }
509

    
510
                                                                                NotificationManager.showMessageError(PluginServices.getText(null, "Failed_getting_geometry"), ex);
511
                                                                                log.addLine(PluginServices.getText(null, "Failed_getting_a_geometry_a_polygon_wont_be_created"));
512

    
513
                                                                                numGeomsFailed ++;
514
                                                                                points.clear();
515
                                                                                percentage += inc;
516

    
517
                                                                                continue;
518
                                                                        }
519

    
520
                                                                        /* Tries to create the new geometry */
521
                                                                        try {
522
                                                                                if (cancelProcess.isCanceled()) {
523
                                                                                        throw new InterruptedException();
524
                                                                                }
525

    
526
                                                                                dest_geometry = GeometryUtilities.getPolygon2D((FPoint2D[])points.toArray(new FPoint2D[0]));
527

    
528
                                                                                // If has only one or two points the polygon couldn't be closed
529
                                                                                if (dest_geometry == null) {
530
                                                                                        try {
531
                                                                                                log.addLine(PluginServices.getText(null, "Impossible_convert_to_polygon") + " : " + Arrays.toString(indexes));
532
                                                                                        }
533
                                                                                        catch (Exception except) {
534
                                                                                                NotificationManager.showMessageError(PluginServices.getText(null, "Impossible_convert_to_polygon"), except);
535
                                                                                                log.addLine(PluginServices.getText(null, "Impossible_convert_to_polygon"));
536
                                                                                        }
537
                                                                                        numGeomsFailed ++;
538
                                                                                        points.clear();
539
                                                                                        percentage += inc;
540

    
541
                                                                                        continue;
542
                                                                                }
543
                                                                                
544
                                                                                /* Each geometry will only have one column, with a null value */
545
                                                                    Value[] values = new Value[1];
546
                                                                    values[0] = ValueFactory.createNullValue();
547
                                                                
548
                                                                                /* Creates the new row feature with the new geometry and the same alphanumeric values, and id */
549
                                                                                newFeature = new DefaultFeature(dest_geometry, values, source_id.trim());
550
                                                                        
551
                                                                    /* Adds the new row with the new polyline */
552
                                                                                dest_rv.startComplexRow();
553

    
554
                                                                                /* Adds the new feature */
555
                                                                                dest_rv.addRow(newFeature, operationName, EditionEvent.GRAPHIC);
556

    
557
                                                                                /* Disables the edition of the row */
558
                                                                                dest_rv.endComplexRow(operationName);
559

    
560
                                                                                /* Clears the points */
561
                                                                                points.clear();
562

    
563
                                                                                percentage += inc;
564
                                                                        }
565
                                                                        catch(Exception ex) {
566
                                                                                if (cancelProcess.isCanceled()) {
567
                                                                                        throw new InterruptedException();
568
                                                                                }
569

    
570
                                                                                NotificationManager.showMessageError(PluginServices.getText(null, "Failed_creating_geometry"), ex);
571
                                                                                log.addLine(PluginServices.getText(null, "Failed_creating_geometry_a_line_wont_be_created"));
572

    
573
                                                                                numGeomsFailed ++;
574
                                                                                points.clear();
575
                                                                                percentage += inc;
576

    
577
                                                                                continue;
578
                                                                        }
579
                                                                }
580
                                                                break;
581
                                                }
582
                                                break;
583
                                        case FShape.LINE:
584
                                                numGeoms = parameters.getGeometryIndexes()[0].length;
585
                                                operationName = PluginServices.getText(this, "polygon_");
586

    
587
                                                // For each row (geometry) -> copies it to the new layer
588
                                                for (int i = 0; i < parameters.getGeometryIndexes()[0].length; i++) {
589
                                                        if (cancelProcess.isCanceled()) {
590
                                                                throw new InterruptedException();
591
                                                        }
592

    
593
                                                        try {
594
                                                                // Gets each geometry of the source
595
                                                                index = parameters.getGeometryIndexes()[0][i];
596
                                                                
597
                                                                source_rv.start();
598
                                                                source_id = source_rv.getFeature((int)index).getID();
599
                                                                source_geometry = (IGeometry) source_rv.getShape((int)index);
600
                                                                source_row_values = source_rv.getFeature((int)index).getAttributes();
601
                                                                source_rv.stop();
602

    
603
                                                                switch (typeReprojection) {
604
                                                                        case LAYER_NOT_REPROJECTED:
605
                                                                                break;
606
                                                                        case LAYER_REPROJECTED_TO_GEOGRAPHIC_COORDINATES: case LAYER_REPROJECTED_TO_PLAIN_COORDINATES:
607
                                                                                source_geometry.reProject(sourceLayer.getCoordTrans());
608
                                                                        break;
609
                                                                }
610

    
611
                                                                // Geometry conversion according the source layer geometry type and the option selection
612

    
613
                                                                // Closes the lines -> converting to polygon
614
                                                                if (cancelProcess.isCanceled()) {
615
                                                                        throw new InterruptedException();
616
                                                                }
617

    
618
                                                                dest_geometry = GeometryUtilities.closeLine(source_geometry);
619

    
620
                                                                // If has only one or two points the polygon couldn't be closed
621
                                                                if (dest_geometry == null) {
622
                                                                        log.addLine(PluginServices.getText(null, "Impossible_convert_to_polygon_the_geometry") + " : " + source_id);
623
                                                                        numGeomsFailed ++;
624
                                                                        
625
                                                                        continue;
626
                                                                }
627

    
628
                                                                dest_rv.startComplexRow();
629

    
630
                                                                // Tries to process all the selected geometries
631
                                                                if (cancelProcess.isCanceled()) {
632
                                                                        throw new InterruptedException();
633
                                                                }
634

    
635
                                                                // Creates the new row feature with the new geometry and the same alphanumeric values, and id
636
                                                                newFeature = new DefaultFeature(dest_geometry, source_row_values, source_id);
637

    
638
                                                                /* Adds the new feature */
639
                                                                dest_rv.addRow(newFeature, operationName, EditionEvent.GRAPHIC); //EditionEvent.ALPHANUMERIC);
640
                                                        }
641
                                                        catch(Exception exG) {
642
                                                                if (cancelProcess.isCanceled()) {
643
                                                                        throw new InterruptedException();
644
                                                                }
645

    
646
                                                                NotificationManager.showMessageError(PluginServices.getText(null, "Failed_creating_geometry"), exG);
647
                                                                log.addLine(PluginServices.getText(null, "Failed_creating_geometry"));
648

    
649
                                                                numGeomsFailed ++;
650
                                                                
651
                                                                /* Forces to disable the edition of the row */
652
                                                                dest_rv.endComplexRow(operationName);
653
                                                                
654
                                                                // And continues with the next geometry
655
                                                                continue;
656
                                                        }
657
                
658
                                                        /* Disables the edition of the row */
659
                                                        dest_rv.endComplexRow(operationName);
660
                                                }
661

    
662
                                                percentage += inc;
663
                                                break;
664
                                }
665
                                
666
                                switch (typeReprojection) {
667
                                        case LAYER_NOT_REPROJECTED:
668
                                                break;
669
                                        case LAYER_REPROJECTED_TO_GEOGRAPHIC_COORDINATES: case LAYER_REPROJECTED_TO_PLAIN_COORDINATES:
670
                                                        sourceLayer.setProjection(tempProjection);
671
                                                break;
672
                                }
673
                                
674

    
675
                                /* 6- Ends layer in edition */
676
                                if (cancelProcess.isCanceled()) {
677
                                        throw new InterruptedException();
678
                                }
679

    
680
                                percentage = 75;
681
                                log.addLine(PluginServices.getText(null, "Stopping_the_layer_of_edition_mode"));
682
                                mapControl.getCanceldraw().setCanceled(true);
683

    
684
                                VectorialLayerEdited lyrEd = (VectorialLayerEdited)        editionManager.getActiveLayerEdited();
685
                                if (lyrEd != null)
686
                                        lyrEd.clearSelection(false);
687

    
688
                                percentage = 80;
689
                                
690
                                /* 6.1- Saves the layer */
691
                                /* This part can't be canceled */
692
                                if (layerAdded.isWritable()) {
693
                                        try {
694
                                                saveLayer(layerAdded);
695
                                        }
696
                                        catch (Exception e) {
697
                                                log.addLine(PluginServices.getText(null, "Failed_saving_the_layer"));
698
                                                throw e;
699
                                        }
700

    
701
                                        percentage = 90;
702

    
703
                                        /* 6.2- Only finish the edition mode if wasn't being edited */
704
                                        dest_rv.getCommandRecord().removeCommandListener(mapControl);
705
                                        layerAdded.setEditing(false);
706
                                        if (layerAdded.isSpatiallyIndexed()) {
707
                                    if (layerAdded.getISpatialIndex() != null) {
708
                                                        PluginServices.cancelableBackgroundExecution(new CreateSpatialIndexMonitorableTask((FLyrVect)layerAdded));
709
                                }
710
                                        }
711

    
712
                                        /* 6.3- If has ended successfully the editing */
713
                                        layerAdded.removeLayerListener(editionManager);
714
                                        if (layerAdded instanceof FLyrAnnotation) {
715
                                                FLyrAnnotation lva = (FLyrAnnotation)layerAdded;
716
                                    lva.setMapping(lva.getMapping());
717
                                        }
718

    
719
                                        /* 6.4.b- Restores the previous tool */
720
                                        mapControl.setTool(previousTool_ID);
721
                                        percentage = 91;
722

    
723
                                        parameters.getView().hideConsole();
724
                                        percentage = 94;
725
                                        
726
                                        mapControl.drawMap(false);
727
                                        percentage = 98;
728
                                        CADExtension.clearView();
729
                                }
730
                                
731
                                if (cancelProcess.isCanceled()) {
732
                                        throw new InterruptedException();
733
                                }
734
                                
735
                                percentage = 100;
736
                                log.addLine(PluginServices.getText(null, "Process_finished_successfully"));
737
                                return;
738
                        }
739
                        catch(Exception ex3) {
740
                                if (! cancelProcess.isCanceled()) {
741
                                        NotificationManager.showMessageError(PluginServices.getText(null, "Failed_processing_the_geometries"), ex3);
742
                                        log.addLine(PluginServices.getText(null, "Failed_processing_the_geometries"));
743
                                }
744

    
745
                                // CANCELS THE EDITION OF THE LAYER
746
                                try {
747
                                        // Emergency restore
748
                                        // This code can't be cancelled
749
                                        // Only finish the edition mode if wasn't being edited
750
                                        cancelEdition(layerAdded);
751
                                        layerAdded.setEditing(false);
752

    
753
                                        mapControl.setTool(previousTool_ID);
754
                                        parameters.getView().hideConsole();
755
                                        mapControl.drawMap(false);
756
                                        CADExtension.clearView();
757
                                }
758
                                catch (Exception ex) {
759
                                        NotificationManager.showMessageError(PluginServices.getText(null, "Failed_restoring_layer_in_edition_mode"), ex);
760
                                        log.addLine(PluginServices.getText(null, "Failed_restoring_layer_in_edition_mode"));
761
                                }
762

    
763
                                throw new InterruptedException();
764
                        }
765
                }
766
                catch (Exception ex4) {
767
                        if (! cancelProcess.isCanceled()) {
768
                                NotificationManager.showMessageError(PluginServices.getText(null, "Failed_the_process"), ex4);
769
                                log.addLine(PluginServices.getText(null, "Failed_the_process"));
770
                        }
771

    
772
                        /* CANCELLATION PROCESS */
773

    
774
                        // Forces to end the atomic transaction
775
                        parameters.getMapControl().getMapContext().endAtomicEvent();
776

    
777
                        /* Removes the layer added */
778
                        try {
779
                                parameters.getMapControl().getMapContext().getLayers().removeLayer(layerAdded);
780
                        }
781
                        catch (RuntimeException rE) {
782
                                // Skips the runtime exception launched when this thread tries to update the main frame
783
                                if ((rE.getMessage() != null) && (rE.getMessage().compareTo("No Event Dispatch Thread") == 0)) {
784
                                        log.addLine(PluginServices.getText(this, "Runtime_exception_refreshing_the_main_frame_by_a_Swing_thread"));
785
                                }
786
                                else {
787
                                        log.addLine(PluginServices.getText(this, "Runtime_exception_refreshing_the_main_frame_by_a_Swing_thread"));
788
                                }
789
                        }
790

    
791
                        layerAdded = null;
792
                        parameters.setDestLayer(null);
793

    
794
                        throw new InterruptedException();
795
                }
796
                finally {
797
                        /* Summary of geometries processed */
798
                        log.addLine("    " + PluginServices.getText(null, "Number_of_geometries_to_create") + " : " + numGeoms);
799
                        log.addLine("    " + PluginServices.getText(null, "Number_of_geometries_that_couldnt_be_created") + " : " + numGeomsFailed);
800
                        log.addLine("    " + PluginServices.getText(null, "Number_of_geometries_created_successfully") + " : " + (numGeoms - numGeomsFailed));
801
                        
802
                        // Ends the progress panel
803
                        iTask.getButtonsPanel().getButton(ButtonsPanel.BUTTON_ACCEPT).doClick();
804
                }
805
        }
806

    
807
        /*
808
         * (non-Javadoc)
809
         * @see org.gvsig.gui.beans.incrementabletask.IncrementableListener#actionCanceled(org.gvsig.gui.beans.incrementabletask.IncrementableEvent)
810
         */
811
        public void actionCanceled(IncrementableEvent e) {
812
                if (percentage < 100) {
813
                        ended = true;
814
                        
815
                        cancelProcess.setCanceled(true);
816
                        
817
                        blinker.interrupt();
818
                }
819
                else {
820
                        JOptionPane.showMessageDialog(null, PluginServices.getText(null, "Process_finished_wont_be_cancelled"), PluginServices.getText(null, "Warning"), JOptionPane.WARNING_MESSAGE);
821
                }
822
        }
823

    
824
//        /**
825
//         * <p>Starts layer in edition mode.</p>
826
//         * 
827
//         * @param mapControl the <code>MapControl</code> object that contains the layer
828
//         * @param cad_extension extension that allows edit a layer
829
//         * @param editionManager manager for editing layers
830
//         * @param vea adapter of the editable vector layers
831
//         * @param layer the layer to start in edition mode
832
//         * 
833
//         * @throws Exception any exception produced starting in edition the layer
834
//         */
835
//        private void startLayerInEdition(MapControl mapControl, CADExtension cad_extension, EditionManager editionManager, VectorialEditableAdapter vea, FLyrVect layer) throws Exception {
836
//                log.addLine(PluginServices.getText(null, "Starting_the_layer_in_edition_mode"));
837
//                mapControl.getMapContext().clearAllCachingImageDrawnLayers();
838
//                cad_extension = (CADExtension) PluginServices.getExtension(CADExtension.class);
839
//                editionManager = cad_extension.getEditionManager();
840
//                editionManager.setMapControl(mapControl);
841
//
842
//                layer.addLayerListener(editionManager);
843
//
844
//                Legend legendOriginal = layer.getLegend();
845
//
846
//                if (! layer.isWritable()) {
847
//                        JOptionPane.showMessageDialog((Component) PluginServices.getMDIManager().getActiveWindow(),
848
//                                PluginServices.getText(this, "this_layer_is_not_self_editable"),
849
//                                PluginServices.getText(this, "warning_title"),
850
//                                JOptionPane.WARNING_MESSAGE);
851
//
852
//                        throw new InterruptedException();
853
//                }
854
//
855
//                /* N.1- Sets the cad tool adapter if wasn't added */
856
//                CADToolAdapter cta = CADExtension.getCADToolAdapter();
857
//                if (! mapControl.getNamesMapTools().containsKey("cadtooladapter")) {
858
//                        mapControl.addMapTool("cadtooladapter", cta);
859
//                }
860
//
861
//                layer.setEditing(true);
862
//                vea = (VectorialEditableAdapter) layer.getSource();
863
//
864
//                vea.getRules().clear();
865
//                if (vea.getShapeType() == FShape.POLYGON) {
866
//                        IRule rulePol = new RulePolygon();
867
//                        vea.getRules().add(rulePol);
868
//                }
869
//
870
//                if (! (layer.getSource().getDriver() instanceof IndexedShpDriver)) {
871
//                        VectorialLayerEdited vle=(VectorialLayerEdited)editionManager.getLayerEdited(layer);
872
//                        vle.setLegend(legendOriginal);
873
//                }
874
//
875
//                vea.getCommandRecord().addCommandListener(mapControl);
876
//
877
//                /* N.2- If exits any layer associated, changes its model by the VectorialEditableAdapter's one */
878
//                ProjectExtension pe = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class);
879
//
880
//                ProjectTable pt = pe.getProject().getTable(layer);
881
//                //this.layerProjectTable = pt;
882
//
883
//                if (pt != null){
884
//                        pt.setModel(vea);
885
//
886
//                        /* N.3- If there is any view with the table associated to this vector layer -> updates the table */
887
//                        // This step is executed after finishing the process, to avoid problems with Swing threads
888
////                           com.iver.andami.ui.mdiManager.IWindow[] views = PluginServices.getMDIManager().getAllWindows();
889
////
890
////                        for (int i = 0 ; i < views.length ; i++) {
891
////                                if (views[i] instanceof Table) {
892
////                                        Table table = (Table)views[i];
893
////                                        ProjectTable model = table.getModel();
894
////
895
////                                        if (model.equals(pt)) {
896
////                                                table.setModel(pt);
897
////                                                vea.getCommandRecord().addCommandListener(table);
898
////                                        }
899
////                                }
900
////                        }
901
//                }
902
//
903
//                /* N.4- Repaints the view */
904
//                mapControl.drawMap(false);
905
//        }
906

    
907
        /**
908
         * <p>Saves and stops the edition of a vector layer.</p>
909
         * 
910
         * @param layer the vector layer to save
911
         * 
912
         * @throws Exception if fails saving the layer
913
         */
914
        private void saveLayer(FLyrVect layer) throws Exception {
915
                try {
916
                        layer.setProperty("stoppingEditing", new Boolean(true));
917
                        VectorialEditableAdapter vea = (VectorialEditableAdapter) layer.getSource();
918
                        
919
                        ISpatialWriter writer = (ISpatialWriter) vea.getWriter();
920
                        com.iver.andami.ui.mdiManager.IWindow[] views = PluginServices.getMDIManager().getAllWindows();
921
                        for (int j = 0; j < views.length; j++) {
922
                                if (views[j] instanceof Table) {
923
                                        Table table = (Table) views[j];
924
                                        if (table.getModel().getAssociatedTable() != null
925
                                                        && table.getModel().getAssociatedTable().equals(layer)) {
926
                                                table.stopEditingCell();
927
                                        }
928
                                }
929
                        }
930
                        vea.cleanSelectableDatasource();
931
                        layer.setRecordset(vea.getRecordset());
932
        
933
                        // Queremos que el recordset del layer
934
                        // refleje los cambios en los campos.
935
                        ILayerDefinition lyrDef = EditionUtilities.createLayerDefinition(layer);
936
                        String aux = "FIELDS:";
937
                        FieldDescription[] flds = lyrDef.getFieldsDesc();
938
                        for (int i=0; i < flds.length; i++)        {
939
                                aux = aux + ", " + flds[i].getFieldAlias();
940
                        }
941
        
942
                        System.err.println("Escribiendo la capa " + lyrDef.getName() + " con los campos " + aux);
943
                        lyrDef.setShapeType(layer.getShapeType());
944
                        writer.initialize(lyrDef);
945
                        vea.stopEdition(writer, EditionEvent.GRAPHIC);
946
                        layer.setProperty("stoppingEditing", new Boolean(false));
947
                }
948
                catch (Exception e) {
949
                        log.addLine(PluginServices.getText(null, "Failed_saving_the_layer"));
950
                        throw e;                        
951
                }
952
        }
953

    
954
        /**
955
         * <p>Cancels the edition process without saving.</p>
956
         * 
957
         * @param layer the layer being edited
958
         * 
959
         * @throws Exception if fails canceling the layer
960
         */
961
        private void cancelEdition(FLyrVect layer) throws Exception {
962
                try {
963
                        layer.setProperty("stoppingEditing",new Boolean(true));
964
                        com.iver.andami.ui.mdiManager.IWindow[] views = PluginServices.getMDIManager().getAllWindows();
965
                        VectorialEditableAdapter vea = (VectorialEditableAdapter) layer.getSource();
966
                        vea.cancelEdition(EditionEvent.GRAPHIC);
967
        
968
                        for (int j = 0; j < views.length; j++) {
969
                                if (views[j] instanceof Table) {
970
                                        Table table = (Table) views[j];
971
                                        if ((table.getModel().getAssociatedTable() != null) && (table.getModel().getAssociatedTable().equals(layer))) {
972
                                                // Avoid conflicts with the Swing threads
973
                                            table.cancelEditingCell();
974
                                        table.getModel().getModelo().cancelEdition(EditionEvent.ALPHANUMERIC);
975
                                                //table.cancelEditing();
976
                                        }
977
                                }
978
                        }
979
        
980
                        layer.setProperty("stoppingEditing", new Boolean(false));
981
                }
982
                catch (Exception e) {
983
                        log.addLine(PluginServices.getText(null, "Failed_canceling_the_layer"));
984
                        throw e;
985
                }
986
        }
987
}