Statistics
| Revision:

svn-gvsig-desktop / trunk / applications / appgvSIG / src / com / iver / cit / gvsig / TableOperations.java @ 28248

History | View | Annotate | Download (16.9 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.JoinWizardController;
70
import com.iver.cit.gvsig.project.documents.table.gui.Table;
71
import com.iver.utiles.swing.objectSelection.SelectionException;
72
import com.iver.utiles.swing.wizard.WizardControl;
73
import com.iver.utiles.swing.wizard.WizardEvent;
74
import com.iver.utiles.swing.wizard.WizardListener;
75

    
76

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

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

    
103
                                final ObjectSelectionStep targetTable = new ObjectSelectionStep();
104
                                targetTable.setModel(new TableSelectionModel(pts,
105
                                        PluginServices.getText(this, "seleccione_tabla_a_enlazar")));
106

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

    
116
                                wiz.addWizardListener(new WizardListener() {
117
                                                public void cancel(WizardEvent w) {
118
                                                        PluginServices.getMDIManager().closeWindow(wiz);
119
                                                }
120

    
121
                                                public void finished(WizardEvent w) {
122
                                                        PluginServices.getMDIManager().closeWindow(wiz);
123

    
124
                                                        ProjectTable sourceProjectTable = (ProjectTable) sourceTable.getSelected();
125
                                                        SelectableDataSource sds1=null;;
126
                                                        try {
127
                                                                sds1 = sourceProjectTable.getModelo().getRecordset();
128
                                                        } catch (ReadDriverException e) {
129
                                                                e.printStackTrace();
130
                                                        }
131
                                                        //String tableName1 = sds1.getName();
132

    
133
                                                        ProjectTable targetProjectTable = (ProjectTable) targetTable.getSelected();
134
                                                        SelectableDataSource sds2=null;
135
                                                        try {
136
                                                                sds2 = targetProjectTable.getModelo().getRecordset();
137
                                                        } catch (ReadDriverException e) {
138
                                                                e.printStackTrace();
139
                                                        }
140

    
141
                                                        //String tableName2 = sds2.getName();
142

    
143
                                                        String field1 = (String) firstTableField.getSelected();
144
                                                        String field2 = (String) secondTableField.getSelected();
145
                                                        sourceProjectTable.setLinkTable(sds2.getName(),field1,field2);
146
                                                        ((ProjectExtension)PluginServices.getExtension(ProjectExtension.class)).getProject().setLinkTable();
147
                                                }
148

    
149
                                                public void next(WizardEvent w) {
150
                                                        WizardControl wiz = w.wizard;
151
                                                        wiz.enableBack(true);
152
                                                        wiz.enableNext(((ObjectSelectionStep) wiz.getCurrentStep()).getSelectedItem() != null);
153

    
154
                                                        if (w.currentStep == 1) {
155
                                                                ProjectTable pt = (ProjectTable) sourceTable.getSelected();
156

    
157
                                                                try {
158
                                                                        firstTableField.setModel(new FieldSelectionModel(
159
                                                                                        pt.getModelo().getRecordset(),
160
                                                                                        PluginServices.getText(this, "seleccione_campo_enlace"),
161
                                                                                        -1));
162
                                                                } catch (SelectionException e) {
163
                                                                        NotificationManager.addError("Error obteniendo los campos de la tabla",
164
                                                                                e);
165
                                                                } catch (ReadDriverException e) {
166
                                                                        e.printStackTrace();
167
                                                                }
168
                                                        } else if (w.currentStep == 3) {
169
                                                                try {
170
                                                                        //tabla
171
                                                                        ProjectTable pt = (ProjectTable) sourceTable.getSelected();
172

    
173
                                                                        //?ndice del campo
174
                                                                        SelectableDataSource sds = pt.getModelo().getRecordset();
175
                                                                        String fieldName = (String) firstTableField.getSelected();
176
                                                                        int fieldIndex = sds.getFieldIndexByName(fieldName);
177
                                                                        int type = sds.getFieldType(fieldIndex);
178

    
179
                                                                        secondTableField.setModel(new FieldSelectionModel(
180
                                                                                        ((ProjectTable) targetTable.getSelected()).getModelo().getRecordset(),
181
                                                                                        PluginServices.getText(this, "seleccione_campo_enlace"),
182
                                                                                        type));
183
                                                                } catch (SelectionException e) {
184
                                                                        NotificationManager.addError("Error obteniendo los campos de la tabla",
185
                                                                                e);
186
                                                                } catch (ReadDriverException e) {
187
                                                                        NotificationManager.addError("Error obteniendo los campos de la tabla",
188
                                                                                e);
189
                                                                }
190
                                                        }
191
                                                }
192

    
193
                                                public void back(WizardEvent w) {
194
                                                        WizardControl wiz = w.wizard;
195
                                                        wiz.enableBack(true);
196
                                                        wiz.enableNext(((ObjectSelectionStep) wiz.getCurrentStep()).getSelectedItem() != null);
197
                                                }
198
                                        });
199
                                project.setModified(true);
200
                                PluginServices.getMDIManager().addWindow(wiz);
201
                        } catch (SelectionException e) {
202
                                NotificationManager.addError("Error abriendo el asistente", e);
203
                        }
