Statistics
| Revision:

root / trunk / extensions / extGeoProcessing / src / com / iver / gvsig / geoprocessing / gui / GeoProcessingPanel.java @ 2996

History | View | Annotate | Download (84.4 KB)

1
/*
2
 * Created on 01-jul-2005
3
 *
4
 * gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
5
 *
6
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
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., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
21
 *
22
 * For more information, contact:
23
 *
24
 *  Generalitat Valenciana
25
 *   Conselleria d'Infraestructures i Transport
26
 *   Av. Blasco Ib??ez, 50
27
 *   46010 VALENCIA
28
 *   SPAIN
29
 *
30
 *      +34 963862235
31
 *   gvsig@gva.es
32
 *      www.gvsig.gva.es
33
 *
34
 *    or
35
 *
36
 *   IVER T.I. S.A
37
 *   Salamanca 50
38
 *   46005 Valencia
39
 *   Spain
40
 *
41
 *   +34 963163400
42
 *   dac@iver.es
43
 */
44
package com.iver.gvsig.geoprocessing.gui;
45

    
46
import javax.swing.JCheckBox;
47
import javax.swing.JComboBox;
48
import javax.swing.JDialog;
49
import javax.swing.JList;
50
import javax.swing.JPanel;
51
import javax.swing.JRadioButton;
52
import javax.swing.JTextField;
53
import javax.swing.JScrollPane;
54

    
55
import com.hardcode.driverManager.DriverLoadException;
56
import com.hardcode.gdbms.engine.data.DataSource;
57
import com.hardcode.gdbms.engine.data.DataSourceFactory;
58
import com.hardcode.gdbms.engine.data.NoSuchTableException;
59
import com.hardcode.gdbms.engine.data.edition.DataWare;
60
import com.hardcode.gdbms.engine.instruction.IncompatibleTypesException;
61
import com.hardcode.gdbms.engine.values.BooleanValue;
62
import com.hardcode.gdbms.engine.values.Value;
63
import com.hardcode.gdbms.engine.values.ValueFactory;
64
import com.iver.andami.PluginServices;
65
import com.iver.andami.ui.mdiManager.View;
66
import com.iver.andami.ui.mdiManager.ViewInfo;
67
import com.iver.cit.gvsig.fmap.DriverException;
68
import com.iver.cit.gvsig.fmap.core.FPolygon2D;
69
import com.iver.cit.gvsig.fmap.core.FShape;
70
import com.iver.cit.gvsig.fmap.core.IGeometry;
71
import com.iver.cit.gvsig.fmap.core.ShapeFactory;
72
import com.iver.cit.gvsig.fmap.core.v02.FConverter;
73
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
74
import com.iver.cit.gvsig.fmap.layers.FBitSet;
75
import com.iver.cit.gvsig.fmap.layers.FLayer;
76
import com.iver.cit.gvsig.fmap.layers.FLayers;
77
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
78
import com.iver.cit.gvsig.fmap.layers.VectorialAdapter;
79
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
80
import com.iver.cit.gvsig.fmap.layers.layerOperations.Selectable;
81
import com.iver.cit.gvsig.fmap.layers.layerOperations.SingleLayer;
82
import com.iver.cit.gvsig.fmap.layers.layerOperations.VectorialData;
83
import com.iver.cit.gvsig.fmap.operations.strategies.SelectedShapeVisitor;
84
import com.iver.cit.gvsig.fmap.operations.strategies.SelectedZoomVisitor;
85
import com.iver.cit.gvsig.fmap.operations.strategies.VisitException;
86
import com.iver.gvsig.geoprocessing.gui.operationpanels.GeoProcessingBufferPanel;
87
import com.iver.gvsig.geoprocessing.gui.operationpanels.GeoProcessingClipPanel;
88
import com.iver.gvsig.geoprocessing.gui.operationpanels.GeoProcessingDissolvePanel;
89
import com.iver.gvsig.geoprocessing.gui.operationpanels.GeoProcessingIntersectPanel;
90
import com.iver.gvsig.geoprocessing.gui.operationpanels.GeoProcessingMergePanel;
91
import com.iver.gvsig.geoprocessing.gui.operationpanels.GeoProcessingSpatialjoinPanel;
92
import com.iver.gvsig.geoprocessing.gui.operationpanels.GeoProcessingUnionPanel;
93
import com.iver.gvsig.geoprocessing.operations.GeoProcessingPersistenceOperations;
94
import com.iver.gvsig.geoprocessing.operations.GeoProcessingTableOperations;
95
import com.iver.gvsig.geoprocessing.operations.GeoProcessingTopologyOperations;
96
import com.iver.gvsig.geoprocessing.operations.strategies.SelectedShapeToJTSVisitor;
97
import com.vividsolutions.jts.geom.Coordinate;
98
import com.vividsolutions.jts.geom.Geometry;
99
import com.vividsolutions.jts.geom.GeometryCollection;
100
import com.vividsolutions.jts.geom.GeometryFactory;
101
import com.vividsolutions.jts.geom.LineString;
102
import com.vividsolutions.jts.geom.MultiPoint;
103
import com.vividsolutions.jts.geom.Point;
104
import com.vividsolutions.jts.geom.Polygon;
105
import com.vividsolutions.jts.operation.distance.DistanceOp;
106

    
107
import java.awt.Component;
108
import java.awt.GridLayout;
109
import java.awt.GridBagLayout;
110
import java.awt.GridBagConstraints;
111
import java.awt.FlowLayout;
112
import java.awt.CardLayout;
113
import javax.swing.BoxLayout;
114
import java.awt.BorderLayout;
115
import java.io.File;
116
import java.sql.Types;
117
import java.util.BitSet;
118
import java.util.Vector;
119

    
120
import javax.swing.JButton;
121

    
122
public class GeoProcessingPanel extends JPanel implements View {
123

    
124
    /**
125
     * 
126
     */
127
    private static final long serialVersionUID = 1L;
128
    private GeoProcessingOperationSelectorPanel geoProcessingOperationSelectorPanel = null;
129
    private GeoProcessingBufferPanel geoProcessingBufferPanel = null;
130
    private GeoProcessingClipPanel geoProcessingClipPanel = null;
131
    private GeoProcessingDissolvePanel geoProcessingDissolvePanel = null;
132
    private GeoProcessingMergePanel geoProcessingMergePanel = null;
133
    private GeoProcessingIntersectPanel geoProcessingIntersectPanel = null;
134
    private GeoProcessingUnionPanel geoProcessingUnionPanel = null;
135
    private GeoProcessingSpatialjoinPanel geoProcessingSpatialjoinPanel = null;
136
    private JPanel buttonsPanel = null;
137

    
138
        private JButton jButton = null;
139
        private JButton jButton1 = null;
140
        private JButton jButton2 = null;
141
    private ViewInfo viewInfo = null;
142
    private FLayers layers = null;
143
    /**
144
     * This constructor initializes the set of layers
145
     */
146
    public GeoProcessingPanel(FLayers layers) {
147
        super();
148
        this.layers = layers;
149
        initialize();
150
    }
151

    
152
    /**
153
     * This method initializes this
154
     * 
155
     * @return void
156
     */
157
    private void initialize() {
158
        this.setLayout(new BorderLayout());
159
        this.setSize(416, 271);
160
        this.add(getButtonsPanel(), java.awt.BorderLayout.SOUTH);
161
        this.add(getGeoProcessingOperationSelectorPanel(), java.awt.BorderLayout.NORTH);
162
        this.add(getGeoProcessingBufferPanel(), java.awt.BorderLayout.NORTH);
163
        this.add(getGeoProcessingClipPanel(), java.awt.BorderLayout.NORTH);
164
        this.add(getGeoProcessingDissolvePanel(), java.awt.BorderLayout.NORTH);
165
        this.add(getGeoProcessingMergePanel(), java.awt.BorderLayout.NORTH);
166
        this.add(getGeoProcessingIntersectPanel(), java.awt.BorderLayout.NORTH);
167
        this.add(getGeoProcessingUnionPanel(), java.awt.BorderLayout.NORTH);
168
        this.add(getGeoProcessingSpatialjoinPanel(), java.awt.BorderLayout.NORTH);
169
        geoProcessingOperationSelectorPanel.setVisible(true);
170
        geoProcessingBufferPanel.setVisible(false);
171
        geoProcessingClipPanel.setVisible(false);
172
        geoProcessingDissolvePanel.setVisible(false);
173
        geoProcessingMergePanel.setVisible(false);
174
        geoProcessingIntersectPanel.setVisible(false);
175
        geoProcessingUnionPanel.setVisible(false);
176
        geoProcessingSpatialjoinPanel.setVisible(false);
177
        jButton1.setEnabled(false);
178
    }
179

    
180
    public ViewInfo getViewInfo() {
181
        // TODO Auto-generated method stub
182
        if (viewInfo == null) {
183
            viewInfo=new ViewInfo(ViewInfo.MODALDIALOG);
184
            viewInfo.setTitle(PluginServices.getText(this,"Herramientas_de_analisis"));
185
        }
186
        return viewInfo;
187
    }
188

    
189
    /**
190
     * This method initializes geoProcessingOperationSelectorPanel        
191
     *         
192
     * @return javax.swing.JPanel        
193
     */    
194
    private JPanel getGeoProcessingOperationSelectorPanel() {
195
            if (geoProcessingOperationSelectorPanel == null) {
196
                    geoProcessingOperationSelectorPanel = new GeoProcessingOperationSelectorPanel();
197
                    geoProcessingOperationSelectorPanel.setName("geoProcessingOperationSelectorPanel");
198
            }
199
            return geoProcessingOperationSelectorPanel;
200
    }
201

    
202
    /**
203
     * This method initializes geoProcessingBufferPanel        
204
     *         
205
     * @return javax.swing.JPanel        
206
     */    
207
    private JPanel getGeoProcessingBufferPanel() {
208
            if (geoProcessingBufferPanel == null) {
209
                    geoProcessingBufferPanel = new GeoProcessingBufferPanel(layers);
210
                    geoProcessingBufferPanel.setName("geoProcessingBufferPanel");
211
            }
212
            return geoProcessingBufferPanel;
213
    }
214

    
215
    /**
216
     * This method initializes geoProcessingClipPanel        
217
     *         
218
     * @return javax.swing.JPanel        
219
     */    
220
    private JPanel getGeoProcessingClipPanel() {
221
            if (geoProcessingClipPanel == null) {
222
                    geoProcessingClipPanel = new GeoProcessingClipPanel(layers);
223
                    geoProcessingClipPanel.setName("geoProcessingClipPanel");
224
                    // Si no le meto esta l?nea, no se visualiza el men?. Ver que puede
225
            // estar pasando ...
226
            geoProcessingClipPanel.setPreferredSize(new java.awt.Dimension(300,300));
227
            }
228
            return geoProcessingClipPanel;
229
    }
230

    
231
    /**
232
     * This method initializes geoProcessingDissolvePanel 
233
     *  
234
     * @return javax.swing.JPanel   
235
     */    
236
    private JPanel getGeoProcessingDissolvePanel() {
237
        if (geoProcessingDissolvePanel == null) {
238
            geoProcessingDissolvePanel = new GeoProcessingDissolvePanel(layers);
239
            geoProcessingDissolvePanel.setName("geoProcessingDissolvePanel");
240
        }
241
        return geoProcessingDissolvePanel;
242
    }
243

    
244
    /**
245
     * This method initializes geoProcessingMergePanel 
246
     *  
247
     * @return javax.swing.JPanel   
248
     */    
249
    private JPanel getGeoProcessingMergePanel() {
250
        if (geoProcessingMergePanel == null) {
251
            geoProcessingMergePanel = new GeoProcessingMergePanel(layers);
252
            geoProcessingMergePanel.setName("geoProcessingMergePanel");
253
        }
254
        return geoProcessingMergePanel;
255
    }
256

    
257
    /**
258
     * This method initializes geoProcessingIntersectPanel 
259
     *  
260
     * @return javax.swing.JPanel   
261
     */    
262
    private JPanel getGeoProcessingIntersectPanel() {
263
        if (geoProcessingIntersectPanel == null) {
264
            geoProcessingIntersectPanel = new GeoProcessingIntersectPanel(layers);
265
            geoProcessingIntersectPanel.setName("geoProcessingIntersectPanel");
266
        }
267
        return geoProcessingIntersectPanel;
268
    }
269

    
270
    /**
271
     * This method initializes geoProcessingUnionPanel 
272
     *  
273
     * @return javax.swing.JPanel   
274
     */    
275
    private JPanel getGeoProcessingUnionPanel() {
276
        if (geoProcessingUnionPanel == null) {
277
            geoProcessingUnionPanel = new GeoProcessingUnionPanel(layers);
278
            geoProcessingUnionPanel.setName("geoProcessingUnionPanel");
279
        }
280
        return geoProcessingUnionPanel;
281
    }
282

    
283
    /**
284
     * This method initializes geoProcessingSpatialjoinPanel 
285
     *  
286
     * @return javax.swing.JPanel   
287
     */    
288
    private JPanel getGeoProcessingSpatialjoinPanel() {
289
        if (geoProcessingSpatialjoinPanel == null) {
290
            geoProcessingSpatialjoinPanel = new GeoProcessingSpatialjoinPanel(layers);
291
            geoProcessingSpatialjoinPanel.setName("geoProcessingSpatialjoinPanel");
292
            // Si no le meto esta l?nea, no se visualiza el men?. Ver que puede
293
            // estar pasando ...
294
            geoProcessingSpatialjoinPanel.setPreferredSize(new java.awt.Dimension(300,300));
295
        }
296
        return geoProcessingSpatialjoinPanel;
297
    }
298

    
299
    /**
300
     * This method initializes buttonsPanel        
301
     *         
302
     * @return javax.swing.JPanel        
303
     */    
304
    private JPanel getButtonsPanel() {
305
            if (buttonsPanel == null) {
306
                    buttonsPanel = new JPanel();
307
                    buttonsPanel.setName("buttonsPanel");
308
                    buttonsPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.LOWERED));
309
                    buttonsPanel.add(getJButton(), null);
310
                    buttonsPanel.add(getJButton1(), null);
311
                    buttonsPanel.add(getJButton2(), null);
312
            }
