Statistics
| Revision:

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

History | View | Annotate | Download (27.7 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.ProjectExtension;
44
import com.iver.cit.gvsig.fmap.edition.EditableAdapter;
45
import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter;
46
import com.iver.cit.gvsig.fmap.layers.FLayer;
47
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
48
import com.iver.cit.gvsig.fmap.layers.ReadableVectorial;
49
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
50
import com.iver.cit.gvsig.fmap.layers.WFSLayerNode;
51
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
52
import com.iver.cit.gvsig.gui.filter.ExpressionDataSource;
53
import com.iver.cit.gvsig.gui.filter.ExpressionListener;
54
import com.iver.cit.gvsig.gui.filter.FilterException;
55
import com.iver.cit.gvsig.gui.panels.attributesTree.AttributesTreeTableModel;
56
import com.iver.cit.gvsig.project.ProjectFactory;
57
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
58
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
59
import com.iver.cit.gvsig.project.documents.table.gui.Table;
60
import com.iver.cit.gvsig.project.documents.view.gui.View;
61
import com.iver.utiles.DefaultCharSet;
62
import com.iver.utiles.StringUtilities;
63
import com.iver.utiles.exceptionHandling.ExceptionHandlingSupport;
64
import com.iver.utiles.exceptionHandling.ExceptionListener;
65

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

    
107
/**
108
 * This will be the tab for add a filter to a WFS query.
109
 * This class gets the graphical interface from FilterQueryJPanel and add logic.
110
 * 
111
 * @author Pablo Piqueras Bartolom? (p_queras@hotmail.com)
112
 */
113
public class WFSFilterPanel extends FilterQueryJPanel implements IWindow, IWindowListener {
114
        private static Logger logger = Logger.getLogger(Table.class.getName());
115
        private WFSParamsPanel parent = null;
116
        private ArrayList expressionListeners = new ArrayList();
117
        private ExpressionDataSource model = null;
118
        private NumberFormat nf = NumberFormat.getNumberInstance();
119
        private ExceptionHandlingSupport exceptionHandlingSupport = new ExceptionHandlingSupport();
120
        private AttributesTreeTableModel attributesTreeTableModel;
121
        private boolean panelAsATabForWFSLayersLoad;
122
        private TreePath currentPath;
123
        private String featureName;
124
        
125
        /**
126
         * This method initializes
127
         *
128
         */
129
        public WFSFilterPanel(WFSParamsPanel parent) {
130
                super();
131
                this.parent = parent;
132
                currentPath = null;
133
                featureName = null;
134

    
135
                // At beginning, the JList is disabled (and its set a particular color for user could knew it)
136
                super.getValuesJList().setEnabled(false);
137
                getValuesJList().setBackground(new Color(220, 220, 220));
138
        }
139
        
140
        /*
141
         *  (non-Javadoc)
142
         * @see org.gvsig.gui.beans.filterPanel.AbstractFilterQueryJPanel#initialize()
143
         */
144
        protected void initialize() {
145
                super.initialize();
146
                this.resizeHeight(380);
147

    
148
                defaultTreeModel = (DefaultTreeModel)fieldsJTree.getModel();
149
                
150
                this.addNewListeners();
151
                panelAsATabForWFSLayersLoad = true;                
152
        }
153
        
154
        /**
155
         * Adds some more listener to the components of the panel
156
         */
157
        private void addNewListeners() {
158
                txtExpression.getDocument().addDocumentListener(new DocumentListener() {
159
                        /*
160
                         *  (non-Javadoc)
161
                         * @see javax.swing.event.DocumentListener#changedUpdate(javax.swing.event.DocumentEvent)
162
                         */
163
                        public void changedUpdate(DocumentEvent e) {
164
                        }
165

    
166
                        /*
167
                         *  (non-Javadoc)
168
                         * @see javax.swing.event.DocumentListener#insertUpdate(javax.swing.event.DocumentEvent)
169
                         */
170
                        public void insertUpdate(DocumentEvent e) {
171
                                if (!panelAsATabForWFSLayersLoad)
172
                                        parent.isApplicable(true);
173
                        }
174

    
175
                        /*
176
                         *  (non-Javadoc)
177
                         * @see javax.swing.event.DocumentListener#removeUpdate(javax.swing.event.DocumentEvent)
178
                         */
179
                        public void removeUpdate(DocumentEvent e) {
180
                                if (!panelAsATabForWFSLayersLoad)
181
                                        parent.isApplicable(true);
182
                        }
183
                });
184
                
185
                // Listener for "fieldsJTree" 
186
                getFieldsJTree().addMouseListener(new MouseAdapter() {
187
                        /*
188
                         *  (non-Javadoc)
189
                         * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
190
                         */
191
                        public void mouseClicked(MouseEvent e) {
192
                                int row = fieldsJTree.getRowForLocation(e.getX(), e.getY());
193
                                TreePath treePath = fieldsJTree.getPathForLocation(e.getX(), e.getY());
194

    
195
                                if (row > -1) {
196
                                        switch (e.getClickCount()) {
197
                                                case 2:                                                        
198
                                                        putSymbolOfSelectedByMouseBranch(treePath);
199
                                                        break;
200
                                        }
201
                                }
202
                        }
203
                });
204
                
205
                // Listener for "valuesJList"
206
                getValuesJList().addMouseListener(new MouseAdapter() {
207
                        /*
208
                         *  (non-Javadoc)
209
                         * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
210
                         */
211
                        public void mouseClicked(MouseEvent e) {
212
                                if (e.getClickCount() == 2) {
213
                                        Value valor = (Value) valuesListModel.getElementAt(getValuesJList().getSelectedIndex());
214
                                        
215
                                        if (getNodeOfCurrentPath().getEntityType().getName().compareTo("xs:string") == 0) {
216
                                                putSymbol("'" + valor.toString() + "'");
217
                                        }
218
                                        else {
219
                                                putSymbol(valor.toString());
220
                                        }                                        
221
                                }
222
                        }
223
                });
224
                
225
                // Listener for a branch of the tree selection
226
                getFieldsJTree().addTreeSelectionListener(new TreeSelectionListener() {
227
                        /*
228
                         *  (non-Javadoc)
229
                         * @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent)
230
                         */
231
                        public void valueChanged(TreeSelectionEvent e) {
232
                                if (!panelAsATabForWFSLayersLoad) {
233
                                        DataReturnedOfDataLoadingFromActiveView data = DataLoadingFromActiveView.getDefaultExpressionDataSource();
234
                
235
                                        if ((data != null) && (data.getData() != null)) {
236
                                                setModel(data.getData());
237
                                                currentPath = e.getPath();
238
                                                fillValuesByPath(currentPath);
239
                                        }
240
                                }
241
                        }                        
242
                });
243
        }
244
        
245
        /**
246
         * If there is a field selected, show its new values
247
         */
248
        public void updateFieldValues() {
249
                if (currentPath != null) {
250
                        DataReturnedOfDataLoadingFromActiveView data = DataLoadingFromActiveView.getDefaultExpressionDataSource();
251
                        
252
                        if ((data != null) && (data.getData() != null)) {
253
                                setModel(data.getData());                                
254
                                fillValuesByPath(currentPath);
255
                                
256
                                // Update all tables that their data is about the changed view
257
                                IWindow[] activeNoModalWindows = PluginServices.getMDIManager().getAllWindows();
258
                                
259
        
260
                                for (int i = 0; i < activeNoModalWindows.length; i++) {
261
                                        IWindow window = activeNoModalWindows[i];
262
                                        if (window instanceof Table) {
263
                                                Table table = (Table) window;
264
                                                
265
                                                int pos1 = featureName.indexOf(':');
266
                                                
267
                                                if ((pos1 >= 0) && (pos1 < featureName.length()))                                                
268
                                                        featureName = featureName.substring(pos1 +1, featureName.length());
269
                                                
270
//                                                        String featureOfTable = ((XMLElement)currentPath.getParentPath().getLastPathComponent()).getName();
271
                                                        String featureOfTable = table.getModel().getName();
272
                                                        int pos2 = featureOfTable.indexOf(':');
273
                                                                                                                
274
                                                        if ((pos2 >= 0) && (pos2 < featureName.length()))
275
                                                                featureOfTable = featureOfTable.substring(pos2 +1, featureOfTable.length());                                                
276
                                                
277
                                                if (featureName.trim().compareTo(featureOfTable.trim()) == 0) {                                
278
                                                        setNewDataToTable();
279
                                                
280
                                                        // Refresh the table with the new data
281
                                                        table.refresh();
282
                                                }
283
                                        }
284
                                }
285
                        }
286
                }
287
        }
288
        
289
        /**
290
         * This method is a modification of the "execute" method from the "ShowTable" class 
291
         * @see com.iver.cit.gvsig.ShowTable#execute(String)
292
         */
293
        private void setNewDataToTable() {
294
                View vista = (View) PluginServices.getMDIManager().getActiveWindow();
295
                FLayer[] actives = vista.getModel().getMapContext().getLayers().getActives();
296

    
297
                try {
298
                        for (int i = 0; i < actives.length; i++) {
299
                                if (actives[i] instanceof AlphanumericData) {
300
                                        AlphanumericData co = (AlphanumericData) actives[i];
301

    
302
                                        //SelectableDataSource dataSource;
303
                                        //dataSource = co.getRecordset();
304

    
305
                                        ProjectExtension ext = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class);
306

    
307
                                        ProjectTable projectTable = ext.getProject().getTable(co);
308
                                        EditableAdapter ea=null;
309
                                        ReadableVectorial rv=((FLyrVect)actives[i]).getSource();
310
                                        if (rv instanceof VectorialEditableAdapter){
311
                                                ea=(EditableAdapter)((FLyrVect)actives[i]).getSource();
312
                                        }else{
313
                                                ea=new EditableAdapter();
314
                                                SelectableDataSource sds=((FLyrVect)actives[i]).getRecordset();
315
                                                ea.setOriginalDataSource(sds);
316
                                        }
317

    
318
                                        if (projectTable == null) {
319
                                                projectTable = ProjectFactory.createTable(PluginServices.getText(this, "Tabla_de_Atributos") + ": " + actives[i].getName(),
320
                                                                ea);
321
                                                projectTable.setProjectDocumentFactory(new ProjectTableFactory());
322
                                                projectTable.setAssociatedTable(co);
323
                                                ext.getProject().addDocument(projectTable);
324
                                        }
325
                                        projectTable.setModel(ea);                                        
326
//                                        Table t = new Table();
327
//                                        t.setModel(projectTable);
328
//                                        PluginServices.getMDIManager().addWindow(t);
329
                                }
330
                        }
331
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
332
            NotificationManager.addError(PluginServices.getText(this,"No_se_pudo_obtener_la_tabla_de_la_capa"), e);
333
        } catch (com.iver.cit.gvsig.fmap.DriverException e) {
334
                        e.printStackTrace();
335
                        NotificationManager.addError(PluginServices.getText(this,"No_se_pudo_obtener_la_tabla_de_la_capa"), e);
336
        }
337
        }
338

    
339
        /**
340
         * Sets the value of the inner attribute: 'panelAsATabForWFSLayersLoad'
341
         * 
342
         * @param b A boolean value
343
         */
344
        public void setWFSFilterPanelIsAsTabForWFSLayersLoad (boolean b) {
345
                this.panelAsATabForWFSLayersLoad = b;
346
                
347
                if (this.panelAsATabForWFSLayersLoad == true) {
348
                        // At beginning, the JList is disabled (and its set a particular color for user could knew it)
349
                        super.getValuesJList().setEnabled(false);
350
                        super.getValuesJList().setBackground(new Color(220, 220, 220));
351
                }
352
                else {
353
                        super.getValuesJList().setEnabled(true);
354
                        super.getValuesJList().setBackground(Color.WHITE);
355
                }
356
        }
357
        
358
        /**
359
         * Rellena la lista con los valores del campo seleccionado
360
         */
361
        private void fillValuesByPath(TreePath treePath) {
362
                // Duplicates are removed
363
                TreeSet conjunto = new TreeSet(new Comparator() {
364
                        public int compare(Object o1, Object o2) {
365
                                if ((o1 != null) && (o2 != null)) {
366
                                        Value v2 = (Value) o2;
367
                                        Value v1 = (Value) o1;
368
                                        BooleanValue boolVal;
369
                                        
370
                                        try {
371
                                                boolVal = (BooleanValue) (v1.greater(v2));
372
                                                
373
                                                if (boolVal.getValue()) {
374
                                                        return 1;
375
                                                }
376
                                                
377
                                                boolVal = (BooleanValue) (v1.less(v2));
378
                                                
379
                                                if (boolVal.getValue()) {
380
                                                        return -1;
381
                                                }
382
                                        } catch (IncompatibleTypesException e) {
383
                                                throw new RuntimeException(e);
384
                                        }
385
                                }
386
                                
387
                                return 0;
388
                        }
389
                }); // For ordernation
390
                
391
                // Remove the previous items
392
                valuesListModel.clear();
393
                
394
                try {
395
                        //Object root = treePath.getPath()[0];
396
                        XMLElement element = ((XMLElement)treePath.getLastPathComponent());
397
                        
398
                        // Gets the values associated to the selected branch 
399
                        switch (element.getEntityType().getType()) {
400
                                case IXMLType.SIMPLE:
401
                                        
402
                                        if(element.getParentElement().getParentElement() == null) {                                        
403
                                                // Find the selected field and try to obtein values related
404
                                                for (int i = 0; i < model.getFieldCount(); i++) {                                        
405
                                                        String name = model.getFieldName(i);
406
                                                        
407
                                                        // If we find the field (this means that are loaded its values and we can obtein them)
408
                                                        if (name.equals(element.getName())) {                                                
409
                                                                for (int j = 0; j < model.getRowCount(); j++) {                                        
410
                                                                        Value value = model.getFieldValue(j, i);
411
                                                                        
412
                                                                        if (value instanceof NullValue)
413
                                                                            continue;
414
                                                                        
415
                                                                        if (!conjunto.contains(value)) {
416
                                                                                conjunto.add(value);
417
                                                                        }
418
                                                                }
419
                                                                
420
                                                                break;
421
                                                        }
422
                                                }
423
                                        }else{
424
                                                //create a vector with the parent names from the leaf until the root
425
                                                XMLElement parent = element.getParentElement();
426
                                                Vector parentNames = new Vector();
427
                                                parentNames.add(element.getName());
428
                                                while (parent != null){
429
                                                        parentNames.add(parent.getName());
430
                                                        parent = parent.getParentElement();                                                        
431
                                                }
432
                                                
433
                                                //The field name (in the gvSIG table) is the second field name
434
                                                String fieldName = (String)parentNames.get(parentNames.size()-2);
435
                                                
436
                                                for (int i = 0; i < model.getFieldCount(); i++) {                                        
437
                                                        String name = model.getFieldName(i);
438
                                                        
439
                                                        // If we find the field (this means that are loaded its values and we can obtein them)
440
                                                        if (name.equals(fieldName)) {                                                
441
                                                                for (int j = 0; j < model.getRowCount(); j++) {                                        
442
                                                                        Value value = model.getFieldValue(j, i);
443
                                                                                                                        
444
                                                                        if (value instanceof NullValue)
445
                                                                            continue;
446
                                                                        
447
                                                                        if (value instanceof ComplexValue){
448
                                                                                for (int k=parentNames.size()-3 ; k>=0 ; k--){
449
                                                                                        ComplexValue complex = (ComplexValue)value;
450
                                                                                        Value childValue = (Value)complex.get(parentNames.get(k));
451
                                                                                        if (k==0){
452
                                                                                                if (!conjunto.contains(childValue)) {
453
                                                                                                        conjunto.add(childValue);
454
                                                                                                }
455
                                                                                        }else{
456
                                                                                                value = childValue;
457
                                                                                        }
458
                                                                                }
459
                                                                        }
460
                                                                }
461
                                                                
462
                                                                break;
463
                                                        }
464
                                                }
465
                                        }
466
                                        break;
467
                                case IXMLType.COMPLEX:
468
                                        break;
469
                                default:
470
                                        // Do Nothing
471
                        }
472
                        
473
                        // Add the values to the model of the graphic list
474
                        Iterator it = conjunto.iterator();
475

    
476
                        while (it.hasNext())
477
                                valuesListModel.addElement(it.next());
478
                } catch (Exception e) {
479
                        throwException(e);
480
                }
481
        }
482
        
483
        /**
484
         * Puts the symbol of selected brach
485
         * 
486
         * @param mouseEvent A MouseEvent with information  of the selected branch
487
         */
488
        public void putSymbolOfSelectedByMouseBranch(TreePath treePath) {
489
                // Sets the node selected
490
                if (treePath != null) {
491
                        Object node = treePath.getLastPathComponent();
492
                        if ((node != null) && (node instanceof XMLElement)) {
493
                                XMLElement element = (XMLElement) node;
494
                                XMLElement parent = element.getParentElement();
495
                                String path = element.getName();
496
                                while (parent.getParentElement() != null){
497
                                        path = parent.getName() + "/" + path;
498
                                        parent = parent.getParentElement();
499
                                }
500
                                putSymbol("\"" + path + "\"");
501
                        }
502
                }
503
        }
504
        
505
        /**
506
         * Gets the element that the 'currentPath' attribute aims
507
         * 
508
         * @return An XMLElement
509
         */
510
        private XMLElement getNodeOfCurrentPath() {
511
                
512
                if (currentPath != null) {
513
                        Object node = currentPath.getLastPathComponent();
514
                        
515
                        if ((node != null) && (node instanceof XMLElement)) {
516
//                                XMLElement element = (XMLElement) node;
517
                                return (XMLElement) node;
518
                        }
519
                }
520
                
521
                return null;
522
        }
523
        
524
        /**
525
         * Gets the query that will be send to the server
526
         * @return
527
         * SQL query (just the where part)
528
         */
529
        public String getQuery(){
530
                try {
531
                        return this.validateExpression();
532
                } catch (ParseException e) {                        
533
                        e.printStackTrace();
534
                        return null;
535
                }                
536
        }
537
        
538
        /**
539
         * Writes the query in the user interface
540
         * @param query
541
         * SQL query (just the where part)
542
         */
543
        public void setQuery(String query){
544
                this.txtExpression.setText(query);
545
        }
546
        
547
        /**
548
         * DOCUMENT ME!
549
         *
550
         * @param arg0
551
         *
552
         * @return
553
         */
554
        public boolean addExpressionListener(ExpressionListener arg0) {
555
                return expressionListeners.add(arg0);
556
        }
557

    
558
        /**
559
         * DOCUMENT ME!
560
         *
561
         * @param arg0
562
         *
563
         * @return
564
         */
565
        public boolean removeExpressionListener(ExpressionListener arg0) {
566
                return expressionListeners.remove(arg0);
567
        }
568
        /**
569
         * DOCUMENT ME!
570
         *
571
         * @param o DOCUMENT ME!
572
         *
573
         * @return DOCUMENT ME!
574
         */
575
        public boolean removeExceptionListener(ExceptionListener o) {
576
                return exceptionHandlingSupport.removeExceptionListener(o);
577
        }
578

    
579
        /**
580
         * DOCUMENT ME!
581
         *
582
         * @param t DOCUMENT ME!
583
         */
584
        private void throwException(Throwable t) {
585
                exceptionHandlingSupport.throwException(t);
586
        }
587

    
588
        /**
589
         * DOCUMENT ME!
590
         *
591
         * @param t DOCUMENT ME!
592
         */
593
        public void setModel(ExpressionDataSource t) {
594
                try {
595
                        model = t;
596
            model.start();
597
        } catch (DriverException e1) {
598
            NotificationManager.addError(e1.getMessage(), e1);
599
        }
600
                
601
        try {
602
                int numberOfFields = model.getFieldCount();
603

    
604
                if (numberOfFields > 0) {
605
                        Vector fields = new Vector(0, 1);
606
                        int j = 0;
607
                
608
                                for (int i = 0; i < numberOfFields; i++) {
609
                                         Object field = model.getFieldName(i);
610
                                        
611
                                        if (field != null) {
612
                                                fields.add(field);
613
                                                j++;
614
                                        }
615
                                }
616
                        
617
                                attributesTreeTableModel = new AttributesTreeTableModel(fields.toArray());                        
618
                }
619
                } catch (FilterException e) {
620
                        throwException(e);
621
                }
622
        }
623

    
624
        /**
625
         * DOCUMENT ME!
626
         *
627
         * @param expresion DOCUMENT ME!
628
         * @param substring DOCUMENT ME!
629
         * @param startingPos DOCUMENT ME!
630
         *
631
         * @return DOCUMENT ME!
632
         */
633
        private int getIndex(String expresion, String substring, int startingPos) {
634
                int index = startingPos;
635

    
636
                do {
637
                        index = expresion.indexOf(substring, index);
638
                } while ((StringUtilities.isBetweenSymbols(expresion, index, "\"")) &&
639
                                (index != -1));
640

    
641
                return index;
642
        }
643

    
644
        /**
645
         * DOCUMENT ME!
646
         *
647
         * @param expresion DOCUMENT ME!
648
         * @param word DOCUMENT ME!
649
         * @param translation DOCUMENT ME!
650
         *
651
         * @return DOCUMENT ME!
652
         *
653
         * @throws ParseException DOCUMENT ME!
654
         */
655
        private String translateWord(String expresion, String word,
656
                String translation) throws ParseException {
657
                int booleanIndex = 0;
658
                int endIndex = 0;
659
                StringBuffer res = new StringBuffer();
660

    
661
                while ((booleanIndex = getIndex(expresion, word, booleanIndex)) != -1) {
662
                        res.append(expresion.substring(endIndex, booleanIndex));
663
                        endIndex = booleanIndex + word.length();
664
                        booleanIndex++;
665
                        res.append(translation);
666
                }
667

    
668
                if (endIndex < expresion.length()) {
669
                        res.append(expresion.substring(endIndex));
670
                }
671

    
672
                return res.toString();
673
        }
674

    
675
        /**
676
         * DOCUMENT ME!
677
         *
678
         * @param expresion DOCUMENT ME!
679
         *
680
         * @return DOCUMENT ME!
681
         *
682
         * @throws ParseException DOCUMENT ME!
683
         */
684
        private String translateDates(String expresion) throws ParseException {
685
                //Se obtiene el valor de la fecha
686
                String date = StringUtilities.substringDelimited(expresion, "Date(",
687
                                ")", 0);
688

    
689
                if (date == null) {
690
                        return expresion;
691
                }
692

    
693
                //Se comprueba que no est? entre comillas 
694
                int startIndex = expresion.indexOf(date);
695

    
696
                while (startIndex != -1) {
697
                        if (!StringUtilities.isBetweenSymbols(expresion, startIndex, "\"")) {
698
                                
699
                                //Se sustituye por el valor ordinal de la fecha
700
                                expresion = expresion.substring(0, startIndex - 5) +
701
                                        expresion.substring(startIndex).replaceFirst(date + "\\)",
702
                                                new Long((filterButtonsJPanel.getDateFormat().parse(date)).getTime()).toString());
703
                                ;
704
                        } else {
705
                                startIndex += date.length();
706
                        }
707
                        
708
                        if (date == null) {
709
                                return expresion;
710
                        }
711

    
712
                        startIndex = expresion.indexOf(date, startIndex);
713
                }
714

    
715
                return expresion;
716
        }
717

    
718
        /**
719
         * DOCUMENT ME!
720
         *
721
         * @param expresion DOCUMENT ME!
722
         *
723
         * @return DOCUMENT ME!
724
         *
725
         * @throws ParseException DOCUMENT ME!
726
         */
727
        public String translateNumber(String expresion) throws ParseException {
728
                DefaultCharSet ss = new DefaultCharSet();
729
                ss.addInterval('0', '9');
730
                ss.addCharacter(',');
731
                ss.addCharacter('.');
732

    
733
                String number = StringUtilities.substringWithSymbols(expresion, ss, 0);
734

    
735
                if (number == null) {
736
                        return expresion;
737
                }
738

    
739
                int startIndex = expresion.indexOf(number);
740

    
741
                while (startIndex != -1) {
742
                        Number n = nf.parse(number);
743

    
744
                        if (!StringUtilities.isBetweenSymbols(expresion, startIndex, "\"")) {
745
                                
746
                                //Se sustituye por el valor ordinal de la fecha
747
                                expresion = expresion.substring(0, startIndex) +
748
                                        expresion.substring(startIndex).replaceFirst(number,
749
                                                n.toString());
750
                        } else {
751
                                startIndex += n.toString().length();
752
                        }
753

    
754
                        number = StringUtilities.substringWithSymbols(expresion, ss,
755
                                        startIndex);
756

    
757
                        if (number == null) {
758
                                return expresion;
759
                        }
760

    
761
                        startIndex = expresion.indexOf(number, startIndex);
762
                }
763

    
764
                return expresion;
765
        }
766
        
767
        /**
768
         * Encodes an string to ISO 8859_1 with each ' symbol converted to '' 
769
         * 
770
         * @param text An string started and finished with simple apostrophes
771
         * @return An string started and finished with simple apostrophes
772
         */
773
        private String translateString(String text) {
774
                // Encode to the string to ISO 8859_1 (the URL codification)
775
                try {
776
                        
777
                        // Ignore the first and last apostrophes
778
                        if (text.length() > 2) {
779
                                text = text.substring(1, text.length() -1);
780
                                
781
                                // Convert the string to ISO 8859_1 codification
782
                                text = URLEncoder.encode(text, "8859_1");
783
                                
784
                                // Change '  (%27 code) to '' for the SQL parser (bebore sent the query)
785
                                text = text.replaceAll("\\%27", "\\'\\'");
786
                        }
787

    
788
                } catch (UnsupportedEncodingException e1) {
789
                        e1.printStackTrace();
790
                }
791
                
792
                return "'" + text + "'";
793
        }
794
        
795
        /**
796
         * DOCUMENT ME!
797
         * (Queda por implementar, hay una versi?n reducida)
798
         * 
799
         * @return An string
800
         * @throws ParseException An expection produced by the parser
801
         */
802
        private String validateExpression() throws ParseException {
803
                String expression = txtExpression.getText().trim(); // Ignores the spaces at beginning and end of the chain of characters
804
                String result = new String("");
805
                
806
                // Encode each string of the query
807
                int index = 0;
808
                int lastIndex = 0;
809
                boolean endInnerLoop;
810
                
811
                // Encodes all inner strings to the equivalent codification in ISO-8859_1 with each ' symbol converted to ''
812
                while (index != -1) {
813
                        index = expression.indexOf("'", index);
814
                        
815
                        // Add the parts of the chain of characters that not are string
816
                        if (index == -1) {
817
                                result += expression.substring(lastIndex, expression.length());
818
                        }
819
                        else {
820
                                result += expression.substring(lastIndex, index).replaceAll(" [ ]+", " ");
821
                        }
822
                        
823
                        lastIndex = index;
824
                        endInnerLoop = false;
825
                        
826
                        // Tries to find each first apostrophe of each string of the query
827
                        if ((index > 0) && (expression.charAt(index - 1) == ' ')) {
828
                                index++;
829
                                
830
                                // Ignore all inner apostrophes and try to find the last of the string
831
                                while (!endInnerLoop)  {
832
                                        index = expression.indexOf("'", index);
833
                                        index++;
834
                                        
835
                                        // If we haven't arrived to the finish of the string
836
                                        if (index != expression.length()) {
837
                                                if ((index == -1) || (expression.charAt(index) == ' ')) {
838
                                                        result += translateString(expression.substring(lastIndex, index));
839
                                                        endInnerLoop = true;
840
                                                }
841
                                        }
842
                                        else {
843
                                                result += translateString(expression.substring(lastIndex, index));
844
                                                endInnerLoop = true;
845
                                                index = -1; // Force to finish the external loop
846
                                        }
847
                                }
848
                                lastIndex = index;
849
                        }
850
                }
851
                
852
                //Se transforman los nombres de los campos en las variables xix que analizar?n
853
                //Se quitan los Date(fecha) y se mete la fecha correspondiente
854
                result = translateDates(result);
855
                result = translateNumber(result);
856
                result = translateWord(result, "true", "1");
857
                result = translateWord(result, "false", "0");
858

    
859
                logger.debug(result);
860

    
861
                return result;
862
        }
863
        
864
        /**
865
         * DOCUMENT ME!
866
         *
867
         * @return DOCUMENT ME!
868
         *
869
         * @throws ParseException DOCUMENT ME!
870
         */
871
        private String oldValidateExpressionMethod() throws ParseException {
872
                String expression = txtExpression.getText();
873
//                HashSet variablesIndexes = new HashSet();
874
//
875
//                StringBuffer traducida = new StringBuffer();
876

    
877
                //Se transforman los nombres de los campos en las variables xix que analizar?n
878
                //Se quitan los Date(fecha) y se mete la fecha correspondiente
879
                expression = translateDates(expression);
880
                expression = translateNumber(expression);
881
                expression = translateWord(expression, "true", "1");
882
                expression = translateWord(expression, "false", "0");
883

    
884
                String replacement;
885
                Pattern patron = Pattern.compile("[^<>!]=");
886
                Matcher m = patron.matcher(expression);
887
                int index = 0;
888

    
889
                while (m.find(index)) {
890
                        index = m.start();
891
                        replacement = expression.charAt(index) + "==";
892
                        m.replaceFirst(replacement);
893
                        index++;
894
                }
895

    
896
                expression = expression.replaceAll("[^<>!]=", "==");
897

    
898
                logger.debug(expression);
899

    
900
                return expression;
901
        }
902

    
903
    /* (non-Javadoc)
904
     * @see com.iver.andami.ui.mdiManager.ViewListener#viewActivated()
905
     */
906
    public void windowActivated() {
907
    }
908

    
909
    /* (non-Javadoc)
910
     * @see com.iver.andami.ui.mdiManager.ViewListener#viewClosed()
911
     */
912
    public void windowClosed() {
913
        try {
914
            model.stop();
915
        } catch (DriverException e) {
916
            NotificationManager.addError(e.getMessage(), e);
917
        }        
918
    }
919

    
920
        public WindowInfo getWindowInfo() {
921
                return null;
922
        }
923

    
924
        public void refresh(WFSLayerNode feature) {
925
                setFields(feature);
926
                featureName = feature.getTitle();
927
        }
928
        
929
        /**
930
         * Sets Fields
931
         *
932
         * @param feature
933
         */
934
        private void setFields(WFSLayerNode feature) {
935
                Vector fields = feature.getFields();
936
                                
937
                this.resetFieldsAndValuesData();
938
                
939
                int numberOfFields = fields.size();
940
                
941
                if (numberOfFields > 0) {
942
                        Vector fieldBranches = new Vector(0, 1);
943
                        
944
                        for (int i=0; i<fields.size(); i++) {
945
                                XMLElement field = (XMLElement)fields.get(i);
946

    
947
                                IXMLType type = field.getEntityType();
948
                                
949
                                if (type != null) {                                        
950
                                        
951
                                        switch (type.getType()) {
952
                                                case IXMLType.GML_GEOMETRY:
953
                                                        break;
954
                                                case IXMLType.COMPLEX: case IXMLType.SIMPLE:
955
                                                        fieldBranches.add(field);
956
                                                        break;
957
                                        }
958
                                }
959
                        }
960
                        
961
                        attributesTreeTableModel = new AttributesTreeTableModel(fieldBranches.get(0));
962
                        fieldsJTree.setModel(new AttributesTreeTableModel(fieldBranches.get(0), false));
963
                }
964
        }
965

    
966
        /**
967
         * Resets the data of fields and their values of the current layer feature, and removes the branches of JTree
968
         */
969
        private void resetFieldsAndValuesData() {
970
                fieldsJTree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode()));
971
                txtExpression.setText("");
972
                ((DefaultListModel)valuesJList.getModel()).removeAllElements();
973
        }
974
        
975
        
976
        /**
977
         * @see WFSParamsPanel#isApplicable(boolean)
978
         * 
979
         * @param b A boolean value
980
         */
981
        private void setApplicate(boolean b) {
982
                parent.isApplicable(b);
983
        }
984
}