204
              }
205
        }
206

    
207
        /**
208
         * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#newSet(java.lang.String)
209
         */
210
        public void newSet(String expression) {
211
                // By Pablo: if no expression -> no element selected
212
                if (! this.filterExpressionFromWhereIsEmpty(expression)) {
213
                        long[] sel = doSet(expression);
214

    
215
                        if (sel == null) {
216
                                throw new RuntimeException("Not a 'where' clause?");
217
                        }
218

    
219
                        FBitSet selection = new FBitSet();
220

    
221
                        for (int i = 0; i < sel.length; i++) {
222
                                selection.set((int) sel[i]);
223
                        }
224

    
225
                        dataSource.clearSelection();
226
                        dataSource.setSelection(selection);
227
                }
228
                else {
229
                        // By Pablo: if no expression -> no element selected
230
                        dataSource.clearSelection();
231
                }
232
        }
233

    
234
        /**
235
         * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#newSet(java.lang.String)
236
         */
237
        private long[] doSet(String expression) {
238
                try {
239
                        DataSource ds = LayerFactory.getDataSourceFactory().executeSQL(expression,
240
                                        DataSourceFactory.MANUAL_OPENING);
241

    
242
                        return ds.getWhereFilter();
243
                } catch (DriverLoadException e) {
244
                        NotificationManager.addError("Error cargando el driver", e);
245
                } catch (ReadDriverException e) {
246
                        NotificationManager.addError("Error accediendo al driver", e);
247
                } catch (ParseException e) {
248
                        NotificationManager.addError("Parse error", e);
249
                } catch (SemanticException e) {
250
                        NotificationManager.addError(e.getMessage(), e);
251
                } catch (IOException e) {
252
                        NotificationManager.addError("GDBMS internal error", e);
253
                } catch (EvaluationException e) {
254
                        NotificationManager.addError("Error con la expresi?n", e);
255
        }
256

    
257
                return null;
258
        }
259

    
260
        /**
261
         * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#addToSet(java.lang.String)
262
         */
263
        public void addToSet(String expression) {
264
                // By Pablo: if no expression -> don't add more elements to set
265
                if (! this.filterExpressionFromWhereIsEmpty(expression)) {
266
                        long[] sel = doSet(expression);
267

    
268
                        if (sel == null) {
269
                                throw new RuntimeException("Not a 'where' clause?");
270
                        }
271

    
272
                        FBitSet selection = new FBitSet();
273

    
274
                        for (int i = 0; i < sel.length; i++) {
275
                                selection.set((int) sel[i]);
276
                        }
277

    
278
                        FBitSet fbs = dataSource.getSelection();
279
                        fbs.or(selection);
280
                        dataSource.setSelection(fbs);
281
                }
282
        }
283

    
284
        /**
285
         * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#fromSet(java.lang.String)
286
         */
287
        public void fromSet(String expression) {
288
                // By Pablo: if no expression -> no element selected
289
                if (! this.filterExpressionFromWhereIsEmpty(expression)) {
290
                        long[] sel = doSet(expression);
291

    
292
                        if (sel == null) {
293
                                throw new RuntimeException("Not a 'where' clause?");
294
                        }
295

    
296
                        FBitSet selection = new FBitSet();
297

    
298
                        for (int i = 0; i < sel.length; i++) {
299
                                selection.set((int) sel[i]);
300
                        }
301

    
302
                        FBitSet fbs = dataSource.getSelection();
303
                        fbs.and(selection);
304
                        dataSource.setSelection(fbs);
305
                }
306
                else {
307
                        // By Pablo: if no expression -> no element selected
308
                        dataSource.clearSelection();
309
                }
310
        }
