Statistics
| Revision:

root / branches / v2_0_0_prep / extensions / extWFS2 / src / org / gvsig / wfs / gui / panels / WFSFilterPanel.java @ 34132

History | View | Annotate | Download (54.8 KB)

1
package org.gvsig.wfs.gui.panels;
2

    
3
import java.awt.Color;
4
import java.awt.event.MouseAdapter;
5
import java.awt.event.MouseEvent;
6
import java.io.ByteArrayInputStream;
7
import java.io.InputStream;
8
import java.io.UnsupportedEncodingException;
9
import java.net.URLEncoder;
10
import java.text.DateFormat;
11
import java.text.ParseException;
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

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

    
31
import Zql.ZExp;
32
import Zql.ZqlParser;
33

    
34
import org.slf4j.Logger;
35
import org.slf4j.LoggerFactory;
36

    
37
import org.gvsig.andami.PluginServices;
38
import org.gvsig.andami.messages.NotificationManager;
39
import org.gvsig.app.gui.filter.ExpressionDataSource;
40
import org.gvsig.app.gui.filter.FilterException;
41
import org.gvsig.app.sqlQueryValidation.SQLQueryValidation;
42
import org.gvsig.fmap.dal.feature.Feature;
43
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
44
import org.gvsig.fmap.dal.feature.FeatureStore;
45
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
46
import org.gvsig.gui.beans.Messages;
47
import org.gvsig.gui.beans.filterPanel.filterQueryPanel.FilterQueryJPanel;
48
import org.gvsig.gui.beans.panelGroup.IPanelGroup;
49
import org.gvsig.remoteclient.wfs.WFSFeatureField;
50
import org.gvsig.tools.dataTypes.DataTypes;
51
import org.gvsig.tools.dispose.DisposableIterator;
52
import org.gvsig.utils.stringNumberUtilities.StringNumberUtilities;
53
import org.gvsig.wfs.gui.panels.fieldstree.FieldsTreeTableModel;
54
import org.gvsig.wfs.gui.panels.model.WFSSelectedFeature;
55
import org.gvsig.xmlschema.lib.api.som.IXSElementDeclaration;
56

    
57

    
58

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

    
100
/**
101
 * <p>Panel that provides tools to apply a filter to the values of a feature.</p>
102
 * <p>Improves the functionality of {@link FilterQueryJPanel FilterQueryJPanel}.</p>
103
 *
104
 * @see FilterQueryJPanel
105
 * 
106
 * @author Pablo Piqueras Bartolom? (p_queras@hotmail.com)
107
 */
108
public class WFSFilterPanel extends FilterQueryJPanel implements IWFSPanel {
109
    private static final long serialVersionUID = -6041218260822015810L;
110
    private static final Logger LOG = LoggerFactory.getLogger(WFSFilterPanel.class);
111

    
112
    private static Logger logger = LoggerFactory.getLogger(WFSFilterPanel.class);
113
    private ExpressionDataSource model = null;
114
    private FieldsTreeTableModel fieldsTreeTableModel;
115
    private boolean panelAsATabForWFSLayersLoad;
116
    private TreePath currentPath;
117
    private String featureName;
118
    private Map<String, Map<String, String>> allFieldsAndValuesKnownOfCurrentLayer; // This will have all values (not repeated) known of all fields (not repeated)
119

    
120
    private FLyrVect selectedLayer = null;
121

    
122
    ///// GUI METHODS ////
123

    
124
    /**
125
     * This method initializes
126
     *
127
     * @param parent A reference to the parent container component of this component
128
     */
129
    public WFSFilterPanel() {
130
        super();
131
        currentPath = null;
132
        featureName = null;
133
        allFieldsAndValuesKnownOfCurrentLayer = new HashMap<String, Map<String, String>>(); // Initial capacity = 0
134

    
135
        // At beginning, the JList is disabled (and its set a particular color for user could knew it)
136
        super.getValuesJList().setEnabled(false);
137
        //getValuesJList().setBackground(new Color(220, 220, 220));
138

    
139
        //The validation option is disabled by default
140
        this.getValidateFilterExpressionJCheckBox().setSelected(false);
141
    }
142

    
143
    /*
144
     *  (non-Javadoc)
145
     * @see org.gvsig.gui.beans.filterPanel.AbstractFilterQueryJPanel#initialize()
146
     */
147
    protected void initialize() {
148
        setLabel(PluginServices.getText(this, "filter"));
149
        setLabelGroup(PluginServices.getText(this, "wfs"));
150
        super.initialize();
151
        this.resizeHeight(380);
152

    
153
        defaultTreeModel = (DefaultTreeModel)fieldsJTree.getModel();
154

    
155
        this.addNewListeners();
156
        panelAsATabForWFSLayersLoad = true;
157
        getValidateFilterExpressionJCheckBox().setSelected(true);
158

    
159
        getValuesJLabel().setToolTipText(Messages.getText("values_of_the_selected_field_explanation"));
160
        getFieldsJLabel().setToolTipText(Messages.getText("fields_of_the_selected_feature_explanation"));
161
    }
162

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

    
176
            /*
177
             *  (non-Javadoc)
178
             * @see javax.swing.event.DocumentListener#insertUpdate(javax.swing.event.DocumentEvent)
179
             */
180
            public void insertUpdate(DocumentEvent e) {
181
                if (!panelAsATabForWFSLayersLoad) {
182
                    IPanelGroup panelGroup = getPanelGroup();
183

    
184
                    if (panelGroup == null)
185
                        return;
186

    
187
                    ((WFSParamsPanel)panelGroup).setApplicable(true);
188
                }
189
            }
190

    
191
            /*
192
             *  (non-Javadoc)
193
             * @see javax.swing.event.DocumentListener#removeUpdate(javax.swing.event.DocumentEvent)
194
             */
195
            public void removeUpdate(DocumentEvent e) {
196
                if (!panelAsATabForWFSLayersLoad) {
197
                    IPanelGroup panelGroup = getPanelGroup();
198

    
199
                    if (panelGroup == null)
200
                        return;
201

    
202
                    ((WFSParamsPanel)panelGroup).setApplicable(true);
203
                }
204
            }
205
        });
