Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extWFS2 / src / com / iver / cit / gvsig / gui / panels / WFSFilterPanel.java @ 10608

History | View | Annotate | Download (48.5 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.DateFormat;
9
import java.text.NumberFormat;
10
import java.text.ParseException;
11
import java.util.ArrayList;
12
import java.util.Comparator;
13
import java.util.HashMap;
14
import java.util.Iterator;
15
import java.util.Map;
16
import java.util.Set;
17
import java.util.StringTokenizer;
18
import java.util.TreeSet;
19
import java.util.Vector;
20
import java.util.regex.Matcher;
21
import java.util.regex.Pattern;
22

    
23
import javax.swing.DefaultListModel;
24
import javax.swing.JLabel;
25
import javax.swing.JOptionPane;
26
import javax.swing.event.DocumentEvent;
27
import javax.swing.event.DocumentListener;
28
import javax.swing.event.TreeSelectionEvent;
29
import javax.swing.event.TreeSelectionListener;
30
import javax.swing.tree.DefaultMutableTreeNode;
31
import javax.swing.tree.DefaultTreeModel;
32
import javax.swing.tree.TreePath;
33

    
34
import org.apache.log4j.Logger;
35
import org.gvsig.gui.beans.Messages;
36
import org.gvsig.gui.beans.filterPanel.filterQueryPanel.FilterQueryJPanel;
37
import org.gvsig.gui.beans.filterPanel.filterQueryPanel.jLabelAsCell.DefaultListModelForJLabelAsCell;
38
import org.gvsig.gui.beans.filterPanel.filterQueryPanel.jLabelAsCell.JLabelAsCellValueLoaded;
39
import org.gvsig.gui.beans.filterPanel.filterQueryPanel.jLabelAsCell.JLabelAsCellValueNotLoaded;
40
import org.gvsig.remoteClient.gml.schemas.XMLElement;
41
import org.gvsig.remoteClient.gml.types.IXMLType;
42

    
43
import com.hardcode.gdbms.engine.data.driver.DriverException;
44
import com.hardcode.gdbms.engine.instruction.IncompatibleTypesException;
45
import com.hardcode.gdbms.engine.values.BooleanValue;
46
import com.hardcode.gdbms.engine.values.ComplexValue;
47
import com.hardcode.gdbms.engine.values.NullValue;
48
import com.hardcode.gdbms.engine.values.Value;
49
import com.iver.andami.PluginServices;
50
import com.iver.andami.messages.NotificationManager;
51
import com.iver.andami.ui.mdiManager.IWindow;
52
import com.iver.cit.gvsig.ProjectExtension;
53
import com.iver.cit.gvsig.fmap.edition.EditableAdapter;
54
import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter;
55
import com.iver.cit.gvsig.fmap.layers.FLayer;
56
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
57
import com.iver.cit.gvsig.fmap.layers.ReadableVectorial;
58
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
59
import com.iver.cit.gvsig.fmap.layers.WFSLayerNode;
60
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
61
import com.iver.cit.gvsig.gui.filter.ExpressionDataSource;
62
import com.iver.cit.gvsig.gui.filter.ExpressionListener;
63
import com.iver.cit.gvsig.gui.filter.FilterException;
64
import com.iver.cit.gvsig.gui.panels.fieldsTree.FieldsTreeTableModel;
65
import com.iver.cit.gvsig.project.ProjectFactory;
66
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
67
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
68
import com.iver.cit.gvsig.project.documents.table.gui.Table;
69
import com.iver.cit.gvsig.project.documents.view.gui.View;
70
import com.iver.cit.gvsig.sqlQueryValidation.SQLQueryValidation;
71
import com.iver.utiles.DefaultCharSet;
72
import com.iver.utiles.StringUtilities;
73
import com.iver.utiles.exceptionHandling.ExceptionHandlingSupport;
74
import com.iver.utiles.exceptionHandling.ExceptionListener;
75
import com.iver.utiles.stringNumberUtilities.StringNumberUtilities;
76

    
77

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

    
119
/**
120
 * This will be the tab for add a filter to a WFS query.
121
 * This class gets the graphical interface from FilterQueryJPanel and add logic.
122
 * 
123
 * @author Pablo Piqueras Bartolom? (p_queras@hotmail.com)
124
 */
125
public class WFSFilterPanel extends FilterQueryJPanel {
126
        private static Logger logger = Logger.getLogger(Table.class.getName());
127
        private WFSParamsPanel parent = null;
128
        private ArrayList expressionListeners = new ArrayList();
129
        private ExpressionDataSource model = null;
130
        private NumberFormat nf = NumberFormat.getNumberInstance();
131
        private ExceptionHandlingSupport exceptionHandlingSupport = new ExceptionHandlingSupport();
132
        private FieldsTreeTableModel fieldsTreeTableModel;
133
        private boolean panelAsATabForWFSLayersLoad;
134
        private TreePath currentPath;
135
        private String featureName;
136
        private Map allFieldsAndValuesKnownOfCurrentLayer; // This will have all values (not repeated) known of all fields (not repeated)
137
        
138
        ///// GUI METHODS ////
139
        
140
        /**
141
         * This method initializes
142
         * 
143
         * @param parent A reference to the parent container component of this component
144
         */
145
        public WFSFilterPanel(WFSParamsPanel parent) {
146
                super();
147
                this.parent = parent;
148
                currentPath = null;
149
                featureName = null;
150
                allFieldsAndValuesKnownOfCurrentLayer = new HashMap(); // Initial capacity = 0
151

    
152
                // At beginning, the JList is disabled (and its set a particular color for user could knew it)
153
                super.getValuesJList().setEnabled(false);
154
                getValuesJList().setBackground(new Color(220, 220, 220));
155
        }
156
        
157
        /*
158
         *  (non-Javadoc)
159
         * @see org.gvsig.gui.beans.filterPanel.AbstractFilterQueryJPanel#initialize()
160
         */
161
        protected void initialize() {
162
                super.initialize();
163
                this.resizeHeight(380);
164

    
165
                defaultTreeModel = (DefaultTreeModel)fieldsJTree.getModel();
166
                
167
                this.addNewListeners();
168
                panelAsATabForWFSLayersLoad = true;
169
                getValidateFilterExpressionJCheckBox().setSelected(true);
170
                
171
                getValuesJLabel().setToolTipText(Messages.getText("values_of_the_selected_field_explanation"));
172
                getFieldsJLabel().setToolTipText(Messages.getText("fields_of_the_selected_feature_explanation"));
173
        }
174
        
175
        /**
176
         * Adds some more listener to the components of the panel
177
         */
178
        private void addNewListeners() {
179
                
180
                // Enable "Apply" button when user changes the filter query
181
                txtExpression.getDocument().addDocumentListener(new DocumentListener() {
182
                        /*
183
                         *  (non-Javadoc)
184
                         * @see javax.swing.event.DocumentListener#changedUpdate(javax.swing.event.DocumentEvent)
185
                         */
186
                        public void changedUpdate(DocumentEvent e) {
187
                        }
188

    
189
                        /*
190
                         *  (non-Javadoc)
191
                         * @see javax.swing.event.DocumentListener#insertUpdate(javax.swing.event.DocumentEvent)
192
                         */
193
                        public void insertUpdate(DocumentEvent e) {
194
                                if (!panelAsATabForWFSLayersLoad)
195
                                        parent.isApplicable(true);
196
                        }
197

    
198
                        /*
199
                         *  (non-Javadoc)
200
                         * @see javax.swing.event.DocumentListener#removeUpdate(javax.swing.event.DocumentEvent)
201
                         */
202
                        public void removeUpdate(DocumentEvent e) {
203
                                if (!panelAsATabForWFSLayersLoad)
204
                                        parent.isApplicable(true);
205
                        }
206
                });
207
                
208
                // Listener for "fieldsJTree" 
209
                getFieldsJTree().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
                                int row = fieldsJTree.getRowForLocation(e.getX(), e.getY());
216
                                TreePath treePath = fieldsJTree.getPathForLocation(e.getX(), e.getY());
217

    
218
                                if (row > -1) {
219
                                        switch (e.getClickCount()) {
220
                                                case 2:                                                        
221
                                                        putSymbolOfSelectedByMouseBranch(treePath);
222
                                                        break;
223
                                        }
224
                                }
225
                        }
226
                });
