Statistics
| Revision:

root / branches / v2_0_0_prep / applications / appgvSIG / src / org / gvsig / app / extension / FiltroExtension.java @ 38603

History | View | Annotate | Download (12.9 KB)

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

    
43
import java.awt.Component;
44
import java.util.Iterator;
45

    
46
import javax.swing.JOptionPane;
47

    
48
import org.gvsig.andami.IconThemeHelper;
49
import org.gvsig.andami.PluginServices;
50
import org.gvsig.andami.messages.NotificationManager;
51
import org.gvsig.andami.plugins.Extension;
52
import org.gvsig.andami.ui.mdiManager.IWindow;
53
import org.gvsig.app.gui.filter.ExpressionListener;
54
import org.gvsig.app.gui.filter.FilterDialog;
55
import org.gvsig.app.project.documents.AbstractDocument;
56
import org.gvsig.app.project.documents.view.ViewDocument;
57
import org.gvsig.fmap.dal.DALLocator;
58
import org.gvsig.fmap.dal.DataManager;
59
import org.gvsig.fmap.dal.exception.DataException;
60
import org.gvsig.fmap.dal.feature.Feature;
61
import org.gvsig.fmap.dal.feature.FeatureQuery;
62
import org.gvsig.fmap.dal.feature.FeatureSelection;
63
import org.gvsig.fmap.dal.feature.FeatureSet;
64
import org.gvsig.fmap.dal.feature.FeatureStore;
65
import org.gvsig.fmap.mapcontext.layers.FLayer;
66
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
67
import org.gvsig.utils.exceptionHandling.ExceptionListener;
68

    
69
/**
70
 * Extensi?n que abre un di?logo para poder hacer un filtro de una capa o tabla.
71
 * 
72
 * @author Vicente Caballero Navarro
73
 */