206

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

    
217
                if (row > -1) {
218
                    switch (e.getClickCount()) {
219
                    case 2:
220
                        putSymbolOfSelectedByMouseBranch(treePath);
221
                        break;
222
                    }
223
                }
224
            }
225
        });
226

    
227
        // Listener for "valuesJList"
228
        getValuesJList().addMouseListener(new MouseAdapter() {
229
            /*
230
             *  (non-Javadoc)
231
             * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
232
             */
233
            public void mouseClicked(MouseEvent e) {
234
                int index = getValuesJList().getSelectedIndex();
235

    
236
                // Avoids exception when no value is in the list
237
                if (index == -1)
238
                    return;
239

    
240
                if (e.getClickCount() == 2){
241
                    String valor = valuesListModel.getElementAt(index).toString();
242

    
243
                    // If value is an string -> set it between apostrophes
244
                    if (getNodeOfCurrentPath().getDataType().getType() == DataTypes.STRING) {
245
                        putSymbol("'" + valor + "'");
246
                    }
247
                    else {
248
                        putSymbol(valor);
249
                    }
250
                }
251
            }
252
        });
253

    
254
        // Listener for a branch of the tree selection
255
        getFieldsJTree().addTreeSelectionListener(new TreeSelectionListener() {
256
            /*
257
             *  (non-Javadoc)
258
             * @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent)
259
             */
260
            public void valueChanged(TreeSelectionEvent e) {
261
                if (selectedLayer != null){
262
                    currentPath = e.getPath();
263
                    fillValuesByPath(currentPath);
264
                }
265
            }
266
        });
267

    
268
        // Listener: when a user writes something on the textarea -> set it's foreground color to black
