Statistics
| Revision:

root / trunk / extensions / extWFS2 / src / com / iver / cit / gvsig / gui / panels / WFSFilterPanel.java @ 9461

History | View | Annotate | Download (43.2 KB)

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

    
3
import java.awt.Color;
4
import java.awt.event.MouseAdapter;
5
import java.awt.event.MouseEvent;
6
import java.io.UnsupportedEncodingException;
7
import java.net.URLEncoder;
8
import java.text.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.remoteClient.gml.schemas.XMLElement;
38
import org.gvsig.remoteClient.gml.types.IXMLType;
39

    
40
import com.hardcode.gdbms.engine.data.driver.DriverException;
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.andami.ui.mdiManager.IWindowListener;
50
import com.iver.andami.ui.mdiManager.WindowInfo;
51
import com.iver.cit.gvsig.ProjectExtension;
52
import com.iver.cit.gvsig.fmap.edition.EditableAdapter;
53
import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter;
54
import com.iver.cit.gvsig.fmap.layers.FLayer;
55
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
56
import com.iver.cit.gvsig.fmap.layers.ReadableVectorial;
57
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
58
import com.iver.cit.gvsig.fmap.layers.WFSLayerNode;
59
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
60
import com.iver.cit.gvsig.gui.filter.ExpressionDataSource;
61
import com.iver.cit.gvsig.gui.filter.ExpressionListener;
62
import com.iver.cit.gvsig.gui.filter.FilterException;
63
import com.iver.cit.gvsig.gui.panels.fieldsTree.FieldsTreeTableModel;
64
import com.iver.cit.gvsig.gui.panels.sqlQueryValidation.SQLQueryValidation;
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.utiles.DefaultCharSet;
71
import com.iver.utiles.StringUtilities;
72
import com.iver.utiles.exceptionHandling.ExceptionHandlingSupport;
73
import com.iver.utiles.exceptionHandling.ExceptionListener;
74
import com.iver.utiles.stringNumberUtilities.StringNumberUtilities;
75

    
76

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

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

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

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

    
184
                        /*
185
                         *  (non-Javadoc)
186
                         * @see javax.swing.event.DocumentListener#insertUpdate(javax.swing.event.DocumentEvent)
187
                         */
188
                        public void insertUpdate(DocumentEvent e) {
189
                                if (!panelAsATabForWFSLayersLoad)
190
                                        parent.isApplicable(true);
191
                        }
192

    
193
                        /*
194
                         *  (non-Javadoc)
195
                         * @see javax.swing.event.DocumentListener#removeUpdate(javax.swing.event.DocumentEvent)
196
                         */
197
                        public void removeUpdate(DocumentEvent e) {
198
                                if (!panelAsATabForWFSLayersLoad)
199
                                        parent.isApplicable(true);
200
                        }
201
                });
202
                
203
                // Listener for "fieldsJTree" 
204
                getFieldsJTree().addMouseListener(new MouseAdapter() {
205
                        /*
206
                         *  (non-Javadoc)
207
                         * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
208
                         */
209
                        public void mouseClicked(MouseEvent e) {
210
                                int row = fieldsJTree.getRowForLocation(e.getX(), e.getY());
211
                                TreePath treePath = fieldsJTree.getPathForLocation(e.getX(), e.getY());
212

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

    
278
                        /*
279
                         *  (non-Javadoc)
280
                         * @see javax.swing.event.DocumentListener#insertUpdate(javax.swing.event.DocumentEvent)
281
                         */
282
                        public void insertUpdate(DocumentEvent e) {
283
                                getTxtExpression().setForeground(Color.BLACK);
284
                        }
285

    
286
                        /*
287
                         *  (non-Javadoc)
288
                         * @see javax.swing.event.DocumentListener#removeUpdate(javax.swing.event.DocumentEvent)
289
                         */
290
                        public void removeUpdate(DocumentEvent e) {                                
291
                                getTxtExpression().setForeground(Color.BLACK);
292
                        }                        
293
                });
294
                
295
//                .addKeyListener(new KeyAdapter() {
296
//                        /*
297
//                         *  (non-Javadoc)
298
//                         * @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
299
//                         */
300
//                        public void keyTyped(KeyEvent e) {
301
//                                ((JTextArea)e.getSource()).setForeground(Color.black);
302
//                        }                        
303
//                });
304
        }
305
        
306
        /**
307
         * Gets the element that the 'currentPath' field aims
308
         * 
309
         * @return An XMLElement
310
         */
311
        private XMLElement getNodeOfCurrentPath() {
312
                
313
                if (currentPath != null) {
314
                        Object node = currentPath.getLastPathComponent();
315
                        
316
                        if ((node != null) && (node instanceof XMLElement)) {
317
//                                XMLElement element = (XMLElement) node;
318
                                return (XMLElement) node;
319
                        }
320
                }
321
                
322
                return null;
323
        }
324
        
325
        /**
326
         * Puts the symbol of selected brach
327
         * 
328
         * @param mouseEvent A MouseEvent with information  of the selected branch
329
         */
330
        public void putSymbolOfSelectedByMouseBranch(TreePath treePath) {
331
                // Sets the node selected
332
                if (treePath != null) {
333
                        Object node = treePath.getLastPathComponent();
334
                        if ((node != null) && (node instanceof XMLElement)) {
335
                                XMLElement element = (XMLElement) node;
336
                                XMLElement parent = element.getParentElement();
337
                                String path = element.getName();
338
                                while (parent.getParentElement() != null){
339
                                        path = parent.getName() + "/" + path;
340
                                        parent = parent.getParentElement();
341
                                }
342
                                putSymbol("\"" + path + "\"");
343
                        }
344
                }
345
        }
346
        
347
        /**
348
         * Gets the value of the inner attribute: 'panelAsATabForWFSLayersLoad'
349
         * 
350
         * @return A boolean value
351
         */
352
        public boolean getWFSFilterPanelIsAsTabForWFSLayersLoad() {
353
                return this.panelAsATabForWFSLayersLoad;
354
        }
355
        
356
        /**
357
         * Sets the value of the inner attribute: 'panelAsATabForWFSLayersLoad'
358
         * 
359
         * @param b A boolean value
360
         */
