Statistics
| Revision:

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

History | View | Annotate | Download (42.8 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.ParseException;
10
import java.util.Comparator;
11
import java.util.HashMap;
12
import java.util.Iterator;
13
import java.util.Map;
14
import java.util.Set;
15
import java.util.StringTokenizer;
16
import java.util.TreeSet;
17
import java.util.Vector;
18

    
19
import javax.swing.DefaultListModel;
20
import javax.swing.JLabel;
21
import javax.swing.JOptionPane;
22
import javax.swing.event.DocumentEvent;
23
import javax.swing.event.DocumentListener;
24
import javax.swing.event.TreeSelectionEvent;
25
import javax.swing.event.TreeSelectionListener;
26
import javax.swing.tree.DefaultMutableTreeNode;
27
import javax.swing.tree.DefaultTreeModel;
28
import javax.swing.tree.TreePath;
29

    
30
import org.apache.log4j.Logger;
31
import org.gvsig.gui.beans.Messages;
32
import org.gvsig.gui.beans.filterPanel.filterQueryPanel.FilterQueryJPanel;
33
import org.gvsig.gui.beans.filterPanel.filterQueryPanel.jLabelAsCell.DefaultListModelForJLabelAsCell;
34
import org.gvsig.gui.beans.filterPanel.filterQueryPanel.jLabelAsCell.JLabelAsCellValueLoaded;
35
import org.gvsig.gui.beans.filterPanel.filterQueryPanel.jLabelAsCell.JLabelAsCellValueNotLoaded;
36
import org.gvsig.gui.beans.panelGroup.IPanelGroup;
37
import org.gvsig.remoteClient.gml.schemas.XMLElement;
38
import org.gvsig.remoteClient.gml.types.IXMLType;
39

    
40
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
41
import com.hardcode.gdbms.engine.instruction.IncompatibleTypesException;
42
import com.hardcode.gdbms.engine.values.BooleanValue;
43
import com.hardcode.gdbms.engine.values.ComplexValue;
44
import com.hardcode.gdbms.engine.values.NullValue;
45
import com.hardcode.gdbms.engine.values.Value;
46
import com.iver.andami.PluginServices;
47
import com.iver.andami.messages.NotificationManager;
48
import com.iver.andami.ui.mdiManager.IWindow;
49
import com.iver.cit.gvsig.ProjectExtension;
50
import com.iver.cit.gvsig.fmap.edition.EditableAdapter;
51
import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter;
52
import com.iver.cit.gvsig.fmap.layers.FLayer;
53
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
54
import com.iver.cit.gvsig.fmap.layers.ReadableVectorial;
55
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
56
import com.iver.cit.gvsig.fmap.layers.WFSLayerNode;
57
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
58
import com.iver.cit.gvsig.gui.filter.DefaultExpressionDataSource;
59
import com.iver.cit.gvsig.gui.filter.ExpressionDataSource;
60
import com.iver.cit.gvsig.gui.filter.FilterException;
61
import com.iver.cit.gvsig.gui.panels.fieldstree.FieldsTreeTableModel;
62
import com.iver.cit.gvsig.project.ProjectFactory;
63
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
64
import com.iver.cit.gvsig.project.documents.table.ProjectTableFactory;
65
import com.iver.cit.gvsig.project.documents.table.gui.Table;
66
import com.iver.cit.gvsig.sqlQueryValidation.SQLQueryValidation;
67
import com.iver.utiles.stringNumberUtilities.StringNumberUtilities;
68

    
69

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

    
111
/**
112
 * <p>Panel that provides tools to apply a filter to the values of a feature.</p>
113
 * <p>Improves the functionality of {@link FilterQueryJPanel FilterQueryJPanel}.</p>
114
 *
115
 * @see FilterQueryJPanel
116
 * 
117
 * @author Pablo Piqueras Bartolom? (p_queras@hotmail.com)
118
 */
119
public class WFSFilterPanel extends FilterQueryJPanel implements IWFSPanel {
120
        private static final long serialVersionUID = -6041218260822015810L;
121

    
122
        private static Logger logger = Logger.getLogger(WFSFilterPanel.class.getName());
123
        private ExpressionDataSource model = null;
124
        private FieldsTreeTableModel fieldsTreeTableModel;
125
        private boolean panelAsATabForWFSLayersLoad;
126
        private TreePath currentPath;
127
        private String featureName;
128
        private Map<String, Map<String, String>> allFieldsAndValuesKnownOfCurrentLayer; // This will have all values (not repeated) known of all fields (not repeated)
129

    
130
        ///// GUI METHODS ////
131

    
132
        /**
133
         * This method initializes
134
         *
135
         * @param parent A reference to the parent container component of this component
136
         */
137
        public WFSFilterPanel() {
138
                super();
139
                currentPath = null;
140
                featureName = null;
141
                allFieldsAndValuesKnownOfCurrentLayer = new HashMap<String, Map<String, String>>(); // Initial capacity = 0
142

    
143
                // At beginning, the JList is disabled (and its set a particular color for user could knew it)
144
                super.getValuesJList().setEnabled(false);
145
                getValuesJList().setBackground(new Color(220, 220, 220));
146
        }
147

    
148
        /*
149
         *  (non-Javadoc)
150
         * @see org.gvsig.gui.beans.filterPanel.AbstractFilterQueryJPanel#initialize()
151
         */
152
        protected void initialize() {
153
                setLabel(PluginServices.getText(this, "filter"));
154
                setLabelGroup(PluginServices.getText(this, "wfs"));
155
                super.initialize();
156
                this.resizeHeight(380);
157

    
158
                defaultTreeModel = (DefaultTreeModel)fieldsJTree.getModel();
159

    
160
                this.addNewListeners();
161
                panelAsATabForWFSLayersLoad = true;
162
                getValidateFilterExpressionJCheckBox().setSelected(true);
163

    
164
                getValuesJLabel().setToolTipText(Messages.getText("values_of_the_selected_field_explanation"));
165
                getFieldsJLabel().setToolTipText(Messages.getText("fields_of_the_selected_feature_explanation"));
166
        }
167

    
168
        /**
169
         * Adds some more listener to the components of the panel
170
         */
171
        private void addNewListeners() {
172
                // Enable "Apply" button when user changes the filter query
173
                txtExpression.getDocument().addDocumentListener(new DocumentListener() {
174
                        /*
175
                         *  (non-Javadoc)
176
                         * @see javax.swing.event.DocumentListener#changedUpdate(javax.swing.event.DocumentEvent)
177
                         */
178
                        public void changedUpdate(DocumentEvent e) {
179
                        }
180

    
181
                        /*
182
                         *  (non-Javadoc)
183
                         * @see javax.swing.event.DocumentListener#insertUpdate(javax.swing.event.DocumentEvent)
184
                         */
185
                        public void insertUpdate(DocumentEvent e) {
186
                                if (!panelAsATabForWFSLayersLoad) {
187
                                        IPanelGroup panelGroup = getPanelGroup();
188
                                        
189
                                        if (panelGroup == null)
190
                                                return;
191
                                        
192
                                        ((WFSParamsPanel)panelGroup).setApplicable(true);
193
                                }
194
                        }
195

    
196
                        /*
197
                         *  (non-Javadoc)
198
                         * @see javax.swing.event.DocumentListener#removeUpdate(javax.swing.event.DocumentEvent)
199
                         */
200
                        public void removeUpdate(DocumentEvent e) {
201
                                if (!panelAsATabForWFSLayersLoad) {
202
                                        IPanelGroup panelGroup = getPanelGroup();
203
                                        
204
                                        if (panelGroup == null)
205
                                                return;
206
                                        
207
                                        ((WFSParamsPanel)panelGroup).setApplicable(true);
208
                                }
209
                        }
210
                });
211

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

    
222
                                if (row > -1) {
223
                                        switch (e.getClickCount()) {
224
                                                case 2:
225
                                                        putSymbolOfSelectedByMouseBranch(treePath);
226
                                                        break;
227
                                        }
228
                                }
229
                        }
230
                });