269
        getTxtExpression().getDocument().addDocumentListener(new DocumentListener() {
270
            /*
271
             *  (non-Javadoc)
272
             * @see javax.swing.event.DocumentListener#changedUpdate(javax.swing.event.DocumentEvent)
273
             */
274
            public void changedUpdate(DocumentEvent e) {
275
            }
276

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

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

    
295
    /**
296
     * Gets the element that the 'currentPath' field aims
297
     *
298
     * @return An XMLElement
299
     */
300
    private WFSFeatureField getNodeOfCurrentPath() {
301

    
302
        if (currentPath != null) {
303
            Object node = currentPath.getLastPathComponent();
304

    
305
            if ((node != null) && (node instanceof WFSFeatureField)) {
306
                return (WFSFeatureField) node;
307
            }
308
        }
309

    
310
        return null;
311
    }
312

    
313
    /**
314
     * Puts the symbol of selected branch
315
     *
316
     * @param mouseEvent A MouseEvent with information  of the selected branch
317
     */
318
    public void putSymbolOfSelectedByMouseBranch(TreePath treePath) {
319
        // Sets the node selected
320
        if (treePath != null) {
321
            putSymbol("\"" + this.getPathOfLeafWithoutRoot(treePath.getLastPathComponent().toString()) + "\"");
322
        }
323
    }
324

    
325
    /**
326
     * This method returns the path without the root, of a node of a tree
327
     * Each node is separated from its parent with the symbol "/"
328
     *
329
     * @param node A leaf node
330
     * @return An string with the path
331
     */
332
    private String getPathOfLeafWithoutRoot(Object node) {
333
        String path = "";
334

    
335
        if ((node != null) && (node instanceof IXSElementDeclaration)) {
336
            IXSElementDeclaration element = (IXSElementDeclaration) node;
337
            IXSElementDeclaration parent = element.getParentElement();
338
            path = element.getNodeName();
339

    
340
            while (parent.getParentElement() != null){
341
                path = parent.getNodeName() + "/" + path;
342
                parent = parent.getParentElement();
343
            }
344
        }else if (node instanceof String){
345
            path = node.toString();
346
        }
347

    
348
        return path;
349
    }
350

    
351
    /**
352
     * Gets the value of the inner attribute: 'panelAsATabForWFSLayersLoad'
353
     *
354
     * @return A boolean value
355
     */
356
    public boolean getWFSFilterPanelIsAsTabForWFSLayersLoad() {
357
        return this.panelAsATabForWFSLayersLoad;
358
    }
359

    
360
    /**
361
     * Sets the value of the inner attribute: 'panelAsATabForWFSLayersLoad'
362
     *
363
     * @param b A boolean value
364
     */
365
    public void setWFSFilterPanelIsAsTabForWFSLayersLoad (boolean b) {
366
        //                this.panelAsATabForWFSLayersLoad = b;
367
        //
368
        //                if (this.panelAsATabForWFSLayersLoad == true) {
369
        //                        // At beginning, the JList is disabled (and its set a particular color for user could knew it)
370
        //                        super.getValuesJList().setEnabled(false);
371
        //                        super.getValuesJList().setBackground(new Color(220, 220, 220)); // a grey color
372
        //
373
        //                        this.allFieldsAndValuesKnownOfCurrentLayer.clear();
374
        //                        getValidateFilterExpressionJCheckBox().setSelected(true);
375
        //                }
376
        //                else {
377
        //                        // Unselect the selected path in the tree (if there was any selected)
378
        //                        if (this.currentPath != null) {
379
        //                                this.currentPath = null;
380
        //                                this.getFieldsJTree().removeSelectionPath(this.getFieldsJTree().getSelectionPath());
381
        //                        }
382
        //
383
        //                        // Resets data loaded
384
        //                        super.getValuesJList().setEnabled(true);
385
        //                        super.getValuesJList().setBackground(Color.WHITE);
386
        //
387
        //                        this.getFieldsJTree().removeAll();
388
        //                        this.getValuesJList().removeAll();
389
        //
390
        //                        // Updates data associated to view with the new layer data
391
        //                        this.setNewDataToTable();
392
        //
393
        //                        // Reads that new data
394
        //                        DefaultExpression data = DataLoadingFromActiveView.getDefaultExpressionDataSource();
395
        //
396
        //                        if (data != null) {
397
        //                                setModel(data);
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 a feature with fields
409
     */
410
    public void refresh(WFSSelectedFeature feature) {
411
        featureName = feature.getTitle();
412
        setFields(feature);        
413
        setFilterExpressionIntoInterface(feature.getFilter());
414
    }
415

    
416
    ///// END GUI METHODS /////
417

    
418
    ///// METHODS FOR THE FILTER QUERY /////
419

    
420
    /**
421
     * Gets the query that will be send to the server
422
     * @return SQL query (just the where part)
423
     */
424
    public String getQuery(){
425
        String writtenQuery = txtExpression.getText().trim();
426

    
427
        // Validate expression
428
        if (!this.validateExpression(writtenQuery)) {
429
            getTxtExpression().setForeground(Color.red);
430
            return null;
431
        }
432
        else {
433
            logger.debug("Codified WFS filter query: " + writtenQuery);
434

    
435
            if (writtenQuery.trim().length() == 0){
436
                return null;
437
            }
438
            // Codify expression (only if the validation has been successful)
439
            return this.codifyExpression(writtenQuery); // Ignores the spaces at beginning and end of the chain of characters
440
        }
441
    }
442

    
443
    /**
444
     * Gets the filter expression from the user interface
445
     */
446
    public String getFilterExpressionFromInterface() {
447
        return getTxtExpression().getText();
448
    }
449

    
450
    /**
451
     * Writes the filter expression into the user interface
452
     * @param filterExpression An string
453
     */
454
    public void setFilterExpressionIntoInterface(String filterExpression){
455
        getTxtExpression().setText(filterExpression);
456
    }
457

    
458
    /**
459
     * Removes text in the JTextArea that has the filter subconsultation
460
     */
461
    public void removeFilterExpression() {
462
        getTxtExpression().setText("");
463
    }
464

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

    
475
        // Encode each string of the query
476
        int index = 0;
477
        int lastIndex = 0;
478
        boolean endInnerLoop;
479

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

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

    
492
            lastIndex = index;
493
            endInnerLoop = false;
494

    
495
            // Tries to find each first apostrophe of each string of the query
496
            if ((index > 0) && (expression.charAt(index - 1) == ' ')) {
497
                index++;
498

    
499
                // Ignore all inner apostrophes and try to find the last of the string
500
                while (!endInnerLoop)  {
501
                    index = expression.indexOf("'", index);
502
                    index++;
503

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

    
521
        return formatResutl(result);      
522
    }
523
    
524
    private String formatResutl(String query) {
525
        if ((query == null) || (query.equals(""))){
526
            return null;
527
        }
528
        InputStream is = new ByteArrayInputStream(query.getBytes());
529
        ZqlParser parser = new ZqlParser();
530
        parser.initParser(is);
531
        ZExp exp;
532
        try {
533
            exp = parser.readExpression();
534
            return exp.toString();    
535
        } catch (Zql.ParseException e) {
536
           LOG.error("Formatting the filter request", e);
537
           JOptionPane.showMessageDialog(null, PluginServices.getText(null, "filter_with_an_incorrect_format"), PluginServices.getText(null, "error_validating_filter_query"), JOptionPane.ERROR_MESSAGE);
538
        }
539
        return query;
540
    }
541

    
542
    /**
543
     * Checks the filter expression if it's correct
544
     *
545
     * @param query The query expression to analyze
546
     * @return True if it's valid or false if not
547
     */
548
    private boolean validateExpression(String query) {
549
        try {
550
            // If it's needed to validate the query
551
            if (getValidateFilterExpressionJCheckBox().isSelected()) {
552
                // If it's an empty query -> ok
553
                if (query.trim().length() == 0)
554
                    return true;
555

    
556
                // Replace all Date(dd-mmm-yyyy) format to ddd-mmm-yyyy (characters will replaced to spaces)
557
                int index = 0;
558
                String query_copy = new String(query);
559
                while ((index = query_copy.indexOf("Date(", index)) != -1) {
560
                    if (index > 0) {
561
                        if ((query_copy.charAt(index-1) != ' ') && (query_copy.charAt(index-1) != '('))
562
                            break;
563
                    }
564

    
565
                    if (((index + 16) < query_copy.length()) && (query_copy.charAt(index + 16) == ')')) { // +17 is the length of Date(dd-mmm-yyyy)
566
                        if ((index + 17) < query_copy.length()) {
567
                            query_copy = query_copy.substring(0, index) + "     " + query_copy.substring(index+6, index+16) + " " + query_copy.substring(index+17);
568
                        }
569
                        else {
570
                            query_copy = query_copy.substring(0, index) + "     " + query_copy.substring(index+6, index+16);
571
                        }
572
                    }
573
                }
574

    
575
                SQLQueryValidation sQLQueryValidation = new SQLQueryValidation(formatSQLQuery(query_copy), true);
576

    
577
                // Tries to validate the query, and if fails shows a message
578
                if (!sQLQueryValidation.validateQuery()) {
579
                    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);
580
                    return false;
581
                }
582
                else {
583
                    // Analyzes tokens in query
584
                    StringTokenizer tokens = new StringTokenizer(query, " ");
585
                    String token, token_aux;
586
                    boolean finish = false;
587

    
588
                    // If there is a field or a value with spaces, (and then it's on differents tokens) -> unify them
589
                    while (tokens.hasMoreTokens()) {
590
                        token = tokens.nextToken().trim();
591

    
592
                        if (token.charAt(0) == '\'') {
593
                            if (token.charAt(token.length() -1) != '\'') {
594
                                while (!finish) {
595
                                    if (!tokens.hasMoreTokens()) {
596
                                        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);
597
                                        return false;
598
                                    }
599
                                    else {
600
                                        token_aux = tokens.nextToken().trim();
601
                                        token += " " + token_aux;
602

    
603
                                        if (token_aux.charAt(token_aux.length() -1) == '\'')
604
                                            finish = true;
605
                                    }
606
                                }
607

    
608
                                finish = false;
609
                            }
610
                        }
611

    
612
                        if (token.charAt(0) == '\"') {
613
                            if (token.charAt(token.length() -1) != '\"') {
614
                                while (!finish) {
615
                                    if (!tokens.hasMoreTokens()) {
616
                                        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);
617
                                        return false;
618
                                    }
619
                                    else {
620
                                        token_aux = tokens.nextToken().trim();
621
                                        token += " " + token_aux;
622

    
623
                                        if (token_aux.charAt(token_aux.length() -1) == '\"')
624
                                            finish = true;
625
                                    }
626
                                }
627

    
628
                                finish = false;
629
                            }
630
                        }
631

    
632
                        // Tries to find an invalid token
633
                        if (token.length() > 0) {
634
                            // Validates if a supposed field exists
635
                            if ( (token.length() > 2) && (token.charAt(0) == '\"') && (token.charAt(token.length()-1) == '\"') ) {
636
                                if (! this.isAField(token.substring(1, token.length()-1))) {
637
                                    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);
638
                                    return false;
639
                                }
640
                            }
641
                            else {
642
                                // If it's an string -> ignore
643
                                if (! ((token.charAt(0) == token.charAt(token.length() - 1)) && (token.charAt(0) == '\''))) {
644

    
645
                                    // If it's a date -> ignore
646
                                    int returnValue = validateDate(token);
647

    
648
                                    if (returnValue == 1) {
649
                                        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);
650
                                        return false;
651
                                    }
652

    
653
                                    if (returnValue == 2) {
654
                                        // Else -> Checks if the current token is a valid number or symbol
655
                                        if ((! StringNumberUtilities.isRealNumberWithIntegerExponent(token)) && (! this.isAnOperatorNameOrSymbol(token, getAllOperatorSymbols()))) {
656
                                            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);
657
                                            return false;
658
                                        }
659
                                    }
660
                                }
661
                            }
662
                        }
663
                    }
664

    
665
                    // If has validate all tokens -> query validated
666
                    return true;
667
                }
668
            }