361
        public void setWFSFilterPanelIsAsTabForWFSLayersLoad (boolean b) {
362
                this.panelAsATabForWFSLayersLoad = b;
363
                
364
                if (this.panelAsATabForWFSLayersLoad == true) {
365
                        // At beginning, the JList is disabled (and its set a particular color for user could knew it)
366
                        super.getValuesJList().setEnabled(false);
367
                        super.getValuesJList().setBackground(new Color(220, 220, 220)); // a grey color
368
                        
369
                        this.allFieldsAndValuesKnownOfCurrentLayer.clear();
370
                }
371
                else {
372
                        // Unselect the selected path in the tree (if there was any selected)
373
                        if (this.currentPath != null) {
374
                                this.currentPath = null;
375
                                this.getFieldsJTree().removeSelectionPath(this.getFieldsJTree().getSelectionPath());
376
                        }
377
                        
378
                        // Resets data loaded
379
                        super.getValuesJList().setEnabled(true);
380
                        super.getValuesJList().setBackground(Color.WHITE);
381
                        
382
                        this.getFieldsJTree().removeAll();
383
                        this.getValuesJList().removeAll();
384
                        
385
                        // Updates data associated to view with the new layer data
386
                        this.setNewDataToTable();
387
                        
388
                        // If theres is any table associated to the current view -> update that table/s
389
//                        this.updateTablesThatHasNewData();
390
                        
391
                        // Reads that new data
392
                        DataReturnedOfDataLoadingFromActiveView data = DataLoadingFromActiveView.getDefaultExpressionDataSource();
393
                        
394
                        if ((data != null) && (data.getData() != null)) {
395
                                setModel(data.getData());
396
//                                currentPath = e.getPath();
397
//                                fillValuesByPath(currentPath);
398
                        }
399
                        
400
                        // Loads values known of fields
401
                        this.setValuesKnownOfFields();
402
                }
403
        }
404
        
405
        /**
406
         * Refresh all information about fields
407
         * 
408
         * @param feature
409
         */
410
        public void refresh(WFSLayerNode feature) {
411
                featureName = feature.getTitle();
412
                setFields(feature);
413
        }
414
        
415
        ///// END GUI METHODS /////
416

    
417
        ///// METHODS FOR THE FILTER QUERY /////
418
        
419
        /**
420
         * Gets the query that will be send to the server
421
         * @return SQL query (just the where part)
422
         */
423
        public String getQuery(){
424
                String writtenQuery = txtExpression.getText().trim();
425
                
426
                // Validate expression
427
                if (!this.validateExpression(writtenQuery)) {
428
                        getTxtExpression().setForeground(Color.red);
429
                        return null;
430
                }
431
                else
432
                        // Codify expression (only if the validation has been successful)
433
                        return this.codifyExpression(writtenQuery); // Ignores the spaces at beginning and end of the chain of characters
434
        }
435
        
436
        /**
437
         * Gets the filter expression from the user interface
438
         */
439
        public String getFilterExpressionFromInterface() {
440
                return getTxtExpression().getText();
441
        }
442
        
443
        /**
444
         * Writes the filter expression into the user interface
445
         * @param filterExpression An string
446
         */
447
        public void setFilterExpressionIntoInterface(String filterExpression){
448
                getTxtExpression().setText(filterExpression);
449
        }
450
        
451
        /**
452
         * Codifies the expression to ISO ISO-8859_1 and a format that the SQL parser could validate
453
         * 
454
         * @param expression The expression to be codified 
455
         * 
456
         * @return The expression codified
457
         */
458
        private String codifyExpression(String expression) {
459
                String result = new String("");
460
                
461
                try
462
                {                        
463
                        // Encode each string of the query
464
                        int index = 0;
465
                        int lastIndex = 0;
466
                        boolean endInnerLoop;
467
                        // Encodes all inner strings to the equivalent codification in ISO-8859_1 with each ' symbol converted to ''
468
                        while (index != -1) {
469
                                index = expression.indexOf("'", index);
470
                                
471
                                // Add the parts of the chain of characters that not are string
472
                                if (index == -1) {
473
                                        result += expression.substring(lastIndex, expression.length());
474
                                }
475
                                else {
476
                                        result += expression.substring(lastIndex, index).replaceAll(" [ ]+", " ");
477
                                }
478
                                
479
                                lastIndex = index;
480
                                endInnerLoop = false;
481
                                
482
                                // Tries to find each first apostrophe of each string of the query
483
                                if ((index > 0) && (expression.charAt(index - 1) == ' ')) {
484
                                        index++;
485
                                        
486
                                        // Ignore all inner apostrophes and try to find the last of the string
487
                                        while (!endInnerLoop)  {
488
                                                index = expression.indexOf("'", index);
489
                                                index++;
490
                                                
491
                                                // If we haven't arrived to the finish of the string
492
                                                if (index != expression.length()) {
493
                                                        if ((index == -1) || (expression.charAt(index) == ' ')) {
494
                                                                result += translateString(expression.substring(lastIndex, index));
495
                                                                endInnerLoop = true;
496
                                                        }
497
                                                }
498
                                                else {
499
                                                        result += translateString(expression.substring(lastIndex, index));
500
                                                        endInnerLoop = true;
501
                                                        index = -1; // Force to finish the external loop
502
                                                }
503
                                        }
504
                                        lastIndex = index;
505
                                }
506
                        }
507
                        
508
                        // Field names are transformated in xix variables that will be analyzed
509
                        // Date(date) is substituted by the correct date format
510
                        result = translateDates(result);
511
                        result = translateNumber(result);
512
                        result = translateWord(result, "true", "1");
513
                        result = translateWord(result, "false", "0");
514
        
515
                        logger.debug(result);                        
516
                }
517
                catch(Exception e) {
518
                        JOptionPane.showMessageDialog(this, Messages.getText("error_coding_filter_query"), Messages.getText("error"), JOptionPane.ERROR_MESSAGE);
519
                        return null;
520
                }
521

    
522
                return result;
523
        }
524
        
