Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / extensions / org.gvsig.app.document.table.app / org.gvsig.app.document.table.app.mainplugin / src / main / java / org / gvsig / app / extension / TableOperations.java @ 36443

History | View | Annotate | Download (16.1 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
 *
3
 * Copyright (C) 2007-2008 Infrastructures and Transports Department
4
 * of the Valencian Government (CIT)
5
 * 
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 2
9
 * of the License, or (at your option) any later version.
10
 * 
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 * 
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 
19
 * MA  02110-1301, USA.
20
 * 
21
 */
22
package org.gvsig.app.extension;
23

    
24
import java.awt.Component;
25
import java.awt.Dimension;
26
import java.util.List;
27

    
28
import javax.swing.JOptionPane;
29

    
30
import org.gvsig.andami.PluginServices;
31
import org.gvsig.andami.messages.NotificationManager;
32
import org.gvsig.andami.plugins.Extension;
33
import org.gvsig.andami.ui.mdiManager.IWindow;
34
import org.gvsig.app.gui.filter.ExpressionListener;
35
import org.gvsig.app.project.Project;
36
import org.gvsig.app.project.ProjectManager;
37
import org.gvsig.app.project.documents.Document;
38
import org.gvsig.app.project.documents.gui.AndamiWizard;
39
import org.gvsig.app.project.documents.gui.ObjectSelectionStep;
40
import org.gvsig.app.project.documents.table.FieldSelectionModel;
41
import org.gvsig.app.project.documents.table.TableDocument;
42
import org.gvsig.app.project.documents.table.TableManager;
43
import org.gvsig.app.project.documents.table.TableSelectionModel;
44
import org.gvsig.app.project.documents.table.gui.FeatureTableDocumentPanel;
45
import org.gvsig.fmap.dal.DALLocator;
46
import org.gvsig.fmap.dal.exception.DataException;
47
import org.gvsig.fmap.dal.feature.Feature;
48
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
49
import org.gvsig.fmap.dal.feature.FeatureQuery;
50
import org.gvsig.fmap.dal.feature.FeatureSelection;
51
import org.gvsig.fmap.dal.feature.FeatureSet;
52
import org.gvsig.fmap.dal.feature.FeatureStore;
53
import org.gvsig.tools.dispose.DisposableIterator;
54
import org.gvsig.tools.dispose.DisposeUtils;
55
import org.gvsig.utils.swing.objectSelection.SelectionException;
56
import org.gvsig.utils.swing.wizard.WizardControl;
57
import org.gvsig.utils.swing.wizard.WizardEvent;
58
import org.gvsig.utils.swing.wizard.WizardListener;
59

    
60
/**
61
 * Extensi?n que controla las operaciones realizadas sobre las tablas.
62
 * 
63
 * @author Fernando Gonz?lez Cort?s
64
 */
65
public class TableOperations extends Extension implements ExpressionListener {
66

    
67
    private FeatureStore featureStore = null;
68

    
69
    public void execute(String actionCommand) {
70
        final Project project =
71
            ProjectManager.getInstance().getCurrentProject();
72
        List<Document> tableDcouments =
73
            project.getDocuments(TableManager.TYPENAME);
74
        TableDocument[] pts =
75
            tableDcouments
76
                .toArray(new TableDocument[tableDcouments.size()]);
77

    
78
        if ("LINK".equals(actionCommand)) {
79
            try {
80
                final ObjectSelectionStep sourceTable =
81
                    new ObjectSelectionStep();
82
                sourceTable.setModel(new TableSelectionModel(pts,
83
                    PluginServices.getText(this, "seleccione_tabla_origen")));
84

    
85
                final ObjectSelectionStep targetTable =
86
                    new ObjectSelectionStep();
87
                targetTable
88
                    .setModel(new TableSelectionModel(pts, PluginServices
89
                        .getText(this, "seleccione_tabla_a_enlazar")));
90

    
91
                final ObjectSelectionStep firstTableField =
92
                    new ObjectSelectionStep();
93
                final ObjectSelectionStep secondTableField =
94
                    new ObjectSelectionStep();
95
                final AndamiWizard wiz =
96
                    new AndamiWizard(PluginServices.getText(this, "back"),
97
                        PluginServices.getText(this, "next"),
98
                        PluginServices.getText(this, "finish"),
99
                        PluginServices.getText(this, "cancel"));
100
                wiz.setSize(new Dimension(450, 200));
101
                wiz.addStep(sourceTable);
102
                wiz.addStep(firstTableField);
103
                wiz.addStep(targetTable);
104
                wiz.addStep(secondTableField);
105

    
106
                wiz.addWizardListener(new WizardListener() {
107

    
108
                    public void cancel(WizardEvent w) {
109
                        PluginServices.getMDIManager().closeWindow(wiz);
110
                    }
111

    
112
                    public void finished(WizardEvent w) {
113
                        PluginServices.getMDIManager().closeWindow(wiz);
114

    
115
                        TableDocument sourceProjectTable =
116
                            (TableDocument) sourceTable.getSelected();
117

    
118
                        TableDocument targetProjectTable =
119
                            (TableDocument) targetTable.getSelected();
120
                        FeatureStore sds2 = targetProjectTable.getStore();
121

    
122
                        String field1 = (String) firstTableField.getSelected();
123
                        String field2 = (String) secondTableField.getSelected();
124
                        sourceProjectTable.addLinkTable(sds2.getName(), field1,
125
                            field2);
126

    
127
                    }
128

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

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

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

    
157
                                    // ?ndice del campo
158
                                    FeatureStore fs = pt.getStore();
159
                                    String fieldName =
160
                                        (String) firstTableField.getSelected();
161
                                    int type =
162
                                        ((FeatureAttributeDescriptor) fs
163
                                            .getDefaultFeatureType().get(
164
                                                fieldName)).getType();
165

    
166
                                    secondTableField
167
                                        .setModel(new FieldSelectionModel(
168
                                            ((TableDocument) targetTable
169
                                                .getSelected()).getStore(),
170
                                            PluginServices.getText(this,
171
                                                "seleccione_campo_enlace"),
172
                                            type));
173
                                } catch (SelectionException e) {
174
                                    NotificationManager
175
                                        .addError(
176
                                            "Error obteniendo los campos de la tabla",
177
                                            e);
178
                                } catch (DataException e) {
179
                                    NotificationManager
180
                                        .addError(
181
                                            "Error obteniendo los campos de la tabla",
182
                                            e);
183
                                }
184
                            }
185
                    }
186

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

    
202
    /**
203
     * @see org.gvsig.app.gui.filter.ExpressionListener#newSet(java.lang.String)
204
     */
205
    public void newSet(String expression) throws DataException {
206
        // By Pablo: if no filter expression -> no element selected
207
        if (!this.filterExpressionFromWhereIsEmpty(expression)) {
208
            FeatureSet set = null;
209
            try {
210
                set = doSet(expression);
211

    
212
                if (set == null) {
213
                    throw new RuntimeException("Not a 'where' clause?");
214
                }
215
                FeatureSelection newSel = featureStore.createFeatureSelection();
216
                newSel.select(set);
217
                featureStore.setSelection(newSel);
218
            } catch (Exception e) {
219
                JOptionPane.showMessageDialog(
220
                    (Component) PluginServices.getMainFrame(),
221
                    "Asegurate de que la consulta es correcta.");
222
            } finally {
223
                if (set != null) {
224
                    set.dispose();
225
                }
226
            }
227
        } else {
228
            // By Pablo: if no expression -> no element selected
229
            featureStore.getFeatureSelection().deselectAll();
230
        }
231
    }
232

    
233
    /**
234
     * @see org.gvsig.app.gui.filter.ExpressionListener#newSet(java.lang.String)
235
     */
236
    private FeatureSet doSet(String expression) throws DataException {
237
        FeatureQuery query = featureStore.createFeatureQuery();
238
        query
239
            .setFilter(DALLocator.getDataManager().createExpresion(expression));
240
        return featureStore.getFeatureSet(query);
241
    }
242

    
243
    /**
244
     * @see org.gvsig.app.gui.filter.ExpressionListener#addToSet(java.lang.String)
245
     */
246
    public void addToSet(String expression) throws DataException {
247
        // By Pablo: if no filter expression -> don't add more elements to set
248
        if (!this.filterExpressionFromWhereIsEmpty(expression)) {
249
            FeatureSet set = null;
250
            try {
251
                set = doSet(expression);
252

    
253
                featureStore.getFeatureSelection().select(set);
254
            } finally {
255
                if (set != null) {
256
                    set.dispose();
257
                }
258
            }
259
        }
260
    }
261

    
262
    /**
263
     * @see org.gvsig.app.gui.filter.ExpressionListener#fromSet(java.lang.String)
264
     */
265
    public void fromSet(String expression) throws DataException {
266
        // By Pablo: if no filter expression -> no element selected
267
        if (!this.filterExpressionFromWhereIsEmpty(expression)) {
268

    
269
            FeatureSet set = null;
270
            DisposableIterator iterator = null;
271
            try {
272
                set = doSet(expression);
273

    
274
                if (set == null) {
275
                    throw new RuntimeException("Not a 'where' clause?");
276
                }
277
                FeatureSelection oldSelection =
278
                    featureStore.getFeatureSelection();
279

    
280
                FeatureSelection newSelection =
281
                    featureStore.createFeatureSelection();
282
                iterator = set.fastIterator();
283
                while (iterator.hasNext()) {
284
                    Feature feature = (Feature) iterator.next();
285
                    if (oldSelection.isSelected(feature)) {
286
                        newSelection.select(feature);
287
                    }
288
                }
289
                featureStore.setSelection(newSelection);
290
            } finally {
291
                DisposeUtils.dispose(iterator);
292
                DisposeUtils.dispose(set);
293
            }
294
        } else {
295
            // By Pablo: if no expression -> no element selected
296
            // featureStore.setSelection(featureStore.createSelection());
297
            featureStore.getFeatureSelection().deselectAll();
298
        }
299
    }
300

    
301
    /**
302
     * Returns true if the WHERE subconsultation of the filterExpression is
303
     * empty ("")
304
     * 
305
     * @author Pablo Piqueras Bartolom? (p_queras@hotmail.com)
306
     * @param expression
307
     *            An string
308
     * @return A boolean value
309
     */
310
    private boolean filterExpressionFromWhereIsEmpty(String expression) {
311
        String subExpression = expression.trim();
312
        int pos;
313

    
314
        // Remove last ';' if exists
315
        if (subExpression.charAt(subExpression.length() - 1) == ';') {
316
            subExpression =
317
                subExpression.substring(0, subExpression.length() - 1).trim();
318
        }
319

    
320
        // If there is no 'where' clause
321
        if ((pos = subExpression.indexOf("where")) == -1) {
322
            return false;
323
        }
324

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

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

    
347
        if (v == null) {
348
            return false;
349
        }
350

    
351
        if (v instanceof FeatureTableDocumentPanel) {
352
            return true;
353
        } /*
354
           * else {
355
           * if (v instanceof com.iver.cit.gvsig.gui.View) {
356
           * com.iver.cit.gvsig.gui.View view = (com.iver.cit.gvsig.gui.View) v;
357
           * ProjectView pv = view.getModel();
358
           * FLayer[] seleccionadas = pv.getMapContext().getLayers()
359
           * .getActives();
360
           * 
361
           * if (seleccionadas.length == 1) {
362
           * if (seleccionadas[0] instanceof AlphanumericData) {
363
           * return true;
364
           * }
365
           * }
366
           * }
367
           */
368
        return false;
369
        // }
370
    }
371

    
372
    /**
373
     * @see org.gvsig.andami.plugins.IExtension#initialize()
374
     */
375
    public void initialize() {
376
        registerIcons();
377
        // FIXME
378
        // org.gvsig.fmap.data.feature.joinstore.Register.selfRegister();
379

    
380
    }
381

    
382
    private void registerIcons() {
383
        PluginServices.getIconTheme().registerDefault(
384
            "table-join",
385
            this.getClass().getClassLoader()
386
                .getResource("images/tablejoin.png"));
387

    
388
        PluginServices.getIconTheme().registerDefault(
389
            "table-link",
390
            this.getClass().getClassLoader()
391
                .getResource("images/tablelink.png"));
392
    }
393

    
394
    /**
395
     * @see org.gvsig.andami.plugins.IExtension#isEnabled()
396
     */
397
    public boolean isEnabled() {
398
        return true;
399
    }
400

    
401
    /**
402
     * Ensure that field name only has 'safe' characters
403
     * (no spaces, special characters, etc).
404
     */
405
    public String sanitizeFieldName(String fieldName) {
406
        return fieldName.replaceAll("\\W", "_"); // replace any non-word
407
                                                 // character by an underscore
408
    }
409

    
410
}