231

    
232
                // Listener for "valuesJList"
233
                getValuesJList().addMouseListener(new MouseAdapter() {
234
                        /*
235
                         *  (non-Javadoc)
236
                         * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
237
                         */
238
                        public void mouseClicked(MouseEvent e) {
239
                                int index = getValuesJList().getSelectedIndex();
240

    
241
                                // Avoids exception when no value is in the list
242
                                if (index == -1)
243
                                        return;
244

    
245
                                if (e.getClickCount() == 2){
246
                                        String valor = ((JLabel) valuesListModel.getElementAt(index)).getText();
247

    
248
                                        // If value is an string -> set it between apostrophes
249
                                        if (getNodeOfCurrentPath().getEntityType().getName().compareTo("xs:string") == 0) {
250
                                                putSymbol("'" + valor + "'");
251
                                        }
252
                                        else {
253
                                                putSymbol(valor);
254
                                        }
255
                                }
256
                        }
257
                });
258

    
259
                // Listener for a branch of the tree selection
260
                getFieldsJTree().addTreeSelectionListener(new TreeSelectionListener() {
261
                        /*
262
                         *  (non-Javadoc)
263
                         * @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent)
264
                         */
265
                        public void valueChanged(TreeSelectionEvent e) {
266
                                if (!panelAsATabForWFSLayersLoad) {
267
                                        DefaultExpressionDataSource data = DataLoadingFromActiveView.getDefaultExpressionDataSource();
268

    
269
                                        if (data != null) {
270
                                                currentPath = e.getPath();
271
                                                fillValuesByPath(currentPath);
272
                                        }
273
                                }
274
                        }
275
                });
276

    
277
                // Listener: when a user writes something on the textarea -> set it's foreground color to black
278
                getTxtExpression().getDocument().addDocumentListener(new DocumentListener() {
279
                        /*
280
                         *  (non-Javadoc)
281
                         * @see javax.swing.event.DocumentListener#changedUpdate(javax.swing.event.DocumentEvent)
282
                         */
283
                        public void changedUpdate(DocumentEvent e) {
284
                        }
285

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

    
294
                        /*
295
                         *  (non-Javadoc)
296
                         * @see javax.swing.event.DocumentListener#removeUpdate(javax.swing.event.DocumentEvent)
297
                         */
298
                        public void removeUpdate(DocumentEvent e) {
299
                                getTxtExpression().setForeground(Color.BLACK);
300
                        }
301
                });
302
        }
303

    
304
        /**
305
         * Gets the element that the 'currentPath' field aims
306
         *
307
         * @return An XMLElement
308
         */
309
        private XMLElement getNodeOfCurrentPath() {
310

    
311
                if (currentPath != null) {
312
                        Object node = currentPath.getLastPathComponent();
313

    
314
                        if ((node != null) && (node instanceof XMLElement)) {
315
                                return (XMLElement) node;
316
                        }
317
                }
318

    
319
                return null;
320
        }
321

    
322
        /**
323
         * Puts the symbol of selected branch
324
         *
325
         * @param mouseEvent A MouseEvent with information  of the selected branch
326
         */
327
        public void putSymbolOfSelectedByMouseBranch(TreePath treePath) {
328
                // Sets the node selected
329
                if (treePath != null) {
330
                        putSymbol("\"" + this.getPathOfLeafWithoutRoot(treePath.getLastPathComponent()) + "\"");
331
                }
332
        }
333

    
334
        /**
335
         * This method returns the path without the root, of a node of a tree
336
         * Each node is separated from its parent with the symbol "/"
337
         *
338
         * @param node A leaf node
339
         * @return An string with the path
340
         */
341
        private String getPathOfLeafWithoutRoot(Object node) {
342
                String path = "";
343

    
344
                if ((node != null) && (node instanceof XMLElement)) {
345
                        XMLElement element = (XMLElement) node;
346
                        XMLElement parent = element.getParentElement();
347
                        path = element.getName();
348

    
349
                        while (parent.getParentElement() != null){
350
                                path = parent.getName() + "/" + path;
351
                                parent = parent.getParentElement();
352
                        }
353
                }
354

    
355
                return path;
356
        }
357

    
358
        /**
359
         * Gets the value of the inner attribute: 'panelAsATabForWFSLayersLoad'
360
         *
361
         * @return A boolean value
362
         */
363
        public boolean getWFSFilterPanelIsAsTabForWFSLayersLoad() {
364
                return this.panelAsATabForWFSLayersLoad;
365
        }