227
                
228
                // Listener for "valuesJList"
229
                getValuesJList().addMouseListener(new MouseAdapter() {
230
                        /*
231
                         *  (non-Javadoc)
232
                         * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
233
                         */
234
                        public void mouseClicked(MouseEvent e) {
235
                                int index = getValuesJList().getSelectedIndex();
236
                                
237
                                // Avoids exception when no value is in the list
238
                                if (index == -1)
239
                                        return;
240
                                        
241
                                if (e.getClickCount() == 2){
242
                                        String valor = ((JLabel) valuesListModel.getElementAt(index)).getText();
243
                                        
244
                                        // If value is an string -> set it between apostrophes
245
                                        if (getNodeOfCurrentPath().getEntityType().getName().compareTo("xs:string") == 0) {
246
                                                putSymbol("'" + valor + "'");
247
                                        }
248
                                        else {
249
                                                putSymbol(valor);
250
                                        }
251
                                }
252
                        }
253
                });
254
                
255
                // Listener for a branch of the tree selection
256
                getFieldsJTree().addTreeSelectionListener(new TreeSelectionListener() {
257
                        /*
258
                         *  (non-Javadoc)
259
                         * @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent)
260
                         */
261
                        public void valueChanged(TreeSelectionEvent e) {
262
                                if (!panelAsATabForWFSLayersLoad) {                                        
263
                                        DataReturnedOfDataLoadingFromActiveView data = DataLoadingFromActiveView.getDefaultExpressionDataSource();
264
                
265
                                        if ((data != null) && (data.getData() != null)) {
266
//                                                setModel(data.getData());
267
                                                currentPath = e.getPath();
268
                                                fillValuesByPath(currentPath);
269
                                        }
270
                                }
271
                        }                        
272
                });
273
                
274
                // Listener: when a user writes something on the textarea -> set it's foreground color to black
275
                getTxtExpression().getDocument().addDocumentListener(new DocumentListener() {
276
                        /*
277
                         *  (non-Javadoc)
278
                         * @see javax.swing.event.DocumentListener#changedUpdate(javax.swing.event.DocumentEvent)
279
                         */
280
                        public void changedUpdate(DocumentEvent e) {
281
                        }
282

    
283
                        /*
284
                         *  (non-Javadoc)
285
                         * @see javax.swing.event.DocumentListener#insertUpdate(javax.swing.event.DocumentEvent)
286
                         */
287
                        public void insertUpdate(DocumentEvent e) {
288
                                getTxtExpression().setForeground(Color.BLACK);
289
                        }
290

    
291
                        /*
292
                         *  (non-Javadoc)
293
                         * @see javax.swing.event.DocumentListener#removeUpdate(javax.swing.event.DocumentEvent)
294
                         */
295
                        public void removeUpdate(DocumentEvent e) {                                
296
                                getTxtExpression().setForeground(Color.BLACK);
297
                        }                        
298
                });
299
                
300
//                // Listener: if user wants or not that the filter expression would be validated
301
//                getValidateFilterExpressionJCheckBox().addItemListener(new ItemListener() {
302
//                        /*
303
//                         * (non-Javadoc)
304
//                         * @see java.awt.event.ItemListener#itemStateChanged(java.awt.event.ItemEvent)
305
//                         */
306
//                        public void itemStateChanged(ItemEvent e) {
307
//                                if (e.getStateChange() == ItemEvent.SELECTED)
308
//                                        System.out.println("Seleccionada");
309
//                                else {
310
//                                        if (e.getStateChange() == ItemEvent.DESELECTED)
311
//                                                System.out.println("Deseleccionada");
312
//                                }
313
//                        }
314
//                });
315
        }
316
        
317
        /**
318
         * Gets the element that the 'currentPath' field aims
319
         * 
320
         * @return An XMLElement
321
         */
322
        private XMLElement getNodeOfCurrentPath() {
323
                
324
                if (currentPath != null) {
325
                        Object node = currentPath.getLastPathComponent();
326
                        
327
                        if ((node != null) && (node instanceof XMLElement)) {
328
                                return (XMLElement) node;
329
                        }
330
                }
331
                
332
                return null;
333
        }
334
        
335
        /**
336
         * Puts the symbol of selected brach
337
         * 
338
         * @param mouseEvent A MouseEvent with information  of the selected branch
339
         */
340
        public void putSymbolOfSelectedByMouseBranch(TreePath treePath) {
341
                // Sets the node selected
342
                if (treePath != null) {
343
                        putSymbol("\"" + this.getPathOfLeafWithoutRoot(treePath.getLastPathComponent()) + "\"");
344
                }
345
        }
346
        
347
        /**
348
         * This method returns the path of a node of a tree
349
         * Each node is separated from its parent with the symbol "/"
350
         * 
351
         * @param node A node of a 
352
         * @return An string with the path
353
         */
354
        private String getPathOfLeaf(Object node) {
355
                String path = "";
356
                
357
                if ((node != null) && (node instanceof XMLElement)) {
358
                        XMLElement element = (XMLElement) node;
359
                        XMLElement parent = element.getParentElement();
360
                        path = element.getName();
361
                
362
                        while (parent != null){
363
                                path = parent.getName() + "/" + path;
364
                                parent = parent.getParentElement();
365
                        }
366
                }
367
                        
368
                return path;
369
        }
370
        
371
        /**
372
         * This method returns the path without the root, of a node of a tree
373
         * Each node is separated from its parent with the symbol "/"
374
         * 
375
         * @param node A node of a 
376
         * @return An string with the path
377
         */
378
        private String getPathOfLeafWithoutRoot(Object node) {
379
                String path = "";
380
                
381
                if ((node != null) && (node instanceof XMLElement)) {
382
                        XMLElement element = (XMLElement) node;
383
                        XMLElement parent = element.getParentElement();
384
                        path = element.getName();
385
                
386
                        while (parent.getParentElement() != null){
387
                                path = parent.getName() + "/" + path;
388
                                parent = parent.getParentElement();
389
                        }
390
                }
391
                        
392
                return path;
393
        }
394
        
395
        /**
396
         * Gets the value of the inner attribute: 'panelAsATabForWFSLayersLoad'
397
         * 
398
         * @return A boolean value
399
         */
400
        public boolean getWFSFilterPanelIsAsTabForWFSLayersLoad() {
401
                return this.panelAsATabForWFSLayersLoad;
402
        }
403
        
404
        /**
405
         * Sets the value of the inner attribute: 'panelAsATabForWFSLayersLoad'
406
         * 
407
         * @param b A boolean value
408
         */