525
        /**
526
         * Checks the filter expression if it's correct
527
         * 
528
         * @param query The query expression to analyze
529
         * @return True if it's valid or false if not
530
         */
531
        private boolean validateExpression(String query) {
532
                SQLQueryValidation sQLQueryValidation = new SQLQueryValidation(query, true);
533
                
534
                // Analyzes tokens in query
535
                StringTokenizer tokens = new StringTokenizer(query, " ");
536
                String token;
537
                Set operatorNamesAndSymbols = getOperatorNamesAndSymbols();
538

    
539
                while (tokens.hasMoreTokens()) {
540
                        token = tokens.nextToken().trim();
541
                        
542
                        // Tries to find an invalid token
543
                        if (token.length() > 0) {
544
                                // Validates if a supposed field exists
545
                                if ( (token.length() > 2) && (token.charAt(0) == '\"') && (token.charAt(token.length()-1) == '\"') ) {
546
                                        if (! this.isAField(token.substring(1, token.length()-1))) {
547
                                                JOptionPane.showMessageDialog(null, PluginServices.getText(null, "error_validating_sql_filter_query") + ":\n" + PluginServices.getText(null, "the_token") + ": " + token + " " + PluginServices.getText(null, "isnt_a_field_of_layer"), PluginServices.getText(null, "error"), JOptionPane.ERROR_MESSAGE);
548
                                                return false;
549
                                        }
550
                                }
551
                                else {
552
                                        // If it's an string -> ignore
553
                                        if (! ((token.charAt(0) == token.charAt(token.length() - 1)) && (token.charAt(0) == '\''))) {
554
                                                
555
                                                // If it's a date -> ignore
556
                                                int returnValue = validateDate(token);
557
                                                
558
                                                if (returnValue == 1) {
559
                                                        JOptionPane.showMessageDialog(null, PluginServices.getText(null, "error_validating_sql_filter_query") + ":\n" + PluginServices.getText(null, "date_format") + " " + token.substring(5, 16) + " " + PluginServices.getText(null, "incorrect"), PluginServices.getText(null, "error"), JOptionPane.ERROR_MESSAGE);
560
                                                        return false;
561
                                                }
562
                                                
563
                                                if (returnValue == 2) {                                                                
564
                                                        // Else -> Checks if the current token is a valid number or symbol
565
                                                        if ((! StringNumberUtilities.isNumber(token)) && (! this.isAnOperatorNameOrSymbol(token, operatorNamesAndSymbols))) {
566
                                                                JOptionPane.showMessageDialog(null, PluginServices.getText(null, "error_validating_sql_filter_query") + ":\n" + PluginServices.getText(null, "notvalidtoken") + ":" + token, PluginServices.getText(null, "error"), JOptionPane.ERROR_MESSAGE);
567
                                                                return false;
568
                                                        }
569
                                                        else
570
                                                                return true;
571
                                                }
572
                                        }
573
                                }
574
                        }
575
                }
576

    
577
                // Tries to validate the query, and if fails shows a message
578
                if (!sQLQueryValidation.validateQuery()) {
579
                        JOptionPane.showMessageDialog(null, PluginServices.getText(null, "error_validating_sql_filter_query") + ":\n" + sQLQueryValidation.getErrorMessage(), PluginServices.getText(null, "error"), JOptionPane.ERROR_MESSAGE);
580
                        return false;
581
                }
582
                else        
583
                        return true;
584
        }
585
        
586
        /**
587
         * Returns true if there is a field with the same name as 'text'
588
         * 
589
         * @param text An string
590
         * @return A boolean value
591
         */
592
        private boolean isAField(String text) {
593
                return this.allFieldsAndValuesKnownOfCurrentLayer.containsKey(text);                
594
        }
595
        
596
        /**
597
         * Validates if a text has a correct date format as Date(dd-mmm-yyyy)  (Ex. Date(03-feb-2004) )
598
         * 
599
         * @param text
600
         * @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
601
         */
602
        private int validateDate(String text) {
603
                // If it's a date -> check if format is correct (Ex.  Date(01-feb-2004) )
604
                if ( ((text.length() == 17) && (text.startsWith("Date(")) && (text.endsWith(")"))) && (text.charAt(7) == '-') && (text.charAt(11) == '-') ) {
605
                        if ( (StringNumberUtilities.isNaturalNumber(text.substring(5, 7))) && (StringNumberUtilities.isNaturalNumber(text.substring(12, 16))) ) {
606
                                try {
607
                                        // If can parse the date -> date with a correct format 
608
                                        DateFormat.getDateInstance().parse(text.substring(5, 16));
609
                                        return 0;
610
                                } catch (ParseException e) {
611
                                        // If can't parse the date -> date with an incorrect format 
612
                                        return 1;
613
                                }
614
                        }
615
                        else {
616
                                return 1;
617
                        }
618
                }
619
                
620
                return 2;
621

    
622
        }
623

    
624
        /**
625
         * Returns true if there is the 'text' is a symbol or a operator name
626
         * 
627
         * @param text An string
628
         * @return A boolean value
629
         */
630
        private boolean isAnOperatorNameOrSymbol(String text, Set operatorNamesAndSymbols) {                
631
                return operatorNamesAndSymbols.contains(text);
632
        }
633
        
634
        /**
635
         * DOCUMENT ME!
636
         *
637
         * @return DOCUMENT ME!
638
         *
639
         * @throws ParseException DOCUMENT ME!
640
         * @deprecated In this moments its a reference of the old Validate Expression method
641
         */
642
        private String oldValidateExpressionMethod() throws ParseException {
643
                String expression = txtExpression.getText();
644
//                HashSet variablesIndexes = new HashSet();
645
//
646
//                StringBuffer traducida = new StringBuffer();
647

    
648
                //Se transforman los nombres de los campos en las variables xix que analizar?n
649
                //Se quitan los Date(fecha) y se mete la fecha correspondiente
650
                expression = translateDates(expression);
651
                expression = translateNumber(expression);
652
                expression = translateWord(expression, "true", "1");
653
                expression = translateWord(expression, "false", "0");
654

    
655
                String replacement;
656
                Pattern patron = Pattern.compile("[^<>!]=");
657
                Matcher m = patron.matcher(expression);
658
                int index = 0;
659

    
660
                while (m.find(index)) {
661
                        index = m.start();
662
                        replacement = expression.charAt(index) + "==";
663
                        m.replaceFirst(replacement);
664
                        index++;
665
                }
666

    
667
                expression = expression.replaceAll("[^<>!]=", "==");
668

    
669
                logger.debug(expression);
670

    
671
                return expression;
672
        }
