Statistics
| Revision:

root / trunk / applications / appgvSIG / src / com / iver / cit / gvsig / TableOperations.java @ 12213

History | View | Annotate | Download (17.4 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.driver.exceptions.ReadDriverException;
48
import com.hardcode.gdbms.engine.data.DataSource;
49
import com.hardcode.gdbms.engine.data.DataSourceFactory;
50
import com.hardcode.gdbms.engine.instruction.EvaluationException;
51
import com.hardcode.gdbms.engine.instruction.SemanticException;
52
import com.hardcode.gdbms.parser.ParseException;
53
import com.iver.andami.PluginServices;
54
import com.iver.andami.messages.NotificationManager;
55
import com.iver.andami.plugins.Extension;
56
import com.iver.andami.ui.mdiManager.IWindow;
57
import com.iver.cit.gvsig.fmap.edition.EditableAdapter;
58
import com.iver.cit.gvsig.fmap.layers.FBitSet;
59
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
60
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
61
import com.iver.cit.gvsig.gui.filter.ExpressionListener;
62
import com.iver.cit.gvsig.project.Project;
63
import com.iver.cit.gvsig.project.documents.table.FieldSelectionModel;
64
import com.iver.cit.gvsig.project.documents.table.ObjectSelectionStep;
65
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
66
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
67
import com.iver.cit.gvsig.project.documents.table.TableSelectionModel;
68
import com.iver.cit.gvsig.project.documents.table.gui.AndamiWizard;
69
import com.iver.cit.gvsig.project.documents.table.gui.Table;
70
import com.iver.utiles.swing.objectSelection.SelectionException;
71
import com.iver.utiles.swing.wizard.WizardControl;
72
import com.iver.utiles.swing.wizard.WizardEvent;
73
import com.iver.utiles.swing.wizard.WizardListener;
74

    
75

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

    
85
        /**
86
         * @see com.iver.mdiApp.plugins.IExtension#updateUI(java.lang.String)
87
         */
88
        public void execute(String actionCommand) {
89
                ProjectExtension pe = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class);
90
                Project project=pe.getProject();
91
                ProjectTable[] pts = (ProjectTable[]) project.getDocumentsByType(ProjectTableFactory.registerName)
92
                        .toArray(new ProjectTable[0]);
93
                if ("JOIN".equals(actionCommand)) {
94
                        try {
95
                                final ObjectSelectionStep sourceTable = new ObjectSelectionStep();
96
                                sourceTable.setModel(new TableSelectionModel(pts,
97
                                        PluginServices.getText(this, "seleccione_tabla_origen")));
98

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

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

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

    
117
                                                public void finished(WizardEvent w) {
118
                                                        PluginServices.getMDIManager().closeWindow(wiz);
119

    
120
                                                        ProjectTable sourceProjectTable = (ProjectTable) sourceTable.getSelected();
121
                                                        SelectableDataSource sds=null;
122
                                                        try {
123
                                                                sds = sourceProjectTable.getModelo().getRecordset();
124
                                                        } catch (ReadDriverException e) {
125
                                                                e.printStackTrace();
126
                                                        }
127
                                                        String tableName1 = sds.getName();
128

    
129
                                                        ProjectTable targetProjectTable = (ProjectTable) targetTable.getSelected();
130
                                                        try {
131
                                                                sds = targetProjectTable.getModelo().getRecordset();
132
                                                        } catch (ReadDriverException e) {
133
                                                                e.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 (ReadDriverException e) {
161
                                                                NotificationManager.addError("Error leyendo del driver",
162
                                                                        e);
163
                                                        } catch (SemanticException e) {
164
                                                                throw new RuntimeException(e);
165
                                                        } catch (EvaluationException e) {
166
                                                                NotificationManager.addError("Error de evaluaci?n de la expresi?n",
167
                                                                                e);
168
                            }
169
                                                }
170

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

    
176
                                                        if (w.currentStep == 1) {
177
                                                                ProjectTable pt = (ProjectTable) sourceTable.getSelected();
178

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

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

    
202
                                                                        secondTableField.setModel(new FieldSelectionModel(
203
                                                                                        ((ProjectTable) targetTable.getSelected()).getModelo().getRecordset(),
204
                                                                                        PluginServices.getText(this, "seleccione_campo_enlace"),
205
                                                                                        type));
206
                                                                } catch (SelectionException e) {
207
                                                                        NotificationManager.addError("Error obteniendo los campos de la tabla",
208
                                                                                e);
209
                                                                } catch (ReadDriverException e) {
210
                                                                        NotificationManager.addError("Error obteniendo los campos de la tabla",
211
                                                                                e);
212
                                                                }
213
                                                        }
214
                                                }
215

    
216
                                                public void back(WizardEvent w) {
217
                                                        WizardControl wiz = w.wizard;
218
                                                        wiz.enableBack(true);
219
                                                        wiz.enableNext(((ObjectSelectionStep) wiz.getCurrentStep()).getSelectedItem() != null);
220
                                                }
221
                                        });
