Statistics
| Revision:

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

History | View | Annotate | Download (29.2 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.DefaultExpressionDataSource;
53
import com.iver.cit.gvsig.gui.filter.ExpressionDataSource;
54
import com.iver.cit.gvsig.gui.filter.ExpressionListener;
55
import com.iver.cit.gvsig.gui.filter.FilterException;
56
import com.iver.cit.gvsig.gui.panels.attributesTree.AttributesTreeTableModel;
57
import com.iver.cit.gvsig.project.ProjectFactory;
58
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
59
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
60
import com.iver.cit.gvsig.project.documents.table.gui.Table;
61
import com.iver.cit.gvsig.project.documents.view.gui.View;
62
import com.iver.utiles.DefaultCharSet;
63
import com.iver.utiles.StringUtilities;
64
import com.iver.utiles.exceptionHandling.ExceptionHandlingSupport;
65
import com.iver.utiles.exceptionHandling.ExceptionListener;
66

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

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

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

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

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

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

    
198
                                if (row > -1) {
199
                                        switch (e.getClickCount()) {
200
                                                case 2:                                                        
201
                                                        putSymbolOfSelectedByMouseBranch(treePath);
202
                                                        break;
203
                                        }
204
                                }
205
                        }
206
                });
207
                
208
                // Listener for "valuesJList"
209
                getValuesJList().addMouseListener(new MouseAdapter() {
210
                        /*
211
                         *  (non-Javadoc)
212
                         * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
213
                         */
214
                        public void mouseClicked(MouseEvent e) {
215
                                if (e.getClickCount() == 2) {
216
                                        Value valor = (Value) valuesListModel.getElementAt(getValuesJList().getSelectedIndex());
217
                                        
218
                                        if (getNodeOfCurrentPath().getEntityType().getName().compareTo("xs:string") == 0) {
219
                                                putSymbol("'" + valor.toString() + "'");
220
                                        }
221
                                        else {
222
                                                putSymbol(valor.toString());
223
                                        }                                        
224
                                }
225
                        }
226
                });
227
                
228
                // Listener for a branch of the tree selection
229
                getFieldsJTree().addTreeSelectionListener(new TreeSelectionListener() {
230
                        /*
231
                         *  (non-Javadoc)
232
                         * @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent)
233
                         */
234
                        public void valueChanged(TreeSelectionEvent e) {
235
                                if (!panelAsATabForWFSLayersLoad) {                                        
236
                                        DataReturnedOfDataLoadingFromActiveView data = DataLoadingFromActiveView.getDefaultExpressionDataSource();
237
                
238
                                        if ((data != null) && (data.getData() != null)) {
239
//                                                setModel(data.getData());
240
                                                currentPath = e.getPath();
241
                                                fillValuesByPath(currentPath);
242
                                        }
243
                                }
244
                        }                        
245
                });
246
        }
247
        
248
        /**
249
         * If there is a field selected, show its new values
250
         */
251
        public void updateFieldValues() {
252
                
253
                // If has selected and loaded another layer -> reset previous values
254
//                if (this.panelAsATabForWFSLayersLoad) {
255
//                        this.getValuesJList().removeAll();
256
//                }
257

    
258
                
259
                if (currentPath != null) {
260
                        
261
                        DataReturnedOfDataLoadingFromActiveView data = DataLoadingFromActiveView.getDefaultExpressionDataSource();
262
                                                
263
                        if ((data != null) && (data.getData() != null)) {
264
                                setModel(data.getData());                                
265
                                fillValuesByPath(currentPath);
266
                                
267
                                // Updates all tables that their data is about the changed view
268
                                this.updateTablesThatHasNewData();
269
                        }
270
                }
271
        }
272
        
273
        /**
274
         * Updates all tables that their data is about the changed view
275
         */