409
        public void setWFSFilterPanelIsAsTabForWFSLayersLoad (boolean b) {
410
                this.panelAsATabForWFSLayersLoad = b;
411
                
412
                if (this.panelAsATabForWFSLayersLoad == true) {
413
                        // At beginning, the JList is disabled (and its set a particular color for user could knew it)
414
                        super.getValuesJList().setEnabled(false);
415
                        super.getValuesJList().setBackground(new Color(220, 220, 220)); // a grey color
416
                        
417
                        this.allFieldsAndValuesKnownOfCurrentLayer.clear();
418
                        getValidateFilterExpressionJCheckBox().setSelected(true);
419
                }
420
                else {
421
                        // Unselect the selected path in the tree (if there was any selected)
422
                        if (this.currentPath != null) {
423
                                this.currentPath = null;
424
                                this.getFieldsJTree().removeSelectionPath(this.getFieldsJTree().getSelectionPath());
425
                        }
426
                        
427
                        // Resets data loaded
428
                        super.getValuesJList().setEnabled(true);
429
                        super.getValuesJList().setBackground(Color.WHITE);
430
                        
431
                        this.getFieldsJTree().removeAll();
432
                        this.getValuesJList().removeAll();
433
                        
434
                        // Updates data associated to view with the new layer data
435
                        this.setNewDataToTable();
436
                        
437
                        // If theres is any table associated to the current view -> update that table/s
438
//                        this.updateTablesThatHasNewData();
439
                        
440
                        // Reads that new data
441
                        DataReturnedOfDataLoadingFromActiveView data = DataLoadingFromActiveView.getDefaultExpressionDataSource();
442
                        
443
                        if ((data != null) && (data.getData() != null)) {
444
                                setModel(data.getData());
445
//                                currentPath = e.getPath();
446
//                                fillValuesByPath(currentPath);
447
                        }
448
                        
449
                        // Loads values known of fields
450
                        this.setValuesKnownOfFields();
451
                }
452
        }
453
        
454
        /**
455
         * Refresh all information about fields
456
         * 
457
         * @param feature The layer to refresh
458
         * 
459
         * @return True if can refresh, False if not
460
         */
461
        public boolean refresh(WFSLayerNode feature) {
462
                featureName = feature.getTitle();
463
                return setFields(feature);
464
        }
465
        
466
        ///// END GUI METHODS /////
467

    
468
        ///// METHODS FOR THE FILTER QUERY /////
469
        
470
        /**
471
         * Gets the query that will be send to the server
472
         * @return SQL query (just the where part)
473
         */
474
        public String getQuery(){
475
                String writtenQuery = txtExpression.getText().trim();
476
                
477
                // Validate expression
478
                if (!this.validateExpression(writtenQuery)) {
479
                        getTxtExpression().setForeground(Color.red);
480
                        return null;
481
                }
482
                else
483
                        // Codify expression (only if the validation has been successful)
484
                        return this.codifyExpression(writtenQuery); // Ignores the spaces at beginning and end of the chain of characters
485
        }
486
        
487
        /**
488
         * Gets the filter expression from the user interface
489
         */
490
        public String getFilterExpressionFromInterface() {
491
                return getTxtExpression().getText();
492
        }
493
        
494
        /**
495
         * Writes the filter expression into the user interface
496
         * @param filterExpression An string
497
         */
498
        public void setFilterExpressionIntoInterface(String filterExpression){
499
                getTxtExpression().setText(filterExpression);
500
        }
501
        
502
        /**
503
         * Removes text in the JTextArea that has the filter subconsultation
504
         */
505
        public void removeFilterExpression() {
506
                getTxtExpression().setText("");
507
        }
508
        
509
        /**
510
         * Codifies the expression to ISO ISO-8859_1 and a format that the SQL parser could validate
511
         * 
512
         * @param expression The expression to be codified 
513
         * 
514
         * @return The expression codified
515
         */
516
        private String codifyExpression(String expression) {
517
                String result = new String("");
518
                        
519
                // Encode each string of the query
520
                int index = 0;
521
                int lastIndex = 0;
522
                boolean endInnerLoop;
523
                // Encodes all inner strings to the equivalent codification in ISO-8859_1 with each ' symbol converted to ''
524
                while (index != -1) {
525
                        index = expression.indexOf("'", index);
526
                        
527
                        // Add the parts of the chain of characters that not are string
528
                        if (index == -1) {
529
                                result += expression.substring(lastIndex, expression.length());
530
                        }
531
                        else {
532
                                result += expression.substring(lastIndex, index).replaceAll(" [ ]+", " ");
533
                        }
534
                        
535
                        lastIndex = index;
536
                        endInnerLoop = false;
537
                        
538
                        // Tries to find each first apostrophe of each string of the query
539
                        if ((index > 0) && (expression.charAt(index - 1) == ' ')) {
540
                                index++;
541
                                
542
                                // Ignore all inner apostrophes and try to find the last of the string
543
                                while (!endInnerLoop)  {
544
                                        index = expression.indexOf("'", index);
545
                                        index++;
546
                                        
547
                                        // If we haven't arrived to the finish of the string
548
                                        if (index != expression.length()) {
549
                                                if ((index == -1) || (expression.charAt(index) == ' ')) {
550
                                                        result += translateString(expression.substring(lastIndex, index));
551
                                                        endInnerLoop = true;
552
                                                }
553
                                        }
554
                                        else {
555
                                                result += translateString(expression.substring(lastIndex, index));
556
                                                endInnerLoop = true;
557
                                                index = -1; // Force to finish the external loop
558
                                        }
559
                                }
560
                                lastIndex = index;
561
                        }
562
                }
563
                        
564
                // Field names are transformated in xix variables that will be analyzed
565
                // Date(date) is substituted by the correct date format
566
                try {
567
                        result = translateDates(result);
568
                }
569
                catch(ParseException e) {
570
                        JOptionPane.showMessageDialog(this, PluginServices.getText(null, "error_codifying_dates"), PluginServices.getText(null, "error_coding_filter_query"), JOptionPane.ERROR_MESSAGE);
571
                        return null;
572
                }
573

    
574
                try {
575
                        result = translateNumber(result);
576
                }
577
                catch(ParseException e) {
578
                        JOptionPane.showMessageDialog(this, PluginServices.getText(null, "error_codifying_numbers"), PluginServices.getText(null, "error_coding_filter_query"), JOptionPane.ERROR_MESSAGE);
579
                        return null;
580
                }
581

    
582
                try {
583
                        result = translateWord(result, "true", "1");
584
                }
585
                catch(ParseException e) {
586
                        JOptionPane.showMessageDialog(this, PluginServices.getText(null, "error_codifying_words"), PluginServices.getText(null, "error_coding_filter_query"), JOptionPane.ERROR_MESSAGE);
587
                        return null;
588
                }
589

    
590
                try {
591
                        result = translateWord(result, "false", "0");
592
                }
593
                catch(ParseException e) {
594
                        JOptionPane.showMessageDialog(this, PluginServices.getText(null, "error_codifying_words"), PluginServices.getText(null, "error_coding_filter_query"), JOptionPane.ERROR_MESSAGE);
595
                        return null;
596
                }
597
        
598
                logger.debug(result);                        
599

    
600
                return result;
601
        }
602
        
603
        /**
604
         * Checks the filter expression if it's correct
605
         * 
606
         * @param query The query expression to analyze
607
         * @return True if it's valid or false if not
608
         */