311

    
312
        /**
313
         * Returns true if the WHERE subconsultation of the filterExpression is empty ("")
314
         *
315
         * @author Pablo Piqueras Bartolom? (p_queras@hotmail.com)
316
         * @param expression An string
317
         * @return A boolean value
318
         */
319
        private boolean filterExpressionFromWhereIsEmpty(String expression) {
320
                String subExpression = expression.trim();
321
                int pos;
322

    
323
                // Remove last ';' if exists
324
                if (subExpression.charAt(subExpression.length() -1) == ';')
325
                        subExpression = subExpression.substring(0, subExpression.length() -1).trim();
326

    
327
                // If there is no 'where' clause
328
                if ((pos = subExpression.indexOf("where")) == -1)
329
                        return false;
330

    
331
                // If there is no subexpression in the WHERE clause -> true
332
                subExpression = subExpression.substring(pos + 5, subExpression.length()).trim(); // + 5 is the length of 'where'
333
                if ( subExpression.length() == 0 )
334
                        return true;
335
                else
336
                        return false;
337
        }
338

    
339
        /**
340
         * @see com.iver.mdiApp.plugins.IExtension#isVisible()
341
         */
342
        public boolean isVisible() {
343
                IWindow v = PluginServices.getMDIManager().getActiveWindow();
344

    
345
                if (v == null) {
346
                        return false;
347
                }
348

    
349
                if (v instanceof Table) {
350
                        return true;
351
                } /*else {
352
                        if (v instanceof com.iver.cit.gvsig.gui.View) {
353
                                com.iver.cit.gvsig.gui.View view = (com.iver.cit.gvsig.gui.View) v;
354
                                ProjectView pv = view.getModel();
355
                                FLayer[] seleccionadas = pv.getMapContext().getLayers()
356
                                                                                   .getActives();
357

358
                                if (seleccionadas.length == 1) {
359
                                        if (seleccionadas[0] instanceof AlphanumericData) {
360
                                                return true;
361
                                        }
362
                                }
363
                        }
364
*/
365
                        return false;
366
                //}
367
        }
368

    
369
        /**
370
         * @see com.iver.andami.plugins.IExtension#initialize()
371
         */
372
        public void initialize() {
373
                registerIcons();
374
        }
375

    
376
        private void registerIcons(){
377
                PluginServices.getIconTheme().registerDefault(
378
                                "table-join",
379
                                this.getClass().getClassLoader().getResource("images/tablejoin.png")
380
                        );
381

    
382
                PluginServices.getIconTheme().registerDefault(
383
                                "table-link",
384
                                this.getClass().getClassLoader().getResource("images/tablelink.png")
385
                        );
386
        }
387

    
388
        /**
389
         * @see com.iver.andami.plugins.IExtension#isEnabled()
390
         */
391
        public boolean isEnabled() {
392
                return true;
393
        }