276
        private void updateTablesThatHasNewData() {
277
                IWindow[] activeNoModalWindows = PluginServices.getMDIManager().getAllWindows();
278
                
279
                for (int i = 0; i < activeNoModalWindows.length; i++) {
280
                        IWindow window = activeNoModalWindows[i];
281
                        if (window instanceof Table) {
282
                                Table table = (Table) window;
283
                                
284
                                int pos1 = featureName.indexOf(':');
285
                                
286
                                if ((pos1 >= 0) && (pos1 < featureName.length()))                                                
287
                                        featureName = featureName.substring(pos1 +1, featureName.length());
288
                                
289
//                                        String featureOfTable = ((XMLElement)currentPath.getParentPath().getLastPathComponent()).getName();
290
                                        String featureOfTable = table.getModel().getName();
291
                                        int pos2 = featureOfTable.indexOf(':');
292
                                                                                                
293
                                        if ((pos2 >= 0) && (pos2 < featureName.length()))
294
                                                featureOfTable = featureOfTable.substring(pos2 +1, featureOfTable.length());                                                
295
                                
296
                                if (featureName.trim().compareTo(featureOfTable.trim()) == 0) {                                
297
                                        setNewDataToTable();
298
                                
299
                                        // Refresh the table with the new data
300
                                        table.refresh();
301
                                }
302
                        }
303
                }
304
        }        
305
        
306
        /**
307
         * This method is a modification of the "execute" method from the "ShowTable" class 
308
         * @see com.iver.cit.gvsig.ShowTable#execute(String)
309
         */
310
        private void setNewDataToTable() {
311
                View vista = (View) PluginServices.getMDIManager().getActiveWindow();
312
                FLayer[] actives = vista.getModel().getMapContext().getLayers().getActives();
313

    
314
                try {
315
                        for (int i = 0; i < actives.length; i++) {
316
                                if (actives[i] instanceof AlphanumericData) {
317
                                        AlphanumericData co = (AlphanumericData) actives[i];
318

    
319
                                        //SelectableDataSource dataSource;
320
                                        //dataSource = co.getRecordset();
321

    
322
                                        ProjectExtension ext = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class);
323

    
324
                                        ProjectTable projectTable = ext.getProject().getTable(co);
325
                                        EditableAdapter ea=null;
326
                                        ReadableVectorial rv=((FLyrVect)actives[i]).getSource();
327
                                        if (rv instanceof VectorialEditableAdapter){
328
                                                ea=(EditableAdapter)((FLyrVect)actives[i]).getSource();
329
                                        }else{
330
                                                ea=new EditableAdapter();
331
                                                SelectableDataSource sds=((FLyrVect)actives[i]).getRecordset();
332
                                                ea.setOriginalDataSource(sds);
333
                                        }
334

    
335
                                        if (projectTable == null) {
336
                                                projectTable = ProjectFactory.createTable(PluginServices.getText(this, "Tabla_de_Atributos") + ": " + actives[i].getName(),
337
                                                                ea);
338
                                                projectTable.setProjectDocumentFactory(new ProjectTableFactory());
339
                                                projectTable.setAssociatedTable(co);
340
                                                ext.getProject().addDocument(projectTable);
341
                                        }
342
                                        projectTable.setModel(ea);                                        
343
//                                        Table t = new Table();
344
//                                        t.setModel(projectTable);
345
//                                        PluginServices.getMDIManager().addWindow(t);
346
                                }
347
                        }
348
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
349
            NotificationManager.addError(PluginServices.getText(this,"No_se_pudo_obtener_la_tabla_de_la_capa"), e);
350
        } catch (com.iver.cit.gvsig.fmap.DriverException e) {
351
                        e.printStackTrace();
352
                        NotificationManager.addError(PluginServices.getText(this,"No_se_pudo_obtener_la_tabla_de_la_capa"), e);
353
        }
354
        }
355

    
356
        /**
357
         * Sets the value of the inner attribute: 'panelAsATabForWFSLayersLoad'
358
         * 
359
         * @param b A boolean value
360
         */