609
        private boolean validateExpression(String query) {
610
                // If it's needed to validate the query
611
                if (getValidateFilterExpressionJCheckBox().isSelected()) {                
612
                        // If it's an empty query -> ok 
613
                        if (query.trim().length() == 0)
614
                                return true;
615
                        
616
                        // Replace all Date(dd-mmm-yyyy) format to ddd-mmm-yyyy (characters will replaced to spaces)
617
                        int index = 0;
618
                        String query_copy = new String(query);
619
                        while ((index = query_copy.indexOf("Date(", index)) != -1) {
620
                                if (index > 0) {
621
                                        if ((query_copy.charAt(index-1) != ' ') && (query_copy.charAt(index-1) != '('))
622
                                                break;
623
                                }
624
                                
625
                                if (((index + 16) < query_copy.length()) && (query_copy.charAt(index + 16) == ')')) { // +17 is the length of Date(dd-mmm-yyyy)
626
                                        if ((index + 17) < query_copy.length()) {
627
                                                query_copy = query_copy.substring(0, index) + "     " + query_copy.substring(index+6, index+16) + " " + query_copy.substring(index+17);
628
                                        }
629
                                        else {
630
                                                query_copy = query_copy.substring(0, index) + "     " + query_copy.substring(index+6, index+16);
631
                                        }
632
                                }
633
                        }
634
                        
635
                        SQLQueryValidation sQLQueryValidation = new SQLQueryValidation(query_copy, true);
636
        
637
                        // Tries to validate the query, and if fails shows a message
638
                        if (!sQLQueryValidation.validateQuery()) {
639
                                JOptionPane.showMessageDialog(null, PluginServices.getText(null, "filter_with_an_incorrect_format") + ": " + PluginServices.getText(null, "finded") + " " + sQLQueryValidation.getTokenThatProducedTheSyntacticError() + " " + PluginServices.getText(null, "in")  + " " + sQLQueryValidation.getErrorPositionAsMessage() + ".", PluginServices.getText(null, "error_validating_filter_query"), JOptionPane.ERROR_MESSAGE);
640
                                return false;
641
                        }
642
                        else {
643
                                // Analyzes tokens in query
644
                                StringTokenizer tokens = new StringTokenizer(query, " ");
645
                                String token, token_aux;
646
                                boolean finish = false;
647
        
648
                                // If there is a field or a value with spaces, (and then it's on differents tokens) -> unify them
649
                                while (tokens.hasMoreTokens()) {
650
                                        token = tokens.nextToken().trim();
651
                                        
652
                                        if (token.charAt(0) == '\'') {
653
                                                if (token.charAt(token.length() -1) != '\'') {
654
                                                        while (!finish) {
655
                                                                if (!tokens.hasMoreTokens()) {
656
                                                                        JOptionPane.showMessageDialog(null, PluginServices.getText(null, "filter_with_an_incorrect_format") + ": " + PluginServices.getText(null, "the_token") + " " + token + " " + PluginServices.getText(null, "has_bad_format"), PluginServices.getText(null, "error_validating_filter_query"), JOptionPane.ERROR_MESSAGE);
657
                                                                        return false;
658
                                                                }
659
                                                                else {
660
                                                                        token_aux = tokens.nextToken().trim();
661
                                                                        token += " " + token_aux;
662
                                                                        
663
                                                                        if (token_aux.charAt(token_aux.length() -1) == '\'')
664
                                                                                finish = true;
665
                                                                }
666
                                                        }
667
                                                        
668
                                                        finish = false;
669
                                                }
670
                                        }
671
                                        
672
                                        if (token.charAt(0) == '\"') {
673
                                                if (token.charAt(token.length() -1) != '\"') {
674
                                                        while (!finish) {
675
                                                                if (!tokens.hasMoreTokens()) {
676
                                                                        JOptionPane.showMessageDialog(null, PluginServices.getText(null, "filter_with_an_incorrect_format") + ": " + PluginServices.getText(null, "the_token") + " " + token + " " + PluginServices.getText(null, "has_bad_format"), PluginServices.getText(null, "error_validating_filter_query"), JOptionPane.ERROR_MESSAGE);
677
                                                                        return false;
678
                                                                }
679
                                                                else {
680
                                                                        token_aux = tokens.nextToken().trim();
681
                                                                        token += " " + token_aux;
682
                                                                        
683
                                                                        if (token_aux.charAt(token_aux.length() -1) == '\"')
684
                                                                                finish = true;
685
                                                                }
686
                                                        }
687
                                                        
688
                                                        finish = false;
689
                                                }
690
                                        }
691
        
692
                                        // Tries to find an invalid token
693
                                        if (token.length() > 0) {
694
                                                // Validates if a supposed field exists
695
                                                if ( (token.length() > 2) && (token.charAt(0) == '\"') && (token.charAt(token.length()-1) == '\"') ) {
696
                                                        if (! this.isAField(token.substring(1, token.length()-1))) {
697
                                                                JOptionPane.showMessageDialog(null, PluginServices.getText(null, "filter_with_an_incorrect_format") + ": " + PluginServices.getText(null, "the_token") + " " + token + " " + PluginServices.getText(null, "isnt_a_field_of_layer"), PluginServices.getText(null, "error_validating_filter_query"), JOptionPane.ERROR_MESSAGE);
698
                                                                return false;
699
                                                        }
700
                                                }
701
                                                else {
702
                                                        // If it's an string -> ignore
703
                                                        if (! ((token.charAt(0) == token.charAt(token.length() - 1)) && (token.charAt(0) == '\''))) {
704
                                                                
705
                                                                // If it's a date -> ignore
706
                                                                int returnValue = validateDate(token);
707
                                                                
708
                                                                if (returnValue == 1) {
709
                                                                        JOptionPane.showMessageDialog(null, PluginServices.getText(null, "filter_with_an_incorrect_format") + ": " + PluginServices.getText(null, "incorrect_format_on_date") + " " + token.substring(5, 16) + " .", PluginServices.getText(null, "error_validating_filter_query"), JOptionPane.ERROR_MESSAGE);
710
                                                                        return false;
711
                                                                }
712
                                                                
713
                                                                if (returnValue == 2) {                                                                
714
                                                                        // Else -> Checks if the current token is a valid number or symbol
715
                                                                        if ((! StringNumberUtilities.isRealNumberWithRealExponent(token)) && (! this.isAnOperatorNameOrSymbol(token, getAllOperatorSymbols()))) {
716
                                                                                JOptionPane.showMessageDialog(null, PluginServices.getText(null, "filter_with_an_incorrect_format") + ": " + PluginServices.getText(null, "not_valid_token") + ": " + token, PluginServices.getText(null, "error_validating_filter_query"), JOptionPane.ERROR_MESSAGE);
717
                                                                                return false;
718
                                                                        }
719
                                                                }
720
                                                        }
721
                                                }
722
                                        }
723
                                }
724
        
725
                                // If has validate all tokens -> query validated
726
                                return true;
727
                        }
728
                }
729
                else
730
                        return true; // No validation done because user selected that option
731
        }
732
        
733
        /**
734
         * Returns true if there is a field with the same name as 'text'
735
         * 
736
         * @param text An string
737
         * @return A boolean value
738
         */
739
        private boolean isAField(String text) {
740
                return this.allFieldsAndValuesKnownOfCurrentLayer.containsKey(text);                
741
        }
742
        
743
        /**
744
         * Validates if a text has a correct date format as Date(dd-mmm-yyyy)  (Ex. Date(03-feb-2004) )
745
         * 
746
         * @param text
747
         * @return 0 -> if has a date format; 1 -> if it's a date that has a but format; 2 -> if it isn't a date
748
         */
749
        private int validateDate(String text) {
750
                // If it's a date -> check if format is correct (Ex.  Date(01-feb-2004) )
751
                if ( ((text.length() == 17) && (text.startsWith("Date(")) && (text.endsWith(")"))) && (text.charAt(7) == '-') && (text.charAt(11) == '-') ) {
752
                        if ( (StringNumberUtilities.isNaturalNumber(text.substring(5, 7))) && (StringNumberUtilities.isNaturalNumber(text.substring(12, 16))) ) {
753
                                try {
754
                                        // If can parse the date -> date with a correct format 
755
                                        DateFormat.getDateInstance().parse(text.substring(5, 16));
756
                                        return 0;
757
                                } catch (ParseException e) {
758
                                        // If can't parse the date -> date with an incorrect format 
759
                                        return 1;
760
                                }
761
                        }
762
                        else {
763
                                return 1;
764
                        }
765
                }
766
                
767
                return 2;
768

    
769
        }
770

    
771
        /**
772
         * Returns true if there is the 'text' is a symbol or a operator name
773
         * 
774
         * @param text An string
775
         * @return A boolean value
776
         */
777
        private boolean isAnOperatorNameOrSymbol(String text, Set operatorNamesAndSymbols) {                
778
                return operatorNamesAndSymbols.contains(text);
779
        }
780
        
781
        /**
782
         * DOCUMENT ME!
783
         *
784
         * @return DOCUMENT ME!
785
         *
786
         * @throws ParseException DOCUMENT ME!
787
         * @deprecated In this moments its a reference of the old Validate Expression method
788
         */