222
                                project.setModified(true);
223
                                PluginServices.getMDIManager().addWindow(wiz);
224
                        } catch (SelectionException e) {
225
                                NotificationManager.addError("Error abriendo el asistente", e);
226
                        }
227
                }else if ("LINK".equals(actionCommand)) {
228
                        try {
229
                                final ObjectSelectionStep sourceTable = new ObjectSelectionStep();
230
                                sourceTable.setModel(new TableSelectionModel(pts,
231
                                                PluginServices.getText(this, "seleccione_tabla_origen")));
232

    
233
                                final ObjectSelectionStep targetTable = new ObjectSelectionStep();
234
                                targetTable.setModel(new TableSelectionModel(pts,
235
                                        PluginServices.getText(this, "seleccione_tabla_a_enlazar")));
236

    
237
                                final ObjectSelectionStep firstTableField = new ObjectSelectionStep();
238
                                final ObjectSelectionStep secondTableField = new ObjectSelectionStep();
239
                                final AndamiWizard wiz = new AndamiWizard(PluginServices.getText(this, "back"), PluginServices.getText(this, "next"), PluginServices.getText(this, "finish"), PluginServices.getText(this, "cancel"));
240
                                wiz.setSize(new Dimension(450,200));
241
                                wiz.addStep(sourceTable);
242
                                wiz.addStep(firstTableField);
243
                                wiz.addStep(targetTable);
244
                                wiz.addStep(secondTableField);
245

    
246
                                wiz.addWizardListener(new WizardListener() {
247
                                                public void cancel(WizardEvent w) {
248
                                                        PluginServices.getMDIManager().closeWindow(wiz);
249
                                                }
250

    
251
                                                public void finished(WizardEvent w) {
252
                                                        PluginServices.getMDIManager().closeWindow(wiz);
253

    
254
                                                        ProjectTable sourceProjectTable = (ProjectTable) sourceTable.getSelected();
255
                                                        SelectableDataSource sds1=null;;
256
                                                        try {
257
                                                                sds1 = sourceProjectTable.getModelo().getRecordset();
258
                                                        } catch (ReadDriverException e) {
259
                                                                e.printStackTrace();
260
                                                        }
261
                                                        //String tableName1 = sds1.getName();
262

    
263
                                                        ProjectTable targetProjectTable = (ProjectTable) targetTable.getSelected();
264
                                                        SelectableDataSource sds2=null;
265
                                                        try {
266
                                                                sds2 = targetProjectTable.getModelo().getRecordset();
267
                                                        } catch (ReadDriverException e) {
268
                                                                e.printStackTrace();
269
                                                        }
270

    
271
                                                        //String tableName2 = sds2.getName();
272

    
273
                                                        String field1 = (String) firstTableField.getSelected();
274
                                                        String field2 = (String) secondTableField.getSelected();
275
                                                        sourceProjectTable.setLinkTable(sds2.getName(),field1,field2);
276
                                                        ((ProjectExtension)PluginServices.getExtension(ProjectExtension.class)).getProject().setLinkTable();
277
                                                }
278

    
279
                                                public void next(WizardEvent w) {
280
                                                        WizardControl wiz = w.wizard;
281
                                                        wiz.enableBack(true);
282
                                                        wiz.enableNext(((ObjectSelectionStep) wiz.getCurrentStep()).getSelectedItem() != null);
283

    
284
                                                        if (w.currentStep == 1) {
285
                                                                ProjectTable pt = (ProjectTable) sourceTable.getSelected();
286

    
287
                                                                try {
288
                                                                        firstTableField.setModel(new FieldSelectionModel(
289
                                                                                        pt.getModelo().getRecordset(),
290
                                                                                        PluginServices.getText(this, "seleccione_campo_enlace"),
291
                                                                                        -1));
292
                                                                } catch (SelectionException e) {
293
                                                                        NotificationManager.addError("Error obteniendo los campos de la tabla",
294
                                                                                e);
295
                                                                } catch (ReadDriverException e) {
296
                                                                        e.printStackTrace();
297
                                                                }
298
                                                        } else if (w.currentStep == 3) {
299
                                                                try {
300
                                                                        //tabla
301
                                                                        ProjectTable pt = (ProjectTable) sourceTable.getSelected();
302

    
303
                                                                        //?ndice del campo
304
                                                                        SelectableDataSource sds = pt.getModelo().getRecordset();
305
                                                                        String fieldName = (String) firstTableField.getSelected();
306
                                                                        int fieldIndex = sds.getFieldIndexByName(fieldName);
307
                                                                        int type = sds.getFieldType(fieldIndex);
308

    
309
                                                                        secondTableField.setModel(new FieldSelectionModel(
310
                                                                                        ((ProjectTable) targetTable.getSelected()).getModelo().getRecordset(),
311
                                                                                        PluginServices.getText(this, "seleccione_campo_enlace"),
312
                                                                                        type));
313
                                                                } catch (SelectionException e) {
314
                                                                        NotificationManager.addError("Error obteniendo los campos de la tabla",
315
                                                                                e);
316
                                                                } catch (ReadDriverException e) {
317
                                                                        NotificationManager.addError("Error obteniendo los campos de la tabla",
318
                                                                                e);
319
                                                                }
320
                                                        }
321
                                                }
322

    
323
                                                public void back(WizardEvent w) {
324
                                                        WizardControl wiz = w.wizard;
325
                                                        wiz.enableBack(true);
326
                                                        wiz.enableNext(((ObjectSelectionStep) wiz.getCurrentStep()).getSelectedItem() != null);
327
                                                }
328
                                        });
329
                                project.setModified(true);
330
                                PluginServices.getMDIManager().addWindow(wiz);
331
                        } catch (SelectionException e) {
332
                                NotificationManager.addError("Error abriendo el asistente", e);
333
                        }
334
              }