361
        public void setWFSFilterPanelIsAsTabForWFSLayersLoad (boolean b) {
362
                this.panelAsATabForWFSLayersLoad = b;
363
                
364
                if (this.panelAsATabForWFSLayersLoad == true) {
365
                        // At beginning, the JList is disabled (and its set a particular color for user could knew it)
366
                        super.getValuesJList().setEnabled(false);
367
                        super.getValuesJList().setBackground(new Color(220, 220, 220));
368
                }
369
                else {
370
                        // Unselect the selected path in the tree (if there was any selected)
371
                        if (this.currentPath != null) {
372
                                this.currentPath = null;
373
                                this.getFieldsJTree().removeSelectionPath(this.getFieldsJTree().getSelectionPath());
374
                        }
375
                        
376
                        // Resets data loaded
377
                        super.getValuesJList().setEnabled(true);
378
                        super.getValuesJList().setBackground(Color.WHITE);
379
                        
380
                        this.getFieldsJTree().removeAll();
381
                        this.getValuesJList().removeAll();
382
                        
383
                        // Updates data associated to view with the new layer data
384
                        this.setNewDataToTable();
385
                        
386
                        // If theres is any table associated to the current view -> update that table/s
387
//                        this.updateTablesThatHasNewData();
388
                        
389
                        // Reads that new data
390
                        DataReturnedOfDataLoadingFromActiveView data = DataLoadingFromActiveView.getDefaultExpressionDataSource();
391
                        
392
                        if ((data != null) && (data.getData() != null)) {
393
                                setModel(data.getData());
394
//                                currentPath = e.getPath();
395
//                                fillValuesByPath(currentPath);
396
                        }
397
                }
398
        }
399
        
400
        /**
401
         * Gets the value of the inner attribute: 'panelAsATabForWFSLayersLoad'
402
         * 
403
         * @return A boolean value
404
         */
405
        public boolean getWFSFilterPanelIsAsTabForWFSLayersLoad() {
406
                return this.panelAsATabForWFSLayersLoad;
407
        }
408
        
409
        /** 
410
         * FIlls list with the values of selected field
411
         * 
412
         * @param treePath A path in the tree
413
         */
