Statistics
| Revision:

root / branches / v10 / extensions / extWFS2 / src / com / iver / cit / gvsig / gui / panels / WFSFilterPanel.java @ 8854

History | View | Annotate | Download (24.9 KB)

1
package com.iver.cit.gvsig.gui.panels;
2

    
3
import java.awt.Color;
4
import java.awt.event.MouseAdapter;
5
import java.awt.event.MouseEvent;
6
import java.io.UnsupportedEncodingException;
7
import java.net.URLEncoder;
8
import java.text.NumberFormat;
9
import java.text.ParseException;
10
import java.util.ArrayList;
11
import java.util.Comparator;
12
import java.util.Iterator;
13
import java.util.TreeSet;
14
import java.util.Vector;
15
import java.util.regex.Matcher;
16
import java.util.regex.Pattern;
17

    
18
import javax.swing.DefaultListModel;
19
import javax.swing.event.DocumentEvent;
20
import javax.swing.event.DocumentListener;
21
import javax.swing.event.TreeSelectionEvent;
22
import javax.swing.event.TreeSelectionListener;
23
import javax.swing.tree.DefaultMutableTreeNode;
24
import javax.swing.tree.DefaultTreeModel;
25
import javax.swing.tree.TreePath;
26

    
27
import org.apache.log4j.Logger;
28
import org.gvsig.gui.beans.filterPanel.filterQueryPanel.FilterQueryJPanel;
29
import org.gvsig.remoteClient.gml.schemas.IXMLType;
30
import org.gvsig.remoteClient.gml.schemas.XMLElement;
31

    
32
import com.hardcode.gdbms.engine.data.driver.DriverException;
33
import com.hardcode.gdbms.engine.instruction.IncompatibleTypesException;
34
import com.hardcode.gdbms.engine.values.BooleanValue;
35
import com.hardcode.gdbms.engine.values.ComplexValue;
36
import com.hardcode.gdbms.engine.values.NullValue;
37
import com.hardcode.gdbms.engine.values.Value;
38
import com.iver.andami.PluginServices;
39
import com.iver.andami.messages.NotificationManager;
40
import com.iver.andami.ui.mdiManager.IWindow;
41
import com.iver.andami.ui.mdiManager.IWindowListener;
42
import com.iver.andami.ui.mdiManager.WindowInfo;
43
import com.iver.cit.gvsig.fmap.layers.WFSLayerNode;
44
import com.iver.cit.gvsig.gui.filter.ExpressionDataSource;
45
import com.iver.cit.gvsig.gui.filter.ExpressionListener;
46
import com.iver.cit.gvsig.gui.filter.FilterException;
47
import com.iver.cit.gvsig.gui.panels.attributesTree.AttributesTreeTableModel;
48
import com.iver.cit.gvsig.project.documents.table.gui.Table;
49
import com.iver.utiles.DefaultCharSet;
50
import com.iver.utiles.StringUtilities;
51
import com.iver.utiles.exceptionHandling.ExceptionHandlingSupport;
52
import com.iver.utiles.exceptionHandling.ExceptionListener;
53

    
54
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
55
 *
56
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
57
 *
58
 * This program is free software; you can redistribute it and/or
59
 * modify it under the terms of the GNU General Public License
60
 * as published by the Free Software Foundation; either version 2
61
 * of the License, or (at your option) any later version.
62
 *
63
 * This program is distributed in the hope that it will be useful,
64
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
65
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
66
 * GNU General Public License for more details.
67
 *
68
 * You should have received a copy of the GNU General Public License
69
 * along with this program; if not, write to the Free Software
70
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
71
 *
72
 * For more information, contact:
73
 *
74
 *  Generalitat Valenciana
75
 *   Conselleria d'Infraestructures i Transport
76
 *   Av. Blasco Ib??ez, 50
77
 *   46010 VALENCIA
78
 *   SPAIN
79
 *
80
 *      +34 963862235
81
 *   gvsig@gva.es
82
 *      www.gvsig.gva.es
83
 *
84
 *    or
85
 *
86
 *   IVER T.I. S.A
87
 *   Salamanca 50
88
 *   46005 Valencia
89
 *   Spain
90
 *
91
 *   +34 963163400