335
        }
336

    
337
        /**
338
         * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#newSet(java.lang.String)
339
         */
340
        public void newSet(String expression) {
341
                // By Pablo: if no expression -> no element selected
342
                if (! this.filterExpressionFromWhereIsEmpty(expression)) {
343
                        long[] sel = doSet(expression);
344

    
345
                        if (sel == null) {
346
                                throw new RuntimeException("Not a 'where' clause?");
347
                        }
348

    
349
                        FBitSet selection = new FBitSet();
350

    
351
                        for (int i = 0; i < sel.length; i++) {
352
                                selection.set((int) sel[i]);
353
                        }
354

    
355
                        dataSource.clearSelection();
356
                        dataSource.setSelection(selection);
357
                }
358
                else {
359
                        // By Pablo: if no expression -> no element selected
360
                        dataSource.clearSelection();
361
                }
362
        }
363

    
364
        /**
365
         * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#newSet(java.lang.String)
366
         */
367
        private long[] doSet(String expression) {
368
                try {
369
                        DataSource ds = LayerFactory.getDataSourceFactory().executeSQL(expression,
370
                                        DataSourceFactory.MANUAL_OPENING);
371

    
372
                        return ds.getWhereFilter();
373
                } catch (DriverLoadException e) {
374
                        NotificationManager.addError("Error cargando el driver", e);
375
                } catch (ReadDriverException e) {
376
                        NotificationManager.addError("Error accediendo al driver", e);
377
                } catch (ParseException e) {
378
                        NotificationManager.addError("Parse error", e);
379
                } catch (SemanticException e) {
380
                        NotificationManager.addError(e.getMessage(), e);
381
                } catch (IOException e) {
382
                        NotificationManager.addError("GDBMS internal error", e);
383
                } catch (EvaluationException e) {
384
                        NotificationManager.addError("Error con la expresi?n", e);
385
        }
386

    
387
                return null;
388
        }