414
        private void fillValuesByPath(TreePath treePath) {
415
                // Duplicates are removed
416
                TreeSet conjunto = new TreeSet(new Comparator() {
417
                        public int compare(Object o1, Object o2) {
418
                                if ((o1 != null) && (o2 != null)) {
419
                                        Value v2 = (Value) o2;
420
                                        Value v1 = (Value) o1;
421
                                        BooleanValue boolVal;
422
                                        
423
                                        try {
424
                                                boolVal = (BooleanValue) (v1.greater(v2));
425
                                                
426
                                                if (boolVal.getValue()) {
427
                                                        return 1;
428
                                                }
429
                                                
430
                                                boolVal = (BooleanValue) (v1.less(v2));
431
                                                
432
                                                if (boolVal.getValue()) {
433
                                                        return -1;
434
                                                }
435
                                        } catch (IncompatibleTypesException e) {
436
                                                throw new RuntimeException(e);
437
                                        }
438
                                }
439
                                
440
                                return 0;
441
                        }
442
                }); // For ordernation
443
                
444
                // Remove the previous items
445
                valuesListModel.clear();
446
                
447
                try {
448
                        //Object root = treePath.getPath()[0];
449
                        XMLElement element = ((XMLElement)treePath.getLastPathComponent());
450
                        
451
                        // Gets the values associated to the selected branch 
452
                        switch (element.getEntityType().getType()) {
453
                                case IXMLType.SIMPLE:
454
                                        
455
                                        if(element.getParentElement().getParentElement() == null) {                                        
456
                                                // Find the selected field and try to obtein values related
457
                                                for (int i = 0; i < model.getFieldCount(); i++) {                                        
458
                                                        String name = model.getFieldName(i);
459
                                                        
460
                                                        // If we find the field (this means that are loaded its values and we can obtein them)
461
                                                        if (name.equals(element.getName())) {                                                
462
                                                                for (int j = 0; j < model.getRowCount(); j++) {                                        
463
                                                                        Value value = model.getFieldValue(j, i);
464
                                                                        
465
                                                                        if (value instanceof NullValue)
466
                                                                            continue;
467
                                                                        
468
                                                                        if (!conjunto.contains(value)) {
469
                                                                                conjunto.add(value);
470
                                                                        }
471
                                                                }
472
                                                                
473
                                                                break;
474
                                                        }
475
                                                }
476
                                        }else{
477
                                                //create a vector with the parent names from the leaf until the root
478
                                                XMLElement parent = element.getParentElement();
479
                                                Vector parentNames = new Vector();
480
                                                parentNames.add(element.getName());
481
                                                while (parent != null){
482
                                                        parentNames.add(parent.getName());
483
                                                        parent = parent.getParentElement();                                                        
484
                                                }
485
                                                
486
                                                //The field name (in the gvSIG table) is the second field name
487
                                                String fieldName = (String)parentNames.get(parentNames.size()-2);
488
                                                
489
                                                for (int i = 0; i < model.getFieldCount(); i++) {                                        
490
                                                        String name = model.getFieldName(i);
491
                                                        
492
                                                        // If we find the field (this means that are loaded its values and we can obtein them)
493
                                                        if (name.equals(fieldName)) {                                                
494
                                                                for (int j = 0; j < model.getRowCount(); j++) {                                        
495
                                                                        Value value = model.getFieldValue(j, i);
496
                                                                                                                        
497
                                                                        if (value instanceof NullValue)
498
                                                                            continue;
499
                                                                        
500
                                                                        if (value instanceof ComplexValue){
501
                                                                                for (int k=parentNames.size()-3 ; k>=0 ; k--){
502
                                                                                        ComplexValue complex = (ComplexValue)value;
503
                                                                                        Value childValue = (Value)complex.get(parentNames.get(k));
504
                                                                                        if (k==0){
505
                                                                                                if (!conjunto.contains(childValue)) {
506
                                                                                                        conjunto.add(childValue);
507
                                                                                                }
508
                                                                                        }else{
509
                                                                                                value = childValue;
510
                                                                                        }
511
                                                                                }
512
                                                                        }
513
                                                                }
514
                                                                
515
                                                                break;
516
                                                        }
517
                                                }
518
                                        }
519
                                        break;
520
                                case IXMLType.COMPLEX:
521
                                        break;
522
                                default:
523
                                        // Do Nothing
524
                        }
525
                        
526
                        // Add the values to the model of the graphic list
527
                        Iterator it = conjunto.iterator();
528

    
529
                        while (it.hasNext())
530
                                valuesListModel.addElement(it.next());
531
                } catch (Exception e) {
532
                        throwException(e);
533
                }
534
        }
535
        
536
        /**
537
         * Puts the symbol of selected brach
538
         * 
539
         * @param mouseEvent A MouseEvent with information  of the selected branch
540
         */
541
        public void putSymbolOfSelectedByMouseBranch(TreePath treePath) {
542
                // Sets the node selected
543
                if (treePath != null) {
544
                        Object node = treePath.getLastPathComponent();
545
                        if ((node != null) && (node instanceof XMLElement)) {
546
                                XMLElement element = (XMLElement) node;
547
                                XMLElement parent = element.getParentElement();
548
                                String path = element.getName();
549
                                while (parent.getParentElement() != null){
550
                                        path = parent.getName() + "/" + path;
551
                                        parent = parent.getParentElement();
552
                                }
553
                                putSymbol("\"" + path + "\"");
554
                        }
555
                }
556
        }
557
        