366

    
367
        /**
368
         * Sets the value of the inner attribute: 'panelAsATabForWFSLayersLoad'
369
         *
370
         * @param b A boolean value
371
         */
372
        public void setWFSFilterPanelIsAsTabForWFSLayersLoad (boolean b) {
373
                this.panelAsATabForWFSLayersLoad = b;
374

    
375
                if (this.panelAsATabForWFSLayersLoad == true) {
376
                        // At beginning, the JList is disabled (and its set a particular color for user could knew it)
377
                        super.getValuesJList().setEnabled(false);
378
                        super.getValuesJList().setBackground(new Color(220, 220, 220)); // a grey color
379

    
380
                        this.allFieldsAndValuesKnownOfCurrentLayer.clear();
381
                        getValidateFilterExpressionJCheckBox().setSelected(true);
382
                }
383
                else {
384
                        // Unselect the selected path in the tree (if there was any selected)
385
                        if (this.currentPath != null) {
386
                                this.currentPath = null;
387
                                this.getFieldsJTree().removeSelectionPath(this.getFieldsJTree().getSelectionPath());
388
                        }
389

    
390
                        // Resets data loaded
391
                        super.getValuesJList().setEnabled(true);
392
                        super.getValuesJList().setBackground(Color.WHITE);
393

    
394
                        this.getFieldsJTree().removeAll();
395
                        this.getValuesJList().removeAll();
396

    
397
                        // Updates data associated to view with the new layer data
398
                        this.setNewDataToTable();
399

    
400
                        // Reads that new data
401
                        DefaultExpressionDataSource data = DataLoadingFromActiveView.getDefaultExpressionDataSource();
402

    
403
                        if (data != null) {
404
                                setModel(data);
405
                        }
406

    
407
                        // Loads values known of fields
408
                        this.setValuesKnownOfFields();
409
                }
410
        }
411

    
412
        /**
413
         * Refresh all information about fields
414
         *
415
         * @param feature a feature with fields
416
         */
417
        public void refresh(WFSLayerNode feature) {
418
                featureName = feature.getTitle();
419
                setFields(feature);        
420
                setFilterExpressionIntoInterface(feature.getFilter());
421
        }
422

    
423
        ///// END GUI METHODS /////
424

    
425
        ///// METHODS FOR THE FILTER QUERY /////
426

    
427
        /**
428
         * Gets the query that will be send to the server
429
         * @return SQL query (just the where part)
430
         */
431
        public String getQuery(){
432
                String writtenQuery = txtExpression.getText().trim();
433

    
434
                // Validate expression
435
                if (!this.validateExpression(writtenQuery)) {
436
                        getTxtExpression().setForeground(Color.red);
437
                        return null;
438
                }
439
                else {
440
                        logger.debug("Codified WFS filter query: " + writtenQuery);
441

    
442
                        // Codify expression (only if the validation has been successful)
443
                        return this.codifyExpression(writtenQuery); // Ignores the spaces at beginning and end of the chain of characters
444
                }
445
        }
446

    
447
        /**
448
         * Gets the filter expression from the user interface
449
         */
450
        public String getFilterExpressionFromInterface() {
451
                return getTxtExpression().getText();
452
        }
453

    
454
        /**
455
         * Writes the filter expression into the user interface
456
         * @param filterExpression An string
457
         */
458
        public void setFilterExpressionIntoInterface(String filterExpression){
459
                getTxtExpression().setText(filterExpression);
460
        }
461

    
462
        /**
463
         * Removes text in the JTextArea that has the filter subconsultation
464
         */
465
        public void removeFilterExpression() {
466
                getTxtExpression().setText("");
467
        }
468

    
469
        /**
470
         * Codifies the expression to ISO ISO-8859_1 and a format that the SQL parser could validate
471
         *
472
         * @param expression The expression to be codified
473
         *
474
         * @return The expression codified
475
         */
476
        private String codifyExpression(String expression) {
477
                String result = new String("");
478

    
479
                // Encode each string of the query
480
                int index = 0;
481
                int lastIndex = 0;
482
                boolean endInnerLoop;
483

    
484
                // Encodes all inner strings to the equivalent codification in ISO-8859_1 with each ' symbol converted to ''
485
                while (index != -1) {
486
                        index = expression.indexOf("'", index);
487

    
488
                        // Add the parts of the chain of characters that not are string
489
                        if (index == -1) {
490
                                result += expression.substring(lastIndex, expression.length());
491
                        }
492
                        else {
493
                                result += expression.substring(lastIndex, index).replaceAll(" [ ]+", " ");
494
                        }
495

    
496
                        lastIndex = index;
497
                        endInnerLoop = false;
498

    
499
                        // Tries to find each first apostrophe of each string of the query
500
                        if ((index > 0) && (expression.charAt(index - 1) == ' ')) {
501
                                index++;
502

    
503
                                // Ignore all inner apostrophes and try to find the last of the string
504
                                while (!endInnerLoop)  {
505
                                        index = expression.indexOf("'", index);
506
                                        index++;
507

    
508
                                        // If we haven't arrived to the finish of the string
509
                                        if (index != expression.length()) {
510
                                                if ((index == -1) || (expression.charAt(index) == ' ')) {
511
                                                        result += translateString(expression.substring(lastIndex, index));
512
                                                        endInnerLoop = true;
513
                                                }
514
                                        }
515
                                        else {
516
                                                result += translateString(expression.substring(lastIndex, index));
517
                                                endInnerLoop = true;
518
                                                index = -1; // Force to finish the external loop
519
                                        }
520
                                }
521
                                lastIndex = index;
522
                        }
523
                }
524

    
525
                return result;
526
        }
527

    
528
        /**
529
         * Checks the filter expression if it's correct
530
         *
531
         * @param query The query expression to analyze
532
         * @return True if it's valid or false if not
533
         */