92
 *   dac@iver.es
93
 */
94

    
95
/**
96
 * This will be the tab for add a filter to a WFS query.
97
 * This class gets the graphical interface from FilterQueryJPanel and add logic.
98
 * 
99
 * @author Pablo Piqueras Bartolom? (p_queras@hotmail.com)
100
 */
101
public class WFSFilterPanel extends FilterQueryJPanel implements IWindow, IWindowListener {
102
        private static Logger logger = Logger.getLogger(Table.class.getName());
103
        private WFSParamsPanel parent = null;
104
        private ArrayList expressionListeners = new ArrayList();
105
        private ExpressionDataSource model = null;
106
        private NumberFormat nf = NumberFormat.getNumberInstance();
107
        private ExceptionHandlingSupport exceptionHandlingSupport = new ExceptionHandlingSupport();
108
        private AttributesTreeTableModel attributesTreeTableModel;
109
        private boolean panelAsATabForWFSLayersLoad;
110
        private TreePath currentPath;
111
        private String featureName;
112
        
113
        /**
114
         * This method initializes
115
         *
116
         */
117
        public WFSFilterPanel(WFSParamsPanel parent) {
118
                super();
119
                this.parent = parent;
120
                currentPath = null;
121
                featureName = null;
122

    
123
                // At beginning, the JList is disabled (and its set a particular color for user could knew it)
124
                super.getValuesJList().setEnabled(false);
125
                getValuesJList().setBackground(new Color(220, 220, 220));
126
        }
127
        
128
        /*
129
         *  (non-Javadoc)
130
         * @see org.gvsig.gui.beans.filterPanel.AbstractFilterQueryJPanel#initialize()
131
         */
132
        protected void initialize() {
133
                super.initialize();
134
                this.resizeHeight(380);
135

    
136
                defaultTreeModel = (DefaultTreeModel)fieldsJTree.getModel();
137
                
138
                this.addNewListeners();
139
                panelAsATabForWFSLayersLoad = true;                
140
        }
141
        
142
        /**
143
         * Adds some more listener to the components of the panel
144
         */
145
        private void addNewListeners() {
146
                txtExpression.getDocument().addDocumentListener(new DocumentListener() {
147
                        /*
148
                         *  (non-Javadoc)
149
                         * @see javax.swing.event.DocumentListener#changedUpdate(javax.swing.event.DocumentEvent)
150
                         */
151
                        public void changedUpdate(DocumentEvent e) {
152
                        }
153

    
154
                        /*
155
                         *  (non-Javadoc)
156
                         * @see javax.swing.event.DocumentListener#insertUpdate(javax.swing.event.DocumentEvent)
157
                         */
158
                        public void insertUpdate(DocumentEvent e) {
159
                                if (!panelAsATabForWFSLayersLoad)
160
                                        parent.isApplicable(true);
161
                        }
162

    
163
                        /*
164
                         *  (non-Javadoc)
165
                         * @see javax.swing.event.DocumentListener#removeUpdate(javax.swing.event.DocumentEvent)
166
                         */
167
                        public void removeUpdate(DocumentEvent e) {
168
                                if (!panelAsATabForWFSLayersLoad)
169
                                        parent.isApplicable(true);
170
                        }
171
                });
172
                
173
                // Listener for "fieldsJTree" 
174
                getFieldsJTree().addMouseListener(new MouseAdapter() {
175
                        /*
176
                         *  (non-Javadoc)
177
                         * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
178
                         */
179
                        public void mouseClicked(MouseEvent e) {
180
                                int row = fieldsJTree.getRowForLocation(e.getX(), e.getY());
181
                                TreePath treePath = fieldsJTree.getPathForLocation(e.getX(), e.getY());
182

    
183
                                if (row > -1) {
184
                                        switch (e.getClickCount()) {
185
                                                case 2:                                                        
186
                                                        putSymbolOfSelectedByMouseBranch(treePath);
187
                                                        break;
188
                                        }
189
                                }
190
                        }
191
                });
192
                
193
                // Listener for "valuesJList"
194
                getValuesJList().addMouseListener(new MouseAdapter() {
195
                        /*
196
                         *  (non-Javadoc)
197
                         * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
198
                         */
199
                        public void mouseClicked(MouseEvent e) {
200
                                if (e.getClickCount() == 2) {
201
                                        Value valor = (Value) valuesListModel.getElementAt(getValuesJList().getSelectedIndex());
202
                                        
203
                                        if (getNodeOfCurrentPath().getEntityType().getName().compareTo("xs:string") == 0) {
204
                                                putSymbol("'" + valor.toString() + "'");
205
                                        }
206
                                        else {
207
                                                putSymbol(valor.toString());
208
                                        }                                        
209
                                }
210
                        }
211
                });
212
                
213
                // Listener for a branch of the tree selection
214
                getFieldsJTree().addTreeSelectionListener(new TreeSelectionListener() {
215
                        /*
216
                         *  (non-Javadoc)
217
                         * @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent)
218
                         */
219
                        public void valueChanged(TreeSelectionEvent e) {
220
                                if (!panelAsATabForWFSLayersLoad) {
221
                                        DataReturnedOfDataLoadingFromActiveView data = DataLoadingFromActiveView.getDefaultExpressionDataSource();
222
                
223
                                        if ((data != null) && (data.getData() != null)) {
224
                                                setModel(data.getData());
225
                                                currentPath = e.getPath();
226
                                                fillValuesByPath(currentPath);
227
                                        }
228
                                }
229
                        }                        
230
                });
231
        }
232
        
233
        /**
234
         * If there is a field selected, show its new values
235
         */
236
        public void updateFieldValues() {
237
                if (currentPath != null) {
238
                        DataReturnedOfDataLoadingFromActiveView data = DataLoadingFromActiveView.getDefaultExpressionDataSource();
239
                        
240
                        if ((data != null) && (data.getData() != null)) {
241
                                setModel(data.getData());                                
242
                                fillValuesByPath(currentPath);
243
                                
244
                                // Update all tables that their data is about the changed view
245
                                IWindow[] activeNoModalWindows = PluginServices.getMDIManager().getAllWindows();
246
                                
247
        
248
                                for (int i = 0; i < activeNoModalWindows.length; i++) {
249
                                        IWindow window = activeNoModalWindows[i];
250
                                        if (window instanceof Table) {
251
                                                Table table = (Table) window;
252
                                                
253
                                                int pos1 = featureName.indexOf(':');
254
                                                
255
                                                if ((pos1 >= 0) && (pos1 < featureName.length()))                                                
256
                                                        featureName = featureName.substring(pos1 +1, featureName.length());
257
                                                
258
//                                                        String featureOfTable = ((XMLElement)currentPath.getParentPath().getLastPathComponent()).getName();
259
                                                        String featureOfTable = table.getModel().getName();
260
                                                        int pos2 = featureOfTable.indexOf(':');
261
                                                                                                                
262
                                                        if ((pos2 >= 0) && (pos2 < featureName.length()))
263
                                                                featureOfTable = featureOfTable.substring(pos2 +1, featureOfTable.length());                                                
264
                                                
265
                                                if (featureName.trim().compareTo(featureOfTable.trim()) == 0)
266
                                                        table.refresh();
267
                                        }
268
                                }
269
                        }
270
                }
271
        }
272

    
273
        /**
274
         * Sets the value of the inner attribute: 'panelAsATabForWFSLayersLoad'
275
         * 
276
         * @param b A boolean value
277
         */
278
        public void setWFSFilterPanelIsAsTabForWFSLayersLoad (boolean b) {
279
                this.panelAsATabForWFSLayersLoad = b;
280
                
281
                if (this.panelAsATabForWFSLayersLoad == true) {
282
                        // At beginning, the JList is disabled (and its set a particular color for user could knew it)
283
                        super.getValuesJList().setEnabled(false);
284
                        super.getValuesJList().setBackground(new Color(220, 220, 220));
285
                }
286
                else {
287
                        super.getValuesJList().setEnabled(true);
288
                        super.getValuesJList().setBackground(Color.WHITE);
289
                }
290
        }
291
        
292
        /**
293
         * Rellena la lista con los valores del campo seleccionado
294
         */
295
        private void fillValuesByPath(TreePath treePath) {
296
                // Duplicates are removed
297
                TreeSet conjunto = new TreeSet(new Comparator() {
298
                        public int compare(Object o1, Object o2) {
299
                                if ((o1 != null) && (o2 != null)) {
300
                                        Value v2 = (Value) o2;
301
                                        Value v1 = (Value) o1;
302
                                        BooleanValue boolVal;
303
                                        
304
                                        try {
305
                                                boolVal = (BooleanValue) (v1.greater(v2));
306
                                                
307
                                                if (boolVal.getValue()) {
308
                                                        return 1;
309
                                                }
310
                                                
311
                                                boolVal = (BooleanValue) (v1.less(v2));
312
                                                
313
                                                if (boolVal.getValue()) {
314
                                                        return -1;
315
                                                }
316
                                        } catch (IncompatibleTypesException e) {
317
                                                throw new RuntimeException(e);
318
                                        }
319
                                }
320
                                
321
                                return 0;
322
                        }
323
                }); // For ordernation
324
                
325
                // Remove the previous items
326
                valuesListModel.clear();
327
                
328
                try {
329
                        //Object root = treePath.getPath()[0];
330
                        XMLElement element = ((XMLElement)treePath.getLastPathComponent());
331
                        
332
                        // Gets the values associated to the selected branch 
333
                        switch (element.getEntityType().getType()) {
334
                                case IXMLType.SIMPLE:
335
                                        
336
                                        if(element.getParentElement().getParentElement() == null) {                                        
337
                                                // Find the selected field and try to obtein values related
338
                                                for (int i = 0; i < model.getFieldCount(); i++) {                                        
339
                                                        String name = model.getFieldName(i);
340
                                                        
341
                                                        // If we find the field (this means that are loaded its values and we can obtein them)
342
                                                        if (name.equals(element.getName())) {                                                
343
                                                                for (int j = 0; j < model.getRowCount(); j++) {                                        
344
                                                                        Value value = model.getFieldValue(j, i);
345
                                                                        
346
                                                                        if (value instanceof NullValue)
347
                                                                            continue;
348
                                                                        
349
                                                                        if (!conjunto.contains(value)) {
350
                                                                                conjunto.add(value);
351
                                                                        }
352
                                                                }
353
                                                                
354
                                                                break;
355
                                                        }
356
                                                }
357
                                        }else{
358
                                                //create a vector with the parent names from the leaf until the root
359
                                                XMLElement parent = element.getParentElement();
360
                                                Vector parentNames = new Vector();
361
                                                parentNames.add(element.getName());
362
                                                while (parent != null){
363
                                                        parentNames.add(parent.getName());
364
                                                        parent = parent.getParentElement();                                                        
365
                                                }
366
                                                
367
                                                //The field name (in the gvSIG table) is the second field name
368
                                                String fieldName = (String)parentNames.get(parentNames.size()-2);
369
                                                
370
                                                for (int i = 0; i < model.getFieldCount(); i++) {                                        
371
                                                        String name = model.getFieldName(i);
372
                                                        
373
                                                        // If we find the field (this means that are loaded its values and we can obtein them)
374
                                                        if (name.equals(fieldName)) {                                                
375
                                                                for (int j = 0; j < model.getRowCount(); j++) {                                        
376
                                                                        Value value = model.getFieldValue(j, i);
377
                                                                                                                        
378
                                                                        if (value instanceof NullValue)
379
                                                                            continue;
380
                                                                        
381
                                                                        if (value instanceof ComplexValue){
382
                                                                                for (int k=parentNames.size()-3 ; k>=0 ; k--){
383
                                                                                        ComplexValue complex = (ComplexValue)value;
384
                                                                                        Value childValue = (Value)complex.get(parentNames.get(k));
385
                                                                                        if (k==0){
386
                                                                                                if (!conjunto.contains(childValue)) {
387
                                                                                                        conjunto.add(childValue);
388
                                                                                                }
389
                                                                                        }else{
390
                                                                                                value = childValue;
391
                                                                                        }
392
                                                                                }
393
                                                                        }
394
                                                                }
395
                                                                
396
                                                                break;
397
                                                        }
398
                                                }
399
                                        }
400
                                        break;
401
                                case IXMLType.COMPLEX:
402
                                        break;
403
                                default:
404
                                        // Do Nothing
405
                        }
406
                        
407
                        // Add the values to the model of the graphic list
408
                        Iterator it = conjunto.iterator();
409

    
410
                        while (it.hasNext())
411
                                valuesListModel.addElement(it.next());
412
                } catch (Exception e) {
413
                        throwException(e);
414
                }
415
        }
416
        
417
        /**
418
         * Puts the symbol of selected brach
419
         * 
420
         * @param mouseEvent A MouseEvent with information  of the selected branch
421
         */
422
        public void putSymbolOfSelectedByMouseBranch(TreePath treePath) {
423
                // Sets the node selected
424
                if (treePath != null) {
425
                        Object node = treePath.getLastPathComponent();
426
                        if ((node != null) && (node instanceof XMLElement)) {
427
                                XMLElement element = (XMLElement) node;
428
                                XMLElement parent = element.getParentElement();
429
                                String path = element.getName();
430
                                while (parent.getParentElement() != null){
431
                                        path = parent.getName() + "/" + path;
432
                                        parent = parent.getParentElement();
433
                                }
434
                                putSymbol("\"" + path + "\"");
435
                        }
436
                }
437
        }
438
        
439
        /**
440
         * Gets the element that the 'currentPath' attribute aims
441
         * 
442
         * @return An XMLElement
443
         */
444
        private XMLElement getNodeOfCurrentPath() {
445
                
446
                if (currentPath != null) {
447
                        Object node = currentPath.getLastPathComponent();
448
                        
449
                        if ((node != null) && (node instanceof XMLElement)) {
450
//                                XMLElement element = (XMLElement) node;
451
                                return (XMLElement) node;
452
                        }
453
                }
454
                
455
                return null;
456
        }
457
        
458
        /**
459
         * Gets the query that will be send to the server
460
         * @return
461
         * SQL query (just the where part)
462
         */
463
        public String getQuery(){
464
                try {
465
                        return this.validateExpression();
466
                } catch (ParseException e) {                        
467
                        e.printStackTrace();
468
                        return null;
469
                }                
470
        }
471
        
472
        /**
473
         * Writes the query in the user interface
474
         * @param query
475
         * SQL query (just the where part)
476
         */
477
        public void setQuery(String query){
478
                this.txtExpression.setText(query);
479
        }
480
        
481
        /**
482
         * DOCUMENT ME!
483
         *
484
         * @param arg0
485
         *
486
         * @return
487
         */
488
        public boolean addExpressionListener(ExpressionListener arg0) {
489
                return expressionListeners.add(arg0);
490
        }
491

    
492
        /**
493
         * DOCUMENT ME!
494
         *
495
         * @param arg0
496
         *
497
         * @return
498
         */
499
        public boolean removeExpressionListener(ExpressionListener arg0) {
500
                return expressionListeners.remove(arg0);
501
        }
502
        /**
503
         * DOCUMENT ME!
504
         *
505
         * @param o DOCUMENT ME!
506
         *
507
         * @return DOCUMENT ME!
508
         */
509
        public boolean removeExceptionListener(ExceptionListener o) {
510
                return exceptionHandlingSupport.removeExceptionListener(o);
511
        }
512

    
513
        /**
514
         * DOCUMENT ME!
515
         *
516
         * @param t DOCUMENT ME!
517
         */
518
        private void throwException(Throwable t) {
519
                exceptionHandlingSupport.throwException(t);
520
        }
521

    
522
        /**
523
         * DOCUMENT ME!
524
         *
525
         * @param t DOCUMENT ME!
526
         */
527
        public void setModel(ExpressionDataSource t) {
528
                try {
529
                        model = t;
530
            model.start();
531
        } catch (DriverException e1) {
532
            NotificationManager.addError(e1.getMessage(), e1);
533
        }
534
                
535
        try {
536
                int numberOfFields = model.getFieldCount();
537

    
538
                if (numberOfFields > 0) {
539
                        Vector fields = new Vector(0, 1);
540
                        int j = 0;
541
                
542
                                for (int i = 0; i < numberOfFields; i++) {
543
                                         Object field = model.getFieldName(i);
544
                                        
545
                                        if (field != null) {
546
                                                fields.add(field);
547
                                                j++;
548
                                        }
549
                                }
550
                        
551
                                attributesTreeTableModel = new AttributesTreeTableModel(fields.toArray());                        
552
                }
553
                } catch (FilterException e) {
554
                        throwException(e);
555
                }
556
        }
557

    
558
        /**
559
         * DOCUMENT ME!
560
         *
561
         * @param expresion DOCUMENT ME!
562
         * @param substring DOCUMENT ME!
563
         * @param startingPos DOCUMENT ME!
564
         *
565
         * @return DOCUMENT ME!
566
         */
567
        private int getIndex(String expresion, String substring, int startingPos) {
568
                int index = startingPos;
569

    
570
                do {
571
                        index = expresion.indexOf(substring, index);
572
                } while ((StringUtilities.isBetweenSymbols(expresion, index, "\"")) &&
573
                                (index != -1));
574

    
575
                return index;
576
        }
577

    
578
        /**
579
         * DOCUMENT ME!
580
         *
581
         * @param expresion DOCUMENT ME!
582
         * @param word DOCUMENT ME!
583
         * @param translation DOCUMENT ME!
584
         *
585
         * @return DOCUMENT ME!
586
         *
587
         * @throws ParseException DOCUMENT ME!
588
         */
589
        private String translateWord(String expresion, String word,
590
                String translation) throws ParseException {
591
                int booleanIndex = 0;
592
                int endIndex = 0;
593
                StringBuffer res = new StringBuffer();
594

    
595
                while ((booleanIndex = getIndex(expresion, word, booleanIndex)) != -1) {
596
                        res.append(expresion.substring(endIndex, booleanIndex));
597
                        endIndex = booleanIndex + word.length();
598
                        booleanIndex++;
599
                        res.append(translation);
600
                }
601

    
602
                if (endIndex < expresion.length()) {
603
                        res.append(expresion.substring(endIndex));
604
                }
605

    
606
                return res.toString();
607
        }
608

    
609
        /**
610
         * DOCUMENT ME!
611
         *
612
         * @param expresion DOCUMENT ME!
613
         *
614
         * @return DOCUMENT ME!
615
         *
616
         * @throws ParseException DOCUMENT ME!
617
         */
618
        private String translateDates(String expresion) throws ParseException {
619
                //Se obtiene el valor de la fecha
620
                String date = StringUtilities.substringDelimited(expresion, "Date(",
621
                                ")", 0);
622

    
623
                if (date == null) {
624
                        return expresion;
625
                }
626

    
627
                //Se comprueba que no est? entre comillas 
628
                int startIndex = expresion.indexOf(date);
629

    
630
                while (startIndex != -1) {
631
                        if (!StringUtilities.isBetweenSymbols(expresion, startIndex, "\"")) {
632
                                
633
                                //Se sustituye por el valor ordinal de la fecha
634
                                expresion = expresion.substring(0, startIndex - 5) +
635
                                        expresion.substring(startIndex).replaceFirst(date + "\\)",
636
                                                new Long((filterButtonsJPanel.getDateFormat().parse(date)).getTime()).toString());
637
                                ;
638
                        } else {
639
                                startIndex += date.length();
640
                        }
641
                        
642
                        if (date == null) {
643
                                return expresion;
644
                        }
645

    
646
                        startIndex = expresion.indexOf(date, startIndex);
647
                }
648

    
649
                return expresion;
650
        }
651

    
652
        /**
653
         * DOCUMENT ME!
654
         *
655
         * @param expresion DOCUMENT ME!
656
         *
657
         * @return DOCUMENT ME!
658
         *
659
         * @throws ParseException DOCUMENT ME!
660
         */
661
        public String translateNumber(String expresion) throws ParseException {
662
                DefaultCharSet ss = new DefaultCharSet();
663
                ss.addInterval('0', '9');
664
                ss.addCharacter(',');
665
                ss.addCharacter('.');
666

    
667
                String number = StringUtilities.substringWithSymbols(expresion, ss, 0);
668

    
669
                if (number == null) {
670
                        return expresion;
671
                }
672

    
673
                int startIndex = expresion.indexOf(number);
674

    
675
                while (startIndex != -1) {
676
                        Number n = nf.parse(number);
677

    
678
                        if (!StringUtilities.isBetweenSymbols(expresion, startIndex, "\"")) {
679
                                
680
                                //Se sustituye por el valor ordinal de la fecha
681
                                expresion = expresion.substring(0, startIndex) +
682
                                        expresion.substring(startIndex).replaceFirst(number,
683
                                                n.toString());
684
                        } else {
685
                                startIndex += n.toString().length();
686
                        }
687

    
688
                        number = StringUtilities.substringWithSymbols(expresion, ss,
689
                                        startIndex);
690

    
691
                        if (number == null) {
692
                                return expresion;
693
                        }
694

    
695
                        startIndex = expresion.indexOf(number, startIndex);
696
                }
697

    
698
                return expresion;
699
        }
700
        
701
        /**
702
         * Encodes an string to ISO 8859_1 with each ' symbol converted to '' 
703
         * 
704
         * @param text An string started and finished with simple apostrophes
705
         * @return An string started and finished with simple apostrophes
706
         */
707
        private String translateString(String text) {
708
                // Encode to the string to ISO 8859_1 (the URL codification)
709
                try {
710
                        
711
                        // Ignore the first and last apostrophes
712
                        if (text.length() > 2) {
713
                                text = text.substring(1, text.length() -1);
714
                                
715
                                // Convert the string to ISO 8859_1 codification
716
                                text = URLEncoder.encode(text, "8859_1");
717
                                
718
                                // Change '  (%27 code) to '' for the SQL parser (bebore sent the query)
719
                                text = text.replaceAll("\\%27", "\\'\\'");
720
                        }
721

    
722
                } catch (UnsupportedEncodingException e1) {
723
                        e1.printStackTrace();
724
                }
725
                
726
                return "'" + text + "'";
727
        }
728
        
729
        /**
730
         * DOCUMENT ME!
731
         * (Queda por implementar, hay una versi?n reducida)
732
         * 
733
         * @return An string
734
         * @throws ParseException An expection produced by the parser
735
         */
736
        private String validateExpression() throws ParseException {
737
                String expression = txtExpression.getText().trim(); // Ignores the spaces at beginning and end of the chain of characters
738
                String result = new String("");
739
                
740
                // Encode each string of the query
741
                int index = 0;
742
                int lastIndex = 0;
743
                boolean endInnerLoop;
744
                
745
                // Encodes all inner strings to the equivalent codification in ISO-8859_1 with each ' symbol converted to ''
746
                while (index != -1) {
747
                        index = expression.indexOf("'", index);
748
                        
749
                        // Add the parts of the chain of characters that not are string
750
                        if (index == -1) {
751
                                result += expression.substring(lastIndex, expression.length());
752
                        }
753
                        else {
754
                                result += expression.substring(lastIndex, index).replaceAll(" [ ]+", " ");
755
                        }
756
                        
757
                        lastIndex = index;
758
                        endInnerLoop = false;
759
                        
760
                        // Tries to find each first apostrophe of each string of the query
761
                        if ((index > 0) && (expression.charAt(index - 1) == ' ')) {
762
                                index++;
763
                                
764
                                // Ignore all inner apostrophes and try to find the last of the string
765
                                while (!endInnerLoop)  {
766
                                        index = expression.indexOf("'", index);
767
                                        index++;
768
                                        
769
                                        // If we haven't arrived to the finish of the string
770
                                        if (index != expression.length()) {
771
                                                if ((index == -1) || (expression.charAt(index) == ' ')) {
772
                                                        result += translateString(expression.substring(lastIndex, index));
773
                                                        endInnerLoop = true;
774
                                                }
775
                                        }
776
                                        else {
777
                                                result += translateString(expression.substring(lastIndex, index));
778
                                                endInnerLoop = true;
779
                                                index = -1; // Force to finish the external loop
780
                                        }
781
                                }
782
                                lastIndex = index;
783
                        }
784
                }
785
                
786
                //Se transforman los nombres de los campos en las variables xix que analizar?n
787
                //Se quitan los Date(fecha) y se mete la fecha correspondiente
788
                result = translateDates(result);
789
                result = translateNumber(result);
790
                result = translateWord(result, "true", "1");
791
                result = translateWord(result, "false", "0");
792

    
793
                logger.debug(result);
794

    
795
                return result;
796
        }
797
        
798
        /**
799
         * DOCUMENT ME!
800
         *
801
         * @return DOCUMENT ME!
802
         *
803
         * @throws ParseException DOCUMENT ME!
804
         */
805
        private String oldValidateExpressionMethod() throws ParseException {
806
                String expression = txtExpression.getText();
807
//                HashSet variablesIndexes = new HashSet();
808
//
809
//                StringBuffer traducida = new StringBuffer();
810

    
811
                //Se transforman los nombres de los campos en las variables xix que analizar?n
812
                //Se quitan los Date(fecha) y se mete la fecha correspondiente
813
                expression = translateDates(expression);
814
                expression = translateNumber(expression);
815
                expression = translateWord(expression, "true", "1");
816
                expression = translateWord(expression, "false", "0");
817

    
818
                String replacement;
819
                Pattern patron = Pattern.compile("[^<>!]=");
820
                Matcher m = patron.matcher(expression);
821
                int index = 0;
822

    
823
                while (m.find(index)) {
824
                        index = m.start();
825
                        replacement = expression.charAt(index) + "==";
826
                        m.replaceFirst(replacement);
827
                        index++;
828
                }
829

    
830
                expression = expression.replaceAll("[^<>!]=", "==");
831

    
832
                logger.debug(expression);
833

    
834
                return expression;
835
        }
836

    
837
    /* (non-Javadoc)
838
     * @see com.iver.andami.ui.mdiManager.ViewListener#viewActivated()
839
     */
840
    public void windowActivated() {
841
    }
842

    
843
    /* (non-Javadoc)
844
     * @see com.iver.andami.ui.mdiManager.ViewListener#viewClosed()
845
     */
846
    public void windowClosed() {
847
        try {
848
            model.stop();
849
        } catch (DriverException e) {
850
            NotificationManager.addError(e.getMessage(), e);
851
        }        
852
    }
853

    
854
        public WindowInfo getWindowInfo() {
855
                return null;
856
        }
857

    
858
        public void refresh(WFSLayerNode feature) {
859
                setFields(feature);
860
                featureName = feature.getTitle();
861
        }
862
        
863
        /**
864
         * Sets Fields
865
         *
866
         * @param feature
867
         */
868
        private void setFields(WFSLayerNode feature) {
869
                Vector fields = feature.getFields();
870
                                
871
                this.resetFieldsAndValuesData();
872
                
873
                int numberOfFields = fields.size();
874
                
875
                if (numberOfFields > 0) {
876
                        Vector fieldBranches = new Vector(0, 1);
877
                        
878
                        for (int i=0; i<fields.size(); i++) {
879
                                XMLElement field = (XMLElement)fields.get(i);
880

    
881
                                IXMLType type = field.getEntityType();
882
                                
883
                                if (type != null) {                                        
884
                                        
885
                                        switch (type.getType()) {
886
                                                case IXMLType.GML_GEOMETRY:
887
                                                        break;
888
                                                case IXMLType.COMPLEX: case IXMLType.SIMPLE:
889
                                                        fieldBranches.add(field);
890
                                                        break;
891
                                        }
892
                                }
893
                        }
894
                        
895
                        attributesTreeTableModel = new AttributesTreeTableModel(fieldBranches.get(0));
896
                        fieldsJTree.setModel(new AttributesTreeTableModel(fieldBranches.get(0), false));
897
                }
898
        }
899

    
900
        /**
901
         * Resets the data of fields and their values of the current layer feature, and removes the branches of JTree
902
         */
903
        private void resetFieldsAndValuesData() {
904
                fieldsJTree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode()));
905
                txtExpression.setText("");
906
                ((DefaultListModel)valuesJList.getModel()).removeAllElements();
907
        }
908
        
909
        
910
        /**
911
         * @see WFSParamsPanel#isApplicable(boolean)
912
         * 
913
         * @param b A boolean value
914
         */
915
        private void setApplicate(boolean b) {
916
                parent.isApplicable(b);
917
        }
918
}