789
        private String oldValidateExpressionMethod() throws ParseException {
790
                String expression = txtExpression.getText();
791
//                HashSet variablesIndexes = new HashSet();
792
//
793
//                StringBuffer traducida = new StringBuffer();
794

    
795
                //Se transforman los nombres de los campos en las variables xix que analizar?n
796
                //Se quitan los Date(fecha) y se mete la fecha correspondiente
797
                expression = translateDates(expression);
798
                expression = translateNumber(expression);
799
                expression = translateWord(expression, "true", "1");
800
                expression = translateWord(expression, "false", "0");
801

    
802
                String replacement;
803
                Pattern patron = Pattern.compile("[^<>!]=");
804
                Matcher m = patron.matcher(expression);
805
                int index = 0;
806

    
807
                while (m.find(index)) {
808
                        index = m.start();
809
                        replacement = expression.charAt(index) + "==";
810
                        m.replaceFirst(replacement);
811
                        index++;
812
                }
813

    
814
                expression = expression.replaceAll("[^<>!]=", "==");
815

    
816
                logger.debug(expression);
817

    
818
                return expression;
819
        }
820
        
821
        ///// END METHODS FOR THE FILTER QUERY /////
822

    
823
        ///// METHODS FOR TRANSLATE DATA IN FILTER SENTENCES /////
824

    
825
        /** 
826
         * DOCUMENT ME!
827
         *
828
         * @param expresion DOCUMENT ME!
829
         * @param word DOCUMENT ME!
830
         * @param translation DOCUMENT ME!
831
         *
832
         * @return DOCUMENT ME!
833
         *
834
         * @throws ParseException DOCUMENT ME!
835
         */
836
        private String translateWord(String expresion, String word,        String translation) throws ParseException {
837
                int booleanIndex = 0;
838
                int endIndex = 0;
839
                StringBuffer res = new StringBuffer();
840

    
841
                while ((booleanIndex = getIndex(expresion, word, booleanIndex)) != -1) {
842
                        res.append(expresion.substring(endIndex, booleanIndex));
843
                        endIndex = booleanIndex + word.length();
844
                        booleanIndex++;
845
                        res.append(translation);
846
                }
847

    
848
                if (endIndex < expresion.length()) {
849
                        res.append(expresion.substring(endIndex));
850
                }
851

    
852
                return res.toString();
853
        }
854

    
855
        /**
856
         * DOCUMENT ME!
857
         *
858
         * @param expresion DOCUMENT ME!
859
         *
860
         * @return DOCUMENT ME!
861
         *
862
         * @throws ParseException DOCUMENT ME!
863
         */
864
        private String translateDates(String expresion) throws ParseException {
865
                //Se obtiene el valor de la fecha
866
                String date = StringUtilities.substringDelimited(expresion, "Date(", ")", 0);
867

    
868
                if (date == null) {
869
                        return expresion;
870
                }
871

    
872
                //Se comprueba que no est? entre comillas 
873
                int startIndex = expresion.indexOf(date);
874

    
875
                while (startIndex != -1) {
876
                        if (!StringUtilities.isBetweenSymbols(expresion, startIndex, "\"")) {
877
                                
878
                                //Se sustituye por el valor ordinal de la fecha
879
                                expresion = expresion.substring(0, startIndex - 5) +
880
                                        expresion.substring(startIndex).replaceFirst(date + "\\)",                                                        
881
                                                new Long((filterButtonsJPanel.getDateFormat().parse(date)).getTime()).toString());
882

    
883
                        } else {
884
                                startIndex += date.length();
885
                        }
886
                        
887
                        if (date == null) {
888
                                return expresion;
889
                        }
890

    
891
                        startIndex = expresion.indexOf(date, startIndex);
892
                }
893

    
894
                return expresion;
895
        }
896

    
897
        /**
898
         * DOCUMENT ME!
899
         *
900
         * @param expresion DOCUMENT ME!
901
         *
902
         * @return DOCUMENT ME!
903
         *
904
         * @throws ParseException DOCUMENT ME!
905
         */
906
        private String translateNumber(String expresion) throws ParseException {
907
                DefaultCharSet ss = new DefaultCharSet();
908
                ss.addInterval('0', '9');
909
                ss.addCharacter(',');
910
                ss.addCharacter('.');
911

    
912
                String number = StringUtilities.substringWithSymbols(expresion, ss, 0);
913

    
914
                if (number == null) {
915
                        return expresion;
916
                }
917

    
918
                int startIndex = expresion.indexOf(number);
919

    
920
                while (startIndex != -1) {
921
                        Number n = nf.parse(number);
922

    
923
                        if (!StringUtilities.isBetweenSymbols(expresion, startIndex, "\"")) {
924
                                
925
                                //Se sustituye por el valor ordinal de la fecha
926
                                expresion = expresion.substring(0, startIndex) +
927
                                        expresion.substring(startIndex).replaceFirst(number,
928
                                                n.toString());
929
                        } else {
930
                                startIndex += n.toString().length();
931
                        }
932

    
933
                        number = StringUtilities.substringWithSymbols(expresion, ss,
934
                                        startIndex);
935

    
936
                        if (number == null) {
937
                                return expresion;
938
                        }
939

    
940
                        startIndex = expresion.indexOf(number, startIndex);
941
                }
942

    
943
                return expresion;
944
        }
945
        
946
        /**
947
         * Encodes an string to ISO 8859_1 with each ' symbol converted to '' 
948
         * 
949
         * @param text An string started and finished with simple apostrophes
950
         * 
951
         * @return An string started and finished with simple apostrophes
952
         */
953
        private String translateString(String text) {
954
                // Encode to the string to ISO 8859_1 (the URL codification)
955
                try {
956
                        
957
                        // Ignore the first and last apostrophes
958
                        if (text.length() > 2) {
959
                                text = text.substring(1, text.length() -1);
960
                                
961
                                // Convert the string to ISO 8859_1 codification
962
                                text = URLEncoder.encode(text, "8859_1");
963
                                
964
                                // Change '  (%27 code) to '' for the SQL parser (bebore sent the query)
965
                                text = text.replaceAll("\\%27", "\\'\\'");
966
                        }
967

    
968
                } catch (UnsupportedEncodingException e1) {
969
                        e1.printStackTrace();
970
                }
971
                
972
                return "'" + text + "'";
973
        }
974
        
975
        ///// END METHODS FOR TRANSLATE DATA IN FILTER SENTENCES /////
976
        
977
        ///// METHODS FOR MANIPULATE 'fields' and 'values' /////
978
        
979
        /**
980
         * DOCUMENT ME!
981
         *
982
         * @param t DOCUMENT ME!
983
         */
984
        public void setModel(ExpressionDataSource t) {
985
                try {
986
                        model = t;
987
            model.start();
988
        } catch (DriverException e1) {
989
            NotificationManager.addError(e1.getMessage(), e1);
990
        }
991

    
992
        try {
993
                int numberOfFields = model.getFieldCount();
994

    
995
                if (numberOfFields > 0) {
996
                        Vector fields = new Vector(0, 1);
997
                        int j = 0;
998
                
999
                                for (int i = 0; i < numberOfFields; i++) {
1000
                                         Object field = model.getFieldName(i);
1001
                                        
1002
                                        if (field != null) {
1003
                                                fields.add(field);
1004

    
1005
                                                String completeFieldPath = this.getPathOfLeafWithoutRoot(field);
1006
                                                
1007
                                                if (! allFieldsAndValuesKnownOfCurrentLayer.containsKey(completeFieldPath) ) {
1008
                                                        allFieldsAndValuesKnownOfCurrentLayer.put(completeFieldPath, new HashMap());
1009
                                                }
1010
                                                
1011
                                                j++;
1012
                                        }
1013
                                }
1014
                        
1015
                                fieldsTreeTableModel = new FieldsTreeTableModel(fields.toArray());                        
1016
                }
1017
                } catch (FilterException e) {
1018
                        throwException(e);
1019
                }
1020
        }