534
        private boolean validateExpression(String query) {
535
                try {
536
                        // If it's needed to validate the query
537
                        if (getValidateFilterExpressionJCheckBox().isSelected()) {
538
                                // If it's an empty query -> ok
539
                                if (query.trim().length() == 0)
540
                                        return true;
541
        
542
                                // Replace all Date(dd-mmm-yyyy) format to ddd-mmm-yyyy (characters will replaced to spaces)
543
                                int index = 0;
544
                                String query_copy = new String(query);
545
                                while ((index = query_copy.indexOf("Date(", index)) != -1) {
546
                                        if (index > 0) {
547
                                                if ((query_copy.charAt(index-1) != ' ') && (query_copy.charAt(index-1) != '('))
548
                                                        break;
549
                                        }
550
        
551
                                        if (((index + 16) < query_copy.length()) && (query_copy.charAt(index + 16) == ')')) { // +17 is the length of Date(dd-mmm-yyyy)
552
                                                if ((index + 17) < query_copy.length()) {
553
                                                        query_copy = query_copy.substring(0, index) + "     " + query_copy.substring(index+6, index+16) + " " + query_copy.substring(index+17);
554
                                                }
555
                                                else {
556
                                                        query_copy = query_copy.substring(0, index) + "     " + query_copy.substring(index+6, index+16);
557
                                                }
558
                                        }
559
                                }
560
        
561
                                SQLQueryValidation sQLQueryValidation = new SQLQueryValidation(formatSQLQuery(query_copy), true);
562
        
563
                                // Tries to validate the query, and if fails shows a message
564
                                if (!sQLQueryValidation.validateQuery()) {
565
                                        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);
566
                                        return false;
567
                                }
568
                                else {
569
                                        // Analyzes tokens in query
570
                                        StringTokenizer tokens = new StringTokenizer(query, " ");
571
                                        String token, token_aux;
572
                                        boolean finish = false;
573
        
574
                                        // If there is a field or a value with spaces, (and then it's on differents tokens) -> unify them
575
                                        while (tokens.hasMoreTokens()) {
576
                                                token = tokens.nextToken().trim();
577
        
578
                                                if (token.charAt(0) == '\'') {
579
                                                        if (token.charAt(token.length() -1) != '\'') {
580
                                                                while (!finish) {
581
                                                                        if (!tokens.hasMoreTokens()) {
582
                                                                                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);
583
                                                                                return false;
584
                                                                        }
585
                                                                        else {
586
                                                                                token_aux = tokens.nextToken().trim();
587
                                                                                token += " " + token_aux;
588
        
589
                                                                                if (token_aux.charAt(token_aux.length() -1) == '\'')
590
                                                                                        finish = true;
591
                                                                        }
592
                                                                }
593
        
594
                                                                finish = false;
595
                                                        }
596
                                                }
597
        
598
                                                if (token.charAt(0) == '\"') {
599
                                                        if (token.charAt(token.length() -1) != '\"') {
600
                                                                while (!finish) {
601
                                                                        if (!tokens.hasMoreTokens()) {
602
                                                                                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);
603
                                                                                return false;
604
                                                                        }
605
                                                                        else {
606
                                                                                token_aux = tokens.nextToken().trim();
607
                                                                                token += " " + token_aux;
608
        
609
                                                                                if (token_aux.charAt(token_aux.length() -1) == '\"')
610
                                                                                        finish = true;
611
                                                                        }
612
                                                                }
613
        
614
                                                                finish = false;
615
                                                        }
616
                                                }
617
        
618
                                                // Tries to find an invalid token
619
                                                if (token.length() > 0) {
620
                                                        // Validates if a supposed field exists
621
                                                        if ( (token.length() > 2) && (token.charAt(0) == '\"') && (token.charAt(token.length()-1) == '\"') ) {
622
                                                                if (! this.isAField(token.substring(1, token.length()-1))) {
623
                                                                        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);
624
                                                                        return false;
625
                                                                }
626
                                                        }
627
                                                        else {
628
                                                                // If it's an string -> ignore
629
                                                                if (! ((token.charAt(0) == token.charAt(token.length() - 1)) && (token.charAt(0) == '\''))) {
630
        
631
                                                                        // If it's a date -> ignore
632
                                                                        int returnValue = validateDate(token);
633
        
634
                                                                        if (returnValue == 1) {
635
                                                                                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);
636
                                                                                return false;
637
                                                                        }
638
        
639
                                                                        if (returnValue == 2) {
640
                                                                                // Else -> Checks if the current token is a valid number or symbol
641
                                                                                if ((! StringNumberUtilities.isRealNumberWithIntegerExponent(token)) && (! this.isAnOperatorNameOrSymbol(token, getAllOperatorSymbols()))) {
642
                                                                                        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);
643
                                                                                        return false;
644
                                                                                }
645
                                                                        }
646
                                                                }
647
                                                        }
648
                                                }
649
                                        }
650
        
651
                                        // If has validate all tokens -> query validated
652
                                        return true;
653
                                }
654
                        }
655
                        else
656
                                return true; // No validation done because user selected that option
657
                }
658
                catch (Exception e) {
659
                        NotificationManager.showMessageError(PluginServices.getText(null, "filter_with_an_incorrect_format") + ".", e);
660
                        return true; // No validation done because user selected that option
661
                }
662
        }
663

    
664
        /**
665
         * <p>Formats a query removing non English symbols that can produce the SQL validator could invalidate it.</p>
666
         * 
667
         * @param an SQL query
668
         * @return the SQL query without non English symbols
669
         */
670
        private String formatSQLQuery(String token) {
671
                return token = token.replace("?", "n").replace("?", "c").replace("?", "a").
672
                replace("?", "e").replace("?", "i").replace("?", "o").replace("?", "u").replace("?", "a").
673
                replace("?", "e").replace("?", "i").replace("?", "o").replace("?", "u").replace("?", "a").
674
                replace("?", "e").replace("?", "i").replace("?", "o").replace("?", "u").replace("?", "a").
675
                replace("?", "e").replace("?", "i").replace("?", "o").replace("?", "u");
676
        }
677

    
678
        /**
679
         * Returns true if there is a field with the same name as 'text'
680
         *
681
         * @param text An string
682
         * @return A boolean value
683
         */
684
        private boolean isAField(String text) {
685
                return this.allFieldsAndValuesKnownOfCurrentLayer.containsKey(text);
686
        }
687

    
688
        /**
689
         * Validates if a text has a correct date format as Date(dd-mmm-yyyy)  (Ex. Date(03-feb-2004) )
690
         *
691
         * @param text date to validate
692
         * @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
693
         */