669
            else
670
                return true; // No validation done because user selected that option
671
        }
672
        catch (Exception e) {
673
            NotificationManager.showMessageError(PluginServices.getText(null, "filter_with_an_incorrect_format") + ".", e);
674
            return true; // No validation done because user selected that option
675
        }
676
    }
677

    
678
    /**
679
     * <p>Formats a query removing non English symbols that can produce the SQL validator could invalidate it.</p>
680
     * 
681
     * @param an SQL query
682
     * @return the SQL query without non English symbols
683
     */
684
    private String formatSQLQuery(String token) {
685
        return token = token.replace("?", "n").replace("?", "c").replace("?", "a").
686
        replace("?", "e").replace("?", "i").replace("?", "o").replace("?", "u").replace("?", "a").
687
        replace("?", "e").replace("?", "i").replace("?", "o").replace("?", "u").replace("?", "a").
688
        replace("?", "e").replace("?", "i").replace("?", "o").replace("?", "u").replace("?", "a").
689
        replace("?", "e").replace("?", "i").replace("?", "o").replace("?", "u");
690
    }
691

    
692
    /**
693
     * Returns true if there is a field with the same name as 'text'
694
     *
695
     * @param text An string
696
     * @return A boolean value
697
     */
698
    private boolean isAField(String text) {
699
        return this.allFieldsAndValuesKnownOfCurrentLayer.containsKey(text);
700
    }
701

    
702
    /**
703
     * Validates if a text has a correct date format as Date(dd-mmm-yyyy)  (Ex. Date(03-feb-2004) )
704
     *
705
     * @param text date to validate
706
     * @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
707
     */