673
        
674
        ///// END METHODS FOR THE FILTER QUERY /////
675

    
676
        ///// METHODS FOR TRANSLATE DATA IN FILTER SENTENCES /////
677

    
678
        /** 
679
         * DOCUMENT ME!
680
         *
681
         * @param expresion DOCUMENT ME!
682
         * @param word DOCUMENT ME!
683
         * @param translation DOCUMENT ME!
684
         *
685
         * @return DOCUMENT ME!
686
         *
687
         * @throws ParseException DOCUMENT ME!
688
         */
689
        private String translateWord(String expresion, String word,        String translation) throws ParseException {
690
                int booleanIndex = 0;
691
                int endIndex = 0;
692
                StringBuffer res = new StringBuffer();
693

    
694
                while ((booleanIndex = getIndex(expresion, word, booleanIndex)) != -1) {
695
                        res.append(expresion.substring(endIndex, booleanIndex));
696
                        endIndex = booleanIndex + word.length();
697
                        booleanIndex++;
698
                        res.append(translation);
699
                }
700

    
701
                if (endIndex < expresion.length()) {
702
                        res.append(expresion.substring(endIndex));
703
                }
704

    
705
                return res.toString();
706
        }
707

    
708
        /**
709
         * DOCUMENT ME!
710
         *
711
         * @param expresion DOCUMENT ME!
712
         *
713
         * @return DOCUMENT ME!
714
         *
715
         * @throws ParseException DOCUMENT ME!
716
         */
717
        private String translateDates(String expresion) throws ParseException {
718
                //Se obtiene el valor de la fecha
719
                String date = StringUtilities.substringDelimited(expresion, "Date(", ")", 0);
720

    
721
                if (date == null) {
722
                        return expresion;
723
                }
724

    
725
                //Se comprueba que no est? entre comillas 
726
                int startIndex = expresion.indexOf(date);
727

    
728
                while (startIndex != -1) {
729
                        if (!StringUtilities.isBetweenSymbols(expresion, startIndex, "\"")) {
730
                                
731
                                //Se sustituye por el valor ordinal de la fecha
732
                                expresion = expresion.substring(0, startIndex - 5) +
733
                                        expresion.substring(startIndex).replaceFirst(date + "\\)",                                                        
734
                                                new Long((filterButtonsJPanel.getDateFormat().parse(date)).getTime()).toString());
735

    
736
                        } else {
737
                                startIndex += date.length();
738
                        }
739
                        
740
                        if (date == null) {
741
                                return expresion;
742
                        }
743

    
744
                        startIndex = expresion.indexOf(date, startIndex);
745
                }
746

    
747
                return expresion;
748
        }
749

    
750
        /**
751
         * DOCUMENT ME!
752
         *
753
         * @param expresion DOCUMENT ME!
754
         *
755
         * @return DOCUMENT ME!
756
         *
757
         * @throws ParseException DOCUMENT ME!
758
         */
759
        private String translateNumber(String expresion) throws ParseException {
760
                DefaultCharSet ss = new DefaultCharSet();
761
                ss.addInterval('0', '9');
762
                ss.addCharacter(',');
763
                ss.addCharacter('.');
764

    
765
                String number = StringUtilities.substringWithSymbols(expresion, ss, 0);
766

    
767
                if (number == null) {
768
                        return expresion;
769
                }
770

    
771
                int startIndex = expresion.indexOf(number);
772

    
773
                while (startIndex != -1) {
774
                        Number n = nf.parse(number);
775

    
776
                        if (!StringUtilities.isBetweenSymbols(expresion, startIndex, "\"")) {
777
                                
778
                                //Se sustituye por el valor ordinal de la fecha
779
                                expresion = expresion.substring(0, startIndex) +
780
                                        expresion.substring(startIndex).replaceFirst(number,
781
                                                n.toString());
782
                        } else {
783
                                startIndex += n.toString().length();
784
                        }
785

    
786
                        number = StringUtilities.substringWithSymbols(expresion, ss,
787
                                        startIndex);
788

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

    
793
                        startIndex = expresion.indexOf(number, startIndex);
794
                }
795

    
796
                return expresion;
797
        }
798
        
799
        /**
800
         * Encodes an string to ISO 8859_1 with each ' symbol converted to '' 
801
         * 
802
         * @param text An string started and finished with simple apostrophes
803
         * 
804
         * @return An string started and finished with simple apostrophes
805
         */
806
        private String translateString(String text) {
807
                // Encode to the string to ISO 8859_1 (the URL codification)
808
                try {
809
                        
810
                        // Ignore the first and last apostrophes
811
                        if (text.length() > 2) {
812
                                text = text.substring(1, text.length() -1);
813
                                
814
                                // Convert the string to ISO 8859_1 codification
815
                                text = URLEncoder.encode(text, "8859_1");
816
                                
817
                                // Change '  (%27 code) to '' for the SQL parser (bebore sent the query)
818
                                text = text.replaceAll("\\%27", "\\'\\'");
819
                        }
820

    
821
                } catch (UnsupportedEncodingException e1) {
822
                        e1.printStackTrace();
823
                }
824
                
825
                return "'" + text + "'";
826
        }
827
        
828
        ///// END METHODS FOR TRANSLATE DATA IN FILTER SENTENCES /////
829
        
830
        ///// METHODS FOR MANIPULATE 'fields' and 'values' /////
831
        
832
        /**
833
         * DOCUMENT ME!
834
         *
835
         * @param t DOCUMENT ME!
836
         */
