Statistics
| Revision:

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

History | View | Annotate | Download (17.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 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.fmap.mapcontext.rendering.legend.NullValue;
67
import org.gvsig.gui.beans.filterPanel.tableFilterQueryPanel.TableFilterQueryJPanel;
68

    
69
import com.iver.andami.PluginServices;
70
import com.iver.andami.messages.NotificationManager;
71
import com.iver.andami.ui.mdiManager.IWindow;
72
import com.iver.andami.ui.mdiManager.IWindowListener;
73
import com.iver.andami.ui.mdiManager.WindowInfo;
74
import com.iver.cit.gvsig.project.documents.table.gui.Table;
75
import com.iver.utiles.DefaultCharSet;
76
import com.iver.utiles.StringUtilities;
77
import com.iver.utiles.exceptionHandling.ExceptionHandlingSupport;
78
import com.iver.utiles.exceptionHandling.ExceptionListener;
79

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

    
93
        private String title;
94

    
95
        private final int filterDialog_Width = 500;
96
        private final int filterDialog_Height = 362;
97
        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.
98

    
99

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

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

    
123
                super.resizeHeight(filterDialog_Height);
124
                super.resizeWidth(filterDialog_Width - widthIncrementForAndami);
125

    
126
                this.addNewListeners();
127
        }
128

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

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

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

    
173
                                logger.debug(expr);
174

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

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

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

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

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

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

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

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

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

    
276

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

    
283

    
284
                        FeatureQuery query = model.createFeatureQuery();
285
                        query.setAttributeNames(fieldName);
286
                        FeatureSet fs = model
287
                                        .getFeatureSet(query);
288
                        Iterator iterator = fs.iterator();
289
                        while (iterator.hasNext()) {
290
                                Feature feature = (Feature) iterator.next();
291
                                Object value=feature.get(row);
292
                                if (value instanceof NullValue) {
293
                                        continue;
294
                                }
295

    
296
                                if (!conjunto.contains(value)) {
297
                                    conjunto.add(value);
298
                                }
299
                        }
300
                        fs.dispose();
301
                        Iterator it = conjunto.iterator();
302

    
303
                        while (it.hasNext()) {
304
                                valuesListModel.addElement(it.next());
305
                        }
306
                } catch (DataException e) {
307
                        throwException(e);
308
                }
309
        }
310

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

    
324
        jtreeRoot.removeAllChildren();
325

    
326
        try {
327
                Iterator attributes=model.getDefaultFeatureType().iterator();
328
                while (attributes.hasNext()) {
329
                                FeatureAttributeDescriptor descriptor = (FeatureAttributeDescriptor) attributes.next();
330
                                Object field = descriptor.getName();
331

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

    
344
                        defaultTreeModel.setRoot(jtreeRoot);
345
                } catch (DataException e) {
346
                        throwException(e);
347
                }
348
        }
349

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

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

    
370
                        String replacement;
371
                        Pattern patron = Pattern.compile("[^<>!]=");
372
                        Matcher m = patron.matcher(expression);
373
                        int index = 0;
374

    
375
                        while (m.find(index)) {
376
                                index = m.start();
377
                                replacement = expression.charAt(index) + "==";
378
                                m.replaceFirst(replacement);
379
                                index++;
380
                        }
381

    
382
                        expression = expression.replaceAll("[^<>!]=", "==");
383

    
384
                        logger.debug(expression);
385

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

    
404
                if (symbol.equals(" () ")) {
405
                        position = position + 2;
406
                } else {
407
                        position = position + symbol.length();
408
                }
409

    
410
                txtExpression.setCaretPosition(position);
411
        }
412

    
413
        /**
414
         * DOCUMENT ME!
415
         *
416
         * @param expresion DOCUMENT ME!
417
         * @param substring DOCUMENT ME!
418
         * @param startingPos DOCUMENT ME!
419
         *
420
         * @return DOCUMENT ME!
421
         */
422
        private int getIndex(String expresion, String substring, int startingPos) {
423
                int index = startingPos;
424

    
425
                do {
426
                        index = expresion.indexOf(substring, index);
427
                } while ((StringUtilities.isBetweenSymbols(expresion, index, "\"")) &&
428
                                (index != -1));
429

    
430
                return index;
431
        }