708
    private int validateDate(String text) {
709
        // If it's a date -> check if format is correct (Ex.  Date(01-feb-2004) )
710
        if ( ((text.length() == 17) && (text.startsWith("Date(")) && (text.endsWith(")"))) && (text.charAt(7) == '-') && (text.charAt(11) == '-') ) {
711
            if ( (StringNumberUtilities.isNaturalNumber(text.substring(5, 7))) && (StringNumberUtilities.isNaturalNumber(text.substring(12, 16))) ) {
712
                try {
713
                    // If can parse the date -> date with a correct format
714
                    DateFormat.getDateInstance().parse(text.substring(5, 16));
715
                    return 0;
716
                } catch (ParseException e) {
717
                    // If can't parse the date -> date with an incorrect format
718
                    NotificationManager.addError(e);
719
                    return 1;
720
                }
721
            }
722
            else {
723
                return 1;
724
            }
725
        }
726

    
727
        return 2;
728
    }
729

    
730
    /**
731
     * Returns true if there is the 'text' is a symbol or a operator name
732
     *
733
     * @param text An string
734
     * @return A boolean value
735
     */
736
    private boolean isAnOperatorNameOrSymbol(String text, Set<String> operatorNamesAndSymbols) {
737
        return operatorNamesAndSymbols.contains(text);
738
    }
739

    
740
    ///// END METHODS FOR THE FILTER QUERY /////
741

    
742
    ///// METHODS FOR TRANSLATE DATA IN FILTER SENTENCES /////
743

    
744
    /**
745
     * Encodes an string to ISO 8859_1 with each ' symbol converted to ''
746
     *
747
     * @param text An string started and finished with simple apostrophes
748
     *
749
     * @return An string started and finished with simple apostrophes
750
     */
751
    private String translateString(String text) {
752
        // Encode to the string to ISO 8859_1 (the URL codification)
753
        try {
754

    
755
            // Ignore the first and last apostrophes
756
            if (text.length() > 2) {
757
                text = text.substring(1, text.length() -1);
758

    
759
                // Convert the string to ISO 8859_1 codification
760
                text = URLEncoder.encode(text, "8859_1");
761

    
762
                // Change ' (%27 code) to '' for the SQL parser (before send the query)
763
                text = text.replaceAll("\\%27", "\\'\\'");
764
            }
765

    
766
        } catch (UnsupportedEncodingException e1) {
767
            NotificationManager.addError(e1);
768
        }
769

    
770
        return "'" + text + "'";
771
    }
772

    
773
    ///// END METHODS FOR TRANSLATE DATA IN FILTER SENTENCES /////
774

    
775
    ///// METHODS FOR MANIPULATE 'fields' and 'values' /////
776

    
777
    /**
778
     * Sets the model with the fields and values of the feature selected.
779
     *
780
     * @param eds data source with the model of the feature selected
781
     */
782
    public void setModel(ExpressionDataSource eds) {
783
        //                try {
784
        model = eds;
785
        //            model.start();
786
        //        } catch (ReadDriverException e1) {
787
        //                NotificationManager.addError(e1);
788
        //        }
789

    
790
        try {
791
            int numberOfFields = model.getFieldCount();
792

    
793
            if (numberOfFields > 0) {
794
                Vector<Object> fields = new Vector<Object>(0, 1);
795
                int j = 0;
796

    
797
                for (int i = 0; i < numberOfFields; i++) {
798
                    Object field = model.getFieldName(i);
799

    
800
                    if (field != null) {
801
                        fields.add(field);
802

    
803
                        String completeFieldPath = this.getPathOfLeafWithoutRoot(field);
804

    
805
                        if (! allFieldsAndValuesKnownOfCurrentLayer.containsKey(completeFieldPath) ) {
806
                            allFieldsAndValuesKnownOfCurrentLayer.put(completeFieldPath, new HashMap<String, String>());
807
                        }
808

    
809
                        j++;
810
                    }
811
                }
812

    
813
                fieldsTreeTableModel = new FieldsTreeTableModel(fields.toArray());
814
            }
815
        } catch (FilterException e) {
816
            NotificationManager.addError(e);
817
        }
818
    }
819

    
820
    /**
821
     * If there is a field selected, show its new values
822
     */
823
    public void updateFieldValues() {
824
        //                if (currentPath != null) {
825
        //                        DefaultExpression data = DataLoadingFromActiveView.getDefaultExpressionDataSource();
826
        //
827
        //                        if (data != null) {
828
        //                                setModel(data);
829
        //                                fillValuesByPath(currentPath);
830
        //
831
        //                                // Updates all tables that their data is about the changed view
832
        //                                this.updateTablesThatHasNewData();
833
        //
834
        //                                // Adjust JScrollPanes to the the beginning
835
        //                                getFieldsJScrollPane().getHorizontalScrollBar().setValue(-1);
836
        //                                getFieldsJScrollPane().getVerticalScrollBar().setValue(-1);
837
        //
838
        //                                // Adjust JScrollPanes to the the beginning
839
        //                                getValuesJScrollPane().getHorizontalScrollBar().setValue(-1);
840
        //                                getValuesJScrollPane().getVerticalScrollBar().setValue(-1);
841
        //
842
        //                                // Adjusts valuesJList to the default position
843
        //                                getValuesJList().setSelectedIndex(-1); // No item selected
844
        //                        }
845
        //                }
846
    }
847

    
848
    /**
849
     * Adds the fields of the feature.
850
     *
851
     * @param feature A Layer node with fields information
852
     */