837
        public void setModel(ExpressionDataSource t) {
838
                try {
839
                        model = t;
840
            model.start();
841
        } catch (DriverException e1) {
842
            NotificationManager.addError(e1.getMessage(), e1);
843
        }
844

    
845
        try {
846
                int numberOfFields = model.getFieldCount();
847

    
848
                if (numberOfFields > 0) {
849
                        Vector fields = new Vector(0, 1);
850
                        int j = 0;
851
                
852
                                for (int i = 0; i < numberOfFields; i++) {
853
                                         Object field = model.getFieldName(i);
854
                                        
855
                                        if (field != null) {
856
                                                fields.add(field);
857
                                                j++;
858
                                        }
859
                                }
860
                        
861
                                fieldsTreeTableModel = new FieldsTreeTableModel(fields.toArray());                        
862
                }
863
                } catch (FilterException e) {
864
                        throwException(e);
865
                }
866
        }
867
        
868
        /**
869
         * If there is a field selected, show its new values
870
         */
871
        public void updateFieldValues() {
872
                if (currentPath != null) {
873
                        
874
                        DataReturnedOfDataLoadingFromActiveView data = DataLoadingFromActiveView.getDefaultExpressionDataSource();
875
                                                
876
                        if ((data != null) && (data.getData() != null)) {
877
                                setModel(data.getData());                                
878
                                fillValuesByPath(currentPath);
879
                                
880
//                                valuesListModel.clear();
881
                                
882
                                // Updates all tables that their data is about the changed view
883
                                this.updateTablesThatHasNewData();
884
                        }
885
                }
886
        }
887
        
888
        /**
889
         * Sets Fields
890
         *
891
         * @param feature A Layer node with fields information
892
         */
893
        private void setFields(WFSLayerNode feature) {
894
                Vector fields = feature.getFields();
895
                                
896
                this.resetFieldsAndValuesData();
897
                
898
                int numberOfFields = fields.size();
899
                
900
                if (numberOfFields > 0) {
901
                        Vector fieldBranches = new Vector(0, 1);
902
                        
903
                        for (int i=0; i<fields.size(); i++) {
904
                                XMLElement field = (XMLElement)fields.get(i);
905

    
906
                                IXMLType type = field.getEntityType();
907
                                
908
                                if (type != null) {                                        
909
                                        
910
                                        switch (type.getType()) {
911
                                                case IXMLType.GML_GEOMETRY: // Don't add branch / field
912
                                                        break;
913
                                                case IXMLType.COMPLEX: case IXMLType.SIMPLE: // Add branch / field
914
                                                        fieldBranches.add(field);
915
                                                        
916
                                                        break;
917
                                        }
918
                                }
919
                        }
920
                        
921
                        fieldsTreeTableModel = new FieldsTreeTableModel(fieldBranches.get(0));
922
                        fieldsJTree.setModel(new FieldsTreeTableModel(fieldBranches.get(0), false));
923
                        
924
                        // Stores the name of all leafs (fields) of treeTableModel                        
925
                        Object root = fieldsTreeTableModel.getRoot();
926
                        
927
                        if (root != null) {
928
                                Vector fieldsNames = fieldsTreeTableModel.getLeafsFromNodeBranch(root);
929
                                
930
                                for (int j = 0; j < fieldsNames.size(); j++) {
931
                                        Object field = fieldsNames.get(j);
932
                                        
933
                                        // Avoid errors
934
                                        if ( (! (field instanceof XMLElement)) || (field == null) )
935
                                                continue;
936
                                        
937
                                        // Don't load a geometry field                                        
938
                                        if ( ((XMLElement)field).getEntityType().getType() == IXMLType.GML_GEOMETRY )
939
                                                continue;                                        
940
                                        
941
                                        if (! allFieldsAndValuesKnownOfCurrentLayer.containsKey( ((XMLElement)field).getName()) ) {
942
                                                allFieldsAndValuesKnownOfCurrentLayer.put(((XMLElement)field).getName(), new HashMap());
943
                                        }
944
                                }
945
                        }
946
                }
947
        }
948

    
949
        /**
950
         * This method load all values known of all fields known
951
         * (It's used when a new layer is load)
952
         */
953
        private void setValuesKnownOfFields() {
954
                // Desde el modelo se deber?a acceder a los campos y sus valores cargados                
955
                try {
956
                        for (int i = 0; i < model.getFieldCount(); i++) {
957
                                String fieldName = model.getFieldName(i);
958
                                HashMap fieldValues = (HashMap) allFieldsAndValuesKnownOfCurrentLayer.get(fieldName);
959
                                
960
                                if (fieldValues != null) {
961
                                        for (int j = 0; j < model.getRowCount(); j++) {
962
                                                Value value = model.getFieldValue(j, i);                                        
963
                                                
964
                                                if (value instanceof NullValue)
965
                                                    continue;
966
                                                
967
                                                Object obj = (Object)value;
968
                                                
969
                                                if (obj == null)
970
                                                        continue;
971
                                                
972
                                                fieldValues.put(obj.toString(), obj.toString());
973
                                                
974
                                        }
975
                                }
976
                        }
977
                }
978
                catch (Exception e) {
979
                        e.printStackTrace();
980
                }
981
        }
982
        
983
        /**
984
         * Resets the data of fields and their values of the current layer feature, and removes the branches of JTree
985
         */
986
        private void resetFieldsAndValuesData() {
987
                fieldsJTree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode()));
988
                txtExpression.setText("");
989
                ((DefaultListModel)valuesJList.getModel()).removeAllElements();
990
        }
991
        
992
        /** 
993
         * FIlls list with the values of selected field
994
         * 
995
         * @param treePath A path in the tree
996
         */