432

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

    
450
                while ((booleanIndex = getIndex(expresion, word, booleanIndex)) != -1) {
451
                        res.append(expresion.substring(endIndex, booleanIndex));
452
                        endIndex = booleanIndex + word.length();
453
                        booleanIndex++;
454
                        res.append(translation);
455
                }
456

    
457
                if (endIndex < expresion.length()) {
458
                        res.append(expresion.substring(endIndex));
459
                }
460

    
461
                return res.toString();
462
        }
463

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

    
478
                if (date == null) {
479
                        return expresion;
480
                }
481

    
482
                //Se comprueba que no est? entre comillas
483
                int startIndex = expresion.indexOf(date);
484

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

    
496
                        //Se obtiene el valor de la fecha
497

    
498
                        /*            date = StringUtilities.substringDelimited(expresion, "Date(", ")",
499
                           startIndex);
500
                         */
501
                        if (date == null) {
502
                                return expresion;
503
                        }
504

    
505
                        startIndex = expresion.indexOf(date, startIndex);
506
                }
507

    
508
                return expresion;
509
        }
510

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

    
526
                String number = StringUtilities.substringWithSymbols(expresion, ss, 0);
527

    
528
                if (number == null) {
529
                        return expresion;
530
                }
531

    
532
                int startIndex = expresion.indexOf(number);
533

    
534
                while (startIndex != -1) {
535
                        Number n = nf.parse(number);
536

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

    
546
                        number = StringUtilities.substringWithSymbols(expresion, ss,
547
                                        startIndex);
548

    
549
                        if (number == null) {
550
                                return expresion;
551
                        }
552

    
553
                        startIndex = expresion.indexOf(number, startIndex);
554
                }
555

    
556
                return expresion;
557
        }
558

    
559
        /**
560
         * DOCUMENT ME!
561
         *
562
         * @param arg0
563
         *
564
         * @return
565
         */
566
        public boolean addExpressionListener(ExpressionListener arg0) {
567
                return expressionListeners.add(arg0);
568
        }
569

    
570
        /**
571
         * DOCUMENT ME!
572
         *
573
         * @param arg0
574
         *
575
         * @return
576
         */
577
        public boolean removeExpressionListener(ExpressionListener arg0) {
578
                return expressionListeners.remove(arg0);
579
        }
580

    
581
        /**
582
         * @see com.iver.mdiApp.ui.MDIManager.IWindow#getWindowInfo()
583
         */
584
        public WindowInfo getWindowInfo() {
585
                WindowInfo vi = new WindowInfo(WindowInfo.ICONIFIABLE);
586

    
587
                //if (System.getProperty("os.name")co.compareTo(arg0))
588
                vi.setHeight(this.filterDialog_Height);
589
                vi.setWidth(this.filterDialog_Width);
590

    
591
                // Old instructions
592
//                vi.setWidth(480);
593
//                vi.setHeight(362);
594
                vi.setTitle(PluginServices.getText( this, "filtro") + " (" + title + ")");
595
                return vi;
596
        }
597

    
598
        /**
599
         * DOCUMENT ME!
600
         *
601
         * @param o DOCUMENT ME!
602
         */
603
        public void addExceptionListener(ExceptionListener o) {
604
                exceptionHandlingSupport.addExceptionListener(o);
605
        }
606

    
607
        /**
608
         * DOCUMENT ME!
609
         *
610
         * @param o DOCUMENT ME!
611
         *
612
         * @return DOCUMENT ME!
613
         */
614
        public boolean removeExceptionListener(ExceptionListener o) {
615
                return exceptionHandlingSupport.removeExceptionListener(o);
616
        }
617

    
618
        /**
619
         * DOCUMENT ME!
620
         *
621
         * @param t DOCUMENT ME!
622
         */
623
        private void throwException(Throwable t) {
624
                exceptionHandlingSupport.throwException(t);
625
        }
626

    
627
    /* (non-Javadoc)
628
     * @see com.iver.andami.ui.mdiManager.ViewListener#viewActivated()
629
     */
630
    public void windowActivated() {
631
    }
632

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