853
    private boolean setFields(WFSSelectedFeature feature) {                
854

    
855
        this.resetFieldsAndValuesData();
856

    
857
        int numberOfFields = feature.getWFSFeature().getFieldSize();
858

    
859
        if (numberOfFields > 0) {           
860
            Vector<WFSFeatureField> fieldBranches = new Vector<WFSFeatureField>(0, 1);
861

    
862
            for (int i=0 ; i<numberOfFields ; i++) {                
863
                WFSFeatureField featureField = feature.getWFSFeature().getFieldAt(i);
864
                if (!featureField.isGeometry()) {
865
                    fieldBranches.add(featureField);                                                
866
                }
867
            }
868

    
869

    
870
            if (fieldBranches.size() > 0) {
871
                Object obj = fieldBranches.get(0);
872

    
873
                fieldsTreeTableModel = new FieldsTreeTableModel(feature.getWFSFeature(), false);
874
                fieldsJTree.setModel(new FieldsTreeTableModel(feature.getWFSFeature(), false));
875

    
876
                // Stores the name of all leafs (fields) of treeTableModel
877
                Object root = fieldsTreeTableModel.getRoot();
878

    
879
                if (root != null) {
880
                    Vector<Object> fieldsNames = fieldsTreeTableModel.getLeafsFromNodeBranch(root);
881

    
882
                    for (Object field : fieldsNames) {
883
                        // Avoid errors
884
                        if ( (! (field instanceof WFSFeatureField)) || (field == null) )        continue;
885

    
886
                        // Don't load a geometry field
887
                        if (((WFSFeatureField)field).isGeometry()){
888
                            continue;
889
                        }
890

    
891

    
892
                        String completeFieldPath = this.getPathOfLeafWithoutRoot(field);
893

    
894
                        if (! allFieldsAndValuesKnownOfCurrentLayer.containsKey(completeFieldPath) ) {
895
                            allFieldsAndValuesKnownOfCurrentLayer.put(completeFieldPath, new HashMap<String, String>());
896
                        }
897
                    }
898
                }
899
            }
900
        }
901

    
902
        return true;
903
    }
904

    
905
    /**
906
     * This method load all values known of all fields known.
907
     * (It's used when a new layer is loaded).
908
     */
909
    private void setValuesKnownOfFields() {
910
        // Desde el modelo se deber?a acceder a los campos y sus valores cargados
911
        //                try {
912
        //                        for (int i = 0; i < model.getFieldCount(); i++) {
913
        //                                String fieldName = model.getFieldName(i);
914
        //                                HashMap<String, String> fieldValues = (HashMap<String, String>) allFieldsAndValuesKnownOfCurrentLayer.get(fieldName);
915
        //
916
        //                                if (fieldValues != null) {
917
        //                                        for (int j = 0; j < model.getRowCount(); j++) {
918
        //                                                Value value = model.getFieldValue(j, i);
919
        //
920
        //                                                if (value instanceof NullValue)
921
        //                                                    continue;
922
        //
923
        //                                                Object obj = (Object)value;
924
        //
925
        //                                                if (obj == null)
926
        //                                                        continue;
927
        //
928
        //                                                fieldValues.put(obj.toString(), obj.toString());
929
        //
930
        //                                        }
931
        //                                }
932
        //                        }
933
        //                }
934
        //                catch (Exception e) {
935
        //                        NotificationManager.addError(e);
936
        //                }
937
    }
938

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

    
948
    /**
949
     * Fills list with the values of selected field. 
950
     *
951
     * @param treePath A path in the tree
952
     */