694
        private int validateDate(String text) {
695
                // If it's a date -> check if format is correct (Ex.  Date(01-feb-2004) )
696
                if ( ((text.length() == 17) && (text.startsWith("Date(")) && (text.endsWith(")"))) && (text.charAt(7) == '-') && (text.charAt(11) == '-') ) {
697
                        if ( (StringNumberUtilities.isNaturalNumber(text.substring(5, 7))) && (StringNumberUtilities.isNaturalNumber(text.substring(12, 16))) ) {
698
                                try {
699
                                        // If can parse the date -> date with a correct format
700
                                        DateFormat.getDateInstance().parse(text.substring(5, 16));
701
                                        return 0;
702
                                } catch (ParseException e) {
703
                                        // If can't parse the date -> date with an incorrect format
704
                                        NotificationManager.addError(e);
705
                                        return 1;
706
                                }
707
                        }
708
                        else {
709
                                return 1;
710
                        }
711
                }
712

    
713
                return 2;
714
        }
715

    
716
        /**
717
         * Returns true if there is the 'text' is a symbol or a operator name
718
         *
719
         * @param text An string
720
         * @return A boolean value
721
         */
722
        private boolean isAnOperatorNameOrSymbol(String text, Set<String> operatorNamesAndSymbols) {
723
                return operatorNamesAndSymbols.contains(text);
724
        }
725

    
726
        ///// END METHODS FOR THE FILTER QUERY /////
727

    
728
        ///// METHODS FOR TRANSLATE DATA IN FILTER SENTENCES /////
729

    
730
        /**
731
         * Encodes an string to ISO 8859_1 with each ' symbol converted to ''
732
         *
733
         * @param text An string started and finished with simple apostrophes
734
         *
735
         * @return An string started and finished with simple apostrophes
736
         */
737
        private String translateString(String text) {
738
                // Encode to the string to ISO 8859_1 (the URL codification)
739
                try {
740

    
741
                        // Ignore the first and last apostrophes
742
                        if (text.length() > 2) {
743
                                text = text.substring(1, text.length() -1);
744

    
745
                                // Convert the string to ISO 8859_1 codification
746
                                text = URLEncoder.encode(text, "8859_1");
747

    
748
                                // Change ' (%27 code) to '' for the SQL parser (before send the query)
749
                                text = text.replaceAll("\\%27", "\\'\\'");
750
                        }
751

    
752
                } catch (UnsupportedEncodingException e1) {
753
                        NotificationManager.addError(e1);
754
                }
755

    
756
                return "'" + text + "'";
757
        }
758

    
759
        ///// END METHODS FOR TRANSLATE DATA IN FILTER SENTENCES /////
760

    
761
        ///// METHODS FOR MANIPULATE 'fields' and 'values' /////
762

    
763
        /**
764
         * Sets the model with the fields and values of the feature selected.
765
         *
766
         * @param eds data source with the model of the feature selected
767
         */
768
        public void setModel(ExpressionDataSource eds) {
769
                try {
770
                        model = eds;
771
            model.start();
772
        } catch (ReadDriverException e1) {
773
                NotificationManager.addError(e1);
774
        }
775

    
776
        try {
777
                int numberOfFields = model.getFieldCount();
778

    
779
                if (numberOfFields > 0) {
780
                        Vector<Object> fields = new Vector<Object>(0, 1);
781
                        int j = 0;
782

    
783
                                for (int i = 0; i < numberOfFields; i++) {
784
                                         Object field = model.getFieldName(i);
785

    
786
                                        if (field != null) {
787
                                                fields.add(field);
788

    
789
                                                String completeFieldPath = this.getPathOfLeafWithoutRoot(field);
790

    
791
                                                if (! allFieldsAndValuesKnownOfCurrentLayer.containsKey(completeFieldPath) ) {
792
                                                        allFieldsAndValuesKnownOfCurrentLayer.put(completeFieldPath, new HashMap<String, String>());
793
                                                }
794

    
795
                                                j++;
796
                                        }
797
                                }
798

    
799
                                fieldsTreeTableModel = new FieldsTreeTableModel(fields.toArray());
800
                }
801
                } catch (FilterException e) {
802
                        NotificationManager.addError(e);
803
                }
804
        }
805

    
806
        /**
807
         * If there is a field selected, show its new values
808
         */
809
        public void updateFieldValues() {
810
                if (currentPath != null) {
811
                        DefaultExpressionDataSource data = DataLoadingFromActiveView.getDefaultExpressionDataSource();
812

    
813
                        if (data != null) {
814
                                setModel(data);
815
                                fillValuesByPath(currentPath);
816

    
817
                                // Updates all tables that their data is about the changed view
818
                                this.updateTablesThatHasNewData();
819

    
820
                                // Adjust JScrollPanes to the the beginning
821
                                getFieldsJScrollPane().getHorizontalScrollBar().setValue(-1);
822
                                getFieldsJScrollPane().getVerticalScrollBar().setValue(-1);
823

    
824
                                // Adjust JScrollPanes to the the beginning
825
                                getValuesJScrollPane().getHorizontalScrollBar().setValue(-1);
826
                                getValuesJScrollPane().getVerticalScrollBar().setValue(-1);
827

    
828
                                // Adjusts valuesJList to the default position
829
                                getValuesJList().setSelectedIndex(-1); // No item selected
830
                        }
831
                }
832
        }
833

    
834
        /**
835
         * Adds the fields of the feature.
836
         *
837
         * @param feature A Layer node with fields information
838
         */