558
        /**
559
         * Gets the element that the 'currentPath' attribute aims
560
         * 
561
         * @return An XMLElement
562
         */
563
        private XMLElement getNodeOfCurrentPath() {
564
                
565
                if (currentPath != null) {
566
                        Object node = currentPath.getLastPathComponent();
567
                        
568
                        if ((node != null) && (node instanceof XMLElement)) {
569
//                                XMLElement element = (XMLElement) node;
570
                                return (XMLElement) node;
571
                        }
572
                }
573
                
574
                return null;
575
        }
576
        
577
        /**
578
         * Gets the query that will be send to the server
579
         * @return
580
         * SQL query (just the where part)
581
         */
582
        public String getQuery(){
583
                try {
584
                        return this.validateExpression();
585
                } catch (ParseException e) {                        
586
                        e.printStackTrace();
587
                        return null;
588
                }                
589
        }
590
        
591
        /**
592
         * Writes the query in the user interface
593
         * @param query
594
         * SQL query (just the where part)
595
         */
596
        public void setQuery(String query){
597
                this.txtExpression.setText(query);
598
        }
599
        
600
        /**
601
         * DOCUMENT ME!
602
         *
603
         * @param arg0
604
         *
605
         * @return
606
         */
607
        public boolean addExpressionListener(ExpressionListener arg0) {
608
                return expressionListeners.add(arg0);
609
        }
610

    
611
        /**
612
         * DOCUMENT ME!
613
         *
614
         * @param arg0
615
         *
616
         * @return
617
         */
618
        public boolean removeExpressionListener(ExpressionListener arg0) {
619
                return expressionListeners.remove(arg0);
620
        }
621
        /**
622
         * DOCUMENT ME!
623
         *
624
         * @param o DOCUMENT ME!
625
         *
626
         * @return DOCUMENT ME!
627
         */
628
        public boolean removeExceptionListener(ExceptionListener o) {
629
                return exceptionHandlingSupport.removeExceptionListener(o);
630
        }
631

    
632
        /**
633
         * DOCUMENT ME!
634
         *
635
         * @param t DOCUMENT ME!
636
         */
637
        private void throwException(Throwable t) {
638
                exceptionHandlingSupport.throwException(t);
639
        }
640

    
641
        /**
642
         * DOCUMENT ME!
643
         *
644
         * @param t DOCUMENT ME!
645
         */
646
        public void setModel(ExpressionDataSource t) {
647
                try {
648
                        model = t;
649
            model.start();
650
        } catch (DriverException e1) {
651
            NotificationManager.addError(e1.getMessage(), e1);
652
        }
653

    
654
        try {
655
                int numberOfFields = model.getFieldCount();
656

    
657
                if (numberOfFields > 0) {
658
                        Vector fields = new Vector(0, 1);
659
                        int j = 0;
660
                
661
                                for (int i = 0; i < numberOfFields; i++) {
662
                                         Object field = model.getFieldName(i);
663
                                        
664
                                        if (field != null) {
665
                                                fields.add(field);
666
                                                j++;
667
                                        }
668
                                }
669
                        
670
                                attributesTreeTableModel = new AttributesTreeTableModel(fields.toArray());                        
671
                }
672
                } catch (FilterException e) {
673
                        throwException(e);
674
                }
675
        }
676

    
677
        /**
678
         * DOCUMENT ME!
679
         *
680
         * @param expresion DOCUMENT ME!
681
         * @param substring DOCUMENT ME!
682
         * @param startingPos DOCUMENT ME!
683
         *
684
         * @return DOCUMENT ME!
685
         */
686
        private int getIndex(String expresion, String substring, int startingPos) {
687
                int index = startingPos;
688

    
689
                do {
690
                        index = expresion.indexOf(substring, index);
691
                } while ((StringUtilities.isBetweenSymbols(expresion, index, "\"")) &&
692
                                (index != -1));
693

    
694
                return index;
695
        }