313
            return buttonsPanel;
314
    }
315

    
316
        /**
317
         * This method initializes jButton        
318
         *         
319
         * @return javax.swing.JButton        
320
         */    
321
        private JButton getJButton() {
322
                if (jButton == null) {
323
                        jButton = new JButton();
324
                        jButton.setText(PluginServices.getText(this,"Cerrar"));
325
                        jButton.addActionListener(new java.awt.event.ActionListener() { 
326
                                public void actionPerformed(java.awt.event.ActionEvent e) {    
327
                                        System.out.println("actionPerformed()"); // TODO Auto-generated Event stub actionPerformed()
328
                    closeMethod();
329
                                }
330
                        });
331
                }
332
                return jButton;
333
        }
334
        /**
335
         * This method initializes jButton1        
336
         *         
337
         * @return javax.swing.JButton        
338
         */    
339
        private JButton getJButton1() {
340
                if (jButton1 == null) {
341
                        jButton1 = new JButton();
342
                        jButton1.setText(PluginServices.getText(this,"Anterior"));
343
                        jButton1.addActionListener(new java.awt.event.ActionListener() { 
344
                                public void actionPerformed(java.awt.event.ActionEvent e) {    
345
                                        System.out.println("actionPerformed()"); // TODO Auto-generated Event stub actionPerformed()
346
                    getGeoProcessingOperationSelectorPanel().setVisible(true);
347
                    getGeoProcessingBufferPanel().setVisible(false);
348
                    getGeoProcessingClipPanel().setVisible(false);
349
                    getGeoProcessingDissolvePanel().setVisible(false);
350
                    getGeoProcessingMergePanel().setVisible(false);
351
                    getGeoProcessingIntersectPanel().setVisible(false);
352
                    getGeoProcessingUnionPanel().setVisible(false);
353
                    getGeoProcessingSpatialjoinPanel().setVisible(false);
354
                    jButton1.setEnabled(false);
355
                    jButton2.setText(PluginServices.getText(this,"Siguiente"));
356
                                }
357
                        });
358
                }
359
                return jButton1;
360
        }
361
        /**
362
         * This method initializes jButton2        
363
         *         
364
         * @return javax.swing.JButton        
365
         */    
366
        private JButton getJButton2() {
367
                if (jButton2 == null) {
368
                        jButton2 = new JButton();
369
                        jButton2.setText(PluginServices.getText(this,"Siguiente"));
370
                        jButton2.addActionListener(new java.awt.event.ActionListener() { 
371
                                public void actionPerformed(java.awt.event.ActionEvent e) {    
372
                                        System.out.println("actionPerformed()"); // TODO Auto-generated Event stub actionPerformed()
373
                                        if (jButton2.getText().equals(PluginServices.getText(this,"Siguiente"))) {
374
                        if (((JRadioButton)geoProcessingOperationSelectorPanel.getComponent(1)).isSelected()) {
375
                            getGeoProcessingOperationSelectorPanel().setVisible(false);
376
                            getGeoProcessingBufferPanel().setVisible(true);
377
                            getGeoProcessingClipPanel().setVisible(false);
378
                            getGeoProcessingDissolvePanel().setVisible(false);
379
                            getGeoProcessingMergePanel().setVisible(false);
380
                            getGeoProcessingIntersectPanel().setVisible(false);
381
                            getGeoProcessingUnionPanel().setVisible(false);
382
                            getGeoProcessingSpatialjoinPanel().setVisible(false);
383
                        } else if (((JRadioButton)geoProcessingOperationSelectorPanel.getComponent(2)).isSelected()) {
384
                            getGeoProcessingOperationSelectorPanel().setVisible(false);
385
                            getGeoProcessingBufferPanel().setVisible(false);
386
                            getGeoProcessingClipPanel().setVisible(true);
387
                            getGeoProcessingDissolvePanel().setVisible(false);
388
                            getGeoProcessingMergePanel().setVisible(false);
389
                            getGeoProcessingIntersectPanel().setVisible(false);
390
                            getGeoProcessingUnionPanel().setVisible(false);
391
                            getGeoProcessingSpatialjoinPanel().setVisible(false);
392
                        } else if (((JRadioButton)geoProcessingOperationSelectorPanel.getComponent(3)).isSelected()) {
393
                            getGeoProcessingOperationSelectorPanel().setVisible(false);
394
                            getGeoProcessingBufferPanel().setVisible(false);
395
                            getGeoProcessingClipPanel().setVisible(false);
396
                            getGeoProcessingDissolvePanel().setVisible(true);
397
                            getGeoProcessingMergePanel().setVisible(false);
398
                            getGeoProcessingIntersectPanel().setVisible(false);
399
                            getGeoProcessingUnionPanel().setVisible(false);
400
                            getGeoProcessingSpatialjoinPanel().setVisible(false);
401
                        } else if (((JRadioButton)geoProcessingOperationSelectorPanel.getComponent(4)).isSelected()) {
402
                            getGeoProcessingOperationSelectorPanel().setVisible(false);
403
                            getGeoProcessingBufferPanel().setVisible(false);
404
                            getGeoProcessingClipPanel().setVisible(false);
405
                            getGeoProcessingDissolvePanel().setVisible(false);
406
                            getGeoProcessingMergePanel().setVisible(true);
407
                            getGeoProcessingIntersectPanel().setVisible(false);
408
                            getGeoProcessingUnionPanel().setVisible(false);
409
                            getGeoProcessingSpatialjoinPanel().setVisible(false);
410
                        } else if (((JRadioButton)geoProcessingOperationSelectorPanel.getComponent(5)).isSelected()) {
411
                            getGeoProcessingOperationSelectorPanel().setVisible(false);
412
                            getGeoProcessingBufferPanel().setVisible(false);
413
                            getGeoProcessingClipPanel().setVisible(false);
414
                            getGeoProcessingDissolvePanel().setVisible(false);
415
                            getGeoProcessingMergePanel().setVisible(false);
416
                            getGeoProcessingIntersectPanel().setVisible(true);
417
                            getGeoProcessingUnionPanel().setVisible(false);
418
                            getGeoProcessingSpatialjoinPanel().setVisible(false);
419
                        } else if (((JRadioButton)geoProcessingOperationSelectorPanel.getComponent(6)).isSelected()) {
420
                            getGeoProcessingOperationSelectorPanel().setVisible(false);
421
                            getGeoProcessingBufferPanel().setVisible(false);
422
                            getGeoProcessingClipPanel().setVisible(false);
423
                            getGeoProcessingDissolvePanel().setVisible(false);
424
                            getGeoProcessingMergePanel().setVisible(false);
425
                            getGeoProcessingIntersectPanel().setVisible(false);
426
                            getGeoProcessingUnionPanel().setVisible(true);
427
                            getGeoProcessingSpatialjoinPanel().setVisible(false);
428
                        } else if (((JRadioButton)geoProcessingOperationSelectorPanel.getComponent(7)).isSelected()) {
429
                            getGeoProcessingOperationSelectorPanel().setVisible(false);
430
                            getGeoProcessingBufferPanel().setVisible(false);
431
                            getGeoProcessingClipPanel().setVisible(false);
432
                            getGeoProcessingDissolvePanel().setVisible(false);
433
                            getGeoProcessingMergePanel().setVisible(false);
434
                            getGeoProcessingIntersectPanel().setVisible(false);
435
                            getGeoProcessingUnionPanel().setVisible(false);
436
                            getGeoProcessingSpatialjoinPanel().setVisible(true);
437
                        } else {
438
                            // Si no hay ninguna operaci?n de geoprocesamiento seleccionada no se cambia el di?logo de opciones.
439
                            getGeoProcessingOperationSelectorPanel().setVisible(true);
440
                            getGeoProcessingBufferPanel().setVisible(false);
441
                            getGeoProcessingClipPanel().setVisible(false);
442
                            getGeoProcessingDissolvePanel().setVisible(false);
443
                            getGeoProcessingMergePanel().setVisible(false);
444
                            getGeoProcessingIntersectPanel().setVisible(false);
445
                            getGeoProcessingUnionPanel().setVisible(false);
446
                            getGeoProcessingSpatialjoinPanel().setVisible(false);
447
                        }
448
                        jButton1.setEnabled(true);
449
                        jButton2.setText(PluginServices.getText(this,"Terminar"));
450
                    } else if (jButton2.getText().equals(PluginServices.getText(this,"Terminar"))) {
451
                        if (((JRadioButton)geoProcessingOperationSelectorPanel.getComponent(1)).isSelected()) {
452
                            bufferMethod();
453
                        } else if (((JRadioButton)geoProcessingOperationSelectorPanel.getComponent(2)).isSelected()) {
454
                            clipMethod();
455
                        } else if (((JRadioButton)geoProcessingOperationSelectorPanel.getComponent(3)).isSelected()) {
456
                            dissolveMethod();
457
                        } else if (((JRadioButton)geoProcessingOperationSelectorPanel.getComponent(4)).isSelected()) {
458
                            mergeMethod();
459
                        } else if (((JRadioButton)geoProcessingOperationSelectorPanel.getComponent(5)).isSelected()) {
460
                            intersectMethod();
461
                        } else if (((JRadioButton)geoProcessingOperationSelectorPanel.getComponent(6)).isSelected()) {
462
                            unionMethod();
463
                        } else if (((JRadioButton)geoProcessingOperationSelectorPanel.getComponent(7)).isSelected()) {
464
                            spatialjoinMethod();
465
                        } else {
466
                            //
467
                        }
468
                        closeMethod();
469
                    }
470
                                }
471
                        });
472
                }
473
                return jButton2;
474
        }