839
        private boolean setFields(WFSLayerNode feature) {
840
                Vector<Object> fields = feature.getFields();
841

    
842
                this.resetFieldsAndValuesData();
843

    
844
                int numberOfFields = fields.size();
845

    
846
                if (numberOfFields > 0) {
847
                        Vector<XMLElement> fieldBranches = new Vector<XMLElement>(0, 1);
848

    
849
                        for (Object o_field : fields) {
850
                                XMLElement field = (XMLElement) o_field;
851

    
852
                                IXMLType type = field.getEntityType();
853

    
854
                                if (type != null) {
855

    
856
                                        switch (type.getType()) {
857
                                                case IXMLType.GML_GEOMETRY: // Don't add branch / field
858
                                                        break;
859
                                                case IXMLType.COMPLEX: case IXMLType.SIMPLE: // Add branch / field
860
                                                        fieldBranches.add(field);
861
                                                        break;
862
                                        }
863
                                }
864
                        }
865

    
866
                        if (fieldBranches.size() > 0) {
867
                                Object obj = fieldBranches.get(0);
868

    
869
                                fieldsTreeTableModel = new FieldsTreeTableModel(obj);
870
                                fieldsJTree.setModel(new FieldsTreeTableModel(obj, false));
871

    
872
                                // Stores the name of all leafs (fields) of treeTableModel
873
                                Object root = fieldsTreeTableModel.getRoot();
874

    
875
                                if (root != null) {
876
                                        Vector<Object> fieldsNames = fieldsTreeTableModel.getLeafsFromNodeBranch(root);
877

    
878
                                        for (Object field : fieldsNames) {
879
                                                // Avoid errors
880
                                                if ( (! (field instanceof XMLElement)) || (field == null) )        continue;
881

    
882
                                                // Don't load a geometry field
883
                                                if (((XMLElement)field).getEntityType() != null){
884
                                                        if ( ((XMLElement)field).getEntityType().getType() == IXMLType.GML_GEOMETRY ){
885
                                                                continue;
886
                                                        }
887
                                                }
888

    
889
                                                String completeFieldPath = this.getPathOfLeafWithoutRoot(field);
890

    
891
                                                if (! allFieldsAndValuesKnownOfCurrentLayer.containsKey(completeFieldPath) ) {
892
                                                        allFieldsAndValuesKnownOfCurrentLayer.put(completeFieldPath, new HashMap<String, String>());
893
                                                }
894
                                        }
895
                                }
896
                        }
897
                }
898

    
899
                return true;
900
        }
901

    
902
        /**
903
         * This method load all values known of all fields known.
904
         * (It's used when a new layer is loaded).
905
         */
906
        private void setValuesKnownOfFields() {
907
                // Desde el modelo se deber?a acceder a los campos y sus valores cargados
908
                try {
909
                        for (int i = 0; i < model.getFieldCount(); i++) {
910
                                String fieldName = model.getFieldName(i);
911
                                HashMap<String, String> fieldValues = (HashMap<String, String>) allFieldsAndValuesKnownOfCurrentLayer.get(fieldName);
912

    
913
                                if (fieldValues != null) {
914
                                        for (int j = 0; j < model.getRowCount(); j++) {
915
                                                Value value = model.getFieldValue(j, i);
916

    
917
                                                if (value instanceof NullValue)
918
                                                    continue;
919

    
920
                                                Object obj = (Object)value;
921

    
922
                                                if (obj == null)
923
                                                        continue;
924

    
925
                                                fieldValues.put(obj.toString(), obj.toString());
926

    
927
                                        }
928
                                }
929
                        }
930
                }
931
                catch (Exception e) {
932
                        NotificationManager.addError(e);
933
                }
934
        }
935

    
936
        /**
937
         * Resets the data of fields and their values of the current layer feature, and removes the branches of <code>fieldsJTree</code>.
938
         */
939
        private void resetFieldsAndValuesData() {
940
                fieldsJTree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode()));
941
                txtExpression.setText("");
942
                ((DefaultListModel)valuesJList.getModel()).removeAllElements();
943
        }
944

    
945
        /**
946
         * Fills list with the values of selected field. 
947
         *
948
         * @param treePath A path in the tree
949
         */
