Statistics
| Revision:

root / branches / v10 / applications / appgvSIG / src / com / iver / cit / gvsig / TableOperations.java @ 9563

History | View | Annotate | Download (18.1 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package com.iver.cit.gvsig;
42

    
43
import java.awt.Dimension;
44
import java.io.IOException;
45

    
46
import com.hardcode.driverManager.DriverLoadException;
47
import com.hardcode.gdbms.engine.data.DataSource;
48
import com.hardcode.gdbms.engine.data.DataSourceFactory;
49
import com.hardcode.gdbms.engine.instruction.EvaluationException;
50
import com.hardcode.gdbms.engine.instruction.SemanticException;
51
import com.hardcode.gdbms.parser.ParseException;
52
import com.iver.andami.PluginServices;
53
import com.iver.andami.messages.NotificationManager;
54
import com.iver.andami.plugins.Extension;
55
import com.iver.andami.ui.mdiManager.IWindow;
56
import com.iver.cit.gvsig.fmap.edition.EditableAdapter;
57
import com.iver.cit.gvsig.fmap.layers.FBitSet;
58
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
59
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
60
import com.iver.cit.gvsig.gui.filter.ExpressionListener;
61
import com.iver.cit.gvsig.project.documents.table.FieldSelectionModel;
62
import com.iver.cit.gvsig.project.documents.table.ObjectSelectionStep;
63
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
64
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
65
import com.iver.cit.gvsig.project.documents.table.TableSelectionModel;
66
import com.iver.cit.gvsig.project.documents.table.gui.AndamiWizard;
67
import com.iver.cit.gvsig.project.documents.table.gui.Table;
68
import com.iver.utiles.swing.objectSelection.SelectionException;
69
import com.iver.utiles.swing.wizard.WizardControl;
70
import com.iver.utiles.swing.wizard.WizardEvent;
71
import com.iver.utiles.swing.wizard.WizardListener;
72

    
73

    
74
/**
75
 * Extensi?n que controla las operaciones realizadas sobre las tablas.
76
 *
77
 * @author Fernando Gonz?lez Cort?s
78
 */
79
public class TableOperations extends Extension implements ExpressionListener {
80
        private SelectableDataSource dataSource = null;
81
        //private Table vista;
82

    
83
        /**
84
         * @see com.iver.mdiApp.plugins.IExtension#updateUI(java.lang.String)
85
         */
86
        public void execute(String actionCommand) {
87
                if ("JOIN".equals(actionCommand)) {
88
                        ProjectExtension pe = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class);
89
                        ProjectTable[] pts = (ProjectTable[]) pe.getProject().getDocumentsByType(ProjectTableFactory.registerName)
90
                                                                                                        .toArray(new ProjectTable[0]);
91

    
92
                        try {
93
                                final ObjectSelectionStep sourceTable = new ObjectSelectionStep();
94
                                sourceTable.setModel(new TableSelectionModel(pts,
95
                                        PluginServices.getText(this, "seleccione_tabla_origen")));
96

    
97
                                final ObjectSelectionStep targetTable = new ObjectSelectionStep();
98
                                targetTable.setModel(new TableSelectionModel(pts,
99
                                        PluginServices.getText(this, "seleccione_tabla_a_enlazar")));
100

    
101
                                final ObjectSelectionStep firstTableField = new ObjectSelectionStep();
102
                                final ObjectSelectionStep secondTableField = new ObjectSelectionStep();
103
                                final AndamiWizard wiz = new AndamiWizard(PluginServices.getText(this, "back"), PluginServices.getText(this, "next"), PluginServices.getText(this, "finish"), PluginServices.getText(this, "cancel"));
104
                                wiz.setSize(new Dimension(450,200));
105
                                wiz.addStep(sourceTable);
106
                                wiz.addStep(firstTableField);
107
                                wiz.addStep(targetTable);
108
                                wiz.addStep(secondTableField);
109

    
110
                                wiz.addWizardListener(new WizardListener() {
111
                                                public void cancel(WizardEvent w) {
112
                                                        PluginServices.getMDIManager().closeWindow(wiz);
113
                                                }
114

    
115
                                                public void finished(WizardEvent w) {
116
                                                        PluginServices.getMDIManager().closeWindow(wiz);
117

    
118
                                                        ProjectTable sourceProjectTable = (ProjectTable) sourceTable.getSelected();
119
                                                        SelectableDataSource sds=null;
120
                                                        try {
121
                                                                sds = sourceProjectTable.getModelo().getRecordset();
122
                                                        } catch (DriverLoadException e1) {
123
                                                                // TODO Auto-generated catch block
124
                                                                e1.printStackTrace();
125
                                                        }
126
                                                        String tableName1 = sds.getName();
127

    
128
                                                        ProjectTable targetProjectTable = (ProjectTable) targetTable.getSelected();
129
                                                        try {
130
                                                                sds = targetProjectTable.getModelo().getRecordset();
131
                                                        } catch (DriverLoadException e1) {
132
                                                                // TODO Auto-generated catch block
133
                                                                e1.printStackTrace();
134
                                                        }
135

    
136
                                                        String tableName2 = sds.getName();
137

    
138
                                                        String field1 = (String) firstTableField.getSelected();
139
                                                        String field2 = (String) secondTableField.getSelected();
140

    
141
                                                        String sql =
142
                                                                "custom com_iver_cit_gvsig_arcjoin tables '" +
143
                                                                tableName1 + "', '" + tableName2 + "' values(" +
144
                                                                field1 + ", " + field2 + ");";
145
                                                        System.out.println(sql);
146

    
147
                                                        try {
148
                                                                SelectableDataSource result = new SelectableDataSource(LayerFactory.getDataSourceFactory()
149
                                                                                                                                                                                                   .executeSQL(sql,
150
                                                                                        DataSourceFactory.AUTOMATIC_OPENING));
151
                                                                ProjectTable projectTable = (ProjectTable) sourceTable.getSelected();
152
                                                                EditableAdapter auxea=new EditableAdapter();
153
                                                                auxea.setOriginalDataSource(result);
154
                                                                projectTable.replaceDataSource(auxea);
155
                                                        } catch (ParseException e) {
156
                                                                throw new RuntimeException(e);
157
                                                        } catch (DriverLoadException e) {
158
                                                                NotificationManager.addError("Error con la carga de drivers",
159
                                                                        e);
160
                                                        } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
161
                                                                NotificationManager.addError("Error leyendo del driver",
162
                                                                        e);
163
                                                        } catch (SemanticException e) {
164
                                                                throw new RuntimeException(e);
165
                                                        } catch (IOException e) {
166
                                                                NotificationManager.addError("Error de entrada/salida",
167
                                                                        e);
168
                                                        } catch (EvaluationException e) {
169
                                                                NotificationManager.addError("Error de evaluaci?n de la expresi?n",
170
                                                                                e);
171
                            }
172
                                                }
173

    
174
                                                public void next(WizardEvent w) {
175
                                                        WizardControl wiz = w.wizard;
176
                                                        wiz.enableBack(true);
177
                                                        wiz.enableNext(((ObjectSelectionStep) wiz.getCurrentStep()).getSelectedItem() != null);
178

    
179
                                                        if (w.currentStep == 1) {
180
                                                                ProjectTable pt = (ProjectTable) sourceTable.getSelected();
181

    
182
                                                                try {
183
                                                                        firstTableField.setModel(new FieldSelectionModel(
184
                                                                                        pt.getModelo().getRecordset(),
185
                                                                                        PluginServices.getText(this, "seleccione_campo_enlace"),
186
                                                                                        -1));
187
                                                                } catch (SelectionException e) {
188
                                                                        NotificationManager.addError("Error obteniendo los campos de la tabla",
189
                                                                                e);
190
                                                                } catch (DriverLoadException e) {
191
                                                                        // TODO Auto-generated catch block
192
                                                                        e.printStackTrace();
193
                                                                }
194
                                                        } else if (w.currentStep == 3) {
195
                                                                try {
196
                                                                        //tabla
197
                                                                        ProjectTable pt = (ProjectTable) sourceTable.getSelected();
198

    
199
                                                                        //?ndice del campo
200
                                                                        SelectableDataSource sds = pt.getModelo().getRecordset();
201
                                                                        String fieldName = (String) firstTableField.getSelected();
202
                                                                        int fieldIndex = sds.getFieldIndexByName(fieldName);
203
                                                                        int type = sds.getFieldType(fieldIndex);
204

    
205
                                                                        secondTableField.setModel(new FieldSelectionModel(
206
                                                                                        ((ProjectTable) targetTable.getSelected()).getModelo().getRecordset(),
207
                                                                                        PluginServices.getText(this, "seleccione_campo_enlace"),
208
                                                                                        type));
209
                                                                } catch (SelectionException e) {
210
                                                                        NotificationManager.addError("Error obteniendo los campos de la tabla",
211
                                                                                e);
212
                                                                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
213
                                                                        NotificationManager.addError("Error obteniendo los campos de la tabla",
214
                                                                                e);
215
                                                                } catch (DriverLoadException e) {
216
                                                                        // TODO Auto-generated catch block
217
                                                                        e.printStackTrace();
218
                                                                }
219
                                                        }
220
                                                }
221

    
222
                                                public void back(WizardEvent w) {
223
                                                        WizardControl wiz = w.wizard;
224
                                                        wiz.enableBack(true);
225
                                                        wiz.enableNext(((ObjectSelectionStep) wiz.getCurrentStep()).getSelectedItem() != null);
226
                                                }
227
                                        });
228
                                PluginServices.getMDIManager().addWindow(wiz);
229
                        } catch (SelectionException e) {
230
                                NotificationManager.addError("Error abriendo el asistente", e);
231
                        }
232
                }else if ("LINK".equals(actionCommand)) {
233
                        ProjectExtension pe = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class);
234
                        ProjectTable[] pts = (ProjectTable[]) pe.getProject().getDocumentsByType(ProjectTableFactory.registerName)
235
                                                                                                        .toArray(new ProjectTable[0]);
236

    
237
                        try {
238
                                final ObjectSelectionStep sourceTable = new ObjectSelectionStep();
239
                                sourceTable.setModel(new TableSelectionModel(pts,
240
                                                PluginServices.getText(this, "seleccione_tabla_origen")));
241

    
242
                                final ObjectSelectionStep targetTable = new ObjectSelectionStep();
243
                                targetTable.setModel(new TableSelectionModel(pts,
244
                                        PluginServices.getText(this, "seleccione_tabla_a_enlazar")));
245

    
246
                                final ObjectSelectionStep firstTableField = new ObjectSelectionStep();
247
                                final ObjectSelectionStep secondTableField = new ObjectSelectionStep();
248
                                final AndamiWizard wiz = new AndamiWizard(PluginServices.getText(this, "back"), PluginServices.getText(this, "next"), PluginServices.getText(this, "finish"), PluginServices.getText(this, "cancel"));
249
                                wiz.setSize(new Dimension(450,200));
250
                                wiz.addStep(sourceTable);
251
                                wiz.addStep(firstTableField);
252
                                wiz.addStep(targetTable);
253
                                wiz.addStep(secondTableField);
254

    
255
                                wiz.addWizardListener(new WizardListener() {
256
                                                public void cancel(WizardEvent w) {
257
                                                        PluginServices.getMDIManager().closeWindow(wiz);
258
                                                }
259

    
260
                                                public void finished(WizardEvent w) {
261
                                                        PluginServices.getMDIManager().closeWindow(wiz);
262

    
263
                                                        ProjectTable sourceProjectTable = (ProjectTable) sourceTable.getSelected();
264
                                                        SelectableDataSource sds1=null;;
265
                                                        try {
266
                                                                sds1 = sourceProjectTable.getModelo().getRecordset();
267
                                                        } catch (DriverLoadException e) {
268
                                                                // TODO Auto-generated catch block
269
                                                                e.printStackTrace();
270
                                                        }
271
                                                        //String tableName1 = sds1.getName();
272

    
273
                                                        ProjectTable targetProjectTable = (ProjectTable) targetTable.getSelected();
274
                                                        SelectableDataSource sds2=null;
275
                                                        try {
276
                                                                sds2 = targetProjectTable.getModelo().getRecordset();
277
                                                        } catch (DriverLoadException e) {
278
                                                                // TODO Auto-generated catch block
279
                                                                e.printStackTrace();
280
                                                        }
281

    
282
                                                        //String tableName2 = sds2.getName();
283

    
284
                                                        String field1 = (String) firstTableField.getSelected();
285
                                                        String field2 = (String) secondTableField.getSelected();
286
                                                        sourceProjectTable.setLinkTable(sds2.getName(),field1,field2);
287
                                                        ((ProjectExtension)PluginServices.getExtension(ProjectExtension.class)).getProject().setLinkTable();
288
                                                }
289

    
290
                                                public void next(WizardEvent w) {
291
                                                        WizardControl wiz = w.wizard;
292
                                                        wiz.enableBack(true);
293
                                                        wiz.enableNext(((ObjectSelectionStep) wiz.getCurrentStep()).getSelectedItem() != null);
294

    
295
                                                        if (w.currentStep == 1) {
296
                                                                ProjectTable pt = (ProjectTable) sourceTable.getSelected();
297

    
298
                                                                try {
299
                                                                        firstTableField.setModel(new FieldSelectionModel(
300
                                                                                        pt.getModelo().getRecordset(),
301
                                                                                        PluginServices.getText(this, "seleccione_campo_enlace"),
302
                                                                                        -1));
303
                                                                } catch (SelectionException e) {
304
                                                                        NotificationManager.addError("Error obteniendo los campos de la tabla",
305
                                                                                e);
306
                                                                } catch (DriverLoadException e) {
307
                                                                        // TODO Auto-generated catch block
308
                                                                        e.printStackTrace();
309
                                                                }
310
                                                        } else if (w.currentStep == 3) {
311
                                                                try {
312
                                                                        //tabla
313
                                                                        ProjectTable pt = (ProjectTable) sourceTable.getSelected();
314

    
315
                                                                        //?ndice del campo
316
                                                                        SelectableDataSource sds = pt.getModelo().getRecordset();
317
                                                                        String fieldName = (String) firstTableField.getSelected();
318
                                                                        int fieldIndex = sds.getFieldIndexByName(fieldName);
319
                                                                        int type = sds.getFieldType(fieldIndex);
320

    
321
                                                                        secondTableField.setModel(new FieldSelectionModel(
322
                                                                                        ((ProjectTable) targetTable.getSelected()).getModelo().getRecordset(),
323
                                                                                        PluginServices.getText(this, "seleccione_campo_enlace"),
324
                                                                                        type));
325
                                                                } catch (SelectionException e) {
326
                                                                        NotificationManager.addError("Error obteniendo los campos de la tabla",
327
                                                                                e);
328
                                                                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
329
                                                                        NotificationManager.addError("Error obteniendo los campos de la tabla",
330
                                                                                e);
331
                                                                } catch (DriverLoadException e) {
332
                                                                        // TODO Auto-generated catch block
333
                                                                        e.printStackTrace();
334
                                                                }
335
                                                        }
336
                                                }
337

    
338
                                                public void back(WizardEvent w) {
339
                                                        WizardControl wiz = w.wizard;
340
                                                        wiz.enableBack(true);
341
                                                        wiz.enableNext(((ObjectSelectionStep) wiz.getCurrentStep()).getSelectedItem() != null);
342
                                                }
343
                                        });
344
                                PluginServices.getMDIManager().addWindow(wiz);
345
                        } catch (SelectionException e) {
346
                                NotificationManager.addError("Error abriendo el asistente", e);
347
                        }
348
              }