953
    private void fillValuesByPath(TreePath treePath) {
954
        // Duplicates are removed
955
        TreeSet<Object> fieldValueSet = new TreeSet<Object>(new Comparator<Object>() {
956
            public int compare(Object o1, Object o2) {                                               
957
                if ((o1 != null) && (o2 != null)) {
958
                    return o1.toString().compareTo(o2.toString());
959
                }        
960
                return 0;
961
            }
962
        }); // For ordernation
963

    
964
        // Remove the previous items
965
        valuesListModel.clear();
966

    
967
        try {
968
            WFSFeatureField wfsFeatureField = ((WFSFeatureField)treePath.getLastPathComponent());
969

    
970
            if (wfsFeatureField == null){
971
                return;
972
            }
973

    
974
            FeatureStore featureStore = (FeatureStore)selectedLayer.getDataStore();
975
            FeatureAttributeDescriptor featureAttributeDescriptor = featureStore.getDefaultFeatureType().getAttributeDescriptor(wfsFeatureField.getName());
976

    
977
            if (featureAttributeDescriptor == null){
978
                return;
979
            }
980

    
981
            if(!wfsFeatureField.isComplex()){
982
                DisposableIterator disposableIterator = featureStore.getFeatureSet().iterator();
983
                while (disposableIterator.hasNext()){
984
                    Feature feature = (Feature)disposableIterator.next();
985
                    Object obj = feature.get(featureAttributeDescriptor.getIndex());
986
                    if (!fieldValueSet.contains(obj)){
987
                        fieldValueSet.add(obj);
988
                    }
989
                }
990

    
991
                Iterator it = fieldValueSet.iterator();
992
                while (it.hasNext()) {
993
                    String text = it.next().toString();                  
994
                    valuesListModel.addElement(text);                   
995
                }               
996
            }
997

    
998
            this.getValuesJList().setEnabled(valuesListModel.getSize() > 0);
999

    
1000

    
1001
            //                    // Find the selected field and try to obtein values related
1002
            //                    for (int i = 0; i < model.getFieldCount(); i++) {
1003
            //                        String name = model.getFieldName(i);
1004
            //
1005
            //                        // If we find the field (this means that are loaded its values and we can obtein them)
1006
            //                        if (name.equals(element.getName())) {
1007
            //                            for (int j = 0; j < model.getRowCount(); j++) {
1008
            //                                Value value = model.getFieldValue(j, i);
1009
            //
1010
            //                                if (value instanceof NullValue)
1011
            //                                    continue;
1012
            //
1013
            //                                if (!conjunto.contains(value)) {
1014
            //                                    conjunto.add(value);
1015
            //                                }
1016
            //                            }
1017
            //
1018
            //                            break;
1019
            //                        }
1020
            //                    }
1021
            //                } else {
1022
            //                    //create a vector with the parent names from the leaf until the root
1023
            //                    XMLElement parent = element.getParentElement();
1024
            //                    Vector<String> parentNames = new Vector<String>();
1025
            //                    parentNames.add(element.getName());
1026
            //                    while (parent != null){
1027
            //                        parentNames.add(parent.getName());
1028
            //                        parent = parent.getParentElement();
1029
            //                    }
1030
            //
1031
            //                    //The field name (in the gvSIG table) is the second field name
1032
            //                    String fieldName = parentNames.get(parentNames.size()-2);
1033
            //
1034
            //                    for (int i = 0; i < model.getFieldCount(); i++) {
1035
            //                        String name = model.getFieldName(i);
1036
            //
1037
            //                        // If we find the field (this means that are loaded its values and we can obtein them)
1038
            //                        if (name.equals(fieldName)) {
1039
            //                            for (int j = 0; j < model.getRowCount(); j++) {
1040
            //                                Value value = model.getFieldValue(j, i);
1041
            //
1042
            //                                if (value instanceof NullValue)
1043
            //                                    continue;
1044
            //
1045
            //                                if (value instanceof ComplexValue){
1046
            //                                    for (int k=parentNames.size()-3 ; k >= 0 ; k--){
1047
            //                                        ComplexValue complex = (ComplexValue)value;
1048
            //                                        Value childValue = (Value)complex.get(parentNames.get(k));
1049
            //                                        if (k == 0) {
1050
            //                                            if (!conjunto.contains(childValue)) {
1051
            //                                                conjunto.add(childValue);
1052
            //                                            }
1053
            //                                        } else {
1054
            //                                            value = childValue;
1055
            //                                        }
1056
            //                                    }
1057
            //                                }
1058
            //                            }
1059
            //
1060
            //                            break;
1061
            //                        }
1062
            //                    }
1063
            //                }
1064
            //                break;
1065
            //            case IXMLType.COMPLEX:
1066
            //                break;
1067
            //            default:
1068
            //                // Do Nothing
1069
            //            }
1070
            //
1071
            //            // Add the values to the model of the graphic list
1072
            //            Iterator<Object> it = conjunto.iterator();
1073
            //            Object[] objects = currentPath.getPath();
1074
            //
1075
            //            if (objects.length == 0)
1076
            //                return;
1077
            //
1078
            //            String selectedField = ((XMLElement)objects[objects.length-1]).getName(); // Gets the selected field
1079
            //
1080
            //            if (selectedField != null) { // If there is a selected field
1081
            //                Map<String, String> fieldValues = (HashMap<String, String>)allFieldsAndValuesKnownOfCurrentLayer.get(selectedField); // Gets values stored associated to this field
1082
            //                JLabel currentValueLabel = null;
1083
            //
1084
            //                // If the field doesn't exits -> create a new Map with its values
1085
            //                if (fieldValues == null) {
1086
            //                    fieldValues = new HashMap<String, String>();
1087
            //                    allFieldsAndValuesKnownOfCurrentLayer.put(selectedField, fieldValues);
1088
            //
1089
            //                    while (it.hasNext()) {
1090
            //                        // A label with text with yellow background color for values that are loaded in the layer
1091
            //                        currentValueLabel = new JLabelAsCellValueLoaded();
1092
            //
1093
            //                        currentValueLabel.setText(it.next().toString());
1094
            //
1095
            //                        if (currentValueLabel.getText().compareTo("") != 0) {
1096
            //                            fieldValues.put(currentValueLabel.getText(), currentValueLabel.getText());
1097
            //
1098
            //                            // All values loaded in this loop must be at beginning of the list (and in a differenciated color)
1099
            //                            if ( ! valuesListModel.contains(currentValueLabel) )
1100
            //                                valuesListModel.addElement(currentValueLabel);
1101
            //                        }
1102
            //                    }
1103
            //                }
1104
            //                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)
1105
            //
1106
            //                    // Changes element labels that have changed  (before were loaded and now not, or before weren't loaded but now yes)
1107
            //                    ((DefaultListModelForJLabelAsCell)valuesListModel).setAllElementsToNotLoaded();
1108
            //
1109
            //                    // For each current value associated to de current selected field -> if its loaded -> put it at beginning of the list and change to 'JLabelLoadedValue'
1110
            //                    while (it.hasNext()) {
1111
            //                        String text = it.next().toString();
1112
            //                        int elementPosition = ((DefaultListModelForJLabelAsCell)valuesListModel).getIndexOfJLabelText(text);
1113
            //
1114
            //                        if (elementPosition == -1) // If it must be added
1115
            //                            valuesListModel.addElement(new JLabelAsCellValueLoaded(text));
1116
            //                        else
1117
            //                            ((DefaultListModelForJLabelAsCell)valuesListModel).changeElementThatHasTextToJLabelLoadedValue(text); // Change to 'JLabelLoadedValue'
1118
            //                    }
1119
            //                }
1120
            //
1121
            //                // Load the rest of the values associated to the current selected field
1122
            //                if (fieldValues != null) {
1123
            //                    // A label with text with yellow background color for values that are loaded in the layer
1124
            //                    currentValueLabel = new JLabelAsCellValueNotLoaded();
1125
            //
1126
            //                    Set<String> values = fieldValues.keySet();
1127
            //
1128
            //                    for (String name : values) {
1129
            //                        if ( ! ((DefaultListModelForJLabelAsCell)valuesListModel).containsJLabelText(name) )
1130
            //                            valuesListModel.addElement(new JLabelAsCellValueNotLoaded(name));
1131
            //                    }
1132
            //                }
1133
            //            }
1134

    
1135
        } catch (Exception e) {
1136
            NotificationManager.addError(e);
1137
        }
1138
    }
