Statistics
| Revision:

root / branches / v2_0_0_prep / applications / appgvSIG / src / org / gvsig / app / extension / TableOperations.java @ 31496

History | View | Annotate | Download (12.1 KB)

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

    
43
import java.awt.Component;
44
import java.awt.Dimension;
45

    
46
import javax.swing.JOptionPane;
47

    
48
import org.gvsig.andami.PluginServices;
49
import org.gvsig.andami.messages.NotificationManager;
50
import org.gvsig.andami.plugins.Extension;
51
import org.gvsig.andami.ui.mdiManager.IWindow;
52
import org.gvsig.app.gui.filter.ExpressionListener;
53
import org.gvsig.app.project.Project;
54
import org.gvsig.app.project.ProjectManager;
55
import org.gvsig.app.project.documents.gui.AndamiWizard;
56
import org.gvsig.app.project.documents.gui.ObjectSelectionStep;
57
import org.gvsig.app.project.documents.table.TableDocument;
58
import org.gvsig.app.project.documents.table.TableManager;
59
import org.gvsig.app.project.documents.table.FieldSelectionModel;
60
import org.gvsig.app.project.documents.table.TableSelectionModel;
61
import org.gvsig.app.project.documents.table.gui.FeatureTableDocumentPanel;
62
import org.gvsig.fmap.dal.DALLocator;
63
import org.gvsig.fmap.dal.DataTypes;
64
import org.gvsig.fmap.dal.exception.DataException;
65
import org.gvsig.fmap.dal.feature.DisposableIterator;
66
import org.gvsig.fmap.dal.feature.Feature;
67
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
68
import org.gvsig.fmap.dal.feature.FeatureQuery;
69
import org.gvsig.fmap.dal.feature.FeatureSelection;
70
import org.gvsig.fmap.dal.feature.FeatureSet;
71
import org.gvsig.fmap.dal.feature.FeatureStore;
72
import org.gvsig.tools.dispose.DisposeUtils;
73
import org.gvsig.utils.swing.objectSelection.SelectionException;
74
import org.gvsig.utils.swing.wizard.WizardControl;
75
import org.gvsig.utils.swing.wizard.WizardEvent;
76
import org.gvsig.utils.swing.wizard.WizardListener;
77

    
78

    
79

    
80
/**
81
 * Extensi?n que controla las operaciones realizadas sobre las tablas.
82
 *
83
 * @author Fernando Gonz?lez Cort?s
84
 */
85
public class TableOperations extends Extension implements ExpressionListener {
86
        private FeatureStore featureStore = null;
87

    
88
        public void execute(String actionCommand) {
89
                final Project project = ProjectManager.getInstance().getCurrentProject();
90
                TableDocument[] pts = (TableDocument[]) project.getDocuments(TableManager.TYPENAME).toArray(); 
91
                
92
                if ("LINK".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
                                                TableDocument sourceProjectTable = (TableDocument) sourceTable.getSelected();
120
                                                FeatureStore sds1 = sourceProjectTable.getStore();
121

    
122
                                                TableDocument targetProjectTable = (TableDocument) targetTable.getSelected();
123
                                                FeatureStore sds2 = targetProjectTable.getStore();
124

    
125
                                                String field1 = (String) firstTableField.getSelected();
126
                                                String field2 = (String) secondTableField.getSelected();
127
                                                sourceProjectTable.setLinkTable(sds2.getName(),field1,field2);
128

    
129
                                        }
130

    
131
                                        public void next(WizardEvent w) {
132
                                                WizardControl wiz = w.wizard;
133
                                                wiz.enableBack(true);
134
                                                wiz.enableNext(((ObjectSelectionStep) wiz.getCurrentStep()).getSelectedItem() != null);
135

    
136
                                                if (w.currentStep == 1) {
137
                                                        TableDocument pt = (TableDocument) sourceTable.getSelected();
138

    
139
                                                        try {
140
                                                                firstTableField.setModel(new FieldSelectionModel(
141
                                                                                pt.getStore(),
142
                                                                                PluginServices.getText(this, "seleccione_campo_enlace"),
143
                                                                                DataTypes.STRING));
144
                                                        } catch (SelectionException e) {
145
                                                                NotificationManager.addError("Error obteniendo los campos de la tabla",
146
                                                                                e);
147
                                                        }
148
                                                } else if (w.currentStep == 3) {
149
                                                        try {
150
                                                                //tabla
151
                                                                TableDocument pt = (TableDocument) sourceTable.getSelected();
152

    
153
                                                                //?ndice del campo
154
                                                                FeatureStore fs = pt.getStore();
155
                                                                String fieldName = (String) firstTableField.getSelected();
156
                                                                int type = ((FeatureAttributeDescriptor)fs.getDefaultFeatureType().get(fieldName)).getDataType();
157

    
158
                                                                secondTableField.setModel(new FieldSelectionModel(
159
                                                                                ((TableDocument) targetTable
160
                                                                                                .getSelected())
161
                                                                                                .getStore(),
162
                                                                                                PluginServices.getText(this, "seleccione_campo_enlace"),
163
                                                                                                type));
164
                                                        } catch (SelectionException e) {
165
                                                                NotificationManager.addError("Error obteniendo los campos de la tabla",
166
                                                                                e);
167
                                                        } catch (DataException e) {
168
                                                                NotificationManager.addError("Error obteniendo los campos de la tabla",
169
                                                                                e);
170
                                                        }
171
                                                }
172
                                        }
173

    
174
                                        public void back(WizardEvent w) {
175
                                                WizardControl wiz = w.wizard;
176
                                                wiz.enableBack(true);
177
                                                wiz.enableNext(((ObjectSelectionStep) wiz.getCurrentStep()).getSelectedItem() != null);
178
                                        }
179
                                });