475
    private Geometry[] getJtsGeometries(FLayer bufferingLayer, boolean selected) {
476
        FBitSet fBitSet = ((Selectable)bufferingLayer).getSelection();
477
        // Extraigo todos los elementos de la capa o solo los seleccionados
478
        //if (!((JCheckBox)component).isSelected()) {
479
        if (!selected) {
480
            VectorialAdapter va = (VectorialAdapter)((SingleLayer)bufferingLayer).getSource();
481
            fBitSet = new FBitSet();
482
            try {
483
                for (int i=0;i<va.getShapeCount();i++) {
484
                   fBitSet.set(i);
485
                }
486
            } catch (DriverIOException e) {
487
                // TODO Auto-generated catch block
488
                e.printStackTrace();
489
            }
490
            ((Selectable)bufferingLayer).setSelection(fBitSet);
491
        }
492
        SelectedShapeToJTSVisitor visitor = new SelectedShapeToJTSVisitor();
493
        try {
494
            ((VectorialData)bufferingLayer).process(visitor);
495
        } catch (DriverException e1) {
496
            // TODO Auto-generated catch block
497
            e1.printStackTrace();
498
        } catch (VisitException e1) {
499
            // TODO Auto-generated catch block
500
            e1.printStackTrace();
501
        }
502
        // Si no hab?an elementos seleccionados, cambio la selecci?n temporal
503
        // completa actual por la original selecci?n nula
504
        if (!selected) ((Selectable)bufferingLayer).clearSelection();
505
        // Almaceno en un vector los elementos para el buffer
506
        return visitor.getJtsGeometries();
507
    }
508
    private IGeometry[] getFmapGeometries(Geometry[] jtsGeometries) {
509
        FShape[] shapes = new FShape[jtsGeometries.length];
510
        IGeometry[] geoms = new IGeometry[jtsGeometries.length];
511
        for (int i=0;i<jtsGeometries.length;i++) {
512
            if (jtsGeometries[i] instanceof MultiPoint) {
513
                double[] xcoords = new double[jtsGeometries[i].getNumGeometries()];
514
                double[] ycoords = new double[jtsGeometries[i].getNumGeometries()];
515
                for (int j=0;j<jtsGeometries[i].getNumGeometries();j++) {
516
                    xcoords[j] = ((Point)jtsGeometries[i].getGeometryN(j)).getX();
517
                    ycoords[j] = ((Point)jtsGeometries[i].getGeometryN(j)).getY();
518
                }
519
                geoms[i] = ShapeFactory.createMultipoint2D(xcoords, ycoords);
520
            } else {
521
                shapes[i] = FConverter.jts_to_java2d(jtsGeometries[i]);
522
                geoms[i] = ShapeFactory.createGeometry(shapes[i]);
523
            }
524
        }
525
        return geoms;
526
    }
527
    private void bufferMethod() {
528
        String bufferingLayerName = (String)((JComboBox)geoProcessingBufferPanel.getComponent(2)).getSelectedItem();
529
        // TODO: Provisional. Hasta que Fernando le meta PKs al resto de ficheros.
530
        //System.out.println("bufferingLayerName = " + bufferingLayerName);
531
        boolean isDbfFile = false;
532
        if (bufferingLayerName.endsWith(".shp") || bufferingLayerName.endsWith(".SHP")) isDbfFile = true;
533
        FLayer bufferingLayer = layers.getLayer(bufferingLayerName);
534
        boolean selected = false;
535
        if (((JCheckBox)geoProcessingBufferPanel.getComponent(3)).isSelected()) selected = true;
536
        Geometry[] geometries = getJtsGeometries(bufferingLayer, selected);
537
        IGeometry[] shapes = null;
538
        boolean dissolveBuffer = false;
539
        // Realizo el buffer llamando al metodo makeBuffer de GeoProcessingTopologyOperations
540
        if (((JRadioButton)geoProcessingBufferPanel.getComponent(4)).isSelected()) {
541
            //dissolveBuffer = true;
542
            double bufferDistance = Double.parseDouble(((JTextField)geoProcessingBufferPanel.getComponent(7)).getText());
543
            if (((JCheckBox)geoProcessingBufferPanel.getComponent(13)).isSelected()) {
544
                dissolveBuffer = true;
545
                Geometry jtsBuffer = GeoProcessingTopologyOperations.makeDissolveBuffer(geometries, bufferDistance, getQuadrantSegments());
546
                // Realizo las operaciones relacionadas con tablas que el buffer requiere llamando a los m?todos convenientes de GeoProcessingTableOperations
547
                // (A lo mejor este paso no es necesario) Convierto las tablas modificadas y las nuevas entidades JTS al modelo de gvSIG
548
                System.out.println("jtsBuffer = " + jtsBuffer);
549
                FPolygon2D shapeBuffer = (FPolygon2D)FConverter.jts_to_java2d(jtsBuffer);
550
                System.out.println("shapeBuffer = " + shapeBuffer);
551
                shapes = new IGeometry[]{ShapeFactory.createGeometry(shapeBuffer)};
552
                // Guardo la tabla mediante gdbms. Guardo tambi?n las entidades JTS mediante gvSIG o usando solo gdbms (probablemente bastar? con usar gdbms)
553
                // Con dissolve. Habr? que hacer una tabla para un ?nico pol?gono o
554
                // multipol?gono. En la tabla solo meteremos los campos para los
555
                // que todos los elementos tengan atributos comunes. Si no hay
556
                // ning?n campo con estas caracter?sticas crearemos la tabla en
557
                // blanco.
558
            } else {
559
                double[] bufferDistances = new double[geometries.length];
560
                for (int i=0;i<bufferDistances.length;i++) {
561
                    bufferDistances[i] = bufferDistance;
562
                }
563
                Geometry[] jtsBuffers = GeoProcessingTopologyOperations.makeBuffers(geometries, bufferDistances, getQuadrantSegments());
564
                // Realizo las operaciones relacionadas con tablas que el buffer requiere llamando a los m?todos convenientes de GeoProcessingTableOperations
565
                // (A lo mejor este paso no es necesario) Convierto las tablas modificadas y las nuevas entidades JTS al modelo de gvSIG
566
                shapes = getFmapGeometries(jtsBuffers);
567
                // Guardo la tabla mediante gdbms. Guardo tambi?n las entidades JTS mediante gvSIG o usando solo gdbms (probablemente bastar? con usar gdbms)
568
                // En este caso se guarda una tabla semejante a la del tema de entrada
569
                // solo que ahora los atributos se corresponden con los buffers
570
                // producidos por las entidades a las que correspond?an estos
571
                // atributos.
572
            }
573
        } else if (((JRadioButton)geoProcessingBufferPanel.getComponent(5)).isSelected()) {
574
            //dissolveBuffer = false;
575
            double[] bufferDistances = getBufferDistancesFromTable(bufferingLayer);
576
            if (((JCheckBox)geoProcessingBufferPanel.getComponent(13)).isSelected()) {
577
                dissolveBuffer = true;
578
                // Aqu? hay problemas ... Con distintas distancias y haciendo dissolve ...
579
                Geometry jtsBuffer = GeoProcessingTopologyOperations.makeDissolveBuffer(geometries, bufferDistances, getQuadrantSegments());
580
                // Realizo las operaciones relacionadas con tablas que el buffer requiere llamando a los m?todos convenientes de GeoProcessingTableOperations
581
                // (A lo mejor este paso no es necesario) Convierto las tablas modificadas y las nuevas entidades JTS al modelo de gvSIG
582
                System.out.println("jtsBuffer = " + jtsBuffer);
583
                FPolygon2D shapeBuffer = (FPolygon2D)FConverter.jts_to_java2d(jtsBuffer);
584
                System.out.println("shapeBuffer = " + shapeBuffer);
585
                shapes = new IGeometry[]{ShapeFactory.createGeometry(shapeBuffer)};
586
                // Guardo la tabla mediante gdbms. Guardo tambi?n las entidades JTS mediante gvSIG o usando solo gdbms (probablemente bastar? con usar gdbms)
587
            } else {
588
                Geometry[] jtsBuffers = GeoProcessingTopologyOperations.makeBuffers(geometries, bufferDistances, getQuadrantSegments());
589
                // Realizo las operaciones relacionadas con tablas que el buffer requiere llamando a los m?todos convenientes de GeoProcessingTableOperations
590
                // (A lo mejor este paso no es necesario) Convierto las tablas modificadas y las nuevas entidades JTS al modelo de gvSIG
591
                shapes = getFmapGeometries(jtsBuffers);
592
                // Guardo la tabla mediante gdbms. Guardo tambi?n las entidades JTS mediante gvSIG o usando solo gdbms (probablemente bastar? con usar gdbms)
593
            }
594
        }
595
        AlphanumericData lyr = (AlphanumericData)(layers.getLayer(geoProcessingBufferPanel.getSelectedLayerName()));
596
        GeoProcessingPersistenceOperations.saveResultsToShapeFile(shapes, geoProcessingBufferPanel.getOutputFile());
597
        try {
598
            // TODO: Provisional. Hasta que Fernando le meta PKs al resto de ficheros.
599
            GeoProcessingTableOperations.saveBufferResultsToDbaseFile(geoProcessingBufferPanel.getOutputFile(), lyr, dissolveBuffer, isDbfFile);
600
        } catch (IncompatibleTypesException e) {
601
            // TODO Auto-generated catch block
602
            e.printStackTrace();
603
        } catch (DriverException e) {
604
            // TODO Auto-generated catch block
605
            e.printStackTrace();
606
        } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
607
            // TODO Auto-generated catch block
608
            e.printStackTrace();
609
        } catch (DriverLoadException e) {
610
            // TODO Auto-generated catch block
611
            e.printStackTrace();
612
        } catch (NoSuchTableException e) {
613
            // TODO Auto-generated catch block
614
            e.printStackTrace();
615
        }
616
        if (!((JCheckBox)geoProcessingBufferPanel.getComponent(3)).isSelected()) ((Selectable)bufferingLayer).clearSelection();
617
    }