74
public class FiltroExtension extends Extension implements ExpressionListener {
75

    
76
    protected FeatureStore featureStore = null;
77
    private String filterTitle;
78

    
79
    /**
80
     * DOCUMENT ME!
81
     */
82
    public void initialize() {
83
            IconThemeHelper.registerIcon("action", "layer-filter", this);
84
    }
85

    
86
    /**
87
     * DOCUMENT ME!
88
     * 
89
     * @param actionCommand
90
     *            DOCUMENT ME!
91
     */
92
    public void execute(String actionCommand) {
93
        if ("layer-filter".equalsIgnoreCase(actionCommand)) {
94
            // try {
95
            IWindow v = PluginServices.getMDIManager().getActiveWindow();
96

    
97
            if (v instanceof org.gvsig.app.project.documents.view.gui.DefaultViewPanel) {
98
                ViewDocument pv =
99
                    ((org.gvsig.app.project.documents.view.gui.DefaultViewPanel) v)
100
                        .getModel();
101
                filterTitle =
102
                    ((org.gvsig.app.project.documents.view.gui.DefaultViewPanel) v)
103
                        .getModel().getName();
104
                FLayer layer = pv.getMapContext().getLayers().getActives()[0];
105
                featureStore = ((FLyrVect) layer).getFeatureStore();// pv.getProject().getDataSourceByLayer(layer);
106
                ((AbstractDocument) pv).setModified(true);
107
            }
108
            // } catch (ReadException e) {
109
            // NotificationManager.addError("Error filtrando", e);
110
            // }
111

    
112
            doExecute();
113
        }
114
    }
115

    
116
    /**
117
     * "execute" method action.
118
     * 
119
     */
120
    protected void doExecute() {
121
        // DefaultExpressionDataSource ds = new DefaultExpressionDataSource();
122
        // ds.setTable(featureStore);
123
        FilterDialog dlg = new FilterDialog(filterTitle);
124
        dlg.addExpressionListener(this);
125
        dlg.addExceptionListener(new ExceptionListener() {
126

    
127
            public void exceptionThrown(Throwable t) {
128
                NotificationManager.addError(t.getMessage(), t);
129
            }
130
        });
131
        dlg.setModel(featureStore);
132
        PluginServices.getMDIManager().addWindow(dlg);
133
    }
134

    
135
    /**
136
     * DOCUMENT ME!
137
     * 
138
     * @return DOCUMENT ME!
139
     */
140
    public boolean isEnabled() {
141
        IWindow v = PluginServices.getMDIManager().getActiveWindow();
142

    
143
        if (v == null) {
144
            return false;
145
        }
146

    
147
        if (v instanceof org.gvsig.app.project.documents.view.gui.DefaultViewPanel) {
148
            org.gvsig.app.project.documents.view.gui.DefaultViewPanel view =
149
                (org.gvsig.app.project.documents.view.gui.DefaultViewPanel) v;
150
            ViewDocument pv = view.getModel();
151
            FLayer[] seleccionadas =
152
                pv.getMapContext().getLayers().getActives();
153

    
154
            if (seleccionadas.length == 1) {
155
                if (seleccionadas[0].isAvailable()
156
                    && (seleccionadas[0] instanceof FLyrVect)) {
157
                    return true;
158
                }
159
            }
160
        }
161
        return false;
162
    }
163

    
164
    /**
165
     * DOCUMENT ME!
166
     * 
167
     * @return DOCUMENT ME!
168
     */
169
    public boolean isVisible() {
170
        IWindow v = PluginServices.getMDIManager().getActiveWindow();
171

    
172
        if (v == null) {
173
            return false;
174
        }
175

    
176
        if (v instanceof org.gvsig.app.project.documents.view.gui.DefaultViewPanel) {
177
            org.gvsig.app.project.documents.view.gui.DefaultViewPanel view =
178
                (org.gvsig.app.project.documents.view.gui.DefaultViewPanel) v;
179
            ViewDocument pv = view.getModel();
180
            FLayer[] seleccionadas =
181
                pv.getMapContext().getLayers().getActives();
182

    
183
            if (seleccionadas.length == 1) {
184
                if (seleccionadas[0] instanceof FLyrVect) {
185
                    return true;
186
                }
187
            }
188
        }
189

    
190
        return false;
191
    }
192

    
193
    /**
194
     * DOCUMENT ME!
195
     * 
196
     * @param expression
197
     *            DOCUMENT ME!
198
     */
199
    // By Pablo: if no filter expression -> no element selected
200
    public void newSet(String expression) throws DataException {
201
        if (!this.filterExpressionFromWhereIsEmpty(expression)) {
202
            FeatureSet set = null;
203
            try {
204
                set = doSet(expression);
205

    
206
                if (set == null) {
207
                    // throw new RuntimeException("Not a 'where' clause?");
208
                    return;
209
                }
210
                featureStore.setSelection(set);
211

    
212
            } catch (Exception e) {
213
                JOptionPane.showMessageDialog((Component) PluginServices
214
                    .getMainFrame(),
215
                    "Asegurate de que la consulta es correcta.");
216
            } finally {
217
                if (set != null) {
218
                    set.dispose();
219
                }
220
            }
221
        } else {
222
            // By Pablo: if no expression -> no element selected
223
            featureStore.getFeatureSelection().deselectAll();
224
        }
225
    }
226

    
227
    /**
228
     * @throws DataException
229
     * @see org.gvsig.app.gui.filter.ExpressionListener#newSet(java.lang.String)
230
     */
231
    private FeatureSet doSet(String expression) throws DataException {
232
        FeatureQuery query = featureStore.createFeatureQuery();
233
        DataManager manager = DALLocator.getDataManager();
234
        query.setFilter(manager.createExpresion(expression));
235
        return featureStore.getFeatureSet(query);
236
        // try {
237
        // DataSource ds =
238
        // LayerFactory.getDataSourceFactory().executeSQL(expression,
239
        // DataSourceFactory.MANUAL_OPENING);
240
        //
241
        // return ds.getWhereFilter();
242
        // } catch (DriverLoadException e) {
243
        // JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"driver_error")+"\n"+e.getMessage());
244
        // } catch (ReadDriverException e) {
245
        // JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"driver_error")+"\n"+e.getMessage());
246
        // } catch (ParseException e) {
247
        // JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"parse_expresion_error")+"\n"+e.getMessage());
248
        // } catch (SemanticException e) {
249
        // JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"semantic_expresion_error")+"\n"+e.getMessage());
250
        // } catch (IOException e) {
251
        // JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"input_output_error")+"\n"+e.getMessage());
252
        // } catch (EvaluationException e) {
253
        // JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"parse_expresion_error")+"\n"+e.getMessage());
254
        // } catch (com.hardcode.gdbms.parser.TokenMgrError e) {
255
        // JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"expresion_error")+"\n"+e.getMessage());
256
        // }
257
        // return null;
258
    }
259

    
260
    /**
261
     * DOCUMENT ME!
262
     * 
263
     * @param expression
264
     *            DOCUMENT ME!
265
     * @throws DataException
266
     */
267
    public void addToSet(String expression) throws DataException {
268
        // By Pablo: if no filter expression -> don't add more elements to set
269
        if (!this.filterExpressionFromWhereIsEmpty(expression)) {
270
            FeatureSet set = null;
271
            try {
272
                set = doSet(expression);
273

    
274
                if (set == null) {
275
                    // throw new RuntimeException("Not a 'where' clause?");
276
                    return;
277
                }
278
                featureStore.getFeatureSelection().select(set);
279
            } finally {
280
                if (set != null) {
281
                    set.dispose();
282
                }
283
            }
284

    
285
            // FBitSet selection = new FBitSet();
286
            //
287
            // for (int i = 0; i < sel.length; i++) {
288
            // selection.set((int) sel[i]);
289
            // }
290
            //
291
            // FBitSet fbs = featureStore.getSelection();
292
            // fbs.or(selection);
293
            // featureStore.setSelection(fbs);
294
        }
295
    }
296

    
297
    /**
298
     * DOCUMENT ME!
299
     * 
300
     * @param expression
301
     *            DOCUMENT ME!
302
     */
303
    public void fromSet(String expression) throws DataException {
304
        // By Pablo: if no filter expression -> no element selected
305
        try {
306
            if (!this.filterExpressionFromWhereIsEmpty(expression)) {
307
                // NotificationManager.showMessageInfo("Falta por implementar",
308
                // null);
309

    
310
                FeatureSet set = null;
311
                set = doSet(expression);
312

    
313
                if (set == null) {
314
                    throw new RuntimeException("Not a 'where' clause?");
315
                }
316

    
317
                FeatureSelection oldSelection =
318
                    featureStore.getFeatureSelection();
319

    
320
                FeatureSelection newSelection =
321
                    featureStore.createFeatureSelection();
322
                Iterator iterator = set.iterator();
323
                while (iterator.hasNext()) {
324
                    Feature feature = (Feature) iterator.next();
325
                    if (oldSelection.isSelected(feature)) {
326
                        newSelection.select(feature);
327
                    }
328
                }
329
                featureStore.setSelection(newSelection);
330
                set.dispose();
331

    
332
            } else {
333
                // By Pablo: if no expression -> no element selected
334
                featureStore.getFeatureSelection().deselectAll();
335
                ;
336
            }
337
        } catch (DataException e) {
338
            NotificationManager.addError(e);
339
        }
340

    
341
    }
342

    
343
    /**
344
     * Returns true if the WHERE subconsultation of the filterExpression is
345
     * empty ("")
346
     * 
347
     * @author Pablo Piqueras Bartolom? (p_queras@hotmail.com)
348
     * @param expression
349
     *            An string
350
     * @return A boolean value
351
     */
352
    private boolean filterExpressionFromWhereIsEmpty(String expression) {
353
        String subExpression = expression.trim();
354
        int pos;
355

    
356
        // Remove last ';' if exists
357
        if (subExpression.charAt(subExpression.length() - 1) == ';') {
358
            subExpression =
359
                subExpression.substring(0, subExpression.length() - 1).trim();
360
        }
361

    
362
        // If there is no 'where' clause
363
        if ((pos = subExpression.indexOf("where")) == -1) {
364
            return false;
365
        }
366

    
367
        // If there is no subexpression in the WHERE clause -> true
368
        subExpression =
369
            subExpression.substring(pos + 5, subExpression.length()).trim(); // +
370
        // 5
371
        // is
372
        // the
373
        // length
374
        // of
375
        // 'where'
376
        if (subExpression.length() == 0) {
377
            return true;
378
        } else {
379
            return false;
380
        }
381
    }
382
}