1139

    
1140
    ///// END METHODS FOR MANIPULATE 'fields' and 'values' /////
1141

    
1142
    ///// METHOS FOR 'allFieldsAndValuesKnownOfCurrentLayer' /////
1143

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

    
1156
    /**
1157
     * Gets all fields and values known about the current layer
1158
     *
1159
     * @return _allFieldsAndValuesKnownOfCurrentLayer A Map object
1160
     */
1161
    public Map<String, Map<String, String>> getAllFieldsAndValuesKnownOfCurrentLayer() {
1162
        return allFieldsAndValuesKnownOfCurrentLayer;
1163
    }
1164

    
1165
    ///// METHOS FOR 'allFieldsAndValuesKnownOfCurrentLayer' /////
1166

    
1167
    ///// UPDATE TABLES DATA /////
1168

    
1169
    /**
1170
     * Updates all tables that their data is about the changed view
1171
     */
1172
    private void updateTablesThatHasNewData() {
1173
        //                boolean oneTimeNewDataToTableAdded = false;
1174
        //
1175
        //                IWindow[] activeNoModalWindows = PluginServices.getMDIManager().getAllWindows();
1176
        //
1177
        //                for (int i = 0; i < activeNoModalWindows.length; i++) {
1178
        //                        IWindow window = activeNoModalWindows[i];
1179
        //                        if (window instanceof Table) {
1180
        //                                Table table = (Table) window;
1181
        //
1182
        //                                int pos1 = featureName.indexOf(':');
1183
        //
1184
        //                                if ((pos1 >= 0) && (pos1 < featureName.length()))
1185
        //                                        featureName = featureName.substring(pos1 +1, featureName.length());
1186
        //
1187
        //                                        String featureOfTable = table.getModel().getName();
1188
        //                                        int pos2 = featureOfTable.indexOf(':');
1189
        //
1190
        //                                        if ((pos2 >= 0) && (pos2 < featureName.length()))
1191
        //                                                featureOfTable = featureOfTable.substring(pos2 +1, featureOfTable.length());
1192
        //
1193
        //                                if (featureName.trim().compareTo(featureOfTable.trim()) == 0) {
1194
        //                                        // Only add the new data associated to the table one time
1195
        //                                        if (oneTimeNewDataToTableAdded == false) {
1196
        //                                                setNewDataToTable();
1197
        //                                                oneTimeNewDataToTableAdded = true;
1198
        //                                        }
1199
        //
1200
        //                                        // Refresh the table with the new data
1201
        //                                        table.invalidate();
1202
        //                                        table.refresh();
1203
        //                                }
1204
        //                        }
1205
        //                }
1206
    }
1207

    
1208
    /**
1209
     * This method is a modification of the "execute" method from the "ShowTable" class
1210
     *
1211
     * @see org.gvsig.app.extension.ShowTable#execute(String)
1212
     */
1213
    private void setNewDataToTable() {
1214
        //                try {
1215
        //                        if (getPanelGroup().getReference() == null)
1216
        //                                return;
1217
        //
1218
        //                        FLayer activeLayer = (FLayer) getPanelGroup().getReference();
1219
        //                        AlphanumericData co = (AlphanumericData) activeLayer;
1220
        //
1221
        //                        ProjectExtension ext = (ProjectExtension) PluginServices.getExtension(ProjectExtension.class);
1222
        //                        ProjectTable projectTable = ext.getProject().getTable(co);
1223
        //
1224
        //                        EditableAdapter ea = null;
1225
        //                        ReadableVectorial rv = ((FLyrVect)activeLayer).getSource();
1226
        //
1227
        //                        if (rv instanceof VectorialEditableAdapter) {
1228
        //                                ea = (EditableAdapter)((FLyrVect)activeLayer).getSource();
1229
        //                        } else {
1230
        //                                ea = new EditableAdapter();
1231
        //                                SelectableDataSource sds = ((FLyrVect)activeLayer).getRecordset();
1232
        //                                ea.setOriginalDataSource(sds);
1233
        //                        }
1234
        //
1235
        //                        if (projectTable == null) {
1236
        //                                projectTable = ProjectFactory.createTable(PluginServices.getText(this, "Tabla_de_Atributos") + ": " + activeLayer.getName(), ea);
1237
        //                                projectTable.setProjectDocumentFactory(new ProjectTableFactory());
1238
        //                                projectTable.setAssociatedTable(co);
1239
        //                                ext.getProject().addDocument(projectTable);
1240
        //                        }
1241
        //
1242
        //                        projectTable.setModel(ea);
1243
        //                } catch (ReadDriverException e) {
1244
        //                        NotificationManager.addError(PluginServices.getText(this,"No_se_pudo_obtener_la_tabla_de_la_capa"), e);
1245
        //        }
1246
    }
1247

    
1248
    /**
1249
     * @param layer
1250
     */
1251
    public void setSelectedLayer(FLyrVect layer) {
1252
        this.selectedLayer = layer;
1253

    
1254
    }
1255

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

    
1298
    ///// END UPDATE TABLES DATA /////
1299
}