618
    private void mergeMethod() {
619
        Object[] layerNamesToMerge = geoProcessingMergePanel.getLayerSelectedNames();
620
        String fieldsFromLayerName = geoProcessingMergePanel.getFieldsFromLayerName();
621
        // TODO: Provisional. Hasta que Fernando le meta PKs al resto de ficheros.
622
        boolean isDbfFile = false;
623
        if (fieldsFromLayerName.endsWith(".shp") || fieldsFromLayerName.endsWith(".SHP")) isDbfFile = true;
624
        AlphanumericData lyr = (AlphanumericData)layers.getLayer(fieldsFromLayerName);
625
        FLayer[] layersToMerge = new FLayer[layerNamesToMerge.length];
626
        boolean[] selecteds = new boolean[layersToMerge.length];
627
        Vector allGeometriesToMerge = new Vector();
628
        for (int i=0;i<layerNamesToMerge.length;i++) {
629
            layersToMerge[i] = layers.getLayer((String)layerNamesToMerge[i]);
630
            if (!((Selectable)layersToMerge[i]).getSelection().isEmpty()) selecteds[i] = true;
631
            Geometry[] geometriesToMerge = getJtsGeometries(layersToMerge[i], selecteds[i]);
632
            for (int j=0;j<geometriesToMerge.length;j++) {
633
                allGeometriesToMerge.add(geometriesToMerge[j]);
634
            }
635
        }
636
        Geometry[] mergedGeometries = new Geometry[allGeometriesToMerge.size()];
637
        for (int i=0;i<allGeometriesToMerge.size();i++) {
638
            mergedGeometries[i] = (Geometry)allGeometriesToMerge.get(i);
639
        }
640
        IGeometry[] shapes = getFmapGeometries(mergedGeometries);
641
        AlphanumericData[] lyrs = new AlphanumericData[layersToMerge.length];
642
        for (int i=0;i<layersToMerge.length;i++) {
643
            lyrs[i] = (AlphanumericData)layersToMerge[i];
644
        }
645
        // Pasarle tb la capa con los campos.
646
        GeoProcessingPersistenceOperations.saveResultsToShapeFile(shapes, geoProcessingMergePanel.getOutputFile());
647
        try {
648
            GeoProcessingTableOperations.saveMergeResultsToDbaseFile(geoProcessingMergePanel.getOutputFile(), lyrs, lyr, isDbfFile);
649
            for (int i=0;i<lyrs.length;i++) {
650
                lyrs[i].getRecordset().getSelection().clear();
651
            }
652
        } catch (IncompatibleTypesException e) {
653
            // TODO Auto-generated catch block
654
            e.printStackTrace();
655
        } catch (DriverException e) {
656
            // TODO Auto-generated catch block
657
            e.printStackTrace();
658
        } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
659
            // TODO Auto-generated catch block
660
            e.printStackTrace();
661
        } catch (DriverLoadException e) {
662
            // TODO Auto-generated catch block
663
            e.printStackTrace();
664
        } catch (NoSuchTableException e) {
665
            // TODO Auto-generated catch block
666
            e.printStackTrace();
667
        }
668
    }
669
    private void dissolveMethod() {
670
        String layerToDissolveName = (String)((JComboBox)geoProcessingDissolvePanel.getComponent(2)).getSelectedItem();
671
        FLayer layerToDissolve = layers.getLayer(layerToDissolveName);
672
        boolean selected = false;
673
        if (((JCheckBox)geoProcessingDissolvePanel.getComponent(3)).isSelected()) selected = true;
674
        Geometry[] geometriesToDissolve = getJtsGeometries(layerToDissolve, selected);
675
        String dissolveAttributeName = (String)((JComboBox)geoProcessingDissolvePanel.getComponent(5)).getSelectedItem();
676
        AlphanumericData lyr = (AlphanumericData)layerToDissolve;
677
        // No lo puedo llevar a GeoProcessingTopologyOperations porque no es solo
678
        // un problema JTS. Tampoco lo puedo llevar a GeoProcessingTableOperations
679
        // porque tampoco es un problema solo de GDBMS. Es mixto y por el momento
680
        // se queda aqu?.
681
        Vector resultGeometries = new Vector(); 
682
        DataSource ds;
683
        SelectableDataSource sds;
684
        try {
685
            ds = lyr.getRecordset();
686
            sds = lyr.getRecordset();
687
            int fieldId = ds.getFieldIndexByName(dissolveAttributeName);
688
            FBitSet fBitSet = sds.getSelection();
689
            if (fBitSet.cardinality()==0) fBitSet.set(0, (int)lyr.getRecordset().getRowCount());
690
            Value[] fieldValues = new Value[sds.getSelection().cardinality()];
691
            int k=0;
692
            for (int i=0;i<ds.getRowCount();i++) {
693
                if (fBitSet.get(i)) {
694
                    fieldValues[k] = ds.getFieldValue(i, fieldId);
695
                    k++;
696
                }
697
            }
698
            for (int i=0;i<fieldValues.length;i++) {
699
                Value valuei = fieldValues[i];
700
                Geometry geometryi = geometriesToDissolve[i];
701
                for (int j=0;j<fieldValues.length;j++) {
702
                    if (j!=i) {
703
                        Value valuej = fieldValues[j];
704
                        if (((BooleanValue)(valuej.equals(valuei))).getValue()) {
705
                            Geometry geometryj = geometriesToDissolve[j];
706
                                geometryi = geometryj.union(geometryi);
707
                        }
708
                    }
709
                }
710
                resultGeometries.add(geometryi);
711
            }
712
            for (int i=0;i<resultGeometries.size();i++) {
713
                for (int j=0;j<resultGeometries.size();j++) {
714
                    if (j>i) {
715
                        if (((Geometry)resultGeometries.get(i)).equals((Geometry)resultGeometries.get(j))) {
716
                            resultGeometries.remove(j);
717
                            j--;
718
                        }
719
                    }
720
                }
721
            }
722
        } catch (DriverException e) {
723
            // TODO Auto-generated catch block
724
            e.printStackTrace();
725
        } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
726
            // TODO Auto-generated catch block
727
            e.printStackTrace();
728
        } catch (IncompatibleTypesException e) {
729
            // TODO Auto-generated catch block
730
            e.printStackTrace();
731
        }
732
        Geometry[] dissolvedGeometries = new Geometry[resultGeometries.size()];
733
        for (int i=0;i<resultGeometries.size();i++) {
734
            dissolvedGeometries[i] = (Geometry)resultGeometries.get(i);
735
        }
736
        //
737
        //Geometry[] dissolvedGeometries = GeoProcessingTopologyOperations.makeDissolve(geometriesToDissolve, lyr, dissolveAttributeName);
738
        IGeometry[] shapes = getFmapGeometries(dissolvedGeometries);
739
        // Guardo la tabla mediante gdbms. Guardo tambi?n las entidades JTS mediante gvSIG o usando solo gdbms (probablemente bastar? con usar gdbms)
740
        GeoProcessingPersistenceOperations.saveResultsToShapeFile(shapes, geoProcessingDissolvePanel.getOutputFile());
741
        try {
742
            GeoProcessingTableOperations.saveDissolveResultsToDbaseFile(geoProcessingDissolvePanel.getOutputFile(), lyr, dissolveAttributeName);
743
            lyr.getRecordset().getSelection().clear();
744
        } catch (IncompatibleTypesException e) {
745
            // TODO Auto-generated catch block
746
            e.printStackTrace();
747
        } catch (DriverException e) {
748
            // TODO Auto-generated catch block
749
            e.printStackTrace();
750
        } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
751
            // TODO Auto-generated catch block
752
            e.printStackTrace();
753
        } catch (DriverLoadException e) {
754
            // TODO Auto-generated catch block
755
            e.printStackTrace();
756
        } catch (NoSuchTableException e) {
757
            // TODO Auto-generated catch block
758
            e.printStackTrace();
759
        }
760
    }