997
        private void fillValuesByPath(TreePath treePath) {
998
                // Duplicates are removed
999
                TreeSet conjunto = new TreeSet(new Comparator() {
1000
                        public int compare(Object o1, Object o2) {
1001
                                if ((o1 != null) && (o2 != null)) {
1002
                                        Value v2 = (Value) o2;
1003
                                        Value v1 = (Value) o1;
1004
                                        BooleanValue boolVal;
1005
                                        
1006
                                        try {
1007
                                                boolVal = (BooleanValue) (v1.greater(v2));
1008
                                                
1009
                                                if (boolVal.getValue()) {
1010
                                                        return 1;
1011
                                                }
1012
                                                
1013
                                                boolVal = (BooleanValue) (v1.less(v2));
1014
                                                
1015
                                                if (boolVal.getValue()) {
1016
                                                        return -1;
1017
                                                }
1018
                                        } catch (IncompatibleTypesException e) {
1019
                                                throw new RuntimeException(e);
1020
                                        }
1021
                                }
1022
                                
1023
                                return 0;
1024
                        }
1025
                }); // For ordernation
1026
                
1027
                // Remove the previous items
1028
                valuesListModel.clear();
1029
                
1030
                try {
1031
                        //Object root = treePath.getPath()[0];
1032
                        XMLElement element = ((XMLElement)treePath.getLastPathComponent());
1033
                        
1034
                        // Gets the values associated to the selected branch 
1035
                        switch (element.getEntityType().getType()) {
1036
                                case IXMLType.SIMPLE:
1037
                                        
1038
                                        if(element.getParentElement().getParentElement() == null) {                                        
1039
                                                // Find the selected field and try to obtein values related
1040
                                                for (int i = 0; i < model.getFieldCount(); i++) {                                        
1041
                                                        String name = model.getFieldName(i);
1042
                                                        
1043
                                                        // If we find the field (this means that are loaded its values and we can obtein them)
1044
                                                        if (name.equals(element.getName())) {                                                
1045
                                                                for (int j = 0; j < model.getRowCount(); j++) {                                        
1046
                                                                        Value value = model.getFieldValue(j, i);
1047
                                                                        
1048
                                                                        if (value instanceof NullValue)
1049
                                                                            continue;
1050
                                                                        
1051
                                                                        if (!conjunto.contains(value)) {
1052
                                                                                conjunto.add(value);
1053
                                                                        }
1054
                                                                }
1055
                                                                
1056
                                                                break;
1057
                                                        }
1058
                                                }
1059
                                        }else{
1060
                                                //create a vector with the parent names from the leaf until the root
1061
                                                XMLElement parent = element.getParentElement();
1062
                                                Vector parentNames = new Vector();
1063
                                                parentNames.add(element.getName());
1064
                                                while (parent != null){
1065
                                                        parentNames.add(parent.getName());
1066
                                                        parent = parent.getParentElement();                                                        
1067
                                                }
1068
                                                
1069
                                                //The field name (in the gvSIG table) is the second field name
1070
                                                String fieldName = (String)parentNames.get(parentNames.size()-2);
1071
                                                
1072
                                                for (int i = 0; i < model.getFieldCount(); i++) {                                        
1073
                                                        String name = model.getFieldName(i);
1074
                                                        
1075
                                                        // If we find the field (this means that are loaded its values and we can obtein them)
1076
                                                        if (name.equals(fieldName)) {                                                
1077
                                                                for (int j = 0; j < model.getRowCount(); j++) {                                        
1078
                                                                        Value value = model.getFieldValue(j, i);
1079
                                                                                                                        
1080
                                                                        if (value instanceof NullValue)
1081
                                                                            continue;
1082
                                                                        
1083
                                                                        if (value instanceof ComplexValue){
1084
                                                                                for (int k=parentNames.size()-3 ; k>=0 ; k--){
1085
                                                                                        ComplexValue complex = (ComplexValue)value;
1086
                                                                                        Value childValue = (Value)complex.get(parentNames.get(k));
1087
                                                                                        if (k==0){
1088
                                                                                                if (!conjunto.contains(childValue)) {
1089
                                                                                                        conjunto.add(childValue);
1090
                                                                                                }
1091
                                                                                        }else{
1092
                                                                                                value = childValue;
1093
                                                                                        }
1094
                                                                                }
1095
                                                                        }
1096
                                                                }
1097
                                                                
1098
                                                                break;
1099
                                                        }
1100
                                                }
1101
                                        }
1102
                                        break;
1103
                                case IXMLType.COMPLEX:
1104
                                        break;
1105
                                default:
1106
                                        // Do Nothing
1107
                        }
1108
                        
1109
                        // Add the values to the model of the graphic list
1110
                        Iterator it = conjunto.iterator();
1111
                        Object[] objects = currentPath.getPath();
1112

    
1113
                        if (objects.length == 0)
1114
                                return;
1115
                        
1116
                        String selectedField = ((XMLElement)objects[objects.length-1]).getName(); // Gets the selected field
1117
                        
1118
                        if (selectedField != null) { // If there is a selected field
1119
                                Map fieldValues = (HashMap)allFieldsAndValuesKnownOfCurrentLayer.get(selectedField); // Gets valus stored associated to this field
1120
                                JLabel currentValueLabel = null;
1121
                                
1122
                                // If the field doesn't exits -> create a new Map with its values
1123
                                if (fieldValues == null) {
1124
                                        fieldValues = new HashMap();
1125
                                        allFieldsAndValuesKnownOfCurrentLayer.put(selectedField, fieldValues);        
1126
                                
1127
                                        while (it.hasNext()) {
1128
                                                // A label with text with yelow background color for values that are loaded in the layer
1129
                                                currentValueLabel = new JLabelValueLoaded();
1130
                                                
1131
                                                currentValueLabel.setText(it.next().toString());
1132
                                                
1133
                                                if (currentValueLabel.getText().compareTo("") != 0) {                                                                                
1134
                                                        fieldValues.put(currentValueLabel.getText(), currentValueLabel.getText());
1135
                                                
1136
                                                        // All values loaded in this loop must be at beginning of the list (and in a differenciated color)
1137
                                                        if ( ! valuesListModel.contains(currentValueLabel) )
1138
                                                                valuesListModel.addElement(currentValueLabel);                                                        
1139
                                                }
1140
                                        }
1141
                                }
1142
                                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)
1143
                                        
1144
                                        // Changes element labels that have changed  (before were loaded and now not, or before weren't loaded but now yes)
1145
                                        ((DefaultListModelForJLabelAsCell)valuesListModel).setAllElementsToNotLoaded();
1146
                                        
1147
                                        // For each current value associated to de current selected field -> if its loaded -> put it at beginning of the list and change to 'JLabelLoadedValue' 
1148
                                        while (it.hasNext()) {
1149
                                                String text = it.next().toString();
1150
                                                int elementPosition = ((DefaultListModelForJLabelAsCell)valuesListModel).getIndexOfJLabelText(text);
1151
                                                
1152
//                                                if (! ((DefaultListModelForJLabelAsCell)valuesListModel).containsJLabelText(text) )
1153
                                                if (elementPosition == -1) // If it must be added                                                
1154
                                                        valuesListModel.addElement(new JLabelValueLoaded(text));
1155
                                                else
1156
                                                        ((DefaultListModelForJLabelAsCell)valuesListModel).changeElementThatHasTextToJLabelLoadedValue(text); // Change to 'JLabelLoadedValue'
1157
                                                
1158
                                                        
1159
//                                                // A label with text with yellow background color for values that are loaded in the layer
1160
//                                                currentValueLabel = new JLabelValueLoaded();
1161
//                                                
1162
//                                                currentValueLabel.setText(it.next().toString());                                                                                        
1163
//                                                
1164
//                                                
1165
//                                                if ( ! fieldValues.containsKey(currentValueLabel.getText()) ) {
1166
//                                                        fieldValues.put(currentValueLabel.getText(), currentValueLabel.getText());
1167
//                                                }
1168
//                                                
1169
//                                                // All values loaded in this loop must be at beginning of the list (and in a differenciated color)
1170
//                                                if ( ! (valuesListModel).contains(currentValueLabel) )
1171
//                                                        valuesListModel.addElement(currentValueLabel);
1172
//                                                
1173
//                                                else
1174
                                        }
1175
                                }
1176
                        
1177
                                // Load the rest of the values associated to the current selected field
1178
                                if (fieldValues != null) {
1179
                                        // A label with text with yelow background color for values that are loaded in the layer
1180
                                        currentValueLabel = new JLabelValueNotLoaded();
1181

    
1182
                                        Set values = fieldValues.keySet();
1183

    
1184
                                        it = values.iterator();
1185

    
1186
                                        while (it.hasNext()) {
1187
                                                String name = it.next().toString();
1188
                                                
1189
                                                if ( ! ((DefaultListModelForJLabelAsCell)valuesListModel).containsJLabelText(name) )
1190
                                                        valuesListModel.addElement(new JLabelValueNotLoaded(name));
1191
                                        }
1192
                                }
1193
                        }