696

    
697
        /**
698
         * DOCUMENT ME!
699
         *
700
         * @param expresion DOCUMENT ME!
701
         * @param word DOCUMENT ME!
702
         * @param translation DOCUMENT ME!
703
         *
704
         * @return DOCUMENT ME!
705
         *
706
         * @throws ParseException DOCUMENT ME!
707
         */
708
        private String translateWord(String expresion, String word,
709
                String translation) throws ParseException {
710
                int booleanIndex = 0;
711
                int endIndex = 0;
712
                StringBuffer res = new StringBuffer();
713

    
714
                while ((booleanIndex = getIndex(expresion, word, booleanIndex)) != -1) {
715
                        res.append(expresion.substring(endIndex, booleanIndex));
716
                        endIndex = booleanIndex + word.length();
717
                        booleanIndex++;
718
                        res.append(translation);
719
                }
720

    
721
                if (endIndex < expresion.length()) {
722
                        res.append(expresion.substring(endIndex));
723
                }
724

    
725
                return res.toString();
726
        }
727

    
728
        /**
729
         * DOCUMENT ME!
730
         *
731
         * @param expresion DOCUMENT ME!
732
         *
733
         * @return DOCUMENT ME!
734
         *
735
         * @throws ParseException DOCUMENT ME!
736
         */
737
        private String translateDates(String expresion) throws ParseException {
738
                //Se obtiene el valor de la fecha
739
                String date = StringUtilities.substringDelimited(expresion, "Date(",
740
                                ")", 0);
741

    
742
                if (date == null) {
743
                        return expresion;
744
                }
745

    
746
                //Se comprueba que no est? entre comillas 
747
                int startIndex = expresion.indexOf(date);
748

    
749
                while (startIndex != -1) {
750
                        if (!StringUtilities.isBetweenSymbols(expresion, startIndex, "\"")) {
751
                                
752
                                //Se sustituye por el valor ordinal de la fecha
753
                                expresion = expresion.substring(0, startIndex - 5) +
754
                                        expresion.substring(startIndex).replaceFirst(date + "\\)",
755
                                                new Long((filterButtonsJPanel.getDateFormat().parse(date)).getTime()).toString());
756

    
757
                        } else {
758
                                startIndex += date.length();
759
                        }
760
                        
761
                        if (date == null) {
762
                                return expresion;
763
                        }
764

    
765
                        startIndex = expresion.indexOf(date, startIndex);
766
                }
767

    
768
                return expresion;
769
        }
770

    
771
        /**
772
         * DOCUMENT ME!
773
         *
774
         * @param expresion DOCUMENT ME!
775
         *
776
         * @return DOCUMENT ME!
777
         *
778
         * @throws ParseException DOCUMENT ME!
779
         */
780
        public String translateNumber(String expresion) throws ParseException {
781
                DefaultCharSet ss = new DefaultCharSet();
782
                ss.addInterval('0', '9');
783
                ss.addCharacter(',');
784
                ss.addCharacter('.');
785

    
786
                String number = StringUtilities.substringWithSymbols(expresion, ss, 0);
787

    
788
                if (number == null) {
789
                        return expresion;
790
                }
791

    
792
                int startIndex = expresion.indexOf(number);
793

    
794
                while (startIndex != -1) {
795
                        Number n = nf.parse(number);
796

    
797
                        if (!StringUtilities.isBetweenSymbols(expresion, startIndex, "\"")) {
798
                                
799
                                //Se sustituye por el valor ordinal de la fecha
800
                                expresion = expresion.substring(0, startIndex) +
801
                                        expresion.substring(startIndex).replaceFirst(number,
802
                                                n.toString());
803
                        } else {
804
                                startIndex += n.toString().length();
805
                        }
806

    
807
                        number = StringUtilities.substringWithSymbols(expresion, ss,
808
                                        startIndex);
809

    
810
                        if (number == null) {
811
                                return expresion;
812
                        }
813

    
814
                        startIndex = expresion.indexOf(number, startIndex);
815
                }
816

    
817
                return expresion;
818
        }
