Statistics
| Revision:

root / branches / v2_0_0_prep / applications / appgvSIG / src / com / iver / cit / gvsig / TableOperations.java @ 24759

History | View | Annotate | Download (16.7 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.Component;
44
import java.awt.Dimension;
45
import java.util.Iterator;
46

    
47
import javax.swing.JOptionPane;
48

    
49
import org.gvsig.fmap.dal.DataManager;
50
import org.gvsig.fmap.dal.exception.DataException;
51
import org.gvsig.fmap.dal.exception.ReadException;
52
import org.gvsig.fmap.dal.feature.Feature;
53
import org.gvsig.fmap.dal.feature.FeatureStore;
54
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
55
import org.opengis.feature.FeatureCollection;
56

    
57
import com.iver.andami.PluginServices;
58
import com.iver.andami.messages.NotificationManager;
59
import com.iver.andami.plugins.Extension;
60
import com.iver.andami.ui.mdiManager.IWindow;
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 FeatureStore featureStore = 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 = 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
                                                        FeatureStore fs1 = sourceProjectTable.getModel();
122
                                                        String tableName1 = fs1.getName();
123

    
124
                                                        ProjectTable targetProjectTable = (ProjectTable) targetTable.getSelected();
125
                                                        FeatureStore fs2 = targetProjectTable.getModel();
126

    
127
                                                        String tableName2 = fs2.getName();
128

    
129
                                                        String field1 = (String) firstTableField.getSelected();
130
                                                        String field2 = (String) secondTableField.getSelected();
131

    
132
                                                        String sql =
133
                                                                "custom com_iver_cit_gvsig_arcjoin tables '" +
134
                                                                tableName1 + "', '" + tableName2 + "' values(" +
135
                                                                field1 + ", " + field2 + ");";
136
                                                        System.out.println(sql);
137

    
138
                                                        try {
139
                                                                DataManager dm=DataManager.getManager();
140
                                                                JoinFeatureStoreParameters jfsp=(JoinFeatureStoreParameters)dm.createDataStoreParameters(JoinFeatureStore.DATASTORE_NAME);
141
                                                                jfsp.setStorePrimary(fs1.getParameters());
142
                                                                jfsp.setStoreSecondary(fs2.getParameters());
143
                                                                jfsp.setDefaultGeometry(fs1.getDefaultFeatureType().getDefaultGeometry());
144
                                                                jfsp.setFieldNamePrefix("Join_");
145
                                                                jfsp.setLinkFieldPrimary(field1);
146
                                                                jfsp.setLinkFieldSecondary(field2);
147

    
148
                                                                JoinFeatureStore jfs=(JoinFeatureStore)dm.createDataStore(jfsp);
149
                                                                featureStore=jfs;
150
                                                                ProjectTable projectTable = (ProjectTable) sourceTable.getSelected();
151
                                                                FeatureStore original = projectTable.getModel();
152
                                                                projectTable.setModel(jfs);
153

    
154
                                                                if (projectTable.getAssociatedTable() != null) {
155
                                                                projectTable.getAssociatedTable().setDataStore(
156
                                                                                jfs);
157
                                                        }
158

    
159
                                                                original.dispose();
160

    
161
                                                                IWindow[] windows=PluginServices.getMDIManager().getAllWindows();
162
                                                                Table tableWindow;
163
                                                                for (int i = 0; i < windows.length; i++) {
164
                                                                        if (windows[i] instanceof Table){
165
                                                                                tableWindow = (Table) windows[i];
166
                                                                        if (tableWindow.getModel().equals(
167
                                                                                        projectTable)) {
168
                                                                                tableWindow.setModel(projectTable);
169
                                                                                }
170
                                                                        }
171
                                                                }
172
                                                        } catch (ReadException e) {
173
                                                                NotificationManager.addError("Error leyendo del driver",
174
                                                                        e);
175
                                                        } catch (LoadLayerException e) {
176
                                                                NotificationManager.addError(e);
177
                                                        }
178
                                                }
179

    
180
                                                public void next(WizardEvent w) {
181
                                                        WizardControl wiz = w.wizard;
182
                                                        wiz.enableBack(true);
183
                                                        wiz.enableNext(((ObjectSelectionStep) wiz.getCurrentStep()).getSelectedItem() != null);
184

    
185
                                                        if (w.currentStep == 1) {
186
                                                                ProjectTable pt = (ProjectTable) sourceTable.getSelected();
187

    
188
                                                                try {
189
                                                                        firstTableField.setModel(new FieldSelectionModel(
190
                                                                                        pt.getModel(),
191
                                                                                        PluginServices.getText(this, "seleccione_campo_enlace"),
192
                                                                                        null));
193
                                                                } catch (SelectionException e) {
194
                                                                        NotificationManager.addError("Error obteniendo los campos de la tabla",
195
                                                                                e);
196
                                                                }
197
                                                        } else if (w.currentStep == 3) {
198
                                                                try {
199
                                                                        //tabla
200
                                                                        ProjectTable pt = (ProjectTable) sourceTable.getSelected();
201

    
202
                                                                        //?ndice del campo
203
                                                                        FeatureStore fs = pt.getModel();
204
                                                                        String fieldName = (String) firstTableField.getSelected();
205
                                                                        String type = fs.getDefaultFeatureType().get(fieldName).getDataType();
206

    
207

    
208
                                                                        secondTableField.setModel(new FieldSelectionModel(
209
                                                                                        ((ProjectTable) targetTable
210
                                                                                                                .getSelected())
211
                                                                                                                .getModel(),
212
                                                                                        PluginServices.getText(this, "seleccione_campo_enlace"),
213
                                                                                        type));
214
                                                                } catch (SelectionException e) {
215
                                                                        NotificationManager.addError("Error obteniendo los campos de la tabla",
216
                                                                                e);
217
                                                                }
218
                                                        }
219
                                                }