761
    private void spatialjoinMethod() {
762
        String layerToJoinName = (String)((JComboBox)geoProcessingSpatialjoinPanel.getComponent(0)).getSelectedItem();
763
        FLayer layerToJoin = layers.getLayer(layerToJoinName);
764
        String joiningLayerName = (String)((JComboBox)geoProcessingSpatialjoinPanel.getComponent(3)).getSelectedItem();
765
        FLayer joiningLayer = layers.getLayer(joiningLayerName);
766
        boolean selected = false;
767
        try {
768
            if (((JCheckBox)geoProcessingSpatialjoinPanel.getComponent(1)).isSelected()) selected = true;
769
            Geometry[] geometriesToJoin = getJtsGeometries(layerToJoin, selected);
770
            AlphanumericData lyrToJoin = (AlphanumericData)layerToJoin;
771
            SelectableDataSource lyrToJoinSDS = lyrToJoin.getRecordset();
772
            FBitSet bitsetToJoin = lyrToJoinSDS.getSelection();
773
            if (bitsetToJoin.cardinality()==0) bitsetToJoin.set(0, (int)lyrToJoin.getRecordset().getRowCount());
774
            if (((JCheckBox)geoProcessingSpatialjoinPanel.getComponent(5)).isSelected()) selected = true;
775
            Geometry[] joiningGeometries = getJtsGeometries(joiningLayer, selected);
776
            AlphanumericData joiningLyr = (AlphanumericData)joiningLayer;
777
            SelectableDataSource joiningLyrSDS = joiningLyr.getRecordset();
778
            FBitSet joiningBitset = joiningLyrSDS.getSelection();
779
            if (joiningBitset.cardinality()==0) joiningBitset.set(0, (int)joiningLyr.getRecordset().getRowCount());
780
            DataSource lyrToJoinDS;
781
            DataSource joiningLyrDS;
782
            lyrToJoinDS = lyrToJoin.getRecordset();
783
            joiningLyrDS = joiningLyr.getRecordset();
784
            // Los campos se a?aden siempre. Los valores solo cuando toca ...
785
            String[] lyrToJoinFieldNames = new String[lyrToJoinDS.getFieldCount()];
786
            int[] lyrToJoinFieldTypes = new int[lyrToJoinDS.getFieldCount()];
787
            for (int i = 0; i < lyrToJoinDS.getFieldCount(); i++) {
788
                lyrToJoinFieldNames[i] = lyrToJoinDS.getFieldName(i);
789
                lyrToJoinFieldTypes[i] = lyrToJoinDS.getFieldType(i);
790
            }
791
            String[] joiningLyrFieldNames = new String[joiningLyrDS.getFieldCount()];
792
            int[] joiningLyrFieldTypes = new int[joiningLyrDS.getFieldCount()];
793
            for (int i = 0; i < joiningLyrDS.getFieldCount(); i++) {
794
                joiningLyrFieldNames[i] = joiningLyrDS.getFieldName(i);
795
                joiningLyrFieldTypes[i] = joiningLyrDS.getFieldType(i);
796
            }
797
            String[] joinedLyrFieldNames = new String[lyrToJoinDS.getFieldCount()+joiningLyrDS.getFieldCount()-2]; // Le quito los dos PKs
798
            int[] joinedLyrFieldTypes = new int[lyrToJoinDS.getFieldCount()+joiningLyrDS.getFieldCount()-2];
799
            int l=0;
800
            for (int i=0;i<lyrToJoinFieldNames.length-1;i++) {
801
                joinedLyrFieldNames[i] = lyrToJoinFieldNames[i];
802
                joinedLyrFieldTypes[i] = lyrToJoinFieldTypes[i];
803
                l++;
804
            }
805
            for (int i=0;i<joiningLyrFieldNames.length-1;i++) {
806
                joinedLyrFieldNames[i+l] = joiningLyrFieldNames[i];
807
                joinedLyrFieldTypes[i+l] = joiningLyrFieldTypes[i];
808
            }
809
            DataSourceFactory dsf = lyrToJoinSDS.getDataSourceFactory();
810
            File file = geoProcessingSpatialjoinPanel.getOutputFile();
811
            dsf.createFileDataSource("gdbms dbf driver", "new_table", file.getAbsolutePath().replaceAll(".shp", ".dbf"), joinedLyrFieldNames, joinedLyrFieldTypes);
812
            DataSource ds = dsf.createRandomDataSource("new_table");
813
            ds.start();
814
            DataWare dw = ds.getDataWare(DataSourceFactory.MANUAL_OPENING);
815
            dw.beginTrans();
816
            ds.stop();
817
            lyrToJoinDS.stop();
818
            joiningLyrDS.stop();
819
            lyrToJoinSDS.stop();
820
            joiningLyrSDS.stop();
821
            
822
            // Recorrer las geometr?as buscando las que intersectan. No porque
823
            // por ejemplo los puntos no intersectan ...
824
            // Ver de que combinaci?n se trata y calcular nearest, part of o inside
825
            // seg?n corresponda.
826
            // Si intersecta copiarle los atributos. O sea rellenar Values como
827
            // toque ...
828
            Value[][] values = new Value[geometriesToJoin.length][joinedLyrFieldNames.length+1]; // +1 porque faltaba el PK
829
            // Movida para el nearest entre puntos
830
            //Point[] joiningPoints = new Point[joiningGeometries.length];
831
            Geometry[] joiningGeometrySet = new Geometry[joiningGeometries.length];
832
            /*for (int i=0;i<joiningGeometries.length;i++) {
833
                joiningPoints[i] = (Point)joiningGeometries[i];
834
            }*/
835
            for (int i=0;i<joiningGeometries.length;i++) {
836
                joiningGeometrySet[i] = (Geometry)joiningGeometries[i];
837
            }
838
            //MultiPoint joiningMultiPoint = new MultiPoint(joiningPoints, new GeometryFactory());
839
            GeometryCollection joiningGeometryCollection = new GeometryCollection(joiningGeometrySet, new GeometryFactory());
840
            for (int i=0;i<geometriesToJoin.length;i++) {
841
                Geometry geometryToJoin = geometriesToJoin[i];
842
                // Movida para el nearest entre puntos
843
                //Coordinate[] coords = DistanceOp.closestPoints(geometryToJoin, joiningMultiPoint);
844
                Coordinate[] coords = DistanceOp.closestPoints(geometryToJoin, joiningGeometryCollection);
845
                for (int j=0;j<joiningGeometries.length;j++) {
846
                    Geometry joiningGeometry = joiningGeometries[j];
847
                    if (geometryToJoin instanceof Point && joiningGeometry instanceof Point) {
848
                        // Rellenar el PK. Lo tengo que hacer antes del break
849
                        values[i][joinedLyrFieldNames.length] = ValueFactory.createValue(i);
850
                        for (int k=0;k<lyrToJoinFieldNames.length-1;k++) {
851
                            values[i][k] = lyrToJoinDS.getFieldValue(i, k);
852
                        }
853
                        if (coords[1].equals2D(joiningGeometry.getCoordinate())) {
854
                            for (int k=0;k<joiningLyrFieldNames.length-1;k++) {
855
                                values[i][k+l] = joiningLyrDS.getFieldValue(j, k);
856
                            }
857
                            break; // En el momento encontremos un pol?gono que contiene a otro le metemos los valores y nos vamos
858
                        } else {
859
                            for (int k=0;k<joiningLyrFieldNames.length-1;k++) {
860
                                values[i][k+l] = ValueFactory.createNullValue();
861
                            }
862
                        }
863
                    } else if (geometryToJoin instanceof Point && joiningGeometry instanceof LineString) {
864
                        // part of not supported yet
865
                    } else if (geometryToJoin instanceof Point && joiningGeometry instanceof Polygon) {
866
                        // Rellenar el PK. Lo tengo que hacer antes del break
867
                        values[i][joinedLyrFieldNames.length] = ValueFactory.createValue(i);
868
                        for (int k=0;k<lyrToJoinFieldNames.length-1;k++) {
869
                            values[i][k] = lyrToJoinDS.getFieldValue(i, k);
870
                        }
871
                        if (joiningGeometry.contains(geometryToJoin)) {
872
                            for (int k=0;k<joiningLyrFieldNames.length-1;k++) {
873
                                System.out.println(i);
874
                                values[i][k+l] = joiningLyrDS.getFieldValue(j, k);
875
                            }
876
                            break; // En el momento encontremos un pol?gono que contiene a otro le metemos los valores y nos vamos
877
                        } else {
878
                            for (int k=0;k<joiningLyrFieldNames.length-1;k++) {
879
                                values[i][k+l] = ValueFactory.createNullValue();
880
                            }
881
                        }
882
                    } else if (geometryToJoin instanceof LineString && joiningGeometry instanceof Point) {
883
                        // Rellenar el PK. Lo tengo que hacer antes del break
884
                        values[i][joinedLyrFieldNames.length] = ValueFactory.createValue(i);
885
                        for (int k=0;k<lyrToJoinFieldNames.length-1;k++) {
886
                            values[i][k] = lyrToJoinDS.getFieldValue(i, k);
887
                        }
888
                        if (coords[1].equals2D(joiningGeometry.getCoordinate())) {
889
                            for (int k=0;k<joiningLyrFieldNames.length-1;k++) {
890
                                values[i][k+l] = joiningLyrDS.getFieldValue(j, k);
891
                            }
892
                            break; // En el momento encontremos un pol?gono que contiene a otro le metemos los valores y nos vamos
893
                        } else {
894
                            for (int k=0;k<joiningLyrFieldNames.length-1;k++) {
895
                                values[i][k+l] = ValueFactory.createNullValue();
896
                            }
897
                        }
898
                    } else if (geometryToJoin instanceof LineString && joiningGeometry instanceof LineString) {
899
                        // Rellenar el PK. Lo tengo que hacer antes del break
900
                        values[i][joinedLyrFieldNames.length] = ValueFactory.createValue(i);
901
                        for (int k=0;k<lyrToJoinFieldNames.length-1;k++) {
902
                            values[i][k] = lyrToJoinDS.getFieldValue(i, k);
903
                        }
904
                        //if (coords[1].equals2D(joiningGeometry.getCoordinate())) {
905
                        if (joiningGeometry.contains(geometryToJoin) || geometryToJoin.contains(joiningGeometry)) {
906
                            for (int k=0;k<joiningLyrFieldNames.length-1;k++) {
907
                                values[i][k+l] = joiningLyrDS.getFieldValue(j, k);
908
                            }
909
                            break; // En el momento encontremos un pol?gono que contiene a otro le metemos los valores y nos vamos
910
                        } else {
911
                            for (int k=0;k<joiningLyrFieldNames.length-1;k++) {
912
                                values[i][k+l] = ValueFactory.createNullValue();
913
                            }
914
                        }
915
                    } else if (geometryToJoin instanceof LineString && joiningGeometry instanceof Polygon) {
916
                        // Rellenar el PK. Lo tengo que hacer antes del break
917
                        values[i][joinedLyrFieldNames.length] = ValueFactory.createValue(i);
918
                        for (int k=0;k<lyrToJoinFieldNames.length-1;k++) {
919
                            values[i][k] = lyrToJoinDS.getFieldValue(i, k);
920
                        }
921
                        if (joiningGeometry.contains(geometryToJoin)) {
922
                            for (int k=0;k<joiningLyrFieldNames.length-1;k++) {
923
                                values[i][k+l] = joiningLyrDS.getFieldValue(j, k);
924
                            }
925
                            break; // En el momento encontremos un pol?gono que contiene a otro le metemos los valores y nos vamos
926
                        } else {
927
                            for (int k=0;k<joiningLyrFieldNames.length-1;k++) {
928
                                values[i][k+l] = ValueFactory.createNullValue();
929
                            }
930
                        }
931
                    } else if (geometryToJoin instanceof Polygon && joiningGeometry instanceof Point) {
932
                        // nearest not supported yet
933
                    } else if (geometryToJoin instanceof Polygon && joiningGeometry instanceof LineString) {
934
                        // nearest not supported yet
935
                    } else if (geometryToJoin instanceof Polygon && joiningGeometry instanceof Polygon) {
936
                        // Rellenar el PK. Lo tengo que hacer antes del break
937
                        values[i][joinedLyrFieldNames.length] = ValueFactory.createValue(i);
938
                        for (int k=0;k<lyrToJoinFieldNames.length-1;k++) {
939
                            values[i][k] = lyrToJoinDS.getFieldValue(i, k);
940
                        }
941
                        if (joiningGeometry.contains(geometryToJoin)) {
942
                            for (int k=0;k<joiningLyrFieldNames.length-1;k++) {
943
                                values[i][k+l] = joiningLyrDS.getFieldValue(j, k);
944
                            }
945
                            break; // En el momento encontremos un pol?gono que contiene a otro le metemos los valores y nos vamos
946
                        } else {
947
                            for (int k=0;k<joiningLyrFieldNames.length-1;k++) {
948
                                values[i][k+l] = ValueFactory.createNullValue();
949
                            }
950
                        }
951
                    } else {
952
                        // MultiPoint, LineSegment, LinearRing, MultiLineString, MultiPolygon faltan
953
                        // por implementar ...
954
                    }
955
                }
956
            }
957
            for (int i=0;i<lyrToJoinSDS.getSelection().cardinality();i++) {
958
                dw.insertFilledRow(values[i]);
959
            }
960
            /*for (int i=0;i<lyrToJoinDS.getRowCount();i++) {
961
                dw.insertFilledRow(values[i]);
962
            }*/
963
            dw.commitTrans();
964
            IGeometry[] shapes = getFmapGeometries(geometriesToJoin);
965
            // Guardo la tabla mediante gdbms. Guardo tambi?n las entidades JTS mediante gvSIG o usando solo gdbms (probablemente bastar? con usar gdbms)
966
            // Guardar las viejas geometr?as.
967
            GeoProcessingPersistenceOperations.saveResultsToShapeFile(shapes, geoProcessingSpatialjoinPanel.getOutputFile());
968
            //lyrToJoinSDS.getSelection().clear();
969
            //joiningLyrSDS.getSelection().clear();
970
            lyrToJoinSDS.setSelection(new FBitSet());
971
            joiningLyrSDS.setSelection(new FBitSet());
972
        } catch (DriverException e) {
973
            // TODO Auto-generated catch block
974
            e.printStackTrace();
975
        } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
976
            // TODO Auto-generated catch block
977
            e.printStackTrace();
978
        } catch (DriverLoadException e) {
979
            // TODO Auto-generated catch block
980
            e.printStackTrace();
981
        } catch (NoSuchTableException e) {
982
            // TODO Auto-generated catch block
983
            e.printStackTrace();
984
        }
985
    }
986
    // clip: intersect + dissolve
