Statistics
| Revision:

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

History | View | Annotate | Download (18 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.Project;
62
import com.iver.cit.gvsig.project.documents.table.FieldSelectionModel;
63
import com.iver.cit.gvsig.project.documents.table.ObjectSelectionStep;
64
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
65
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
66
import com.iver.cit.gvsig.project.documents.table.TableSelectionModel;
67
import com.iver.cit.gvsig.project.documents.table.gui.AndamiWizard;
68
import com.iver.cit.gvsig.project.documents.table.gui.Table;
69
import com.iver.utiles.swing.objectSelection.SelectionException;
70
import com.iver.utiles.swing.wizard.WizardControl;
71
import com.iver.utiles.swing.wizard.WizardEvent;
72
import com.iver.utiles.swing.wizard.WizardListener;
73

    
74

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

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

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

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

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

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

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

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

    
137
                                                        String tableName2 = sds.getName();
138

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

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

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

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

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

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

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

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

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

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

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

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

    
258
                                                public void finished(WizardEvent w) {
259
                                                        PluginServices.getMDIManager().closeWindow(wiz);
260

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

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

    
280
                                                        //String tableName2 = sds2.getName();
281

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

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

    
293
                                                        if (w.currentStep == 1) {
294
                                                                ProjectTable pt = (ProjectTable) sourceTable.getSelected();
295

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

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

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

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

    
350
        /**
351
         * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#newSet(java.lang.String)
352
         */
353
        public void newSet(String expression) {
354
                // By Pablo: if no expression -> no element selected
355
                if (! this.filterExpressionFromWhereIsEmpty(expression)) {
356
                        long[] sel = doSet(expression);
357

    
358
                        if (sel == null) {
359
                                throw new RuntimeException("Not a 'where' clause?");
360
                        }
361

    
362
                        FBitSet selection = new FBitSet();
363

    
364
                        for (int i = 0; i < sel.length; i++) {
365
                                selection.set((int) sel[i]);
366
                        }
367

    
368
                        dataSource.clearSelection();
369
                        dataSource.setSelection(selection);
370
                }
371
                else {
372
                        // By Pablo: if no expression -> no element selected
373
                        dataSource.clearSelection();
374
                }
375
        }
376

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

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

    
400
                return null;
401
        }
402

    
403
        /**
404
         * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#addToSet(java.lang.String)
405
         */
406
        public void addToSet(String expression) {
407
                // By Pablo: if no expression -> don't add more elements to set
408
                if (! this.filterExpressionFromWhereIsEmpty(expression)) {
409
                        long[] sel = doSet(expression);
410

    
411
                        if (sel == null) {
412
                                throw new RuntimeException("Not a 'where' clause?");
413
                        }
414

    
415
                        FBitSet selection = new FBitSet();
416

    
417
                        for (int i = 0; i < sel.length; i++) {
418
                                selection.set((int) sel[i]);
419
                        }
420

    
421
                        FBitSet fbs = dataSource.getSelection();
422
                        fbs.or(selection);
423
                        dataSource.setSelection(fbs);
424
                }
425
        }
426

    
427
        /**
428
         * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#fromSet(java.lang.String)
429
         */
430
        public void fromSet(String expression) {
431
                // By Pablo: if no expression -> no element selected
432
                if (! this.filterExpressionFromWhereIsEmpty(expression)) {
433
                        long[] sel = doSet(expression);
434

    
435
                        if (sel == null) {
436
                                throw new RuntimeException("Not a 'where' clause?");
437
                        }
438

    
439
                        FBitSet selection = new FBitSet();
440

    
441
                        for (int i = 0; i < sel.length; i++) {
442
                                selection.set((int) sel[i]);
443
                        }
444

    
445
                        FBitSet fbs = dataSource.getSelection();
446
                        fbs.and(selection);
447
                        dataSource.setSelection(fbs);
448
                }
449
                else {
450
                        // By Pablo: if no expression -> no element selected
451
                        dataSource.clearSelection();
452
                }
453
        }
454

    
455
        /**
456
         * Returns true if the WHERE subconsultation of the filterExpression is empty ("")
457
         *
458
         * @author Pablo Piqueras Bartolom? (p_queras@hotmail.com)
459
         * @param expression An string
460
         * @return A boolean value
461
         */
462
        private boolean filterExpressionFromWhereIsEmpty(String expression) {
463
                String subExpression = expression.trim();
464
                int pos;
465

    
466
                // Remove last ';' if exists
467
                if (subExpression.charAt(subExpression.length() -1) == ';')
468
                        subExpression = subExpression.substring(0, subExpression.length() -1).trim();
469

    
470
                // If there is no 'where' clause
471
                if ((pos = subExpression.indexOf("where")) == -1)
472
                        return false;
473

    
474
                // If there is no subexpression in the WHERE clause -> true
475
                subExpression = subExpression.substring(pos + 5, subExpression.length()).trim(); // + 5 is the length of 'where'
476
                if ( subExpression.length() == 0 )
477
                        return true;
478
                else
479
                        return false;
480
        }
481

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

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

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

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

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

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

    
525

    
526
}