950
        private void fillValuesByPath(TreePath treePath) {
951
                // Duplicates are removed
952
                TreeSet<Object> conjunto = new TreeSet<Object>(new Comparator<Object> () {
953
                        public int compare(Object o1, Object o2) {
954
                                Value v1 = (Value)o1;
955
                                Value v2 = (Value)o2;
956
                                
957
                                if ((v1 != null) && (v2 != null)) {
958
                                        BooleanValue boolVal;
959

    
960
                                        try {
961
                                                boolVal = (BooleanValue) (v1.greater(v2));
962

    
963
                                                if (boolVal.getValue()) {
964
                                                        return 1;
965
                                                }
966

    
967
                                                boolVal = (BooleanValue) (v1.less(v2));
968

    
969
                                                if (boolVal.getValue()) {
970
                                                        return -1;
971
                                                }
972
                                        } catch (IncompatibleTypesException e) {
973
                                                throw new RuntimeException(e);
974
                                        }
975
                                }
976

    
977
                                return 0;
978
                        }
979
                }); // For ordernation
980

    
981
                // Remove the previous items
982
                valuesListModel.clear();
983

    
984
                try {
985
                        //Object root = treePath.getPath()[0];
986
                        XMLElement element = ((XMLElement)treePath.getLastPathComponent());
987

    
988
                        if (element.getEntityType() == null)
989
                                return;
990
                        
991
                        // Gets the values associated to the selected branch
992
                        switch (element.getEntityType().getType()) {
993
                                case IXMLType.SIMPLE:
994

    
995
                                        if(element.getParentElement().getParentElement() == null) {
996
                                                // Find the selected field and try to obtein values related
997
                                                for (int i = 0; i < model.getFieldCount(); i++) {
998
                                                        String name = model.getFieldName(i);
999

    
1000
                                                        // If we find the field (this means that are loaded its values and we can obtein them)
1001
                                                        if (name.equals(element.getName())) {
1002
                                                                for (int j = 0; j < model.getRowCount(); j++) {
1003
                                                                        Value value = model.getFieldValue(j, i);
1004

    
1005
                                                                        if (value instanceof NullValue)
1006
                                                                            continue;
1007

    
1008
                                                                        if (!conjunto.contains(value)) {
1009
                                                                                conjunto.add(value);
1010
                                                                        }
1011
                                                                }
1012

    
1013
                                                                break;
1014
                                                        }
1015
                                                }
1016
                                        } else {
1017
                                                //create a vector with the parent names from the leaf until the root
1018
                                                XMLElement parent = element.getParentElement();
1019
                                                Vector<String> parentNames = new Vector<String>();
1020
                                                parentNames.add(element.getName());
1021
                                                while (parent != null){
1022
                                                        parentNames.add(parent.getName());
1023
                                                        parent = parent.getParentElement();
1024
                                                }
1025

    
1026
                                                //The field name (in the gvSIG table) is the second field name
1027
                                                String fieldName = parentNames.get(parentNames.size()-2);
1028

    
1029
                                                for (int i = 0; i < model.getFieldCount(); i++) {
1030
                                                        String name = model.getFieldName(i);
1031

    
1032
                                                        // If we find the field (this means that are loaded its values and we can obtein them)
1033
                                                        if (name.equals(fieldName)) {
1034
                                                                for (int j = 0; j < model.getRowCount(); j++) {
1035
                                                                        Value value = model.getFieldValue(j, i);
1036

    
1037
                                                                        if (value instanceof NullValue)
1038
                                                                            continue;
1039

    
1040
                                                                        if (value instanceof ComplexValue){
1041
                                                                                for (int k=parentNames.size()-3 ; k >= 0 ; k--){
1042
                                                                                        ComplexValue complex = (ComplexValue)value;
1043
                                                                                        Value childValue = (Value)complex.get(parentNames.get(k));
1044
                                                                                        if (k == 0) {
1045
                                                                                                if (!conjunto.contains(childValue)) {
1046
                                                                                                        conjunto.add(childValue);
1047
                                                                                                }
1048
                                                                                        } else {
1049
                                                                                                value = childValue;
1050
                                                                                        }
1051
                                                                                }
1052
                                                                        }
1053
                                                                }
1054

    
1055
                                                                break;
1056
                                                        }
1057
                                                }
1058
                                        }
1059
                                        break;
1060
                                case IXMLType.COMPLEX:
1061
                                        break;
1062
                                default:
1063
                                        // Do Nothing
1064
                        }
1065

    
1066
                        // Add the values to the model of the graphic list
1067
                        Iterator<Object> it = conjunto.iterator();
1068
                        Object[] objects = currentPath.getPath();
1069

    
1070
                        if (objects.length == 0)
1071
                                return;
1072

    
1073
                        String selectedField = ((XMLElement)objects[objects.length-1]).getName(); // Gets the selected field
1074

    
1075
                        if (selectedField != null) { // If there is a selected field
1076
                                Map<String, String> fieldValues = (HashMap<String, String>)allFieldsAndValuesKnownOfCurrentLayer.get(selectedField); // Gets values stored associated to this field
1077
                                JLabel currentValueLabel = null;
1078

    
1079
                                // If the field doesn't exits -> create a new Map with its values
1080
                                if (fieldValues == null) {
1081
                                        fieldValues = new HashMap<String, String>();
1082
                                        allFieldsAndValuesKnownOfCurrentLayer.put(selectedField, fieldValues);
1083

    
1084
                                        while (it.hasNext()) {
1085
                                                // A label with text with yellow background color for values that are loaded in the layer
1086
                                                currentValueLabel = new JLabelAsCellValueLoaded();
1087

    
1088
                                                currentValueLabel.setText(it.next().toString());
1089

    
1090
                                                if (currentValueLabel.getText().compareTo("") != 0) {
1091
                                                        fieldValues.put(currentValueLabel.getText(), currentValueLabel.getText());
1092

    
1093
                                                        // All values loaded in this loop must be at beginning of the list (and in a differenciated color)
1094
                                                        if ( ! valuesListModel.contains(currentValueLabel) )
1095
                                                                valuesListModel.addElement(currentValueLabel);
1096
                                                }
1097
                                        }
1098
                                }
1099
                                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)
1100

    
1101
                                        // Changes element labels that have changed  (before were loaded and now not, or before weren't loaded but now yes)
1102
                                        ((DefaultListModelForJLabelAsCell)valuesListModel).setAllElementsToNotLoaded();
1103

    
1104
                                        // For each current value associated to de current selected field -> if its loaded -> put it at beginning of the list and change to 'JLabelLoadedValue'
1105
                                        while (it.hasNext()) {
1106
                                                String text = it.next().toString();
1107
                                                int elementPosition = ((DefaultListModelForJLabelAsCell)valuesListModel).getIndexOfJLabelText(text);
1108

    
1109
                                                if (elementPosition == -1) // If it must be added
1110
                                                        valuesListModel.addElement(new JLabelAsCellValueLoaded(text));
1111
                                                else
1112
                                                        ((DefaultListModelForJLabelAsCell)valuesListModel).changeElementThatHasTextToJLabelLoadedValue(text); // Change to 'JLabelLoadedValue'
1113
                                        }
1114
                                }
1115

    
1116
                                // Load the rest of the values associated to the current selected field
1117
                                if (fieldValues != null) {
1118
                                        // A label with text with yellow background color for values that are loaded in the layer
1119
                                        currentValueLabel = new JLabelAsCellValueNotLoaded();
1120

    
1121
                                        Set<String> values = fieldValues.keySet();
1122

    
1123
                                        for (String name : values) {
1124
                                                if ( ! ((DefaultListModelForJLabelAsCell)valuesListModel).containsJLabelText(name) )
1125
                                                        valuesListModel.addElement(new JLabelAsCellValueNotLoaded(name));
1126
                                        }
1127
                                }
1128
                        }
1129

    
1130
                } catch (Exception e) {
1131
                        NotificationManager.addError(e);
1132
                }
1133
        }
1134

    
1135
        ///// END METHODS FOR MANIPULATE 'fields' and 'values' /////
1136

    
1137
        ///// METHOS FOR 'allFieldsAndValuesKnownOfCurrentLayer' /////
1138

    
1139
        /**
1140
         * Sets all fields and values known about the current layer
1141
         *
1142
         * @param _allFieldsAndValuesKnownOfCurrentLayer A Map object
1143
         */
1144
        public void setAllFieldsAndValuesKnownOfCurrentLayer(Map<String, Map<String, String>> _allFieldsAndValuesKnownOfCurrentLayer) {
1145
                if (_allFieldsAndValuesKnownOfCurrentLayer == null)
1146
                        this.allFieldsAndValuesKnownOfCurrentLayer = new HashMap<String, Map<String, String>>();
1147
                else
1148
                        this.allFieldsAndValuesKnownOfCurrentLayer = _allFieldsAndValuesKnownOfCurrentLayer;
1149
        }
1150

    
1151
        /**
1152
         * Gets all fields and values known about the current layer
1153
         *
1154
         * @return _allFieldsAndValuesKnownOfCurrentLayer A Map object
1155
         */