987
    private void clipMethod() {
988
        String layerToClipName = (String)((JComboBox)geoProcessingClipPanel.getComponent(0)).getSelectedItem();
989
        FLayer layerToClip = layers.getLayer(layerToClipName);
990
        boolean selected = false;
991
        //if (((JCheckBox)geoProcessingClipPanel.getComponent(1)).isSelected()) selected = true;
992
        Geometry[] geometriesToClip = getJtsGeometries(layerToClip, selected);
993
        String clippingLayerName = (String)((JComboBox)geoProcessingClipPanel.getComponent(3)).getSelectedItem();
994
        FLayer clippingLayer = layers.getLayer(clippingLayerName);
995
        //if (((JCheckBox)geoProcessingClipPanel.getComponent(5)).isSelected()) selected = true;
996
        Geometry[] clippingGeometries = getJtsGeometries(clippingLayer, selected);
997
        AlphanumericData lyr = (AlphanumericData)layerToClip;
998
        SelectableDataSource sds;
999
        try {
1000
            DataSource ds;
1001
            ds = lyr.getRecordset();
1002
            sds = lyr.getRecordset();
1003
            // Tener en cuenta que podemos estar trabajando solo con una selecci?n
1004
            //FBitSet fBitSet = ((Selectable)lyr).getSelection();
1005
            String[] fieldNames = new String[sds.getFieldCount()-1];
1006
            int[] fieldTypes = new int[sds.getFieldCount()-1];
1007
            for (int i = 0; i < sds.getFieldCount()-1; i++) {
1008
                fieldNames[i] = sds.getFieldName(i);
1009
                fieldTypes[i] = sds.getFieldType(i);
1010
            }
1011
            DataSourceFactory dsf = sds.getDataSourceFactory();
1012
            File file = geoProcessingClipPanel.getOutputFile();
1013
            dsf.createFileDataSource("gdbms dbf driver", "new_table", file.getAbsolutePath().replaceAll(".shp", ".dbf"), fieldNames, fieldTypes);
1014
            DataSource dataSource = dsf.createRandomDataSource("new_table");
1015
            dataSource.start();
1016
            DataWare dw = dataSource.getDataWare(DataSourceFactory.MANUAL_OPENING);
1017
            dw.beginTrans();
1018
            Vector values = new Vector();
1019
            Vector geometriesClipped = new Vector();
1020
            for (int i=0;i<geometriesToClip.length;i++) {
1021
                Geometry geometryToClip = geometriesToClip[i];
1022
                for (int j=0;j<clippingGeometries.length;j++) {
1023
                    Geometry clippingGeometry = clippingGeometries[j];
1024
                    if (clippingGeometry.intersects(geometryToClip)) {
1025
                        geometriesClipped.add(geometryToClip.intersection(clippingGeometry));
1026
                        Value[] row = new Value[fieldNames.length+1]; // +1 porque faltaba el PK
1027
                        for (int m=0;m<fieldNames.length;m++) {
1028
                            row[m] = ds.getFieldValue(i, m);
1029
                        }
1030
                        row[fieldNames.length] = ValueFactory.createValue(i);
1031
                        values.add(row);
1032
                    }
1033
                }
1034
            }
1035
            // Al meter rowj.length en vez de rowj.length-1 se anula esta parte
1036
            /*Vector resultGeometries = new Vector();
1037
            for (int i=0;i<values.size();i++) {
1038
                Value[] rowi = ((Value[])values.get(i));
1039
                Geometry geometryi = ((Geometry)geometriesClipped.get(i));
1040
                for (int j=0;j<values.size();j++) {
1041
                    if (j>i) {
1042
                    //if (j!=i) {
1043
                        Value[] rowj = ((Value[])values.get(j));
1044
                        boolean areTheSameElement = true;
1045
                        //for (int k=0;k<rowj.length;k++) {
1046
                        for (int k=0;k<rowj.length-1;k++) {
1047
                            //Value valuei = ds.getFieldValue(i, k);
1048
                            //Value valuej = ds.getFieldValue(j, k);
1049
                            Value valuei = rowi[k];
1050
                            Value valuej = rowj[k];
1051
                            if (!((BooleanValue)(valuej.equals(valuei))).getValue()) {
1052
                                areTheSameElement = false;
1053
                                break;
1054
                            }
1055
                        }
1056
                        if (areTheSameElement) {
1057
                            Geometry geometryj = ((Geometry)geometriesClipped.get(j));
1058
                            geometryi = geometryj.union(geometryi);
1059
                            //values.remove(j); // igual esto peta ...
1060
                        }
1061
                    }
1062
                }
1063
                resultGeometries.add(geometryi);
1064
            }
1065
            for (int i=0;i<resultGeometries.size();i++) {
1066
                for (int j=0;j<resultGeometries.size();j++) {
1067
                    if (j>i) {
1068
                        if (((Geometry)resultGeometries.get(i)).contains((Geometry)resultGeometries.get(j))) resultGeometries.remove(j);
1069
                    }
1070
                }
1071
            }*/
1072
            Vector resultGeometries = new Vector();
1073
            for (int i=0;i<values.size();i++) {
1074
                //Value valuei = fieldValues[i];
1075
                Value[] rowi = ((Value[])values.get(i));
1076
                Geometry geometryi = ((Geometry)geometriesClipped.get(i));
1077
                for (int j=0;j<values.size();j++) {
1078
                    if (j!=i) {
1079
                        //Value valuej = fieldValues[j];
1080
                        Value[] rowj = ((Value[])values.get(j));
1081
                        /*if (((BooleanValue)(valuej.equals(valuei))).getValue()) {
1082
                            Geometry geometryj = geometriesToDissolve[j];
1083
                                geometryi = geometryj.union(geometryi);
1084
                        }*/
1085
                        boolean areTheSameElement = true;
1086
                        //for (int k=0;k<rowj.length;k++) {
1087
                        for (int k=0;k<rowj.length-1;k++) {
1088
                            Value valuei = rowi[k];
1089
                            Value valuej = rowj[k];
1090
                            if (!((BooleanValue)(valuej.equals(valuei))).getValue()) {
1091
                                areTheSameElement = false;
1092
                                break;
1093
                            }
1094
                        }
1095
                        if (areTheSameElement) {
1096
                            Geometry geometryj = ((Geometry)geometriesClipped.get(j));
1097
                            geometryi = geometryj.union(geometryi);
1098
                            //values.remove(j); // igual esto peta ...
1099
                        }
1100
                    }
1101
                }
1102
                resultGeometries.add(geometryi);
1103
            }
1104
            for (int i=0;i<resultGeometries.size();i++) {
1105
                for (int j=0;j<resultGeometries.size();j++) {
1106
                    if (j>i) {
1107
                        if (((Geometry)resultGeometries.get(i)).equals((Geometry)resultGeometries.get(j))) {
1108
                            resultGeometries.remove(j);
1109
                            j--;
1110
                        }
1111
                    }
1112
                }
1113
            }
1114
            //
1115
            /*for (int i=0;i<values.size();i++) {
1116
                Value[] rowi = ((Value[])values.get(i));
1117
                for (int j=0;j<values.size();j++) {
1118
                    if (j!=i) {
1119
                        Value[] rowj = ((Value[])values.get(j));
1120
                        boolean areTheSameElement = true;
1121
                        //for (int k=0;k<rowj.length;k++) {
1122
                        for (int k=0;k<rowj.length-1;k++) {
1123
                            Value valuei = rowi[k];
1124
                            Value valuej = rowj[k];
1125
                            if (!((BooleanValue)(valuej.equals(valuei))).getValue()) {
1126
                                areTheSameElement = false;
1127
                            }
1128
                        }
1129
                        if (areTheSameElement) {
1130
                            values.remove(j);
1131
                        }
1132
                    }
1133
                }
1134
            }*/
1135
            for (int i=0;i<values.size();i++) {
1136
                Value[] rowi = ((Value[])values.get(i));
1137
                for (int j=0;j<values.size();j++) {
1138
                    if (j>i) {
1139
                        Value[] rowj = ((Value[])values.get(j));
1140
                        boolean areTheSameElement = true;
1141
                        for (int k=0;k<rowj.length-1;k++) {
1142
                            Value valuei = rowi[k];
1143
                            Value valuej = rowj[k];
1144
                            if (!((BooleanValue)(valuej.equals(valuei))).getValue()) {
1145
                                areTheSameElement = false;
1146
                            }
1147
                        }
1148
                        if (areTheSameElement) {
1149
                            values.remove(j);
1150
                            j--;
1151
                        }
1152
                    }
1153
                }
1154
            }
1155
            //
1156
            Geometry[] dissolvedGeometries = new Geometry[resultGeometries.size()];
1157
            for (int i=0;i<resultGeometries.size();i++) {
1158
                dissolvedGeometries[i] = (Geometry)resultGeometries.get(i);
1159
            }
1160
            IGeometry[] shapes = getFmapGeometries(dissolvedGeometries);
1161
            Geometry[] clippedGeometries = new Geometry[geometriesClipped.size()];
1162
            for (int i=0;i<geometriesClipped.size();i++) {
1163
                clippedGeometries[i] = (Geometry)geometriesClipped.get(i);
1164
            }
1165
            GeoProcessingPersistenceOperations.saveResultsToShapeFile(shapes, geoProcessingClipPanel.getOutputFile());
1166
            dataSource.stop();
1167
            sds.stop();
1168
            ds.stop();
1169
            for (int i=0;i<values.size();i++) {
1170
                dw.insertFilledRow(((Value[])values.get(i)));
1171
            }
1172
            dw.commitTrans();
1173
        } catch (DriverException e) {
1174
            // TODO Auto-generated catch block
1175
            e.printStackTrace();
1176
        } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
1177
            // TODO Auto-generated catch block
1178
            e.printStackTrace();
1179
        } catch (DriverLoadException e) {
1180
            // TODO Auto-generated catch block
1181
            e.printStackTrace();
1182
        } catch (NoSuchTableException e) {
1183
            // TODO Auto-generated catch block
1184
            e.printStackTrace();
1185
        } catch (IncompatibleTypesException e) {
1186
            // TODO Auto-generated catch block
1187
            e.printStackTrace();
1188
        }
1189
    }
1190
    // Spatial join con Intersect