349
        }
350

    
351
        /**
352
         * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#newSet(java.lang.String)
353
         */
354
        public void newSet(String expression) {
355
                // By Pablo: if no expression -> no element selected
356
                if (! this.filterExpressionFromWhereIsEmpty(expression)) {
357
                        long[] sel = doSet(expression);
358
        
359
                        if (sel == null) {
360
                                throw new RuntimeException("Not a 'where' clause?");
361
                        }
362
        
363
                        FBitSet selection = new FBitSet();
364
        
365
                        for (int i = 0; i < sel.length; i++) {
366
                                selection.set((int) sel[i]);
367
                        }
368
        
369
                        dataSource.clearSelection();
370
                        dataSource.setSelection(selection);
371
                }
372
                else {
373
                        // By Pablo: if no expression -> no element selected
374
                        dataSource.clearSelection();
375
                }
376
        }
377

    
378
        /**
379
         * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#newSet(java.lang.String)
380
         */
381
        private long[] doSet(String expression) {
382
                try {
383
                        DataSource ds = LayerFactory.getDataSourceFactory().executeSQL(expression,
384
                                        DataSourceFactory.MANUAL_OPENING);
385

    
386
                        return ds.getWhereFilter();
387
                } catch (DriverLoadException e) {
388
                        NotificationManager.addError("Error cargando el driver", e);
389
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
390
                        NotificationManager.addError("Error accediendo al driver", e);
391
                } catch (ParseException e) {
392
                        NotificationManager.addError("Parse error", e);
393
                } catch (SemanticException e) {
394
                        NotificationManager.addError(e.getMessage(), e);
395
                } catch (IOException e) {
396
                        NotificationManager.addError("GDBMS internal error", e);
397
                } catch (EvaluationException e) {
398
                        NotificationManager.addError("Error con la expresi?n", e);
399
        }
400

    
401
                return null;
402
        }
