Statistics
| Revision:

root / trunk / extensions / extWFS2 / src-test / com / iver / cit / gvsig / gui / panels / TestValidationOfFilter.java @ 15728

History | View | Annotate | Download (17.7 KB)

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

    
3
import java.text.DateFormat;
4
import java.text.ParseException;
5
import java.util.HashMap;
6
import java.util.HashSet;
7
import java.util.Map;
8
import java.util.Set;
9
import java.util.StringTokenizer;
10

    
11
import javax.swing.JOptionPane;
12

    
13
import junit.framework.TestCase;
14

    
15
import com.iver.andami.PluginServices;
16
import com.iver.cit.gvsig.sqlQueryValidation.SQLQueryValidation;
17
import com.iver.utiles.stringNumberUtilities.StringNumberUtilities;
18

    
19
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
20
 *
21
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
22
 *
23
 * This program is free software; you can redistribute it and/or
24
 * modify it under the terms of the GNU General Public License
25
 * as published by the Free Software Foundation; either version 2
26
 * of the License, or (at your option) any later version.
27
 *
28
 * This program is distributed in the hope that it will be useful,
29
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
31
 * GNU General Public License for more details.
32
 *
33
 * You should have received a copy of the GNU General Public License
34
 * along with this program; if not, write to the Free Software
35
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
36
 *
37
 * For more information, contact:
38
 *
39
 *  Generalitat Valenciana
40
 *   Conselleria d'Infraestructures i Transport
41
 *   Av. Blasco Ib??ez, 50
42
 *   46010 VALENCIA
43
 *   SPAIN
44
 *
45
 *      +34 963862235
46
 *   gvsig@gva.es
47
 *      www.gvsig.gva.es
48
 *
49
 *    or
50
 *
51
 *   IVER T.I. S.A
52
 *   Salamanca 50
53
 *   46005 Valencia
54
 *   Spain
55
 *
56
 *   +34 963163400
57
 *   dac@iver.es
58
 */
59

    
60
/**
61
 * This class tests a simply version of the method of validation a filter
62
 * 
63
 * @author Pablo Piqueras Bartolom? (p_queras@hotmail.com)
64
 */