1021
        
1022
        /**
1023
         * If there is a field selected, show its new values
1024
         */
1025
        public void updateFieldValues() {
1026
                if (currentPath != null) {
1027
                        
1028
                        DataReturnedOfDataLoadingFromActiveView data = DataLoadingFromActiveView.getDefaultExpressionDataSource();
1029
                                                
1030
                        if ((data != null) && (data.getData() != null)) {
1031
                                setModel(data.getData());                                
1032
                                fillValuesByPath(currentPath);
1033
                                
1034
//                                valuesListModel.clear();
1035
                                
1036
                                // Updates all tables that their data is about the changed view
1037
                                this.updateTablesThatHasNewData();                                
1038
                                
1039
                                // Adjust JScrollPanes to the the beginning
1040
                                getFieldsJScrollPane().getHorizontalScrollBar().setValue(-1);
1041
                                getFieldsJScrollPane().getVerticalScrollBar().setValue(-1);
1042

    
1043
                                // Adjust JScrollPanes to the the beginning
1044
                                getValuesJScrollPane().getHorizontalScrollBar().setValue(-1);
1045
                                getValuesJScrollPane().getVerticalScrollBar().setValue(-1);
1046

    
1047
                                // Adjusts valuesJList to the default position
1048
                                getValuesJList().setSelectedIndex(-1); // No item selected
1049
                        }
1050
                }
1051
        }
1052
        
1053
        /**
1054
         * Sets Fields
1055
         *
1056
         * @param feature A Layer node with fields information
1057
         * 
1058
         * @return True if can refresh, False if not
1059
         */
1060
        private boolean setFields(WFSLayerNode feature) {
1061
                Vector fields = feature.getFields();
1062
                                
1063
                this.resetFieldsAndValuesData();
1064
                
1065
                int numberOfFields = fields.size();
1066
                
1067
                if (numberOfFields > 0) {
1068
                        Vector fieldBranches = new Vector(0, 1);
1069
                        
1070
                        for (int i=0; i<fields.size(); i++) {
1071
                                XMLElement field = (XMLElement)fields.get(i);
1072

    
1073
                                IXMLType type = field.getEntityType();
1074
                                
1075
                                if (type != null) {                                        
1076
                                        
1077
                                        switch (type.getType()) {
1078
                                                case IXMLType.GML_GEOMETRY: // Don't add branch / field
1079
                                                        break;
1080
                                                case IXMLType.COMPLEX: case IXMLType.SIMPLE: // Add branch / field
1081
                                                        fieldBranches.add(field);
1082
                                                        break;
1083
                                        }
1084
                                }
1085
                        }
1086
                        
1087
                        if (fieldBranches.size() > 0) {
1088
                                Object obj = fieldBranches.get(0);
1089
                                
1090
                                fieldsTreeTableModel = new FieldsTreeTableModel(obj);
1091
                                fieldsJTree.setModel(new FieldsTreeTableModel(obj, false));
1092

    
1093
                                // Stores the name of all leafs (fields) of treeTableModel                        
1094
                                Object root = fieldsTreeTableModel.getRoot();
1095
                                
1096
                                if (root != null) {
1097
                                        Vector fieldsNames = fieldsTreeTableModel.getLeafsFromNodeBranch(root);
1098
                                        
1099
                                        for (int j = 0; j < fieldsNames.size(); j++) {
1100
                                                Object field = fieldsNames.get(j);
1101
                                                
1102
                                                // Avoid errors
1103
                                                if ( (! (field instanceof XMLElement)) || (field == null) )
1104
                                                        continue;
1105
                                                
1106
                                                // Don't load a geometry field                                        
1107
                                                if (((XMLElement)field).getEntityType() != null){
1108
                                                        if ( ((XMLElement)field).getEntityType().getType() == IXMLType.GML_GEOMETRY ){
1109
                                                                continue;
1110
                                                        }
1111
                                                }
1112
                                                
1113
                                                String completeFieldPath = this.getPathOfLeafWithoutRoot(field);
1114
                                                
1115
                                                if (! allFieldsAndValuesKnownOfCurrentLayer.containsKey(completeFieldPath) ) {
1116
                                                        allFieldsAndValuesKnownOfCurrentLayer.put(completeFieldPath, new HashMap());
1117
                                                }
1118
                                        }
1119
                                }
1120
                        }
1121
                        else {
1122
                                // If there is no geometry field (that is the root) -> don't load the layer
1123
                                JOptionPane.showMessageDialog(null, PluginServices.getText(null, "gvSIG_cant_load_the_layer_because_hasnt_geometry"), PluginServices.getText(null, "error"), JOptionPane.ERROR_MESSAGE);
1124
                                        
1125
                                return false;
1126
                        }
1127
                }
1128

    
1129
                return true;
1130
        }
1131

    
1132
        /**
1133
         * This method load all values known of all fields known
1134
         * (It's used when a new layer is load)
1135
         */
1136
        private void setValuesKnownOfFields() {
1137
                // Desde el modelo se deber?a acceder a los campos y sus valores cargados                
1138
                try {
1139
                        for (int i = 0; i < model.getFieldCount(); i++) {
1140
                                String fieldName = model.getFieldName(i);
1141
                                HashMap fieldValues = (HashMap) allFieldsAndValuesKnownOfCurrentLayer.get(fieldName);
1142
                                
1143
                                if (fieldValues != null) {
1144
                                        for (int j = 0; j < model.getRowCount(); j++) {
1145
                                                Value value = model.getFieldValue(j, i);                                        
1146
                                                
1147
                                                if (value instanceof NullValue)
1148
                                                    continue;
1149
                                                
1150
                                                Object obj = (Object)value;
1151
                                                
1152
                                                if (obj == null)
1153
                                                        continue;
1154
                                                
1155
                                                fieldValues.put(obj.toString(), obj.toString());
1156
                                                
1157
                                        }
1158
                                }
1159
                        }
1160
                }
1161
                catch (Exception e) {
1162
                        e.printStackTrace();
1163
                }
1164
        }
1165
        
1166
        /**
1167
         * Resets the data of fields and their values of the current layer feature, and removes the branches of JTree
1168
         */
1169
        private void resetFieldsAndValuesData() {
1170
                fieldsJTree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode()));
1171
                txtExpression.setText("");
1172
                ((DefaultListModel)valuesJList.getModel()).removeAllElements();
1173
        }
1174
        
1175
        /** 
1176
         * FIlls list with the values of selected field
1177
         * 
1178
         * @param treePath A path in the tree
1179
         */
