Statistics
| Revision:

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

History | View | Annotate | Download (12.2 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.documents.gui.AndamiWizard;
54
import org.gvsig.app.project.documents.gui.ObjectSelectionStep;
55
import org.gvsig.app.project.documents.table.FeatureTableDocument;
56
import org.gvsig.app.project.documents.table.FeatureTableDocumentFactory;
57
import org.gvsig.app.project.documents.table.FieldSelectionModel;
58
import org.gvsig.app.project.documents.table.TableSelectionModel;
59
import org.gvsig.app.project.documents.table.gui.FeatureTableDocumentPanel;
60
import org.gvsig.fmap.dal.DALLocator;
61
import org.gvsig.fmap.dal.DataTypes;
62
import org.gvsig.fmap.dal.exception.DataException;
63
import org.gvsig.fmap.dal.feature.DisposableIterator;
64
import org.gvsig.fmap.dal.feature.Feature;
65
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
66
import org.gvsig.fmap.dal.feature.FeatureQuery;
67
import org.gvsig.fmap.dal.feature.FeatureSelection;
68
import org.gvsig.fmap.dal.feature.FeatureSet;
69
import org.gvsig.fmap.dal.feature.FeatureStore;
70
import org.gvsig.utils.swing.objectSelection.SelectionException;
71
import org.gvsig.utils.swing.wizard.WizardControl;
72
import org.gvsig.utils.swing.wizard.WizardEvent;
73
import org.gvsig.utils.swing.wizard.WizardListener;
74
import org.opengis.feature.FeatureCollection;
75

    
76

    
77

    
78
/**
79
 * Extensi?n que controla las operaciones realizadas sobre las tablas.
80
 *
81
 * @author Fernando Gonz?lez Cort?s
82
 */
83
public class TableOperations extends Extension implements ExpressionListener {
84
        private FeatureStore featureStore = null;
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
                org.gvsig.app.project.Project project=pe.getProject();
92
                FeatureTableDocument[] pts = project.getDocumentsByType(FeatureTableDocumentFactory.registerName)
93
                .toArray(new FeatureTableDocument[0]);
94
                if ("LINK".equals(actionCommand)) {
95
                        try {
96
                                final ObjectSelectionStep sourceTable = new ObjectSelectionStep();
97
                                sourceTable.setModel(new TableSelectionModel(pts,
98
                                                PluginServices.getText(this, "seleccione_tabla_origen")));
99

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

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

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

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

    
121
                                                FeatureTableDocument sourceProjectTable = (FeatureTableDocument) sourceTable.getSelected();
122
                                                FeatureStore sds1 = sourceProjectTable.getStore();
123

    
124
                                                FeatureTableDocument targetProjectTable = (FeatureTableDocument) targetTable.getSelected();
125
                                                FeatureStore sds2 = targetProjectTable.getStore();
126

    
127
                                                String field1 = (String) firstTableField.getSelected();
128
                                                String field2 = (String) secondTableField.getSelected();
129
                                                sourceProjectTable.setLinkTable(sds2.getName(),field1,field2);
130
                                                ((ProjectExtension)PluginServices.getExtension(ProjectExtension.class)).getProject().setLinkTable();
131

    
132
                                        }
133

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

    
139
                                                if (w.currentStep == 1) {
140
                                                        FeatureTableDocument pt = (FeatureTableDocument) sourceTable.getSelected();
141

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

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

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

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

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

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

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

    
236
                        featureStore.getFeatureSelection().select(set);
237
                        set.dispose();
238
                }
239
        }
240

    
241
        /**
242
         * @see org.gvsig.app.gui.filter.ExpressionListener#fromSet(java.lang.String)
243
         */
244
        public void fromSet(String expression) throws DataException {
245
                // By Pablo: if no filter expression -> no element selected
246
                if (!this.filterExpressionFromWhereIsEmpty(expression)) {
247

    
248
                        FeatureSet set = null;
249
                        DisposableIterator iterator = null;
250
                        try {
251
                                set = doSet(expression);
252

    
253
                                if (set == null) {
254
                                        throw new RuntimeException("Not a 'where' clause?");
255
                                }
256
                                FeatureCollection oldSelection = (FeatureCollection) featureStore
257
                                .getSelection();
258

    
259
                                FeatureSelection newSelection = featureStore
260
                                .createFeatureSelection();
261
                                iterator = set.iterator();
262
                                while (iterator.hasNext()) {
263
                                        Feature feature = (Feature) iterator.next();
264
                                        if (oldSelection.contains(feature)) {
265
                                                newSelection.select(feature);
266
                                        }
267
                                }
268
                                featureStore.setSelection(newSelection);
269
                        } finally {
270
                                if (iterator != null){
271
                                        iterator.dispose();
272
                                }
273
                                if (set != null){
274
                                        set.dispose();
275
                                }
276
                        }
277
                } else {
278
                        // By Pablo: if no expression -> no element selected
279
                        featureStore.setSelection(featureStore.createSelection());
280
                }
281
        }
282

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

    
294
                // Remove last ';' if exists
295
                if (subExpression.charAt(subExpression.length() -1) == ';') {
296
                        subExpression = subExpression.substring(0, subExpression.length() -1).trim();
297
                }
298

    
299
                // If there is no 'where' clause
300
                if ((pos = subExpression.indexOf("where")) == -1) {
301
                        return false;
302
                }
303

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

    
313
        /**
314
         * @see com.iver.mdiApp.plugins.IExtension#isVisible()
315
         */
316
        public boolean isVisible() {
317
                IWindow v = PluginServices.getMDIManager().getActiveWindow();
318

    
319
                if (v == null) {
320
                        return false;
321
                }
322

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

332
                                if (seleccionadas.length == 1) {
333
                                        if (seleccionadas[0] instanceof AlphanumericData) {
334
                                                return true;
335
                                        }
336
                                }
337
                        }
338
                 */
339
                return false;
340
                //}
341
        }
342

    
343
        /**
344
         * @see org.gvsig.andami.plugins.IExtension#initialize()
345
         */
346
        public void initialize() {
347
                registerIcons();
348
                //                FIXME
349
                //                org.gvsig.fmap.data.feature.joinstore.Register.selfRegister();
350

    
351

    
352
        }
353

    
354
        private void registerIcons(){
355
                PluginServices.getIconTheme().registerDefault(
356
                                "table-join",
357
                                this.getClass().getClassLoader().getResource("images/tablejoin.png")
358
                );
359

    
360
                PluginServices.getIconTheme().registerDefault(
361
                                "table-link",
362
                                this.getClass().getClassLoader().getResource("images/tablelink.png")
363
                );
364
        }
365

    
366
        /**
367
         * @see org.gvsig.andami.plugins.IExtension#isEnabled()
368
         */
369
        public boolean isEnabled() {
370
                return true;
371
        }
372

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

    
381

    
382
}