819
        
820
        /**
821
         * Encodes an string to ISO 8859_1 with each ' symbol converted to '' 
822
         * 
823
         * @param text An string started and finished with simple apostrophes
824
         * @return An string started and finished with simple apostrophes
825
         */
826
        private String translateString(String text) {
827
                // Encode to the string to ISO 8859_1 (the URL codification)
828
                try {
829
                        
830
                        // Ignore the first and last apostrophes
831
                        if (text.length() > 2) {
832
                                text = text.substring(1, text.length() -1);
833
                                
834
                                // Convert the string to ISO 8859_1 codification
835
                                text = URLEncoder.encode(text, "8859_1");
836
                                
837
                                // Change '  (%27 code) to '' for the SQL parser (bebore sent the query)
838
                                text = text.replaceAll("\\%27", "\\'\\'");
839
                        }
840

    
841
                } catch (UnsupportedEncodingException e1) {
842
                        e1.printStackTrace();
843
                }
844
                
845
                return "'" + text + "'";
846
        }
847
        
848
        /**
849
         * DOCUMENT ME!
850
         * (Queda por implementar, hay una versi?n reducida)
851
         * 
852
         * @return An string
853
         * @throws ParseException An expection produced by the parser
854
         */
855
        private String validateExpression() throws ParseException {
856
                String expression = txtExpression.getText().trim(); // Ignores the spaces at beginning and end of the chain of characters
857
                String result = new String("");
858
                
859
                // Encode each string of the query
860
                int index = 0;
861
                int lastIndex = 0;
862
                boolean endInnerLoop;
863
                
864
                // Encodes all inner strings to the equivalent codification in ISO-8859_1 with each ' symbol converted to ''
865
                while (index != -1) {
866
                        index = expression.indexOf("'", index);
867
                        
868
                        // Add the parts of the chain of characters that not are string
869
                        if (index == -1) {
870
                                result += expression.substring(lastIndex, expression.length());
871
                        }
872
                        else {
873
                                result += expression.substring(lastIndex, index).replaceAll(" [ ]+", " ");
874
                        }
875
                        
876
                        lastIndex = index;
877
                        endInnerLoop = false;
878
                        
879
                        // Tries to find each first apostrophe of each string of the query
880
                        if ((index > 0) && (expression.charAt(index - 1) == ' ')) {
881
                                index++;
882
                                
883
                                // Ignore all inner apostrophes and try to find the last of the string
884
                                while (!endInnerLoop)  {
885
                                        index = expression.indexOf("'", index);
886
                                        index++;
887
                                        
888
                                        // If we haven't arrived to the finish of the string
889
                                        if (index != expression.length()) {
890
                                                if ((index == -1) || (expression.charAt(index) == ' ')) {
891
                                                        result += translateString(expression.substring(lastIndex, index));
892
                                                        endInnerLoop = true;
893
                                                }
894
                                        }
895
                                        else {
896
                                                result += translateString(expression.substring(lastIndex, index));
897
                                                endInnerLoop = true;
898
                                                index = -1; // Force to finish the external loop
899
                                        }
900
                                }
901
                                lastIndex = index;
902
                        }
903
                }
904
                
905
                //Se transforman los nombres de los campos en las variables xix que analizar?n
906
                //Se quitan los Date(fecha) y se mete la fecha correspondiente
907
                result = translateDates(result);
908
                result = translateNumber(result);
909
                result = translateWord(result, "true", "1");
910
                result = translateWord(result, "false", "0");
911

    
912
                logger.debug(result);
913

    
914
                return result;
915
        }
916
        
917
        /**
918
         * DOCUMENT ME!
919
         *
920
         * @return DOCUMENT ME!
921
         *
922
         * @throws ParseException DOCUMENT ME!
923
         */