220

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

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

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

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

    
256
                                                public void finished(WizardEvent w) {
257
                                                        PluginServices.getMDIManager().closeWindow(wiz);
258

    
259
                                                        ProjectTable sourceProjectTable = (ProjectTable) sourceTable.getSelected();
260
                                                        FeatureStore sds1 = sourceProjectTable.getModel();
261

    
262
                                                        ProjectTable targetProjectTable = (ProjectTable) targetTable.getSelected();
263
                                                        FeatureStore sds2 = targetProjectTable.getModel();
264

    
265
                                                        String field1 = (String) firstTableField.getSelected();
266
                                                        String field2 = (String) secondTableField.getSelected();
267
                                                        sourceProjectTable.setLinkTable(sds2.getName(),field1,field2);
268
                                                        ((ProjectExtension)PluginServices.getExtension(ProjectExtension.class)).getProject().setLinkTable();
269

    
270
                                                }
271

    
272
                                                public void next(WizardEvent w) {
273
                                                        WizardControl wiz = w.wizard;
274
                                                        wiz.enableBack(true);
275
                                                        wiz.enableNext(((ObjectSelectionStep) wiz.getCurrentStep()).getSelectedItem() != null);
276

    
277
                                                        if (w.currentStep == 1) {
278
                                                                ProjectTable pt = (ProjectTable) sourceTable.getSelected();
279

    
280
                                                                try {
281
                                                                        firstTableField.setModel(new FieldSelectionModel(
282
                                                                                        pt.getModel(),
283
                                                                                        PluginServices.getText(this, "seleccione_campo_enlace"),
284
                                                                                        null));
285
                                                                } catch (SelectionException e) {
286
                                                                        NotificationManager.addError("Error obteniendo los campos de la tabla",
287
                                                                                e);
288
                                                                }
289
                                                        } else if (w.currentStep == 3) {
290
                                                                try {
291
                                                                        //tabla
292
                                                                        ProjectTable pt = (ProjectTable) sourceTable.getSelected();
293

    
294
                                                                        //?ndice del campo
295
                                                                        FeatureStore fs = pt.getModel();
296
                                                                        String fieldName = (String) firstTableField.getSelected();
297
                                                                        String type = fs.getDefaultFeatureType().get(fieldName).getDataType();
298

    
299
                                                                        secondTableField.setModel(new FieldSelectionModel(
300
                                                                                        ((ProjectTable) targetTable
301
                                                                                                                .getSelected())
302
                                                                                                                .getModel(),
303
                                                                                        PluginServices.getText(this, "seleccione_campo_enlace"),
304
                                                                                        type));
305
                                                                } catch (SelectionException e) {
306
                                                                        NotificationManager.addError("Error obteniendo los campos de la tabla",
307
                                                                                e);
308
                                                                }
309
                                                        }
310
                                                }
311

    
312
                                                public void back(WizardEvent w) {
313
                                                        WizardControl wiz = w.wizard;
314
                                                        wiz.enableBack(true);
315
                                                        wiz.enableNext(((ObjectSelectionStep) wiz.getCurrentStep()).getSelectedItem() != null);
316
                                                }
317
                                        });
318
                                project.setModified(true);
319
                                PluginServices.getMDIManager().addWindow(wiz);
320
                        } catch (SelectionException e) {
321
                                NotificationManager.addError("Error abriendo el asistente", e);
322
                        }
323
              }
324
        }
325

    
326
        /**
327
         * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#newSet(java.lang.String)
328
         */
329
        public void newSet(String expression) throws DataException {
330
                // By Pablo: if no filter expression -> no element selected
331
                if (! this.filterExpressionFromWhereIsEmpty(expression)) {
332
                        try {
333
                                FeatureCollection sel = doSet(expression);
334

    
335
                                if (sel == null) {
336
                                        throw new RuntimeException("Not a 'where' clause?");
337
                                }
338
                                featureStore.setSelection(sel);
339
                        }catch(Exception e){
340
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), "Asegurate de que la consulta es correcta.");
341
                        }
342
                }
343
                else {
344
                        // By Pablo: if no expression -> no element selected
345
                        featureStore.getSelection().clear();
346
                }
347
        }
348

    
349
        /**
350
         * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#newSet(java.lang.String)
351
         */
352
        private FeatureCollection doSet(String expression) throws ReadException {
353
                return (FeatureCollection)featureStore.getDataCollection(featureStore.getDefaultFeatureType(),expression,null);
354
        }