1194
                        
1195
                } catch (Exception e) {
1196
                        throwException(e);
1197
                }
1198
        }
1199
        
1200
        ///// END METHODS FOR MANIPULATE 'fields' and 'values' /////
1201
        
1202
        ///// METHODS FOR PARENT NOTIFICATIONS /////
1203
        
1204
        /**
1205
         * @see WFSParamsPanel#isApplicable(boolean)
1206
         * 
1207
         * This also loads values of fields 
1208
         * 
1209
         * @param b A boolean value
1210
         */
1211
        private void setApplicate(boolean b) {
1212
                parent.isApplicable(b);
1213
        }
1214
        
1215
        ///// END METHODS FOR PARENT NOTIFICATIONS /////
1216
        
1217
        ///// METHOS FOR 'allFieldsAndValuesKnownOfCurrentLayer' /////
1218
        
1219
        /**
1220
         * Sets all fields and values known about the current layer
1221
         * 
1222
         * @param _allFieldsAndValuesKnownOfCurrentLayer A Map object
1223
         */
1224
        public void setAllFieldsAndValuesKnownOfCurrentLayer(Map _allFieldsAndValuesKnownOfCurrentLayer) {
1225
                if (_allFieldsAndValuesKnownOfCurrentLayer == null)
1226
                        this.allFieldsAndValuesKnownOfCurrentLayer = new HashMap();
1227
                else
1228
                        this.allFieldsAndValuesKnownOfCurrentLayer = _allFieldsAndValuesKnownOfCurrentLayer;
1229
        }
1230
        
1231
        /**
1232
         * Gets all fields and values known about the current layer
1233
         * 
1234
         * @return _allFieldsAndValuesKnownOfCurrentLayer A Map object
1235
         */
1236
        public Map getAllFieldsAndValuesKnownOfCurrentLayer() {
1237
                return allFieldsAndValuesKnownOfCurrentLayer;
1238
        }
1239
        
1240
        ///// METHOS FOR 'allFieldsAndValuesKnownOfCurrentLayer' /////
1241
        
1242
        ///// IMPLEMENTATION OF METHODS OF 'IWindowListener' /////
1243
        
1244
    /* (non-Javadoc)
1245
     * @see com.iver.andami.ui.mdiManager.ViewListener#viewActivated()
1246
     */
1247
    public void windowActivated() {
1248
    }
1249

    
1250
    /* (non-Javadoc)
1251
     * @see com.iver.andami.ui.mdiManager.ViewListener#viewClosed()
1252
     */
1253
    public void windowClosed() {
1254
        try {
1255
            model.stop();
1256
        } catch (DriverException e) {
1257
            NotificationManager.addError(e.getMessage(), e);
1258
        }        
1259
    }
1260
    
1261
    ///// END IMPLEMENTATION OF METHODS OF 'IWindowListener' /////
1262

    
1263
        ///// IMPLEMENTATION OF METHODS OF 'IWindow' /////    
1264
    
1265
    /*
1266
     *  (non-Javadoc)
1267
     * @see com.iver.andami.ui.mdiManager.IWindow#getWindowInfo()
1268
     */
1269
        public WindowInfo getWindowInfo() {
1270
                return null;
1271
        }
1272
        
1273
        ///// END IMPLEMENTATION OF METHODS OF 'IWindow' /////
1274
        
1275
        ///// UPDATE TABLES DATA /////
1276
        
1277
        /**
1278
         * Updates all tables that their data is about the changed view
1279
         */