924
        private String oldValidateExpressionMethod() throws ParseException {
925
                String expression = txtExpression.getText();
926
//                HashSet variablesIndexes = new HashSet();
927
//
928
//                StringBuffer traducida = new StringBuffer();
929

    
930
                //Se transforman los nombres de los campos en las variables xix que analizar?n
931
                //Se quitan los Date(fecha) y se mete la fecha correspondiente
932
                expression = translateDates(expression);
933
                expression = translateNumber(expression);
934
                expression = translateWord(expression, "true", "1");
935
                expression = translateWord(expression, "false", "0");
936

    
937
                String replacement;
938
                Pattern patron = Pattern.compile("[^<>!]=");
939
                Matcher m = patron.matcher(expression);
940
                int index = 0;
941

    
942
                while (m.find(index)) {
943
                        index = m.start();
944
                        replacement = expression.charAt(index) + "==";
945
                        m.replaceFirst(replacement);
946
                        index++;
947
                }
948

    
949
                expression = expression.replaceAll("[^<>!]=", "==");
950

    
951
                logger.debug(expression);
952

    
953
                return expression;
954
        }
955

    
956
    /* (non-Javadoc)
957
     * @see com.iver.andami.ui.mdiManager.ViewListener#viewActivated()
958
     */
959
    public void windowActivated() {
960
    }
961

    
962
    /* (non-Javadoc)
963
     * @see com.iver.andami.ui.mdiManager.ViewListener#viewClosed()
964
     */
965
    public void windowClosed() {
966
        try {
967
            model.stop();
968
        } catch (DriverException e) {
969
            NotificationManager.addError(e.getMessage(), e);
970
        }        
971
    }
972

    
973
        public WindowInfo getWindowInfo() {
974
                return null;
975
        }
976

    
977
        public void refresh(WFSLayerNode feature) {
978
                setFields(feature);
979
                featureName = feature.getTitle();
980
        }
981
        
982
        /**
983
         * Sets Fields
984
         *
985
         * @param feature
986
         */
987
        private void setFields(WFSLayerNode feature) {
988
                Vector fields = feature.getFields();
989
                                
990
                this.resetFieldsAndValuesData();
991
                
992
                int numberOfFields = fields.size();
993
                
994
                if (numberOfFields > 0) {
995
                        Vector fieldBranches = new Vector(0, 1);
996
                        
997
                        for (int i=0; i<fields.size(); i++) {
998
                                XMLElement field = (XMLElement)fields.get(i);
999

    
1000
                                IXMLType type = field.getEntityType();
1001
                                
1002
                                if (type != null) {                                        
1003
                                        
1004
                                        switch (type.getType()) {
1005
                                                case IXMLType.GML_GEOMETRY:
1006
                                                        break;
1007
                                                case IXMLType.COMPLEX: case IXMLType.SIMPLE:
1008
                                                        fieldBranches.add(field);
1009
                                                        break;
1010
                                        }
1011
                                }
1012
                        }
1013
                        
1014
                        attributesTreeTableModel = new AttributesTreeTableModel(fieldBranches.get(0));
1015
                        fieldsJTree.setModel(new AttributesTreeTableModel(fieldBranches.get(0), false));
1016
                }
1017
        }
1018

    
1019
        /**
1020
         * Resets the data of fields and their values of the current layer feature, and removes the branches of JTree
1021
         */
1022
        private void resetFieldsAndValuesData() {
1023
                fieldsJTree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode()));
1024
                txtExpression.setText("");
1025
                ((DefaultListModel)valuesJList.getModel()).removeAllElements();
1026
        }
1027
        
1028
        
1029
        /**
1030
         * @see WFSParamsPanel#isApplicable(boolean)
1031
         * 
1032
         * @param b A boolean value
1033
         */
1034
        private void setApplicate(boolean b) {
1035
                parent.isApplicable(b);
1036
        }
1037
}