394

    
395
        public void execJoin(ProjectTable sourceProjectTable, String field1, String prefix1,
396
                        ProjectTable targetProjectTable, String field2, String prefix2) {
397
                // get source table and source field
398
                SelectableDataSource sds=null;
399
                try {
400
                        sds = sourceProjectTable.getModelo().getRecordset();
401
                } catch (ReadDriverException e) {
402
                        e.printStackTrace();
403
                }
404
                String tableName1 = sds.getName();
405
                // get target table and target field
406
                SelectableDataSource tds=null;
407
                try {
408
                        tds = targetProjectTable.getModelo().getRecordset();
409
                } catch (ReadDriverException e) {
410
                        e.printStackTrace();
411
                }
412
                String tableName2 = tds.getName();
413
                // compute the join
414
                String sql =
415
                        "custom com_iver_cit_gvsig_arcjoin tables '" +
416
                        tableName1 + "', '" + tableName2 + "' values(" +
417
                        field1 + ", " + field2 + ");";
418
                PluginServices.getLogger().debug(sql);
419

    
420
                try {
421
                        SelectableDataSource result = new SelectableDataSource(LayerFactory.getDataSourceFactory()
422
                                        .executeSQL(sql,
423
                                                        DataSourceFactory.AUTOMATIC_OPENING));
424
                        EditableAdapter auxea=new EditableAdapter();
425
                        auxea.setOriginalDataSource(result);
426
                        String[] currentJoinedTables = sourceProjectTable.getJoinedTables();
427
                        String[] joinedTables;
428
                        if (currentJoinedTables!=null) {
429
                                joinedTables = new String[currentJoinedTables.length+1];
430
                                System.arraycopy(currentJoinedTables, 0, joinedTables, 0, currentJoinedTables.length);
431
                        }
432
                        else {
433
                                joinedTables = new String[1];
434
                        }
435
                        joinedTables[joinedTables.length-1] = targetProjectTable.getName();
436
                        sourceProjectTable.setJoinTable(joinedTables);
437
                        sourceProjectTable.replaceDataSource(auxea);
438
                        renameFields(sourceProjectTable, sds, sanitizeFieldName(prefix1),
439
                                        tds, sanitizeFieldName(prefix2));
440
                } catch (ParseException e) {
441
                        throw new RuntimeException(e);
442
                } catch (DriverLoadException e) {
443
                        NotificationManager.addError(PluginServices.getText(this, "Error_loading_driver"),
444
                                        e);
445
                } catch (ReadDriverException e) {
446
                        NotificationManager.addError(PluginServices.getText(this, "Error_reading_from_the_driver"),
447
                                        e);
448
                } catch (SemanticException e) {
449
                        throw new RuntimeException(e);
450
                } catch (EvaluationException e) {
451
                        NotificationManager.addError(PluginServices.getText(this, "Error_evaluationg_expression"),
452
                                        e);
453
                }
454
        }
455
//        
456
//        /**
457
//         * Renames fields in a JOIN, so that fields from TABLE1
458
//         * become sourcePrefix.field1, sourcePrefix.field2, etc, and fields
459
//         * from TABLE2 become targetPrefix.field1, targetPrefix.field2, etc.
460
//         * @param eds
461
//         * @param pt1
462
//         * @param pt1
463
//         */
464
        
465
        /**
466
         * <p>Renames fields in a JOIN, so that fields from DataSource1
467
         * become sourcePrefix_field1, sourcePrefix_field2, etc, and fields
468
         * from TABLE2 become targetPrefix_field1, targetPrefix_field2, etc.
469
         * ProjectTable aliases are used to rename fields.</p>
470
         * 
471
         * @param targetPt The ProjectTable whose fields are to be renamed
472
         * @param ds1 The first datasource in the join
473
         * @param prefix1 The prefix to apply to fields in ds1
474
         * @param ds2 The second datasource in the join
475
         * @param prefix2 The prefix to apply to fields in ds2
476
         */
477
        private void renameFields(ProjectTable targetPt, DataSource ds1, String prefix1,
478
                        DataSource ds2, String prefix2) {
479
                try {
480
                        SelectableDataSource sds = targetPt.getModelo().getRecordset();
481
                        String[] aliases = new String[sds.getFieldCount()];                        
482
                        int i=0;
483
                        while (i<aliases.length && i<ds1.getFieldCount()){
484
                                aliases[i] = prefix1+"_"+sds.getFieldName(i);
485
                                i++;
486
                        }
487
                        while (i<aliases.length) {
488
                                aliases[i] = prefix2 + "_" + sds.getFieldName(i).substring("link_".length());
489
                                i++;
490
                        }
491
                        targetPt.setAliases(aliases);
492
                } catch (ReadDriverException e) {
493
                        //just log the error, it's not bad if fields couldn't be renamed
494
                        PluginServices.getLogger().error("Error renaming fields in a JOIN", e);
495
                } catch (Exception e) {
496
                        //just log the error, it's not bad if fields couldn't be renamed
497
                        PluginServices.getLogger().error("Error renaming fields in a JOIN", e);
498
                }
499
        }
500

    
501
        /**
502
         * Ensure that field name only has 'safe' characters
503
         * (no spaces, special characters, etc).
504
         */
505
        public String sanitizeFieldName(String fieldName) {
506
                return fieldName.replaceAll("\\W", "_"); // replace any non-word character by an underscore
507
        }
508

    
509
}