65
public class TestValidationOfFilter extends TestCase{
66
        Map allFieldsAndValuesKnownOfCurrentLayer;
67
        Set _operatorSymbols = null;
68
        String query;
69
        
70
        /*
71
         *  (non-Javadoc)
72
         * @see junit.framework.TestCase#setUp()
73
         */
74
        protected void setUp() throws Exception {
75
                super.setUp();
76
                                
77
                // Add some fields as example
78
                allFieldsAndValuesKnownOfCurrentLayer = new HashMap();
79

    
80
                allFieldsAndValuesKnownOfCurrentLayer.put("gid", new HashMap());
81
                allFieldsAndValuesKnownOfCurrentLayer.put("entity", new HashMap());
82
                allFieldsAndValuesKnownOfCurrentLayer.put("layer", new HashMap());
83
                allFieldsAndValuesKnownOfCurrentLayer.put("elevation", new HashMap());
84
                allFieldsAndValuesKnownOfCurrentLayer.put("color", new HashMap());
85
                allFieldsAndValuesKnownOfCurrentLayer.put("codigo", new HashMap());
86
                allFieldsAndValuesKnownOfCurrentLayer.put("tipo", new HashMap());
87
                allFieldsAndValuesKnownOfCurrentLayer.put("fecha", new HashMap());
88
                allFieldsAndValuesKnownOfCurrentLayer.put("id", new HashMap());
89
                
90
                // At beginning: no query
91
                query = new String();
92
        }
93

    
94
        /*
95
         *  (non-Javadoc)
96
         * @see junit.framework.TestCase#tearDown()
97
         */
98
        protected void tearDown() throws Exception {
99
                super.tearDown();
100
        }
101
        
102
        ///// TESTS /////
103
        
104
        /**
105
         * A test (Correct)
106
         */
107
        public void test1() {
108
                query = new String("\"codigo\" = 'Canal d'Elx'");
109
                
110
                System.out.println("Test 1: \n? Es v?lida '" + query + "' ? ");
111
                
112
                if (validateExpression(query))
113
                        System.out.println("Si.");
114
                else
115
                        System.out.println("No.");
116
        }
117
        
118
        /**
119
         * A test (Correct)
120
         */
121
        public void test2() {
122
                query = new String("\"codigo\" = 'R?o de Bu?ol'");
123
                
124
                System.out.println("Test 2: \n? Es v?lida '" + query + "' ? ");
125
                
126
                if (validateExpression(query))
127
                        System.out.println("Si.");
128
                else
129
                        System.out.println("No.");
130
        }
131
        
132
        /**
133
         * A test (Correct)
134
         */
135
        public void test3() {
136
                query = new String("\"codigo\" = 'els Banys de la Tia Joana'");
137
                
138
                System.out.println("Test 3: \n? Es v?lida '" + query + "' ? ");
139
                
140
                if (validateExpression(query))
141
                        System.out.println("Si.");
142
                else
143
                        System.out.println("No.");
144
        }
145
        
146
        /**
147
         * A test (Correct)
148
         */
149
        public void test4() {
150
                query = new String("\"codigo\" = 'Barranc d'Adell'");
151
                
152
                System.out.println("Test 4: \n? Es v?lida '" + query + "' ? ");
153
                
154
                if (validateExpression(query))
155
                        System.out.println("Si.");
156
                else
157
                        System.out.println("No.");
158
        }
159
        
160
        /**
161
         * A test (Correct)
162
         */
163
        public void test5() {
164
                query = new String("\"codigo\" = 'els Banys de la Tia Joana' or \"fecha\" = Date(25-ene-2007) or \"fecha\" = Date(03-mar-2008) or \"codigo\" = 'Barranc d'Adell'");
165
                
166
                System.out.println("Test 5: \n? Es v?lida '" + query + "' ? ");
167
                
168
                if (validateExpression(query))
169
                        System.out.println("Si.");
170
                else
171
                        System.out.println("No.");
172
        }
173
        
174
        /**
175
         * A test (Correct)
176
         */
177
        public void test6() {
178
                query = new String(""); // Without query
179
                
180
                System.out.println("Test 6: \n? Es v?lida '" + query + "' ? ");
181
                
182
                if (validateExpression(query))
183
                        System.out.println("Si.");
184
                else
185
                        System.out.println("No.");
186
        }
187
        
188
        /**
189
         * A test (Correct)
190
         */
191
        public void test7() {
192
                query = new String("\"id\" = '354' and \"id\" > '697'");
193
                
194
                System.out.println("Test 7: \n? Es v?lida '" + query + "' ? ");
195
                
196
                if (validateExpression(query))
197
                        System.out.println("Si.");
198
                else
199
                        System.out.println("No.");
200
        }
201
                
202
        /**
203
         * A test (Correct)
204
         */
205
        public void test8() {
206
                query = new String("\"elevation\" = 354 and \"elevation\" > 697");
207
                
208
                System.out.println("Test 8: \n? Es v?lida '" + query + "' ? ");
209
                
210
                if (validateExpression(query))
211
                        System.out.println("Si.");
212
                else
213
                        System.out.println("No.");
214
        }
215
        
216
        /**
217
         * A test (Correct)
218
         */
219
        public void test9() {
220
                String query = "SELECT r.name, f.id FROM room r, flat f WHERE (r.user_name LIKE 'P%') AND (r.flat = f.id) AND (r.color_wall LIKE 'white') AND (r.height < 2.20)";
221
                
222
                System.out.println("Test 9: \n?Es v?lida '" + query + "' ?");
223
                SQLQueryValidation sqlQueryValidation = new SQLQueryValidation(query, false);
224

    
225
                if (sqlQueryValidation.validateQuery()) {
226
                        System.out.println("Yes.");
227
                }
228
                else {
229
                        System.out.println("No.");
230
                        System.out.println(sqlQueryValidation.getErrorPositionAsMessage());
231
                        System.out.println(sqlQueryValidation.getErrorMessage());
232
                        fail();
233
                }
234
        }
235
        
236
        /**
237
         * A test (Correct)
238
         */
239
        public void test10() {
240
                String query = "SELECT * FROM House";
241

    
242
                System.out.println("Test 10: \n?Es v?lida '" + query + "' ?");
243
                SQLQueryValidation sqlQueryValidation = new SQLQueryValidation(query, false);
244

    
245
                if (sqlQueryValidation.validateQuery()) {
246
                        System.out.println("Yes.");
247
                }
248
                else {
249
                        System.out.println("No.");
250
                        System.out.println(sqlQueryValidation.getErrorPositionAsMessage());
251
                        System.out.println(sqlQueryValidation.getErrorMessage());
252
                        fail();
253
                }
254
        }
255

    
256
        /**
257
         * A test (Incorrect)
258
         */
259
        public void test11() {
260
                String query = "SELECT a* FROM House";
261

    
262
                System.out.println("Test 11: \n?Es v?lida '" + query + "' ?");
263
                SQLQueryValidation sqlQueryValidation = new SQLQueryValidation(query, false);
264

    
265
                if (sqlQueryValidation.validateQuery()) {
266
                        System.out.println("Yes.");
267
                }
268
                else {
269
                        System.out.println("No.");
270
                        System.out.println(sqlQueryValidation.getErrorPositionAsMessage());
271
                        System.out.println(sqlQueryValidation.getErrorMessage());
272
                        fail();
273
                }
274
        }
275
        
276
        /**
277
         * A test (Correct)
278
         */
279
        public void test12() {
280
                String query = "SELECT * FROM House";
281

    
282
                System.out.println("Test 12: \n?Es v?lida '" + query + "' ?");
283
                SQLQueryValidation sqlQueryValidation = new SQLQueryValidation(query, false);
284

    
285
                if (sqlQueryValidation.validateQuery()) {
286
                        System.out.println("Yes.");
287
                }
288
                else {
289
                        System.out.println("No.");
290
                        System.out.println(sqlQueryValidation.getErrorPositionAsMessage());
291
                        System.out.println(sqlQueryValidation.getErrorMessage());
292
                        fail();
293
                }
294
        }
295

    
296
        /**
297
         * A test (Correct)
298
         */
299
        public void test13() {
300
                String query = "r.level = f.level AND r.user_name LIKE \'P%\'";
301

    
302
                System.out.println("Test 13: \n?Es v?lida '" + query + "' ?");
303
                SQLQueryValidation sqlQueryValidation = new SQLQueryValidation(query, true);
304

    
305
                if (sqlQueryValidation.validateQuery()) {
306
                        System.out.println("Yes.");
307
                }
308
                else {
309
                        System.out.println("No.");
310
                        System.out.println(sqlQueryValidation.getErrorPositionAsMessage());
311
                        System.out.println(sqlQueryValidation.getErrorMessage());
312
                        fail();
313
                }
314
        }
315

    
316
        /**
317
         * A test (Incorrect)
318
         */
319
        public void test14() {
320
                String query = "r.level = f.level a e3 w         q3          ?32        9'}97AND r.user_name LIKE \'P%\'";
321

    
322
                System.out.println("Test 15: \n?Es v?lida '" + query + "' ?");
323
                SQLQueryValidation sqlQueryValidation = new SQLQueryValidation(query, true);
324

    
325
                if (sqlQueryValidation.validateQuery()) {
326
                        System.out.println("Yes.");
327
                }
328
                else {
329
                        System.out.println("No.");
330
                        System.out.println(sqlQueryValidation.getErrorPositionAsMessage());
331
                        System.out.println(sqlQueryValidation.getErrorMessage());                        
332
                        fail();
333
                }
334
        }
335

    
336
        /**
337
         * A test (Incorrect)
338
         */
339
        public void test15() {
340
                String query = "r.level = ";
341

    
342
                System.out.println("Test 15: \n?Es v?lida '" + query + "' ?");
343
                SQLQueryValidation sqlQueryValidation = new SQLQueryValidation(query, true);
344

    
345
                if (sqlQueryValidation.validateQuery()) {
346
                        System.out.println("Yes.");
347
                }
348
                else {
349
                        System.out.println("No.");
350
                        System.out.println(sqlQueryValidation.getErrorPositionAsMessage());
351
                        System.out.println(sqlQueryValidation.getErrorMessage());                        
352
                        fail();
353
                }
354
        }
355

    
356
        /**
357
         * A test (Correct)
358
         */
359
        public void test16() {
360
                String query = "r.level = 'el fondo d'Elx'";
361

    
362
                System.out.println("Test 16: \n?Es v?lida '" + query + "' ?");
363
                SQLQueryValidation sqlQueryValidation = new SQLQueryValidation(query, true);
364

    
365
                if (sqlQueryValidation.validateQuery()) {
366
                        System.out.println("Yes.");
367
                }
368
                else {
369
                        System.out.println("No.");
370
                        System.out.println(sqlQueryValidation.getErrorPositionAsMessage());
371
                        System.out.println(sqlQueryValidation.getErrorMessage());                        
372
                        fail();
373
                }
374
        }
375

    
376
        /**
377
         * A test (Correct)
378
         */
379
        public void test17() {
380
                String query = "r.level = 'el fondo dElx'";
381

    
382
                System.out.println("Test 17: \n?Es v?lida '" + query + "' ?");
383
                SQLQueryValidation sqlQueryValidation = new SQLQueryValidation(query, true);
384

    
385
                if (sqlQueryValidation.validateQuery()) {
386
                        System.out.println("Yes.");
387
                }
388
                else {
389
                        System.out.println("No.");
390
                        System.out.println(sqlQueryValidation.getErrorPositionAsMessage());
391
                        System.out.println(sqlQueryValidation.getErrorMessage());                        
392
                        fail();
393
                }
394
        }
395
        ///// END TESTS /////
396
        
397
        ///// METHODS RELATED WITH THE VALIDATION OF THE QUERY /////
398
        
399
        /**
400
         * Checks the filter expression if it's correct
401
         * 
402
         * @param query The query expression to analyze
403
         * @return True if it's valid or false if not
404
         */        
405
        private boolean validateExpression(String query) {
406
                // If it's an empty query -> ok 
407
                if (query.trim().length() == 0)
408
                        return true;
409
                
410
                // Replace all Date(dd-mmm-yyyy) format to ddd-mmm-yyyy (characters will replaced to spaces)
411
                int index = 0;
412
                String query_copy = new String(query);
413
                while ((index = query_copy.indexOf("Date(", index)) != -1) {
414
                        if (index > 0) {
415
                                if ((query_copy.charAt(index-1) != ' ') && (query_copy.charAt(index-1) != '('))
416
                                        break;
417
                        }
418
                        
419
                        if (((index + 16) < query_copy.length()) && (query_copy.charAt(index + 16) == ')')) { // +17 is the length of Date(dd-mmm-yyyy)
420
                                if ((index + 17) < query_copy.length()) {
421
                                        query_copy = query_copy.substring(0, index) + "     " + query_copy.substring(index+6, index+16) + " " + query_copy.substring(index+17);
422
                                }
423
                                else {
424
                                        query_copy = query_copy.substring(0, index) + "     " + query_copy.substring(index+6, index+16);
425
                                }
426
                        }
427
                }
428
                
429
                SQLQueryValidation sQLQueryValidation = new SQLQueryValidation(query_copy, true);
430

    
431
                // Tries to validate the query, and if fails shows a message
432
                if (!sQLQueryValidation.validateQuery()) {
433
                        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);
434
                        return false;
435
                }
436
                else {
437
                        // Analyzes tokens in query
438
                        StringTokenizer tokens = new StringTokenizer(query, " ");
439
                        String token, token_aux;
440
                        boolean finish = false;
441

    
442
                        while (tokens.hasMoreTokens()) {
443
                                token = tokens.nextToken().trim();
444
                                
445
                                if (token.charAt(0) == '\'') {
446
                                        if (token.charAt(token.length() -1) != '\'') {
447
                                                while (!finish) {
448
                                                        if (!tokens.hasMoreTokens()) {
449
                                                                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);
450
                                                                return false;
451
                                                        }
452
                                                        else {
453
                                                                token_aux = tokens.nextToken().trim();
454
                                                                token += " " + token_aux;
455
                                                                
456
                                                                if (token_aux.charAt(token_aux.length() -1) == '\'')
457
                                                                        finish = true;
458
                                                        }
459
                                                }
460
                                                
461
                                                finish = false;
462
                                        }
463
                                }
464
                                
465
                                if (token.charAt(0) == '\"') {
466
                                        if (token.charAt(token.length() -1) != '\"') {
467
                                                while (!finish) {
468
                                                        if (!tokens.hasMoreTokens()) {
469
                                                                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);
470
                                                                return false;
471
                                                        }
472
                                                        else {
473
                                                                token_aux = tokens.nextToken().trim();
474
                                                                token += " " + token_aux;
475
                                                                
476
                                                                if (token_aux.charAt(token_aux.length() -1) == '\"')
477
                                                                        finish = true;
478
                                                        }
479
                                                }
480
                                                
481
                                                finish = false;
482
                                        }
483
                                }
484

    
485
                                // Tries to find an invalid token
486
                                if (token.length() > 0) {
487
                                        // Validates if a supposed field exists
488
                                        if ( (token.length() > 2) && (token.charAt(0) == '\"') && (token.charAt(token.length()-1) == '\"') ) {
489
                                                if (! this.isAField(token.substring(1, token.length()-1))) {
490
                                                        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);
491
                                                        return false;
492
                                                }
493
                                        }
494
                                        else {
495
                                                // If it's an string -> ignore
496
                                                if (! ((token.charAt(0) == token.charAt(token.length() - 1)) && (token.charAt(0) == '\''))) {
497
                                                        
498
                                                        // If it's a date -> ignore
499
                                                        int returnValue = validateDate(token);
500
                                                        
501
                                                        if (returnValue == 1) {
502
                                                                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);
503
                                                                return false;
504
                                                        }
505
                                                        
506
                                                        if (returnValue == 2) {                                                                
507
                                                                // Else -> Checks if the current token is a valid number or symbol
508
                                                                if ((! StringNumberUtilities.isNumber(token)) && (! this.isAnOperatorNameOrSymbol(token, getAllOperatorSymbols()))) {
509
                                                                        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);
510
                                                                        return false;
511
                                                                }
512
                                                        }
513
                                                }