1191
    private void intersectMethod() {
1192
        String layerToIntersectName = (String)((JComboBox)geoProcessingIntersectPanel.getComponent(0)).getSelectedItem();
1193
        FLayer layerToIntersect = layers.getLayer(layerToIntersectName);
1194
        String intersectingLayerName = (String)((JComboBox)geoProcessingIntersectPanel.getComponent(3)).getSelectedItem();
1195
        FLayer intersectingLayer = layers.getLayer(intersectingLayerName);
1196
        boolean selected = false;
1197
        Geometry[] geometriesToIntersect = getJtsGeometries(layerToIntersect, selected);
1198
        Geometry[] intersectingGeometries = getJtsGeometries(intersectingLayer, selected);
1199
        try {
1200
            //if (((JCheckBox)geoProcessingIntersectPanel.getComponent(1)).isSelected()) selected = true;
1201
            AlphanumericData lyrToIntersect = (AlphanumericData)layerToIntersect;
1202
            SelectableDataSource lyrToIntersectSDS = lyrToIntersect.getRecordset();
1203
            //if (((JCheckBox)geoProcessingIntersectPanel.getComponent(5)).isSelected()) selected = true;
1204
            AlphanumericData intersectingLyr = (AlphanumericData)intersectingLayer;
1205
            DataSource lyrToIntersectDS;
1206
            DataSource intersectingLyrDS;
1207
            lyrToIntersectDS = lyrToIntersect.getRecordset();
1208
            intersectingLyrDS = intersectingLyr.getRecordset();
1209
            // Los campos se a?aden siempre. Los valores solo cuando toca ...
1210
            String[] lyrToIntersectFieldNames = new String[lyrToIntersectDS.getFieldCount()];
1211
            int[] lyrToIntersectFieldTypes = new int[lyrToIntersectDS.getFieldCount()];
1212
            for (int i = 0; i < lyrToIntersectDS.getFieldCount(); i++) {
1213
                lyrToIntersectFieldNames[i] = lyrToIntersectDS.getFieldName(i);
1214
                lyrToIntersectFieldTypes[i] = lyrToIntersectDS.getFieldType(i);
1215
            }
1216
            String[] intersectingLyrFieldNames = new String[intersectingLyrDS.getFieldCount()];
1217
            int[] intersectingLyrFieldTypes = new int[intersectingLyrDS.getFieldCount()];
1218
            for (int i = 0; i < intersectingLyrDS.getFieldCount(); i++) {
1219
                intersectingLyrFieldNames[i] = intersectingLyrDS.getFieldName(i);
1220
                intersectingLyrFieldTypes[i] = intersectingLyrDS.getFieldType(i);
1221
            }
1222
            String[] intersectedLyrFieldNames = new String[lyrToIntersectDS.getFieldCount()+intersectingLyrDS.getFieldCount()-2]; // Le quito los dos PKs
1223
            int[] intersectedLyrFieldTypes = new int[lyrToIntersectDS.getFieldCount()+intersectingLyrDS.getFieldCount()-2];
1224
            int l=0;
1225
            for (int i=0;i<lyrToIntersectFieldNames.length-1;i++) {
1226
                intersectedLyrFieldNames[i] = lyrToIntersectFieldNames[i];
1227
                intersectedLyrFieldTypes[i] = lyrToIntersectFieldTypes[i];
1228
                l++;
1229
            }
1230
            for (int i=0;i<intersectingLyrFieldNames.length-1;i++) {
1231
                intersectedLyrFieldNames[i+l] = intersectingLyrFieldNames[i];
1232
                intersectedLyrFieldTypes[i+l] = intersectingLyrFieldTypes[i];
1233
            }
1234
            DataSourceFactory dsf = lyrToIntersectSDS.getDataSourceFactory();
1235
            File file = geoProcessingIntersectPanel.getOutputFile();
1236
            dsf.createFileDataSource("gdbms dbf driver", "new_table", file.getAbsolutePath().replaceAll(".shp", ".dbf"), intersectedLyrFieldNames, intersectedLyrFieldTypes);
1237
            DataSource ds = dsf.createRandomDataSource("new_table");
1238
            ds.start();
1239
            DataWare dw = ds.getDataWare(DataSourceFactory.MANUAL_OPENING);
1240
            dw.beginTrans();
1241
            ds.stop();
1242
            // Si cierro no tendr? problemas a continuaci?n?
1243
            lyrToIntersectSDS.stop();
1244
            
1245
            Vector values = new Vector();
1246
            Vector geometriesIntersected = new Vector();
1247
            for (int i=0;i<geometriesToIntersect.length;i++) {
1248
                Geometry geometryToIntersect = geometriesToIntersect[i];
1249
                String geometryToIntersectType = geometryToIntersect.getGeometryType();
1250
                System.out.println("geometryToIntersectType = " + geometryToIntersectType);
1251
                for (int j=0;j<intersectingGeometries.length;j++) {
1252
                    Geometry intersectingGeometry = intersectingGeometries[j];
1253
                    if (intersectingGeometry.intersects(geometryToIntersect)) {
1254
                        geometriesIntersected.add(geometryToIntersect.intersection(intersectingGeometry));
1255
                        /*for (int m=0;m<intersectedLyrFieldNames.length;m++) {
1256
                            rows[m] = ds.getFieldValue(i, m);
1257
                        }*/
1258
                        Value[] rows = new Value[intersectedLyrFieldNames.length+1]; // +1 porque faltaba el PK
1259
                        for (int k=0;k<lyrToIntersectFieldNames.length-1;k++) {
1260
                            rows[k] = lyrToIntersectDS.getFieldValue(i, k);
1261
                        }
1262
                        for (int k=0;k<intersectingLyrFieldNames.length-1;k++) {
1263
                            rows[k+l] = intersectingLyrDS.getFieldValue(j, k);
1264
                        }
1265
                        rows[intersectedLyrFieldNames.length] = ValueFactory.createValue(i);
1266
                        values.add(rows);
1267
                    }
1268
                }
1269
            }
1270
            
1271
            for (int i=0;i<geometriesIntersected.size();i++) {
1272
                dw.insertFilledRow(((Value[])values.get(i)));
1273
            }
1274
            dw.commitTrans();
1275
            Geometry[] geometriesIntersectedArray = new Geometry[geometriesIntersected.size()];
1276
            for (int i=0;i<geometriesIntersected.size();i++) {
1277
                geometriesIntersectedArray[i] = (Geometry)geometriesIntersected.get(i);
1278
            }
1279
            IGeometry[] shapes = getFmapGeometries(geometriesIntersectedArray);
1280
            // Guardo la tabla mediante gdbms. Guardo tambi?n las entidades JTS mediante gvSIG o usando solo gdbms (probablemente bastar? con usar gdbms)
1281
            // Guardar las viejas geometr?as.
1282
            GeoProcessingPersistenceOperations.saveResultsToShapeFile(shapes, geoProcessingIntersectPanel.getOutputFile());
1283
        } catch (DriverException e) {
1284
            // TODO Auto-generated catch block
1285
            e.printStackTrace();
1286
        } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
1287
            // TODO Auto-generated catch block
1288
            e.printStackTrace();
1289
        } catch (DriverLoadException e) {
1290
            // TODO Auto-generated catch block
1291
            e.printStackTrace();
1292
        } catch (NoSuchTableException e) {
1293
            // TODO Auto-generated catch block
1294
            e.printStackTrace();
1295
        }
1296
    }