1280
        private void updateTablesThatHasNewData() {
1281
                boolean oneTimeNewDataToTableAdded = false;
1282
                
1283
                IWindow[] activeNoModalWindows = PluginServices.getMDIManager().getAllWindows();
1284
                
1285
                for (int i = 0; i < activeNoModalWindows.length; i++) {
1286
                        IWindow window = activeNoModalWindows[i];
1287
                        if (window instanceof Table) {
1288
                                Table table = (Table) window;
1289
                                
1290
                                int pos1 = featureName.indexOf(':');
1291
                                
1292
                                if ((pos1 >= 0) && (pos1 < featureName.length()))                                                
1293
                                        featureName = featureName.substring(pos1 +1, featureName.length());
1294
                                
1295
//                                        String featureOfTable = ((XMLElement)currentPath.getParentPath().getLastPathComponent()).getName();
1296
                                        String featureOfTable = table.getModel().getName();
1297
                                        int pos2 = featureOfTable.indexOf(':');
1298
                                                                                                
1299
                                        if ((pos2 >= 0) && (pos2 < featureName.length()))
1300
                                                featureOfTable = featureOfTable.substring(pos2 +1, featureOfTable.length());                                                
1301
                                
1302
                                if (featureName.trim().compareTo(featureOfTable.trim()) == 0) {
1303
                                        // Only add the new data associated to the table one time
1304
                                        if (oneTimeNewDataToTableAdded == false) {
1305
                                                setNewDataToTable();
1306
                                                oneTimeNewDataToTableAdded = true;
1307
                                        }
1308
                                
1309
                                        // Refresh the table with the new data
1310
                                        table.refresh();
1311
                                }
1312
                        }
1313
                }                
1314
        }        
1315
        
1316
        /**
1317
         * This method is a modification of the "execute" method from the "ShowTable" class 
1318
         *
1319
         * @see com.iver.cit.gvsig.ShowTable#execute(String)
1320
         */
1321
        private void setNewDataToTable() {
1322
                View vista = (View) PluginServices.getMDIManager().getActiveWindow();
1323
                FLayer[] actives = vista.getModel().getMapContext().getLayers().getActives();
1324

    
1325
                try {
1326
                        for (int i = 0; i < actives.length; i++) {
1327
                                if (actives[i] instanceof AlphanumericData) {
1328
                                        AlphanumericData co = (AlphanumericData) actives[i];
1329

    
1330
                                        //SelectableDataSource dataSource;
1331
                                        //dataSource = co.getRecordset();
1332

    
1333
                                        ProjectExtension ext = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class);
1334

    
1335
                                        ProjectTable projectTable = ext.getProject().getTable(co);
1336
                                        EditableAdapter ea=null;
1337
                                        ReadableVectorial rv=((FLyrVect)actives[i]).getSource();
1338
                                        if (rv instanceof VectorialEditableAdapter){
1339
                                                ea=(EditableAdapter)((FLyrVect)actives[i]).getSource();
1340
                                        }else{
1341
                                                ea=new EditableAdapter();
1342
                                                SelectableDataSource sds=((FLyrVect)actives[i]).getRecordset();
1343
                                                ea.setOriginalDataSource(sds);
1344
                                        }
1345

    
1346
                                        if (projectTable == null) {
1347
                                                projectTable = ProjectFactory.createTable(PluginServices.getText(this, "Tabla_de_Atributos") + ": " + actives[i].getName(),
1348
                                                                ea);
1349
                                                projectTable.setProjectDocumentFactory(new ProjectTableFactory());
1350
                                                projectTable.setAssociatedTable(co);
1351
                                                ext.getProject().addDocument(projectTable);
1352
                                        }
1353
                                        projectTable.setModel(ea);
1354
                                        
1355
                                        // Removed part of code that created another (visual) table
1356
//                                        Table t = new Table();
1357
//                                        t.setModel(projectTable);
1358
//                                        PluginServices.getMDIManager().addWindow(t);
1359
                                }
1360
                        }
1361
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
1362
            NotificationManager.addError(PluginServices.getText(this,"No_se_pudo_obtener_la_tabla_de_la_capa"), e);
1363
        } catch (com.iver.cit.gvsig.fmap.DriverException e) {
1364
                        e.printStackTrace();
1365
                        NotificationManager.addError(PluginServices.getText(this,"No_se_pudo_obtener_la_tabla_de_la_capa"), e);
1366
        }
1367
        }
1368
        
1369
        ///// END UPDATE TABLES DATA /////
1370
        
1371
        ///// OTHER METHODS /////
1372
        
1373
        /**
1374
         * DOCUMENT ME!
1375
         *
1376
         * @param expresion DOCUMENT ME!
1377
         * @param substring DOCUMENT ME!
1378
         * @param startingPos DOCUMENT ME!
1379
         *
1380
         * @return DOCUMENT ME!
1381
         */
1382
        private int getIndex(String expresion, String substring, int startingPos) {
1383
                int index = startingPos;
1384

    
1385
                do {
1386
                        index = expresion.indexOf(substring, index);
1387
                } while ((StringUtilities.isBetweenSymbols(expresion, index, "\"")) &&
1388
                                (index != -1));
1389

    
1390
                return index;
1391
        }
1392
        
1393
        /**
1394
         * DOCUMENT ME!
1395
         *
1396
         * @param arg0
1397
         *
1398
         * @return
1399
         */
1400
        public boolean addExpressionListener(ExpressionListener arg0) {
1401
                return expressionListeners.add(arg0);
1402
        }
1403

    
1404
        /**
1405
         * DOCUMENT ME!
1406
         *
1407
         * @param arg0
1408
         *
1409
         * @return
1410
         */
1411
        public boolean removeExpressionListener(ExpressionListener arg0) {
1412
                return expressionListeners.remove(arg0);
1413
        }
1414
        /**
1415
         * DOCUMENT ME!
1416
         *
1417
         * @param o DOCUMENT ME!
1418
         *
1419
         * @return DOCUMENT ME!
1420
         */
1421
        public boolean removeExceptionListener(ExceptionListener o) {
1422
                return exceptionHandlingSupport.removeExceptionListener(o);
1423
        }
1424

    
1425
        /**
1426
         * DOCUMENT ME!
1427
         *
1428
         * @param t DOCUMENT ME!
1429
         */
1430
        private void throwException(Throwable t) {
1431
                exceptionHandlingSupport.throwException(t);
1432
        }
1433
        
1434
        ///// END OTHER METHODS ///// 
1435
}