1156
        public Map<String, Map<String, String>> getAllFieldsAndValuesKnownOfCurrentLayer() {
1157
                return allFieldsAndValuesKnownOfCurrentLayer;
1158
        }
1159

    
1160
        ///// METHOS FOR 'allFieldsAndValuesKnownOfCurrentLayer' /////
1161

    
1162
        ///// UPDATE TABLES DATA /////
1163

    
1164
        /**
1165
         * Updates all tables that their data is about the changed view
1166
         */
1167
        private void updateTablesThatHasNewData() {
1168
                boolean oneTimeNewDataToTableAdded = false;
1169

    
1170
                IWindow[] activeNoModalWindows = PluginServices.getMDIManager().getAllWindows();
1171

    
1172
                for (int i = 0; i < activeNoModalWindows.length; i++) {
1173
                        IWindow window = activeNoModalWindows[i];
1174
                        if (window instanceof Table) {
1175
                                Table table = (Table) window;
1176

    
1177
                                int pos1 = featureName.indexOf(':');
1178

    
1179
                                if ((pos1 >= 0) && (pos1 < featureName.length()))
1180
                                        featureName = featureName.substring(pos1 +1, featureName.length());
1181

    
1182
                                        String featureOfTable = table.getModel().getName();
1183
                                        int pos2 = featureOfTable.indexOf(':');
1184

    
1185
                                        if ((pos2 >= 0) && (pos2 < featureName.length()))
1186
                                                featureOfTable = featureOfTable.substring(pos2 +1, featureOfTable.length());
1187

    
1188
                                if (featureName.trim().compareTo(featureOfTable.trim()) == 0) {
1189
                                        // Only add the new data associated to the table one time
1190
                                        if (oneTimeNewDataToTableAdded == false) {
1191
                                                setNewDataToTable();
1192
                                                oneTimeNewDataToTableAdded = true;
1193
                                        }
1194

    
1195
                                        // Refresh the table with the new data
1196
                                        table.invalidate();
1197
                                        table.refresh();
1198
                                }
1199
                        }
1200
                }
1201
        }
1202
        
1203
        /**
1204
         * This method is a modification of the "execute" method from the "ShowTable" class
1205
         *
1206
         * @see com.iver.cit.gvsig.ShowTable#execute(String)
1207
         */
1208
        private void setNewDataToTable() {
1209
                try {
1210
                        if (getPanelGroup().getReference() == null)
1211
                                return;
1212

    
1213
                        FLayer activeLayer = (FLayer) getPanelGroup().getReference();
1214
                        AlphanumericData co = (AlphanumericData) activeLayer;
1215

    
1216
                        ProjectExtension ext = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class);
1217
                        ProjectTable projectTable = ext.getProject().getTable(co);
1218

    
1219
                        EditableAdapter ea = null;
1220
                        ReadableVectorial rv = ((FLyrVect)activeLayer).getSource();
1221

    
1222
                        if (rv instanceof VectorialEditableAdapter) {
1223
                                ea = (EditableAdapter)((FLyrVect)activeLayer).getSource();
1224
                        } else {
1225
                                ea = new EditableAdapter();
1226
                                SelectableDataSource sds = ((FLyrVect)activeLayer).getRecordset();
1227
                                ea.setOriginalDataSource(sds);
1228
                        }
1229

    
1230
                        if (projectTable == null) {
1231
                                projectTable = ProjectFactory.createTable(PluginServices.getText(this, "Tabla_de_Atributos") + ": " + activeLayer.getName(), ea);
1232
                                projectTable.setProjectDocumentFactory(new ProjectTableFactory());
1233
                                projectTable.setAssociatedTable(co);
1234
                                ext.getProject().addDocument(projectTable);
1235
                        }
1236

    
1237
                        projectTable.setModel(ea);
1238
                } catch (ReadDriverException e) {
1239
                        NotificationManager.addError(PluginServices.getText(this,"No_se_pudo_obtener_la_tabla_de_la_capa"), e);
1240
        }
1241
        }
1242

    
1243
//        /** OLD VERSION
1244
//         * This method is a modification of the "execute" method from the "ShowTable" class
1245
//         *
1246
//         * @see com.iver.cit.gvsig.ShowTable#execute(String)
1247
//         */
1248
//        private void setNewDataToTable() {
1249
//                BaseView vista = (BaseView) PluginServices.getMDIManager().getActiveWindow();
1250
//                FLayer[] actives = vista.getModel().getMapContext().getLayers().getActives();
1251
//
1252
//                try {
1253
//                        for (int i = 0; i < actives.length; i++) {
1254
//                                if (actives[i] instanceof AlphanumericData) {
1255
//                                        AlphanumericData co = (AlphanumericData) actives[i];
1256
//
1257
//                                        ProjectExtension ext = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class);
1258
//
1259
//                                        ProjectTable projectTable = ext.getProject().getTable(co);
1260
//                                        EditableAdapter ea=null;
1261
//                                        ReadableVectorial rv=((FLyrVect)actives[i]).getSource();
1262
//                                        if (rv instanceof VectorialEditableAdapter){
1263
//                                                ea = (EditableAdapter)((FLyrVect)actives[i]).getSource();
1264
//                                        } else {
1265
//                                                ea = new EditableAdapter();
1266
//                                                SelectableDataSource sds=((FLyrVect)actives[i]).getRecordset();
1267
//                                                ea.setOriginalDataSource(sds);
1268
//                                        }
1269
//
1270
//                                        if (projectTable == null) {
1271
//                                                projectTable = ProjectFactory.createTable(PluginServices.getText(this, "Tabla_de_Atributos") + ": " + actives[i].getName(),        ea);
1272
//                                                projectTable.setProjectDocumentFactory(new ProjectTableFactory());
1273
//                                                projectTable.setAssociatedTable(co);
1274
//                                                ext.getProject().addDocument(projectTable);
1275
//                                        }
1276
//
1277
//                                        projectTable.setModel(ea);
1278
//                                }
1279
//                        }
1280
//                } catch (ReadDriverException e) {
1281
//                        NotificationManager.addError(PluginServices.getText(this,"No_se_pudo_obtener_la_tabla_de_la_capa"), e);
1282
//        }
1283
//        }
1284

    
1285
        ///// END UPDATE TABLES DATA /////
1286
}