514
                                        }
515
                                }
516
                        }
517

    
518
                        // If has validate all tokens -> query validated
519
                        return true;
520
                }
521
        }
522
        
523
        /**
524
         * Returns true if there is a field with the same name as 'text'
525
         * 
526
         * @param text An string
527
         * @return A boolean value
528
         */
529
        private boolean isAField(String text) {
530
                return this.allFieldsAndValuesKnownOfCurrentLayer.containsKey(text);                
531
        }
532
        
533

    
534
        /**
535
         * Returns true if there is the 'text' is a symbol or a operator name
536
         * 
537
         * @param text An string
538
         * @return A boolean value
539
         */
540
        private boolean isAnOperatorNameOrSymbol(String text, Set operatorNamesAndSymbols) {
541
                // We will ignore the case sensitive (all the rest of operators are in lower case)
542
                return operatorNamesAndSymbols.contains(text.toLowerCase());
543
        }
544
        
545
        
546
        /**
547
         * Validates if a text has a correct date format as Date(dd-mmm-yyyy)  (Ex. Date(03-feb-2004) )
548
         * 
549
         * @param text
550
         * @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
551
         */
552
        private int validateDate(String text) {
553
                // If it's a date -> check if format is correct (Ex.  Date(01-feb-2004) )
554
                if ( ((text.length() == 17) && (text.startsWith("Date(")) && (text.endsWith(")"))) && (text.charAt(7) == '-') && (text.charAt(11) == '-') ) {
555
                        if ( (StringNumberUtilities.isNaturalNumber(text.substring(5, 7))) && (StringNumberUtilities.isNaturalNumber(text.substring(12, 16))) ) {
556
                                try {
557
                                        // If can parse the date -> date with a correct format 
558
                                        DateFormat.getDateInstance().parse(text.substring(5, 16));
559
                                        return 0;
560
                                } catch (ParseException e) {
561
                                        // If can't parse the date -> date with an incorrect format 
562
                                        return 1;
563
                                }
564
                        }
565
                        else {
566
                                return 1;
567
                        }
568
                }
569
                
570
                return 2;
571
        }        
572
        
573
        ///// END METHODS RELATED WITH THE VALIDATION OF THE QUERY /////
574
        
575
        ///// OTHER METHOD AUXILIARS /////
576
        private Set getAllOperatorSymbols() {
577
                if (_operatorSymbols == null) {
578
                        // Add some operations as example
579
                        _operatorSymbols = new HashSet();
580
                        _operatorSymbols.add("and");
581
//                        operatorSymbols.add("Date");
582
                        _operatorSymbols.add("<>"); // In SQL this is the formal operator
583
                        _operatorSymbols.add("!="); // This operator is also supported
584
                        _operatorSymbols.add("=");
585
                        _operatorSymbols.add(">=");
586
                        _operatorSymbols.add("<=");
587
                        _operatorSymbols.add(">");
588
                        _operatorSymbols.add("not");
589
                        _operatorSymbols.add("or");
590
                        _operatorSymbols.add("(");
591
                        _operatorSymbols.add(")");
592
                        _operatorSymbols.add("<");
593
                }
594
                
595
                return _operatorSymbols;
596
        }
597

    
598
        ///// END OTHER METHOD AUXILIARS /////
599
}