180
                                project.setModified(true);
181
                                PluginServices.getMDIManager().addWindow(wiz);
182
                        } catch (SelectionException e) {
183
                                NotificationManager.addError("Error abriendo el asistente", e);
184
                        }
185
                }
186
        }
187

    
188
        /**
189
         * @see org.gvsig.app.gui.filter.ExpressionListener#newSet(java.lang.String)
190
         */
191
        public void newSet(String expression) throws DataException {
192
                // By Pablo: if no filter expression -> no element selected
193
                if (! this.filterExpressionFromWhereIsEmpty(expression)) {
194
                        FeatureSet set = null;
195
                        try {
196
                                set = doSet(expression);
197

    
198
                                if (set == null) {
199
                                        throw new RuntimeException("Not a 'where' clause?");
200
                                }
201
                                FeatureSelection newSel =featureStore.createFeatureSelection();
202
                                newSel.select(set);
203
                                featureStore.setSelection(newSel);
204
                        }catch(Exception e){
205
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), "Asegurate de que la consulta es correcta.");
206
                        }
207
                        finally {
208
                                if (set != null) {
209
                                        set.dispose();
210
                                }
211
                        }
212
                }
213
                else {
214
                        // By Pablo: if no expression -> no element selected
215
                        featureStore.getFeatureSelection().deselectAll();
216
                }
217
        }
218

    
219
        /**
220
         * @see org.gvsig.app.gui.filter.ExpressionListener#newSet(java.lang.String)
221
         */
222
        private FeatureSet doSet(String expression) throws DataException {
223
                FeatureQuery query = featureStore.createFeatureQuery();
224
                query
225
                .setFilter(DALLocator.getDataManager().createExpresion(
226
                                expression));
227
                return featureStore.getFeatureSet(query);
228
        }
229
        /**
230
         * @see org.gvsig.app.gui.filter.ExpressionListener#addToSet(java.lang.String)
231
         */
232
        public void addToSet(String expression) throws DataException {
233
                // By Pablo: if no filter expression -> don't add more elements to set
234
                if (! this.filterExpressionFromWhereIsEmpty(expression)) {
235
                        FeatureSet set = null;
236
                        try {
237
                                set = doSet(expression);
238

    
239
                                featureStore.getFeatureSelection().select(set);
240
                        } finally {
241
                                if (set != null) {
242
                                        set.dispose();
243
                                }
244
                        }
245
                }
246
        }
247

    
248
        /**
249
         * @see org.gvsig.app.gui.filter.ExpressionListener#fromSet(java.lang.String)
250
         */