389

    
390
        /**
391
         * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#addToSet(java.lang.String)
392
         */
393
        public void addToSet(String expression) {
394
                // By Pablo: if no expression -> don't add more elements to set
395
                if (! this.filterExpressionFromWhereIsEmpty(expression)) {
396
                        long[] sel = doSet(expression);
397

    
398
                        if (sel == null) {
399
                                throw new RuntimeException("Not a 'where' clause?");
400
                        }
401

    
402
                        FBitSet selection = new FBitSet();
403

    
404
                        for (int i = 0; i < sel.length; i++) {
405
                                selection.set((int) sel[i]);
406
                        }
407

    
408
                        FBitSet fbs = dataSource.getSelection();
409
                        fbs.or(selection);
410
                        dataSource.setSelection(fbs);
411
                }
412
        }
413

    
414
        /**
415
         * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#fromSet(java.lang.String)
416
         */
417
        public void fromSet(String expression) {
418
                // By Pablo: if no expression -> no element selected
419
                if (! this.filterExpressionFromWhereIsEmpty(expression)) {
420
                        long[] sel = doSet(expression);
421

    
422
                        if (sel == null) {
423
                                throw new RuntimeException("Not a 'where' clause?");
424
                        }
425

    
426
                        FBitSet selection = new FBitSet();
427

    
428
                        for (int i = 0; i < sel.length; i++) {
429
                                selection.set((int) sel[i]);
430
                        }
431

    
432
                        FBitSet fbs = dataSource.getSelection();
433
                        fbs.and(selection);
434
                        dataSource.setSelection(fbs);
435
                }
436
                else {
437
                        // By Pablo: if no expression -> no element selected
438
                        dataSource.clearSelection();
439
                }
440
        }
441

    
442
        /**
443
         * Returns true if the WHERE subconsultation of the filterExpression is empty ("")
444
         *
445
         * @author Pablo Piqueras Bartolom? (p_queras@hotmail.com)
446
         * @param expression An string
447
         * @return A boolean value
448
         */
449
        private boolean filterExpressionFromWhereIsEmpty(String expression) {
450
                String subExpression = expression.trim();
451
                int pos;
452

    
453
                // Remove last ';' if exists
454
                if (subExpression.charAt(subExpression.length() -1) == ';')
455
                        subExpression = subExpression.substring(0, subExpression.length() -1).trim();
456

    
457
                // If there is no 'where' clause
458
                if ((pos = subExpression.indexOf("where")) == -1)
459
                        return false;
460

    
461
                // If there is no subexpression in the WHERE clause -> true
462
                subExpression = subExpression.substring(pos + 5, subExpression.length()).trim(); // + 5 is the length of 'where'
463
                if ( subExpression.length() == 0 )
464
                        return true;
465
                else
466
                        return false;
467
        }
468

    
469
        /**
470
         * @see com.iver.mdiApp.plugins.IExtension#isVisible()
471
         */
472
        public boolean isVisible() {
473
                IWindow v = PluginServices.getMDIManager().getActiveWindow();
474

    
475
                if (v == null) {
476
                        return false;
477
                }
478

    
479
                if (v instanceof Table) {
480
                        return true;
481
                } /*else {
482
                        if (v instanceof com.iver.cit.gvsig.gui.View) {
483
                                com.iver.cit.gvsig.gui.View view = (com.iver.cit.gvsig.gui.View) v;
484
                                ProjectView pv = view.getModel();
485
                                FLayer[] seleccionadas = pv.getMapContext().getLayers()
486
                                                                                   .getActives();
487

488
                                if (seleccionadas.length == 1) {
489
                                        if (seleccionadas[0] instanceof AlphanumericData) {
490
                                                return true;
491
                                        }
492
                                }
493
                        }
494
*/
495
                        return false;
496
                //}
497
        }
498

    
499
        /**
500
         * @see com.iver.andami.plugins.IExtension#initialize()
501
         */
502
        public void initialize() {
503
        }
504

    
505
        /**
506
         * @see com.iver.andami.plugins.IExtension#isEnabled()
507
         */
508
        public boolean isEnabled() {
509
                return true;
510
        }
511

    
512

    
513
}