Statistics
| Revision:

root / branches / v2_0_0_prep / applications / appgvSIG / src / com / iver / cit / gvsig / gui / filter / FilterDialog.java @ 25240

History | View | Annotate | Download (17 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.gui.filter;
42

    
43
import java.awt.event.MouseAdapter;
44
import java.awt.event.MouseEvent;
45
import java.text.NumberFormat;
46
import java.text.ParseException;
47
import java.util.ArrayList;
48
import java.util.Collection;
49
import java.util.Comparator;
50
import java.util.Date;
51
import java.util.Iterator;
52
import java.util.TreeSet;
53
import java.util.regex.Matcher;
54
import java.util.regex.Pattern;
55

    
56
import javax.swing.tree.DefaultMutableTreeNode;
57
import javax.swing.tree.DefaultTreeModel;
58

    
59
import org.apache.log4j.Logger;
60
import org.gvsig.fmap.dal.exception.DataException;
61
import org.gvsig.fmap.dal.feature.Feature;
62
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
63
import org.gvsig.fmap.dal.feature.FeatureQuery;
64
import org.gvsig.fmap.dal.feature.FeatureSet;
65
import org.gvsig.fmap.dal.feature.FeatureStore;
66
import org.gvsig.gui.beans.filterPanel.tableFilterQueryPanel.TableFilterQueryJPanel;
67

    
68
import com.iver.andami.PluginServices;
69
import com.iver.andami.messages.NotificationManager;
70
import com.iver.andami.ui.mdiManager.IWindow;
71
import com.iver.andami.ui.mdiManager.IWindowListener;
72
import com.iver.andami.ui.mdiManager.WindowInfo;
73
import com.iver.utiles.DefaultCharSet;
74
import com.iver.utiles.StringUtilities;
75
import com.iver.utiles.exceptionHandling.ExceptionHandlingSupport;
76
import com.iver.utiles.exceptionHandling.ExceptionListener;
77

    
78
/**
79
 * This class substitutes the old "FilterDialog" class made by "Fernando Gonz?lez Cort?s"
80
 * The functionality is the same, but now the class is made from separately (and reusable) components
81
 *
82
 * @author Pablo Piqueras Bartolom? (p_queras@hotmail.com)
83
 */
84
public class FilterDialog extends TableFilterQueryJPanel implements IWindow, IWindowListener {
85
        private static Logger logger = Logger.getLogger(FilterDialog.class.getName());
86
        private FeatureStore model = null;
87
        private ArrayList expressionListeners = new ArrayList();
88
        private ExceptionHandlingSupport exceptionHandlingSupport = new ExceptionHandlingSupport();
89
        private NumberFormat nf = NumberFormat.getNumberInstance();
90

    
91
        private String title;
92

    
93
        private final int filterDialog_Width = 500;
94
        private final int filterDialog_Height = 362;
95
        private final int widthIncrementForAndami = 20; // This is necessary because when the panel is sent to Andami, that needs a bit more width-space to show that panel.
96

    
97

    
98
        /**
99
         * This is the default constructor
100
         */
101
        public FilterDialog(String _title) {
102
                super();
103
                title = _title;
104
                defaultTreeModel = (DefaultTreeModel)fieldsJTree.getModel();
105
        }
106
        /**
107
         * This is the default constructor
108
         */
109
        public FilterDialog() {
110
                super();
111
                defaultTreeModel = (DefaultTreeModel)fieldsJTree.getModel();
112
        }
113

    
114
        /*
115
         *  (non-Javadoc)
116
         * @see org.gvsig.gui.beans.filterPanel.AbstractFilterQueryJPanel#initialize()
117
         */
118
        protected void initialize() {
119
                super.initialize();
120

    
121
                super.resizeHeight(filterDialog_Height);
122
                super.resizeWidth(filterDialog_Width - widthIncrementForAndami);
123

    
124
                this.addNewListeners();
125
        }
126

    
127
        /**
128
         * Adds some listeners
129
         */
130
        private void addNewListeners() {
131
                // Listener for "btnAdd"
132
                // Adds more elements to the current set
133
                getBtnAddToCurrentSet().addActionListener(new java.awt.event.ActionListener() {
134
                        /*
135
                         *  (non-Javadoc)
136
                         * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
137
                         */
138
                        public void actionPerformed(java.awt.event.ActionEvent e) {
139
//                                final String expr = "select * from '" +
140
//                                        model.getName() + "' where " +
141
//                                        getTxtExpression().getText() + ";";
142
                                final String expr = getTxtExpression().getText();
143
                                logger.debug(expr);
144

    
145
                                PluginServices.backgroundExecution(new Runnable() {
146
                                                public void run() {
147
                                                        for (int i = 0;
148
                                                                        i < expressionListeners.size();
149
                                                                        i++) {
150
                                                                ExpressionListener l = (ExpressionListener) expressionListeners.get(i);
151
                                                                try {
152
                                                                                l.addToSet(expr);
153
                                                                        } catch (DataException e) {
154
                                                                                e.printStackTrace();
155
                                                                        }
156
                                                        }
157
                                                }
158
                                        });
159
                        }
160
                });
161

    
162
                // Listener for "btnNuevo"
163
                // Adds a new set
164
                getBtnNewSet().addActionListener(new java.awt.event.ActionListener() {
165
                        public void actionPerformed(java.awt.event.ActionEvent e) {
166
//                                final String expr = "select * from '" +
167
//                                        model.getName() + "' where " +
168
//                                        getTxtExpression().getText() + ";";
169
                                final String expr = getTxtExpression().getText();
170

    
171
                                logger.debug(expr);
172

    
173
                                PluginServices.backgroundExecution(new Runnable() {
174
                                        public void run() {
175
                                                for (int i = 0; i < expressionListeners.size(); i++) {
176
                                                        ExpressionListener l = (ExpressionListener) expressionListeners.get(i);
177
                                                        try {
178
                                                                l.newSet(expr);
179
                                                        } catch (DataException e) {
180
                                                                // TODO Auto-generated catch block
181
                                                                NotificationManager.addError(e);
182
                                                        }
183
                                                }
184
                                        }
185
                                });
186
                        }
187
                });
188

    
189
                // Listener for "btnFromSet"
190
                // Selects elements in the table that are according the current filter condition
191
                getBtnFromSet().addActionListener(new java.awt.event.ActionListener() {
192
                        public void actionPerformed(java.awt.event.ActionEvent e) {
193
//                                final String expr = "select * from '" +
194
//                                        model.getName() + "' where " +
195
//                                        getTxtExpression().getText() + ";";
196
                                final String expr = getTxtExpression().getText();
197
                                logger.debug(expr);
198

    
199
                                PluginServices.backgroundExecution(new Runnable() {
200
                                        public void run() {
201
                                                for (int i = 0; i < expressionListeners.size(); i++) {
202
                                                        ExpressionListener l = (ExpressionListener) expressionListeners.get(i);
203
                                                        try {
204
                                                                l.fromSet(expr);
205
                                                        } catch (DataException e) {
206
                                                                NotificationManager.addError(e);
207
                                                        }
208
                                                }
209
                                        }
210
                                });
211
                        }
212
                });
213

    
214
                // Listener for "fieldsJTree"
215
                getFieldsJTree().addMouseListener(new MouseAdapter() {
216
                        /*
217
                         *  (non-Javadoc)
218
                         * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
219
                         */
220
                        public void mouseClicked(MouseEvent e) {
221
                                int row = fieldsJTree.getRowForLocation(e.getX(), e.getY());
222

    
223
                                if (row > -1) {
224
                                        switch (e.getClickCount()) {
225
                                                case 1:
226
                                                        fillValues(row);
227
                                                        break;
228
                                                case 2:
229
                                                        putSymbol(jtreeRoot.getChildAt(row).toString());
230
                                                        break;
231
                                        }
232
                                }
233
                        }
234
                });
235

    
236
                // Listener for "valuesJList"
237
                getValuesJList().addMouseListener(new MouseAdapter() {
238
                        /*
239
                         *  (non-Javadoc)
240
                         * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
241
                         */
242
                        public void mouseClicked(MouseEvent e) {
243
                                if (e.getClickCount() == 2) {
244
                                        Object valor = valuesListModel.getElementAt(getValuesJList().getSelectedIndex());
245

    
246
                                        if (valor instanceof Date) {
247
                                                putSymbol("date('" + valor + "')");
248
                                        } else if (valor instanceof Boolean) {
249
                                                putSymbol("boolean('" + valor.toString() + "')");
250
                                        } else if (valor instanceof String) {
251
                                                putSymbol("'" + valor + "'");
252
                                        } else {
253
                                                putSymbol(valor.toString());
254
                                        }
255
                                }
256
                        }
257
                });
258
        }
259

    
260
        /**
261
         * Rellena la lista con los valores del campo seleccionado
262
         */
263
        private void fillValues(int row) {
264
                //int index = lstCampos.getSelectedIndex();
265

    
266
                //Index es ahora el ?ndice del campo seleccionado
267
                //Se eliminan los duplicados
268
                Collection conjunto = new TreeSet(new Comparator() {
269
                        public int compare(Object o1, Object o2) {
270
                                return ((Comparable)o1).compareTo(o2);
271
                        }
272
                }); // Para poder ordenar
273

    
274

    
275
                valuesListModel.clear();
276
                try {
277
                        String[] fieldName = new String[] {
278
                                ((FeatureAttributeDescriptor)model.getDefaultFeatureType().get(row)).getName()
279
                                };
280

    
281

    
282
                        FeatureQuery query = model.createFeatureQuery();
283
                        query.setAttributeNames(fieldName);
284
                        FeatureSet fs = model
285
                                        .getFeatureSet(query);
286
                        Iterator iterator = fs.iterator();
287
                        while (iterator.hasNext()) {
288
                                Feature feature = (Feature) iterator.next();
289
                                Object value = feature.get(fieldName[0]);
290
                                if (value == null) {
291
                                        continue;
292
                                }
293

    
294
                                conjunto.add(value);
295
                        }
296
                        fs.dispose();
297
                        Iterator it = conjunto.iterator();
298

    
299
                        while (it.hasNext()) {
300
                                valuesListModel.addElement(it.next());
301
                        }
302
                } catch (DataException e) {
303
                        throwException(e);
304
                }
305
        }
306

    
307
        /**
308
         * DOCUMENT ME!
309
         *
310
         * @param t DOCUMENT ME!
311
         */
312
        public void setModel(FeatureStore t) {
313
//                try {
314
                        model = t;
315
//            model.start();
316
//        } catch (ReadException e1) {
317
//            NotificationManager.addError(e1.getMessage(), e1);
318
//        }
319

    
320
        jtreeRoot.removeAllChildren();
321

    
322
        try {
323
                Iterator attributes=model.getDefaultFeatureType().iterator();
324
                while (attributes.hasNext()) {
325
                                FeatureAttributeDescriptor descriptor = (FeatureAttributeDescriptor) attributes.next();
326
                                Object field = descriptor.getName();
327

    
328
                                if (field != null) {
329
                                        jtreeRoot.add(new DefaultMutableTreeNode(field.toString()));
330
                                }
331
                        }
332
//                for (int i = 0; i < model.getFieldCount(); i++) {
333
//                                Object field = model.getFieldName(i);
334
//
335
//                                if (field != null) {
336
//                                        jtreeRoot.add(new DefaultMutableTreeNode(field.toString()));
337
//                                }
338
//                        }
339

    
340
                        defaultTreeModel.setRoot(jtreeRoot);
341
                } catch (DataException e) {
342
                        throwException(e);
343
                }
344
        }
345

    
346
                /**
347
                 * DOCUMENT ME!
348
                 *
349
                 * @return DOCUMENT ME!
350
                 *
351
                 * @throws ParseException DOCUMENT ME!
352
                 */
353
                private String validateExpression() throws ParseException {
354
                        String expression = txtExpression.getText();
355
        //                HashSet variablesIndexes = new HashSet();
356
        //
357
        //                StringBuffer traducida = new StringBuffer();
358

    
359
                        //Se transforman los nombres de los campos en las variables xix que analizar?n
360
                        //Se quitan los Date(fecha) y se mete la fecha correspondiente
361
                        expression = translateDates(expression);
362
                        expression = translateNumber(expression);
363
                        expression = translateWord(expression, "true", "1");
364
                        expression = translateWord(expression, "false", "0");
365

    
366
                        String replacement;
367
                        Pattern patron = Pattern.compile("[^<>!]=");
368
                        Matcher m = patron.matcher(expression);
369
                        int index = 0;
370

    
371
                        while (m.find(index)) {
372
                                index = m.start();
373
                                replacement = expression.charAt(index) + "==";
374
                                m.replaceFirst(replacement);
375
                                index++;
376
                        }
377

    
378
                        expression = expression.replaceAll("[^<>!]=", "==");
379

    
380
                        logger.debug(expression);
381

    
382
                        return expression;
383
                }
384
        /**
385
         * Redefinition of the 'putSymbol' method of AbstractFilterQueryJPanel
386
         *   (I've made this redefinition for write the same code as the 'putSymbol'
387
         *    code of the original class (FilterDialog) that was in this project
388
         *    (appgvSIG) and didn't has path troubles to find 'StringUtilities').
389
         *
390
         * Sets a symbol on the filter expression (JTextArea that stores and shows
391
         *   the current filter expression)
392
         *
393
         * @param symbol A symbol: character, characters, number, ...
394
         */
395
        protected void putSymbol(String symbol) {
396
                int position = txtExpression.getCaretPosition();
397
                txtExpression.setText(StringUtilities.insert(txtExpression.getText(),
398
                                position, symbol));
399

    
400
                if (symbol.equals(" () ")) {
401
                        position = position + 2;
402
                } else {
403
                        position = position + symbol.length();
404
                }
405

    
406
                txtExpression.setCaretPosition(position);
407
        }
408

    
409
        /**
410
         * DOCUMENT ME!
411
         *
412
         * @param expresion DOCUMENT ME!
413
         * @param substring DOCUMENT ME!
414
         * @param startingPos DOCUMENT ME!
415
         *
416
         * @return DOCUMENT ME!
417
         */
418
        private int getIndex(String expresion, String substring, int startingPos) {
419
                int index = startingPos;
420

    
421
                do {
422
                        index = expresion.indexOf(substring, index);
423
                } while ((StringUtilities.isBetweenSymbols(expresion, index, "\"")) &&
424
                                (index != -1));
425

    
426
                return index;
427
        }
428

    
429
        /**
430
         * DOCUMENT ME!
431
         *
432
         * @param expresion DOCUMENT ME!
433
         * @param word DOCUMENT ME!
434
         * @param translation DOCUMENT ME!
435
         *
436
         * @return DOCUMENT ME!
437
         *
438
         * @throws ParseException DOCUMENT ME!
439
         */
440
        private String translateWord(String expresion, String word,
441
                String translation) throws ParseException {
442
                int booleanIndex = 0;
443
                int endIndex = 0;
444
                StringBuffer res = new StringBuffer();
445

    
446
                while ((booleanIndex = getIndex(expresion, word, booleanIndex)) != -1) {
447
                        res.append(expresion.substring(endIndex, booleanIndex));
448
                        endIndex = booleanIndex + word.length();
449
                        booleanIndex++;
450
                        res.append(translation);
451
                }
452

    
453
                if (endIndex < expresion.length()) {
454
                        res.append(expresion.substring(endIndex));
455
                }
456

    
457
                return res.toString();
458
        }
459

    
460
        /**
461
         * DOCUMENT ME!
462
         *
463
         * @param expresion DOCUMENT ME!
464
         *
465
         * @return DOCUMENT ME!
466
         *
467
         * @throws ParseException DOCUMENT ME!
468
         */
469
        private String translateDates(String expresion) throws ParseException {
470
                //Se obtiene el valor de la fecha
471
                String date = StringUtilities.substringDelimited(expresion, "Date(",
472
                                ")", 0);
473

    
474
                if (date == null) {
475
                        return expresion;
476
                }
477

    
478
                //Se comprueba que no est? entre comillas
479
                int startIndex = expresion.indexOf(date);
480

    
481
                while (startIndex != -1) {
482
                        if (!StringUtilities.isBetweenSymbols(expresion, startIndex, "\"")) {
483
                                //Se sustituye por el valor ordinal de la fecha
484
                                expresion = expresion.substring(0, startIndex - 5) +
485
                                        expresion.substring(startIndex).replaceFirst(date + "\\)",
486
                                                new Long((filterButtonsJPanel.getDateFormat().parse(date)).getTime()).toString());
487
                                ;
488
                        } else {
489
                                startIndex += date.length();
490
                        }
491

    
492
                        //Se obtiene el valor de la fecha
493

    
494
                        /*            date = StringUtilities.substringDelimited(expresion, "Date(", ")",
495
                           startIndex);
496
                         */
497
                        if (date == null) {
498
                                return expresion;
499
                        }
500

    
501
                        startIndex = expresion.indexOf(date, startIndex);
502
                }
503

    
504
                return expresion;
505
        }
506

    
507
        /**
508
         * DOCUMENT ME!
509
         *
510
         * @param expresion DOCUMENT ME!
511
         *
512
         * @return DOCUMENT ME!
513
         *
514
         * @throws ParseException DOCUMENT ME!
515
         */
516
        public String translateNumber(String expresion) throws ParseException {
517
                DefaultCharSet ss = new DefaultCharSet();
518
                ss.addInterval('0', '9');
519
                ss.addCharacter(',');
520
                ss.addCharacter('.');
521

    
522
                String number = StringUtilities.substringWithSymbols(expresion, ss, 0);
523

    
524
                if (number == null) {
525
                        return expresion;
526
                }
527

    
528
                int startIndex = expresion.indexOf(number);
529

    
530
                while (startIndex != -1) {
531
                        Number n = nf.parse(number);
532

    
533
                        if (!StringUtilities.isBetweenSymbols(expresion, startIndex, "\"")) {
534
                                //Se sustituye por el valor ordinal de la fecha
535
                                expresion = expresion.substring(0, startIndex) +
536
                                        expresion.substring(startIndex).replaceFirst(number,
537
                                                n.toString());
538
                        } else {
539
                                startIndex += n.toString().length();
540
                        }
541

    
542
                        number = StringUtilities.substringWithSymbols(expresion, ss,
543
                                        startIndex);
544

    
545
                        if (number == null) {
546
                                return expresion;
547
                        }
548

    
549
                        startIndex = expresion.indexOf(number, startIndex);
550
                }
551

    
552
                return expresion;
553
        }
554

    
555
        /**
556
         * DOCUMENT ME!
557
         *
558
         * @param arg0
559
         *
560
         * @return
561
         */
562
        public boolean addExpressionListener(ExpressionListener arg0) {
563
                return expressionListeners.add(arg0);
564
        }
565

    
566
        /**
567
         * DOCUMENT ME!
568
         *
569
         * @param arg0
570
         *
571
         * @return
572
         */
573
        public boolean removeExpressionListener(ExpressionListener arg0) {
574
                return expressionListeners.remove(arg0);
575
        }
576

    
577
        /**
578
         * @see com.iver.mdiApp.ui.MDIManager.IWindow#getWindowInfo()
579
         */
580
        public WindowInfo getWindowInfo() {
581
                WindowInfo vi = new WindowInfo(WindowInfo.ICONIFIABLE);
582

    
583
                //if (System.getProperty("os.name")co.compareTo(arg0))
584
                vi.setHeight(this.filterDialog_Height);
585
                vi.setWidth(this.filterDialog_Width);
586

    
587
                // Old instructions
588
//                vi.setWidth(480);
589
//                vi.setHeight(362);
590
                vi.setTitle(PluginServices.getText( this, "filtro") + " (" + title + ")");
591
                return vi;
592
        }
593

    
594
        /**
595
         * DOCUMENT ME!
596
         *
597
         * @param o DOCUMENT ME!
598
         */
599
        public void addExceptionListener(ExceptionListener o) {
600
                exceptionHandlingSupport.addExceptionListener(o);
601
        }
602

    
603
        /**
604
         * DOCUMENT ME!
605
         *
606
         * @param o DOCUMENT ME!
607
         *
608
         * @return DOCUMENT ME!
609
         */
610
        public boolean removeExceptionListener(ExceptionListener o) {
611
                return exceptionHandlingSupport.removeExceptionListener(o);
612
        }
613

    
614
        /**
615
         * DOCUMENT ME!
616
         *
617
         * @param t DOCUMENT ME!
618
         */
619
        private void throwException(Throwable t) {
620
                exceptionHandlingSupport.throwException(t);
621
        }
622

    
623
    /* (non-Javadoc)
624
     * @see com.iver.andami.ui.mdiManager.ViewListener#viewActivated()
625
     */
626
    public void windowActivated() {
627
    }
628

    
629
    /* (non-Javadoc)
630
     * @see com.iver.andami.ui.mdiManager.ViewListener#viewClosed()
631
     */
632
    public void windowClosed() {
633
//        try {
634
//            model.stop();
635
//        } catch (ReadDriverException e) {
636
//            NotificationManager.addError(e.getMessage(), e);
637
//        }
638
    }
639
}