1180
        private void fillValuesByPath(TreePath treePath) {
1181
                // Duplicates are removed
1182
                TreeSet conjunto = new TreeSet(new Comparator() {
1183
                        public int compare(Object o1, Object o2) {
1184
                                if ((o1 != null) && (o2 != null)) {
1185
                                        Value v2 = (Value) o2;
1186
                                        Value v1 = (Value) o1;
1187
                                        BooleanValue boolVal;
1188
                                        
1189
                                        try {
1190
                                                boolVal = (BooleanValue) (v1.greater(v2));
1191
                                                
1192
                                                if (boolVal.getValue()) {
1193
                                                        return 1;
1194
                                                }
1195
                                                
1196
                                                boolVal = (BooleanValue) (v1.less(v2));
1197
                                                
1198
                                                if (boolVal.getValue()) {
1199
                                                        return -1;
1200
                                                }
1201
                                        } catch (IncompatibleTypesException e) {
1202
                                                throw new RuntimeException(e);
1203
                                        }
1204
                                }
1205
                                
1206
                                return 0;
1207
                        }
1208
                }); // For ordernation
1209
                
1210
                // Remove the previous items
1211
                valuesListModel.clear();
1212
                
1213
                try {
1214
                        //Object root = treePath.getPath()[0];
1215
                        XMLElement element = ((XMLElement)treePath.getLastPathComponent());
1216
                        
1217
                        // Gets the values associated to the selected branch 
1218
                        switch (element.getEntityType().getType()) {
1219
                                case IXMLType.SIMPLE:
1220
                                        
1221
                                        if(element.getParentElement().getParentElement() == null) {                                        
1222
                                                // Find the selected field and try to obtein values related
1223
                                                for (int i = 0; i < model.getFieldCount(); i++) {                                        
1224
                                                        String name = model.getFieldName(i);
1225
                                                        
1226
                                                        // If we find the field (this means that are loaded its values and we can obtein them)
1227
                                                        if (name.equals(element.getName())) {                                                
1228
                                                                for (int j = 0; j < model.getRowCount(); j++) {                                        
1229
                                                                        Value value = model.getFieldValue(j, i);
1230
                                                                        
1231
                                                                        if (value instanceof NullValue)
1232
                                                                            continue;
1233
                                                                        
1234
                                                                        if (!conjunto.contains(value)) {
1235
                                                                                conjunto.add(value);
1236
                                                                        }
1237
                                                                }
1238
                                                                
1239
                                                                break;
1240
                                                        }
1241
                                                }
1242
                                        }else{
1243
                                                //create a vector with the parent names from the leaf until the root
1244
                                                XMLElement parent = element.getParentElement();
1245
                                                Vector parentNames = new Vector();
1246
                                                parentNames.add(element.getName());
1247
                                                while (parent != null){
1248
                                                        parentNames.add(parent.getName());
1249
                                                        parent = parent.getParentElement();                                                        
1250
                                                }
1251
                                                
1252
                                                //The field name (in the gvSIG table) is the second field name
1253
                                                String fieldName = (String)parentNames.get(parentNames.size()-2);
1254
                                                
1255
                                                for (int i = 0; i < model.getFieldCount(); i++) {                                        
1256
                                                        String name = model.getFieldName(i);
1257
                                                        
1258
                                                        // If we find the field (this means that are loaded its values and we can obtein them)
1259
                                                        if (name.equals(fieldName)) {                                                
1260
                                                                for (int j = 0; j < model.getRowCount(); j++) {                                        
1261
                                                                        Value value = model.getFieldValue(j, i);
1262
                                                                                                                        
1263
                                                                        if (value instanceof NullValue)
1264
                                                                            continue;
1265
                                                                        
1266
                                                                        if (value instanceof ComplexValue){
1267
                                                                                for (int k=parentNames.size()-3 ; k>=0 ; k--){
1268
                                                                                        ComplexValue complex = (ComplexValue)value;
1269
                                                                                        Value childValue = (Value)complex.get(parentNames.get(k));
1270
                                                                                        if (k==0){
1271
                                                                                                if (!conjunto.contains(childValue)) {
1272
                                                                                                        conjunto.add(childValue);
1273
                                                                                                }
1274
                                                                                        }else{
1275
                                                                                                value = childValue;
1276
                                                                                        }
1277
                                                                                }
1278
                                                                        }
1279
                                                                }
1280
                                                                
1281
                                                                break;
1282
                                                        }
1283
                                                }
1284
                                        }
1285
                                        break;
1286
                                case IXMLType.COMPLEX:
1287
                                        break;
1288
                                default:
1289
                                        // Do Nothing
1290
                        }
1291
                        
1292
                        // Add the values to the model of the graphic list
1293
                        Iterator it = conjunto.iterator();
1294
                        Object[] objects = currentPath.getPath();
1295

    
1296
                        if (objects.length == 0)
1297
                                return;
1298
                        
1299
                        String selectedField = ((XMLElement)objects[objects.length-1]).getName(); // Gets the selected field
1300
                        
1301
                        if (selectedField != null) { // If there is a selected field
1302
                                Map fieldValues = (HashMap)allFieldsAndValuesKnownOfCurrentLayer.get(selectedField); // Gets valus stored associated to this field
1303
                                JLabel currentValueLabel = null;
1304
                                
1305
                                // If the field doesn't exits -> create a new Map with its values
1306
                                if (fieldValues == null) {
1307
                                        fieldValues = new HashMap();
1308
                                        allFieldsAndValuesKnownOfCurrentLayer.put(selectedField, fieldValues);        
1309
                                
1310
                                        while (it.hasNext()) {
1311
                                                // A label with text with yelow background color for values that are loaded in the layer
1312
                                                currentValueLabel = new JLabelAsCellValueLoaded();
1313
                                                
1314
                                                currentValueLabel.setText(it.next().toString());
1315
                                                
1316
                                                if (currentValueLabel.getText().compareTo("") != 0) {                                                                                
1317
                                                        fieldValues.put(currentValueLabel.getText(), currentValueLabel.getText());
1318
                                                
1319
                                                        // All values loaded in this loop must be at beginning of the list (and in a differenciated color)
1320
                                                        if ( ! valuesListModel.contains(currentValueLabel) )
1321
                                                                valuesListModel.addElement(currentValueLabel);                                                        
1322
                                                }
1323
                                        }
1324
                                }
1325
                                else { // Else -> Adds the new ones, and changes element labels that have changed  (before were loaded and now not, or before weren't loaded but now yes)
1326
                                        
1327
                                        // Changes element labels that have changed  (before were loaded and now not, or before weren't loaded but now yes)
1328
                                        ((DefaultListModelForJLabelAsCell)valuesListModel).setAllElementsToNotLoaded();
1329
                                        
1330
                                        // For each current value associated to de current selected field -> if its loaded -> put it at beginning of the list and change to 'JLabelLoadedValue' 
1331
                                        while (it.hasNext()) {
1332
                                                String text = it.next().toString();
1333
                                                int elementPosition = ((DefaultListModelForJLabelAsCell)valuesListModel).getIndexOfJLabelText(text);
1334
                                                
1335
                                                if (elementPosition == -1) // If it must be added                                                
1336
                                                        valuesListModel.addElement(new JLabelAsCellValueLoaded(text));
1337
                                                else
1338
                                                        ((DefaultListModelForJLabelAsCell)valuesListModel).changeElementThatHasTextToJLabelLoadedValue(text); // Change to 'JLabelLoadedValue'
1339
                                        }
1340
                                }
1341
                        
1342
                                // Load the rest of the values associated to the current selected field
1343
                                if (fieldValues != null) {
1344
                                        // A label with text with yelow background color for values that are loaded in the layer
1345
                                        currentValueLabel = new JLabelAsCellValueNotLoaded();
1346

    
1347
                                        Set values = fieldValues.keySet();
1348

    
1349
                                        it = values.iterator();
1350

    
1351
                                        while (it.hasNext()) {
1352
                                                String name = it.next().toString();
1353
                                                
1354
                                                if ( ! ((DefaultListModelForJLabelAsCell)valuesListModel).containsJLabelText(name) )
1355
                                                        valuesListModel.addElement(new JLabelAsCellValueNotLoaded(name));
1356
                                        }
1357
                                }
1358
                        }
1359
                        
1360
                } catch (Exception e) {
1361
                        throwException(e);
1362
                }
1363
        }
1364
        
1365
        ///// END METHODS FOR MANIPULATE 'fields' and 'values' /////
1366
        
1367
        ///// METHODS FOR PARENT NOTIFICATIONS /////
1368
//        
1369
//        /**
1370
//         * @see WFSParamsPanel#isApplicable(boolean)
1371
//         * 
1372
//         * This also loads values of fields 
1373
//         * 
1374
//         * @param b A boolean value
1375
//         */
1376
//        private void setApplicate(boolean b) {
1377
//                parent.isApplicable(b);
1378
//        }
1379
        
1380
        ///// END METHODS FOR PARENT NOTIFICATIONS /////
1381
        