403

    
404
        /**
405
         * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#addToSet(java.lang.String)
406
         */
407
        public void addToSet(String expression) {
408
                // By Pablo: if no expression -> don't add more elements to set
409
                if (! this.filterExpressionFromWhereIsEmpty(expression)) {
410
                        long[] sel = doSet(expression);
411
        
412
                        if (sel == null) {
413
                                throw new RuntimeException("Not a 'where' clause?");
414
                        }
415
        
416
                        FBitSet selection = new FBitSet();
417
        
418
                        for (int i = 0; i < sel.length; i++) {
419
                                selection.set((int) sel[i]);
420
                        }
421
        
422
                        FBitSet fbs = dataSource.getSelection();
423
                        fbs.or(selection);
424
                        dataSource.setSelection(fbs);
425
                }
426
        }
427

    
428
        /**
429
         * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#fromSet(java.lang.String)
430
         */
431
        public void fromSet(String expression) {
432
                // By Pablo: if no expression -> no element selected
433
                if (! this.filterExpressionFromWhereIsEmpty(expression)) {
434
                        long[] sel = doSet(expression);
435
        
436
                        if (sel == null) {
437
                                throw new RuntimeException("Not a 'where' clause?");
438
                        }
439
        
440
                        FBitSet selection = new FBitSet();
441
        
442
                        for (int i = 0; i < sel.length; i++) {
443
                                selection.set((int) sel[i]);
444
                        }
445
        
446
                        FBitSet fbs = dataSource.getSelection();
447
                        fbs.and(selection);
448
                        dataSource.setSelection(fbs);
449
                }
450
                else {
451
                        // By Pablo: if no expression -> no element selected
452
                        dataSource.clearSelection();
453
                }
454
        }