355
        /**
356
         * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#addToSet(java.lang.String)
357
         */
358
        public void addToSet(String expression) throws DataException {
359
                // By Pablo: if no filter expression -> don't add more elements to set
360
                if (! this.filterExpressionFromWhereIsEmpty(expression)) {
361
                        FeatureCollection sel=null;
362
                        try {
363
                                sel = doSet(expression);
364
                        } catch (ReadException e) {
365
                                throw new DataException("Expression",e);
366
                        }
367

    
368
                        if (sel == null) {
369
                                throw new RuntimeException("Not a 'where' clause?");
370
                        }
371
                        FeatureCollection oldSelection=(FeatureCollection)featureStore.getSelection();
372
                        sel.addAll(oldSelection);
373
                        featureStore.setSelection(sel);
374
                }
375
        }
376

    
377
        /**
378
         * @see com.iver.cit.gvsig.gui.filter.ExpressionListener#fromSet(java.lang.String)
379
         */
380
        public void fromSet(String expression) throws DataException {
381
                // By Pablo: if no filter expression -> no element selected
382
                        if (! this.filterExpressionFromWhereIsEmpty(expression)) {
383

    
384
                                FeatureCollection sel=null;
385
                                sel = doSet(expression);
386

    
387
                                if (sel == null) {
388
                                        throw new RuntimeException("Not a 'where' clause?");
389
                                }
390
                                FeatureCollection oldSelection=(FeatureCollection)featureStore.getSelection();
391

    
392
                                MemoryFeatureCollection mfc=new MemoryFeatureCollection(featureStore);
393
                                Iterator iterator=sel.iterator();
394
                                while (iterator.hasNext()) {
395
                                        Feature feature = (Feature) iterator.next();
396
                                        if (oldSelection.contains(feature)){
397
                                                mfc.add(feature);
398
                                        }
399
                                }
400
                                featureStore.setSelection(mfc);
401
                        } else {
402
                                        // By Pablo: if no expression -> no element selected
403
                                        featureStore.setSelection(featureStore.createSelection());
404
                                }
405
        }
406

    
407
        /**
408
         * Returns true if the WHERE subconsultation of the filterExpression is empty ("")
409
         *
410
         * @author Pablo Piqueras Bartolom? (p_queras@hotmail.com)
411
         * @param expression An string
412
         * @return A boolean value
413
         */
414
        private boolean filterExpressionFromWhereIsEmpty(String expression) {
415
                String subExpression = expression.trim();
416
                int pos;
417

    
418
                // Remove last ';' if exists
419
                if (subExpression.charAt(subExpression.length() -1) == ';') {
420
                        subExpression = subExpression.substring(0, subExpression.length() -1).trim();
421
                }
422

    
423
                // If there is no 'where' clause
424
                if ((pos = subExpression.indexOf("where")) == -1) {
425
                        return false;
426
                }
427

    
428
                // If there is no subexpression in the WHERE clause -> true
429
                subExpression = subExpression.substring(pos + 5, subExpression.length()).trim(); // + 5 is the length of 'where'
430
                if ( subExpression.length() == 0 ) {
431
                        return true;
432
                } else {
433
                        return false;
434
                }
435
        }
436

    
437
        /**
438
         * @see com.iver.mdiApp.plugins.IExtension#isVisible()
439
         */
440
        public boolean isVisible() {
441
                IWindow v = PluginServices.getMDIManager().getActiveWindow();
442

    
443
                if (v == null) {
444
                        return false;
445
                }
446

    
447
                if (v instanceof Table) {
448
                        return true;
449
                } /*else {
450
                        if (v instanceof com.iver.cit.gvsig.gui.View) {
451
                                com.iver.cit.gvsig.gui.View view = (com.iver.cit.gvsig.gui.View) v;
452
                                ProjectView pv = view.getModel();
453
                                FLayer[] seleccionadas = pv.getMapContext().getLayers()
454
                                                                                   .getActives();
455

456
                                if (seleccionadas.length == 1) {
457
                                        if (seleccionadas[0] instanceof AlphanumericData) {
458
                                                return true;
459
                                        }
460
                                }
461
                        }
462
*/
463
                        return false;
464
                //}
465
        }
466

    
467
        /**
468
         * @see com.iver.andami.plugins.IExtension#initialize()
469
         */
470
        public void initialize() {
471
                registerIcons();
472
                org.gvsig.fmap.data.feature.joinstore.Register.selfRegister();
473

    
474

    
475
        }
476

    
477
        private void registerIcons(){
478
                PluginServices.getIconTheme().registerDefault(
479
                                "table-join",
480
                                this.getClass().getClassLoader().getResource("images/tablejoin.png")
481
                        );
482

    
483
                PluginServices.getIconTheme().registerDefault(
484
                                "table-link",
485
                                this.getClass().getClassLoader().getResource("images/tablelink.png")
486
                        );
487
        }
488

    
489
        /**
490
         * @see com.iver.andami.plugins.IExtension#isEnabled()
491
         */
492
        public boolean isEnabled() {
493
                return true;
494
        }
495

    
496

    
497
}