251
        public void fromSet(String expression) throws DataException {
252
                // By Pablo: if no filter expression -> no element selected
253
                if (!this.filterExpressionFromWhereIsEmpty(expression)) {
254

    
255
                        FeatureSet set = null;
256
                        DisposableIterator iterator = null;
257
                        try {
258
                                set = doSet(expression);
259

    
260
                                if (set == null) {
261
                                        throw new RuntimeException("Not a 'where' clause?");
262
                                }
263
                                FeatureSelection oldSelection = featureStore
264
                                .getFeatureSelection();
265

    
266
                                FeatureSelection newSelection = featureStore
267
                                .createFeatureSelection();
268
                                iterator = set.iterator();
269
                                while (iterator.hasNext()) {
270
                                        Feature feature = (Feature) iterator.next();
271
                                        if (oldSelection.isSelected(feature)) {
272
                                                newSelection.select(feature);
273
                                        }
274
                                }
275
                                featureStore.setSelection(newSelection);
276
                        } finally {
277
                                DisposeUtils.dispose(iterator);
278
                                DisposeUtils.dispose(set);
279
                        }
280
                } else {
281
                        // By Pablo: if no expression -> no element selected
282
//                        featureStore.setSelection(featureStore.createSelection());
283
                        featureStore.getFeatureSelection().deselectAll();
284
                }
285
        }
286

    
287
        /**
288
         * Returns true if the WHERE subconsultation of the filterExpression is empty ("")
289
         *
290
         * @author Pablo Piqueras Bartolom? (p_queras@hotmail.com)
291
         * @param expression An string
292
         * @return A boolean value
293
         */
294
        private boolean filterExpressionFromWhereIsEmpty(String expression) {
295
                String subExpression = expression.trim();
296
                int pos;
297

    
298
                // Remove last ';' if exists
299
                if (subExpression.charAt(subExpression.length() -1) == ';') {
300
                        subExpression = subExpression.substring(0, subExpression.length() -1).trim();
301
                }
302

    
303
                // If there is no 'where' clause
304
                if ((pos = subExpression.indexOf("where")) == -1) {
305
                        return false;
306
                }
307

    
308
                // If there is no subexpression in the WHERE clause -> true
309
                subExpression = subExpression.substring(pos + 5, subExpression.length()).trim(); // + 5 is the length of 'where'
310
                if ( subExpression.length() == 0 ) {
311
                        return true;
312
                } else {
313
                        return false;
314
                }
315
        }
316

    
317
        /**
318
         * @see com.iver.mdiApp.plugins.IExtension#isVisible()
319
         */
320
        public boolean isVisible() {
321
                IWindow v = PluginServices.getMDIManager().getActiveWindow();
322

    
323
                if (v == null) {
324
                        return false;
325
                }
326

    
327
                if (v instanceof FeatureTableDocumentPanel) {
328
                        return true;
329
                } /*else {
330
                        if (v instanceof com.iver.cit.gvsig.gui.View) {
331
                                com.iver.cit.gvsig.gui.View view = (com.iver.cit.gvsig.gui.View) v;
332
                                ProjectView pv = view.getModel();
333
                                FLayer[] seleccionadas = pv.getMapContext().getLayers()
334
                                                                                   .getActives();
335

336
                                if (seleccionadas.length == 1) {
337
                                        if (seleccionadas[0] instanceof AlphanumericData) {
338
                                                return true;
339
                                        }
340
                                }
341
                        }
342
                 */
343
                return false;
344
                //}
345
        }
346

    
347
        /**
348
         * @see org.gvsig.andami.plugins.IExtension#initialize()
349
         */
350
        public void initialize() {
351
                registerIcons();
352
                //                FIXME
353
                //                org.gvsig.fmap.data.feature.joinstore.Register.selfRegister();
354

    
355

    
356
        }
357

    
358
        private void registerIcons(){
359
                PluginServices.getIconTheme().registerDefault(
360
                                "table-join",
361
                                this.getClass().getClassLoader().getResource("images/tablejoin.png")
362
                );
363

    
364
                PluginServices.getIconTheme().registerDefault(
365
                                "table-link",
366
                                this.getClass().getClassLoader().getResource("images/tablelink.png")
367
                );
368
        }
369

    
370
        /**
371
         * @see org.gvsig.andami.plugins.IExtension#isEnabled()
372
         */
373
        public boolean isEnabled() {
374
                return true;
375
        }
376

    
377
        /**
378
         * Ensure that field name only has 'safe' characters
379
         * (no spaces, special characters, etc).
380
         */
381
        public String sanitizeFieldName(String fieldName) {
382
                return fieldName.replaceAll("\\W", "_"); // replace any non-word character by an underscore
383
        }
384

    
385

    
386
}