455
        
456
        /**
457
         * Returns true if the WHERE subconsultation of the filterExpression is empty ("")
458
         * 
459
         * @author Pablo Piqueras Bartolom? (p_queras@hotmail.com)
460
         * @param expression An string
461
         * @return A boolean value 
462
         */
463
        private boolean filterExpressionFromWhereIsEmpty(String expression) {
464
                String subExpression = expression.trim();
465
                int pos;        
466
                
467
                // Remove last ';' if exists
468
                if (subExpression.charAt(subExpression.length() -1) == ';')
469
                        subExpression = subExpression.substring(0, subExpression.length() -1).trim();
470
                
471
                // If there is no 'where' clause
472
                if ((pos = subExpression.indexOf("where")) == -1)
473
                        return false;
474
                
475
                // If there is no subexpression in the WHERE clause -> true
476
                subExpression = subExpression.substring(pos + 5, subExpression.length()).trim(); // + 5 is the length of 'where'
477
                if ( subExpression.length() == 0 )
478
                        return true;
479
                else
480
                        return false;
481
        }
482

    
483
        /**
484
         * @see com.iver.mdiApp.plugins.IExtension#isVisible()
485
         */
486
        public boolean isVisible() {
487
                IWindow v = PluginServices.getMDIManager().getActiveWindow();
488

    
489
                if (v == null) {
490
                        return false;
491
                }
492

    
493
                if (v instanceof Table) {
494
                        return true;
495
                } /*else {
496
                        if (v instanceof com.iver.cit.gvsig.gui.View) {
497
                                com.iver.cit.gvsig.gui.View view = (com.iver.cit.gvsig.gui.View) v;
498
                                ProjectView pv = view.getModel();
499
                                FLayer[] seleccionadas = pv.getMapContext().getLayers()
500
                                                                                   .getActives();
501

502
                                if (seleccionadas.length == 1) {
503
                                        if (seleccionadas[0] instanceof AlphanumericData) {
504
                                                return true;
505
                                        }
506
                                }
507
                        }
508
*/
509
                        return false;
510
                //}
511
        }
512

    
513
        /**
514
         * @see com.iver.andami.plugins.IExtension#initialize()
515
         */
516
        public void initialize() {
517
        }
518

    
519
        /**
520
         * @see com.iver.andami.plugins.IExtension#isEnabled()
521
         */
522
        public boolean isEnabled() {
523
                return true;
524
        }
525

    
526

    
527
}