1382
        ///// METHOS FOR 'allFieldsAndValuesKnownOfCurrentLayer' /////
1383
        
1384
        /**
1385
         * Sets all fields and values known about the current layer
1386
         * 
1387
         * @param _allFieldsAndValuesKnownOfCurrentLayer A Map object
1388
         */
1389
        public void setAllFieldsAndValuesKnownOfCurrentLayer(Map _allFieldsAndValuesKnownOfCurrentLayer) {
1390
                if (_allFieldsAndValuesKnownOfCurrentLayer == null)
1391
                        this.allFieldsAndValuesKnownOfCurrentLayer = new HashMap();
1392
                else
1393
                        this.allFieldsAndValuesKnownOfCurrentLayer = _allFieldsAndValuesKnownOfCurrentLayer;
1394
        }
1395
        
1396
        /**
1397
         * Gets all fields and values known about the current layer
1398
         * 
1399
         * @return _allFieldsAndValuesKnownOfCurrentLayer A Map object
1400
         */
1401
        public Map getAllFieldsAndValuesKnownOfCurrentLayer() {
1402
                return allFieldsAndValuesKnownOfCurrentLayer;
1403
        }
1404
        
1405
        ///// METHOS FOR 'allFieldsAndValuesKnownOfCurrentLayer' /////
1406
        
1407
        ///// UPDATE TABLES DATA /////
1408
        
1409
        /**
1410
         * Updates all tables that their data is about the changed view
1411
         */
1412
        private void updateTablesThatHasNewData() {
1413
                boolean oneTimeNewDataToTableAdded = false;
1414
                
1415
                IWindow[] activeNoModalWindows = PluginServices.getMDIManager().getAllWindows();
1416
                
1417
                for (int i = 0; i < activeNoModalWindows.length; i++) {
1418
                        IWindow window = activeNoModalWindows[i];
1419
                        if (window instanceof Table) {
1420
                                Table table = (Table) window;
1421
                                
1422
                                int pos1 = featureName.indexOf(':');
1423
                                
1424
                                if ((pos1 >= 0) && (pos1 < featureName.length()))                                                
1425
                                        featureName = featureName.substring(pos1 +1, featureName.length());
1426
                                
1427
//                                        String featureOfTable = ((XMLElement)currentPath.getParentPath().getLastPathComponent()).getName();
1428
                                        String featureOfTable = table.getModel().getName();
1429
                                        int pos2 = featureOfTable.indexOf(':');
1430
                                                                                                
1431
                                        if ((pos2 >= 0) && (pos2 < featureName.length()))
1432
                                                featureOfTable = featureOfTable.substring(pos2 +1, featureOfTable.length());                                                
1433
                                
1434
                                if (featureName.trim().compareTo(featureOfTable.trim()) == 0) {
1435
                                        // Only add the new data associated to the table one time
1436
                                        if (oneTimeNewDataToTableAdded == false) {
1437
                                                setNewDataToTable();
1438
                                                oneTimeNewDataToTableAdded = true;
1439
                                        }
1440
                                
1441
                                        // Refresh the table with the new data
1442
                                        table.refresh();
1443
                                }
1444
                        }
1445
                }                
1446
        }        
1447
        
1448
        /**
1449
         * This method is a modification of the "execute" method from the "ShowTable" class 
1450
         *
1451
         * @see com.iver.cit.gvsig.ShowTable#execute(String)
1452
         */
1453
        private void setNewDataToTable() {
1454
                View vista = (View) PluginServices.getMDIManager().getActiveWindow();
1455
                FLayer[] actives = vista.getModel().getMapContext().getLayers().getActives();
1456

    
1457
                try {
1458
                        for (int i = 0; i < actives.length; i++) {
1459
                                if (actives[i] instanceof AlphanumericData) {
1460
                                        AlphanumericData co = (AlphanumericData) actives[i];
1461

    
1462
                                        //SelectableDataSource dataSource;
1463
                                        //dataSource = co.getRecordset();
1464

    
1465
                                        ProjectExtension ext = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class);
1466

    
1467
                                        ProjectTable projectTable = ext.getProject().getTable(co);
1468
                                        EditableAdapter ea=null;
1469
                                        ReadableVectorial rv=((FLyrVect)actives[i]).getSource();
1470
                                        if (rv instanceof VectorialEditableAdapter){
1471
                                                ea=(EditableAdapter)((FLyrVect)actives[i]).getSource();
1472
                                        }else{
1473
                                                ea=new EditableAdapter();
1474
                                                SelectableDataSource sds=((FLyrVect)actives[i]).getRecordset();
1475
                                                ea.setOriginalDataSource(sds);
1476
                                        }
1477

    
1478
                                        if (projectTable == null) {
1479
                                                projectTable = ProjectFactory.createTable(PluginServices.getText(this, "Tabla_de_Atributos") + ": " + actives[i].getName(),
1480
                                                                ea);
1481
                                                projectTable.setProjectDocumentFactory(new ProjectTableFactory());
1482
                                                projectTable.setAssociatedTable(co);
1483
                                                ext.getProject().addDocument(projectTable);
1484
                                        }
1485
                                        projectTable.setModel(ea);
1486
                                        
1487
                                        // Removed part of code that created another (visual) table
1488
//                                        Table t = new Table();
1489
//                                        t.setModel(projectTable);
1490
//                                        PluginServices.getMDIManager().addWindow(t);
1491
                                }
1492
                        }
1493
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
1494
            NotificationManager.addError(PluginServices.getText(this,"No_se_pudo_obtener_la_tabla_de_la_capa"), e);
1495
        } catch (com.iver.cit.gvsig.fmap.DriverException e) {
1496
                        e.printStackTrace();
1497
                        NotificationManager.addError(PluginServices.getText(this,"No_se_pudo_obtener_la_tabla_de_la_capa"), e);
1498
        }
1499
        }
1500
        
1501
        ///// END UPDATE TABLES DATA /////
1502
        
1503
        ///// OTHER METHODS /////
1504
        
1505
        /**
1506
         * DOCUMENT ME!
1507
         *
1508
         * @param expresion DOCUMENT ME!
1509
         * @param substring DOCUMENT ME!
1510
         * @param startingPos DOCUMENT ME!
1511
         *
1512
         * @return DOCUMENT ME!
1513
         */
1514
        private int getIndex(String expresion, String substring, int startingPos) {
1515
                int index = startingPos;
1516

    
1517
                do {
1518
                        index = expresion.indexOf(substring, index);
1519
                } while ((StringUtilities.isBetweenSymbols(expresion, index, "\"")) &&
1520
                                (index != -1));
1521

    
1522
                return index;
1523
        }
1524
        
1525
        /**
1526
         * DOCUMENT ME!
1527
         *
1528
         * @param arg0
1529
         *
1530
         * @return
1531
         */
1532
        public boolean addExpressionListener(ExpressionListener arg0) {
1533
                return expressionListeners.add(arg0);
1534
        }
1535

    
1536
        /**
1537
         * DOCUMENT ME!
1538
         *
1539
         * @param arg0
1540
         *
1541
         * @return
1542
         */
1543
        public boolean removeExpressionListener(ExpressionListener arg0) {
1544
                return expressionListeners.remove(arg0);
1545
        }
1546
        /**
1547
         * DOCUMENT ME!
1548
         *
1549
         * @param o DOCUMENT ME!
1550
         *
1551
         * @return DOCUMENT ME!
1552
         */
1553
        public boolean removeExceptionListener(ExceptionListener o) {
1554
                return exceptionHandlingSupport.removeExceptionListener(o);
1555
        }
1556

    
1557
        /**
1558
         * DOCUMENT ME!
1559
         *
1560
         * @param t DOCUMENT ME!
1561
         */
1562
        private void throwException(Throwable t) {
1563
                exceptionHandlingSupport.throwException(t);
1564
        }
1565
        
1566
        ///// END OTHER METHODS ///// 
1567
}