1297
    private void unionMethod() {
1298
        String layerToUnionName = (String)((JComboBox)geoProcessingUnionPanel.getComponent(0)).getSelectedItem();
1299
        FLayer layerToUnion = layers.getLayer(layerToUnionName);
1300
        boolean selected = false;
1301
        //if (((JCheckBox)geoProcessingUnionPanel.getComponent(1)).isSelected()) selected = true;
1302
        Geometry[] geometriesToUnion = getJtsGeometries(layerToUnion, selected);
1303
        String uningLayerName = (String)((JComboBox)geoProcessingUnionPanel.getComponent(3)).getSelectedItem();
1304
        FLayer uningLayer = layers.getLayer(uningLayerName);
1305
        //if (((JCheckBox)geoProcessingUnionPanel.getComponent(5)).isSelected()) selected = true;
1306
        Geometry[] uningGeometries = getJtsGeometries(uningLayer, selected);
1307
        
1308
        //if (((JCheckBox)geoProcessingIntersectPanel.getComponent(1)).isSelected()) selected = true;
1309
        AlphanumericData lyrToUnion = (AlphanumericData)layerToUnion;
1310
        SelectableDataSource lyrToUnionSDS;
1311
        try {
1312
            lyrToUnionSDS = lyrToUnion.getRecordset();
1313
            //if (((JCheckBox)geoProcessingIntersectPanel.getComponent(5)).isSelected()) selected = true;
1314
            AlphanumericData uningLyr = (AlphanumericData)uningLayer;
1315
            DataSource lyrToUnionDS;
1316
            DataSource uningLyrDS;
1317
            lyrToUnionDS = lyrToUnion.getRecordset();
1318
            uningLyrDS = uningLyr.getRecordset();
1319
            // Los campos se a?aden siempre. Los valores solo cuando toca ...
1320
            String[] lyrToUnionFieldNames = new String[lyrToUnionDS.getFieldCount()];
1321
            int[] lyrToUnionFieldTypes = new int[lyrToUnionDS.getFieldCount()];
1322
            for (int i = 0; i < lyrToUnionDS.getFieldCount(); i++) {
1323
                lyrToUnionFieldNames[i] = lyrToUnionDS.getFieldName(i);
1324
                lyrToUnionFieldTypes[i] = lyrToUnionDS.getFieldType(i);
1325
            }
1326
            String[] uningLyrFieldNames = new String[uningLyrDS.getFieldCount()];
1327
            int[] uningLyrFieldTypes = new int[uningLyrDS.getFieldCount()];
1328
            for (int i = 0; i < uningLyrDS.getFieldCount(); i++) {
1329
                uningLyrFieldNames[i] = uningLyrDS.getFieldName(i);
1330
                uningLyrFieldTypes[i] = uningLyrDS.getFieldType(i);
1331
            }
1332
            String[] unedLyrFieldNames = new String[lyrToUnionDS.getFieldCount()+uningLyrDS.getFieldCount()-2]; // Le quito los dos PKs
1333
            int[] unedLyrFieldTypes = new int[lyrToUnionDS.getFieldCount()+uningLyrDS.getFieldCount()-2];
1334
            int l=0;
1335
            for (int i=0;i<lyrToUnionFieldNames.length-1;i++) {
1336
                unedLyrFieldNames[i] = lyrToUnionFieldNames[i];
1337
                unedLyrFieldTypes[i] = lyrToUnionFieldTypes[i];
1338
                l++;
1339
            }
1340
            for (int i=0;i<uningLyrFieldNames.length-1;i++) {
1341
                unedLyrFieldNames[i+l] = uningLyrFieldNames[i];
1342
                unedLyrFieldTypes[i+l] = uningLyrFieldTypes[i];
1343
            }
1344
            DataSourceFactory dsf = lyrToUnionSDS.getDataSourceFactory();
1345
            File file = geoProcessingUnionPanel.getOutputFile();
1346
            dsf.createFileDataSource("gdbms dbf driver", "new_table", file.getAbsolutePath().replaceAll(".shp", ".dbf"), unedLyrFieldNames, unedLyrFieldTypes);
1347
            DataSource ds = dsf.createRandomDataSource("new_table");
1348
            ds.start();
1349
            DataWare dw = ds.getDataWare(DataSourceFactory.MANUAL_OPENING);
1350
            dw.beginTrans();
1351
            ds.stop();
1352
            lyrToUnionSDS.stop();
1353
            
1354
            Vector values = new Vector();
1355
            
1356
            //Geometry[] unedGeometries = GeoProcessingTopologyOperations.makeUnion(geometriesToUnion, uningGeometries);
1357
            Geometry[] result = new Geometry[geometriesToUnion.length];
1358
            Vector geometriesUned = new Vector();
1359
            //Selectable selectable = (Selectable)layerToUnion;
1360
            //FBitSet fBitSet = new FBitSet();
1361
            // Metememos en geometriesUned las intersecciones.
1362
            for (int i=0;i<geometriesToUnion.length;i++) {
1363
                Geometry geometryToUnion = geometriesToUnion[i];
1364
                for (int j=0;j<uningGeometries.length;j++) {
1365
                    Geometry uningGeometry = uningGeometries[j];
1366
                    if (uningGeometry.intersects(geometryToUnion)) {
1367
                        //fBitSet.set(i);
1368
                        geometriesUned.add(geometryToUnion.intersection(uningGeometry));
1369
                        Value[] intersectRow = new Value[unedLyrFieldNames.length+1];
1370
                        for (int k=0;k<lyrToUnionFieldNames.length-1;k++) {
1371
                            intersectRow[k] = lyrToUnionDS.getFieldValue(i, k);
1372
                        }
1373
                        for (int k=0;k<uningLyrFieldNames.length-1;k++) {
1374
                            intersectRow[k+l] = uningLyrDS.getFieldValue(j, k);
1375
                        }
1376
                        intersectRow[unedLyrFieldNames.length] = ValueFactory.createValue(i);
1377
                        values.add(intersectRow);
1378
                        //geometriesUned.add(geometryToUnion.difference(uningGeometry));
1379
                    }
1380
                }
1381
            }
1382
            // Rellenamos geometriesUned2 con estas intersecciones.
1383
            Vector geometriesUned2 = new Vector();
1384
            for (int i=0;i<geometriesUned.size();i++) {
1385
                geometriesUned2.add(geometriesUned.get(i));
1386
            }
1387
            //int num = geometriesUned.size();
1388
            // A?ado a geometriesUned2 las geometr?as de geometriesToUnion que no
1389
            // intersectan con uningGeometries.
1390
            for (int i=0;i<geometriesToUnion.length;i++) {
1391
                Geometry geometryToUnion = geometriesToUnion[i];
1392
                boolean intersectsWithAnyGeometry = false;
1393
                for (int j=0;j<geometriesUned.size();j++) {
1394
                    Geometry geometryUned = (Geometry)geometriesUned.get(j);
1395
                    if (geometryToUnion.intersects(geometryUned)) intersectsWithAnyGeometry = true;
1396
                }
1397
                if (intersectsWithAnyGeometry) {
1398
                    //Geometry difference = geometryToUnion.difference(geometryUned);
1399
                    //geometriesUned2.add(difference);
1400
                } else {
1401
                    geometriesUned2.add(geometryToUnion);
1402
                    Value[] unionRow = new Value[unedLyrFieldNames.length+1];
1403
                    for (int k=0;k<lyrToUnionFieldNames.length-1;k++) {
1404
                        unionRow[k] = lyrToUnionDS.getFieldValue(i, k);
1405
                    }
1406
                    for (int k=0;k<uningLyrFieldNames.length-1;k++) {
1407
                        unionRow[k+l] = ValueFactory.createNullValue();
1408
                    }
1409
                    unionRow[unedLyrFieldNames.length] = ValueFactory.createValue(i);
1410
                    values.add(unionRow);
1411
                }
1412
            }
1413
            // A?ado a geometriesUned2 las geometr?as de uningGeometries que no
1414
            // intersectan con geometriesToUnion.
1415
            for (int i=0;i<uningGeometries.length;i++) {
1416
                Geometry uningGeometry = uningGeometries[i];
1417
                boolean intersectsWithAnyGeometry = false;
1418
                for (int j=0;j<geometriesUned.size();j++) {
1419
                    Geometry geometryUned = (Geometry)geometriesUned.get(j);
1420
                    if (uningGeometry.intersects(geometryUned)) intersectsWithAnyGeometry = true;
1421
                }
1422
                if (intersectsWithAnyGeometry) {
1423
                    //Geometry difference = jtsUningGeometry.difference(jtsGeometryUned);
1424
                    //jtsGeometriesUned2.add(difference);
1425
                } else {
1426
                    geometriesUned2.add(uningGeometry);
1427
                    Value[] uningRow = new Value[unedLyrFieldNames.length+1];
1428
                    for (int k=0;k<lyrToUnionFieldNames.length-1;k++) {
1429
                        uningRow[k] = ValueFactory.createNullValue();
1430
                    }
1431
                    for (int k=0;k<uningLyrFieldNames.length-1;k++) {
1432
                        uningRow[k+l] = uningLyrDS.getFieldValue(i, k);
1433
                    }
1434
                    uningRow[unedLyrFieldNames.length] = ValueFactory.createValue(i);
1435
                    values.add(uningRow);
1436
                }
1437
            }
1438
            //System.out.println("geometriesUned2.size() = " + geometriesUned2.size());
1439
            // Le quito los cachos que ya tengo a las geometrias que faltan de
1440
            // uningGeometries.
1441
            BitSet bitSet1 = new BitSet();
1442
            bitSet1.clear();
1443
            //int k1=0;
1444
            for (int i=0;i<geometriesUned2.size();i++) {
1445
                Geometry geometryUned2 = (Geometry)geometriesUned2.get(i);
1446
                for (int j=0;j<uningGeometries.length;j++) {
1447
                    //System.out.println("!(uningGeometries[j].equals(geometryUned2)) = " + !(uningGeometries[j].equals(geometryUned2)));
1448
                    if (uningGeometries[j].intersects(geometryUned2) && !(uningGeometries[j].equals(geometryUned2))) {
1449
                        uningGeometries[j] = uningGeometries[j].difference(geometryUned2);
1450
                        //bitSet1.set(k1);
1451
                        bitSet1.set(j);
1452
                    }
1453
                    //k1++;
1454
                }
1455
            }
1456
            // Le quito los cachos que ya tengo a las geometrias que faltan de
1457
            // geometriesToUnion.
1458
            BitSet bitSet2 = new BitSet();
1459
            bitSet2.clear();
1460
            int k2=0;
1461
            for (int i=0;i<geometriesUned2.size();i++) {
1462
                Geometry geometryUned2 = (Geometry)geometriesUned2.get(i);
1463
                for (int j=0;j<geometriesToUnion.length;j++) {
1464
                    //System.out.println("!(geometriesToUnion[j].equals(geometryUned2)) = " + !(geometriesToUnion[j].equals(geometryUned2)));
1465
                    if (geometriesToUnion[j].intersects(geometryUned2) && !(geometriesToUnion[j].equals(geometryUned2))) {
1466
                        geometriesToUnion[j] = geometriesToUnion[j].difference(geometryUned2);
1467
                        bitSet2.set(k2);
1468
                        //bitSet2.set(j);
1469
                    }
1470
                    k2++;
1471
                }
1472
            }
1473
            //for (int i=0;i<bitSet2.size();i++) {
1474
            //    System.out.println("bitSet2.get(" + i + ") = " + bitSet2.get(i));
1475
            //}
1476
            // Ahora que les he quitado los cachos que ya ten?a, le meto los features que
1477
            // faltaban de uningGeometries
1478
            for (int i=0;i<uningGeometries.length;i++) {
1479
                if (bitSet1.get(i)) {
1480
                    geometriesUned2.add(uningGeometries[i]);
1481
                    Value[] uningRow = new Value[unedLyrFieldNames.length+1];
1482
                    for (int k=0;k<lyrToUnionFieldNames.length-1;k++) {
1483
                        uningRow[k] = ValueFactory.createNullValue();
1484
                    }
1485
                    for (int k=0;k<uningLyrFieldNames.length-1;k++) {
1486
                        uningRow[k+l] = uningLyrDS.getFieldValue(i, k);
1487
                    }
1488
                    uningRow[unedLyrFieldNames.length] = ValueFactory.createValue(i);
1489
                    values.add(uningRow);
1490
                }
1491
            }
1492
            // Ahora que les he quitado los cachos que ya ten?a, le meto los features que
1493
            // faltaban de geometriesToUnion
1494
            for (int i=0;i<geometriesToUnion.length;i++) {
1495
                if (bitSet2.get(i)) {
1496
                    geometriesUned2.add(geometriesToUnion[i]);
1497
                    Value[] unionRow = new Value[unedLyrFieldNames.length+1];
1498
                    for (int k=0;k<lyrToUnionFieldNames.length-1;k++) {
1499
                        unionRow[k] = lyrToUnionDS.getFieldValue(i, k);
1500
                    }
1501
                    for (int k=0;k<uningLyrFieldNames.length-1;k++) {
1502
                        unionRow[k+l] = ValueFactory.createNullValue();
1503
                    }
1504
                    unionRow[unedLyrFieldNames.length] = ValueFactory.createValue(i);
1505
                    values.add(unionRow);
1506
                }
1507
            }
1508
            //selectable.setSelection(fBitSet);
1509
            result = new Geometry[geometriesUned2.size()];
1510
            for (int i=0;i<geometriesUned2.size();i++) {
1511
                result[i] = (Geometry)geometriesUned2.get(i);
1512
            }
1513
            
1514
            for (int i=0;i<result.length;i++) {
1515
                dw.insertFilledRow(((Value[])values.get(i)));
1516
            }
1517
            dw.commitTrans();
1518
            
1519
            IGeometry[] shapes = getFmapGeometries(result);
1520
            // Guardo la tabla mediante gdbms. Guardo tambi?n las entidades JTS mediante gvSIG o usando solo gdbms (probablemente bastar? con usar gdbms)
1521
            GeoProcessingPersistenceOperations.saveResultsToShapeFile(shapes, geoProcessingUnionPanel.getOutputFile());
1522
        } catch (DriverException e) {
1523
            // TODO Auto-generated catch block
1524
            e.printStackTrace();
1525
        } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
1526
            // TODO Auto-generated catch block
1527
            e.printStackTrace();
1528
        } catch (DriverLoadException e) {
1529
            // TODO Auto-generated catch block
1530
            e.printStackTrace();
1531
        } catch (NoSuchTableException e) {
1532
            // TODO Auto-generated catch block
1533
            e.printStackTrace();
1534
        }
1535
    }
1536
    public double[] getBufferDistancesFromTable(FLayer bufferingLayer) {
1537
        AlphanumericData lyr = (AlphanumericData)bufferingLayer;
1538
        DataSource ds;
1539
        double[] bufferDistances = null;
1540
        try {
1541
            ds = lyr.getRecordset();
1542
            int fieldId = ds.getFieldIndexByName(getSelectedField());
1543
            Value[] fieldValues = new Value[(int)ds.getRowCount()];
1544
            SelectableDataSource selectableDataSource = (SelectableDataSource)ds;
1545
            FBitSet fBitSet = selectableDataSource.getSelection();
1546
            if (fBitSet.cardinality()==0) {
1547
                fBitSet.set(0, (int)lyr.getRecordset().getRowCount());
1548
            }
1549
            Value[] valuesSelected = new Value[fBitSet.cardinality()];
1550
            int j = 0;
1551
            for (int i=0;i<ds.getRowCount();i++) {
1552
                boolean isSelected = fBitSet.get(i);
1553
                fieldValues[i] = ds.getFieldValue(i, fieldId);
1554
                if (isSelected) {
1555
                    valuesSelected[j] = fieldValues[i];
1556
                    j++;
1557
                }
1558
            }
1559
            bufferDistances = new double[fBitSet.cardinality()];
1560
            for (int i=0;i<fBitSet.cardinality();i++) {
1561
                bufferDistances[i] = new Double(valuesSelected[i].toString()).doubleValue();
1562
            }
1563
        } catch (DriverException e) {
1564
            // TODO Auto-generated catch block
1565
            e.printStackTrace();
1566
        } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
1567
            // TODO Auto-generated catch block
1568
            e.printStackTrace();
1569
        }
1570
        return bufferDistances;
1571
    }
1572
    private String getSelectedField() {
1573
        return ((String)((JComboBox)geoProcessingBufferPanel.getComponent(6)).getSelectedItem());
1574
    }
1575
    private int getQuadrantSegments() {
1576
        return (Integer.valueOf((String)((JComboBox)geoProcessingBufferPanel.getComponent(11)).getSelectedItem())).intValue();
1577
    }
1578
    private void closeMethod() {
1579
        if (PluginServices.getMainFrame() == null)
1580
            ((JDialog) (getParent().getParent().getParent().getParent())).dispose();
1581
        else
1582
            PluginServices.getMDIManager().closeView(GeoProcessingPanel.this);
1583
    }
1584
   }  //  @jve:decl-index=0:visual-constraint="10,10"