Revision 15728

View differences:

trunk/extensions/extWFS2/src-test/com/iver/cit/gvsig/wfs/AllTests.java
5 5

  
6 6
import com.iver.cit.gvsig.fmap.layers.gml.GMLParseTest;
7 7
import com.iver.cit.gvsig.fmap.layers.gml.GMLWriterTest;
8
import com.iver.cit.gvsig.gui.panels.ValidationOfFilter_Test;
8
import com.iver.cit.gvsig.gui.panels.TestValidationOfFilter;
9 9
import com.iver.cit.gvsig.wfs.filters.FilterEncodingTest;
10 10

  
11 11
public class AllTests {
......
16 16
		suite.addTestSuite(FilterEncodingTest.class);
17 17
		suite.addTestSuite(GMLParseTest.class);
18 18
		suite.addTestSuite(GMLWriterTest.class);
19
		suite.addTestSuite(ValidationOfFilter_Test.class);
19
		suite.addTestSuite(TestValidationOfFilter.class);
20 20
		suite.addTestSuite(WFSTest.class);
21 21
		//$JUnit-END$
22 22
		return suite;
trunk/extensions/extWFS2/src-test/com/iver/cit/gvsig/gui/panels/ValidationOfFilter_Test.java
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 ValidationOfFilter_Test 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
		
89
		// At beginning: no query
90
		query = new String();
91
	}
92

  
93
	/*
94
	 *  (non-Javadoc)
95
	 * @see junit.framework.TestCase#tearDown()
96
	 */
97
	protected void tearDown() throws Exception {
98
		super.tearDown();
99
	}
100
	
101
	///// TESTS /////
102
	
103
	/**
104
	 * A test (Correct)
105
	 */
106
	public void test1() {
107
		query = new String("\"codigo\" = 'Canal d'Elx'");
108
		
109
		System.out.print("? Es v?lida '" + query + "' ? ");
110
		
111
		if (validateExpression(query))
112
			System.out.println("Si.");
113
		else
114
			System.out.println("No.");
115
	}
116
	
117
	/**
118
	 * A test (Correct)
119
	 */
120
	public void test2() {
121
		query = new String("\"codigo\" = 'R?o de Bu?ol'");
122
		
123
		System.out.print("? Es v?lida '" + query + "' ? ");
124
		
125
		if (validateExpression(query))
126
			System.out.println("Si.");
127
		else
128
			System.out.println("No.");
129
	}
130
	
131
	/**
132
	 * A test (Correct)
133
	 */
134
	public void test3() {
135
		query = new String("\"codigo\" = 'els Banys de la Tia Joana'");
136
		
137
		System.out.print("? Es v?lida '" + query + "' ? ");
138
		
139
		if (validateExpression(query))
140
			System.out.println("Si.");
141
		else
142
			System.out.println("No.");
143
	}
144
	
145
	/**
146
	 * A test (Correct)
147
	 */
148
	public void test4() {
149
		query = new String("\"codigo\" = 'Barranc d'Adell'");
150
		
151
		System.out.print("? Es v?lida '" + query + "' ? ");
152
		
153
		if (validateExpression(query))
154
			System.out.println("Si.");
155
		else
156
			System.out.println("No.");
157
	}
158
	
159
	/**
160
	 * A test (Correct)
161
	 */
162
	public void test5() {
163
		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'");
164
		
165
		System.out.print("? Es v?lida '" + query + "' ? ");
166
		
167
		if (validateExpression(query))
168
			System.out.println("Si.");
169
		else
170
			System.out.println("No.");
171
	}
172
	
173
	/**
174
	 * A test (Correct)
175
	 */
176
	public void test6() {
177
		query = new String(""); // Without query
178
		
179
		System.out.print("? Es v?lida '" + query + "' ? ");
180
		
181
		if (validateExpression(query))
182
			System.out.println("Si.");
183
		else
184
			System.out.println("No.");
185
	}
186
	
187
	/**
188
	 * A test (Incorrect)
189
	 */
190
	public void test7() {
191
		query = new String("\"id\" = '354' and \"id\" > '697'");
192
		
193
		System.out.print("? Es v?lida '" + query + "' ? ");
194
		
195
		if (validateExpression(query))
196
			System.out.println("Si.");
197
		else
198
			System.out.println("No.");
199
	}
200
		
201
	/**
202
	 * A test (Correct)
203
	 */
204
	public void test8() {
205
		query = new String("\"elevation\" = 354 and \"elevation\" > 697");
206
		
207
		System.out.print("? Es v?lida '" + query + "' ? ");
208
		
209
		if (validateExpression(query))
210
			System.out.println("Si.");
211
		else
212
			System.out.println("No.");
213
	}	
214
	///// END TESTS /////
215
	
216
	///// METHODS RELATED WITH THE VALIDATION OF THE QUERY /////
217
	
218
	/**
219
	 * Checks the filter expression if it's correct
220
	 * 
221
	 * @param query The query expression to analyze
222
	 * @return True if it's valid or false if not
223
	 */	
224
	private boolean validateExpression(String query) {
225
		// If it's an empty query -> ok 
226
		if (query.trim().length() == 0)
227
			return true;
228
		
229
		// Replace all Date(dd-mmm-yyyy) format to ddd-mmm-yyyy (characters will replaced to spaces)
230
		int index = 0;
231
		String query_copy = new String(query);
232
		while ((index = query_copy.indexOf("Date(", index)) != -1) {
233
			if (index > 0) {
234
				if ((query_copy.charAt(index-1) != ' ') && (query_copy.charAt(index-1) != '('))
235
					break;
236
			}
237
			
238
			if (((index + 16) < query_copy.length()) && (query_copy.charAt(index + 16) == ')')) { // +17 is the length of Date(dd-mmm-yyyy)
239
				if ((index + 17) < query_copy.length()) {
240
					query_copy = query_copy.substring(0, index) + "     " + query_copy.substring(index+6, index+16) + " " + query_copy.substring(index+17);
241
				}
242
				else {
243
					query_copy = query_copy.substring(0, index) + "     " + query_copy.substring(index+6, index+16);
244
				}
245
			}
246
		}
247
		
248
		SQLQueryValidation sQLQueryValidation = new SQLQueryValidation(query_copy, true);
249

  
250
		// Tries to validate the query, and if fails shows a message
251
		if (!sQLQueryValidation.validateQuery()) {
252
			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);
253
			return false;
254
		}
255
		else {
256
			// Analyzes tokens in query
257
			StringTokenizer tokens = new StringTokenizer(query, " ");
258
			String token, token_aux;
259
			boolean finish = false;
260

  
261
			while (tokens.hasMoreTokens()) {
262
				token = tokens.nextToken().trim();
263
				
264
				if (token.charAt(0) == '\'') {
265
					if (token.charAt(token.length() -1) != '\'') {
266
						while (!finish) {
267
							if (!tokens.hasMoreTokens()) {
268
								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);
269
								return false;
270
							}
271
							else {
272
								token_aux = tokens.nextToken().trim();
273
								token += " " + token_aux;
274
								
275
								if (token_aux.charAt(token_aux.length() -1) == '\'')
276
									finish = true;
277
							}
278
						}
279
						
280
						finish = false;
281
					}
282
				}
283
				
284
				if (token.charAt(0) == '\"') {
285
					if (token.charAt(token.length() -1) != '\"') {
286
						while (!finish) {
287
							if (!tokens.hasMoreTokens()) {
288
								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);
289
								return false;
290
							}
291
							else {
292
								token_aux = tokens.nextToken().trim();
293
								token += " " + token_aux;
294
								
295
								if (token_aux.charAt(token_aux.length() -1) == '\"')
296
									finish = true;
297
							}
298
						}
299
						
300
						finish = false;
301
					}
302
				}
303

  
304
				// Tries to find an invalid token
305
				if (token.length() > 0) {
306
					// Validates if a supposed field exists
307
					if ( (token.length() > 2) && (token.charAt(0) == '\"') && (token.charAt(token.length()-1) == '\"') ) {
308
						if (! this.isAField(token.substring(1, token.length()-1))) {
309
							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);
310
							return false;
311
						}
312
					}
313
					else {
314
						// If it's an string -> ignore
315
						if (! ((token.charAt(0) == token.charAt(token.length() - 1)) && (token.charAt(0) == '\''))) {
316
							
317
							// If it's a date -> ignore
318
							int returnValue = validateDate(token);
319
							
320
							if (returnValue == 1) {
321
								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);
322
								return false;
323
							}
324
							
325
							if (returnValue == 2) {								
326
								// Else -> Checks if the current token is a valid number or symbol
327
								if ((! StringNumberUtilities.isNumber(token)) && (! this.isAnOperatorNameOrSymbol(token, getAllOperatorSymbols()))) {
328
									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);
329
									return false;
330
								}
331
							}
332
						}
333
					}
334
				}
335
			}
336

  
337
			// If has validate all tokens -> query validated
338
			return true;
339
		}
340
	}
341
	
342
	/**
343
	 * Returns true if there is a field with the same name as 'text'
344
	 * 
345
	 * @param text An string
346
	 * @return A boolean value
347
	 */
348
	private boolean isAField(String text) {
349
		return this.allFieldsAndValuesKnownOfCurrentLayer.containsKey(text);		
350
	}
351
	
352

  
353
	/**
354
	 * Returns true if there is the 'text' is a symbol or a operator name
355
	 * 
356
	 * @param text An string
357
	 * @return A boolean value
358
	 */
359
	private boolean isAnOperatorNameOrSymbol(String text, Set operatorNamesAndSymbols) {
360
		// We will ignore the case sensitive (all the rest of operators are in lower case)
361
		return operatorNamesAndSymbols.contains(text.toLowerCase());
362
	}
363
	
364
	
365
	/**
366
	 * Validates if a text has a correct date format as Date(dd-mmm-yyyy)  (Ex. Date(03-feb-2004) )
367
	 * 
368
	 * @param text
369
	 * @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
370
	 */
371
	private int validateDate(String text) {
372
		// If it's a date -> check if format is correct (Ex.  Date(01-feb-2004) )
373
		if ( ((text.length() == 17) && (text.startsWith("Date(")) && (text.endsWith(")"))) && (text.charAt(7) == '-') && (text.charAt(11) == '-') ) {
374
			if ( (StringNumberUtilities.isNaturalNumber(text.substring(5, 7))) && (StringNumberUtilities.isNaturalNumber(text.substring(12, 16))) ) {
375
				try {
376
					// If can parse the date -> date with a correct format 
377
					DateFormat.getDateInstance().parse(text.substring(5, 16));
378
					return 0;
379
				} catch (ParseException e) {
380
					// If can't parse the date -> date with an incorrect format 
381
					return 1;
382
				}
383
			}
384
			else {
385
				return 1;
386
			}
387
		}
388
		
389
		return 2;
390
	}	
391
	
392
	///// END METHODS RELATED WITH THE VALIDATION OF THE QUERY /////
393
	
394
	///// OTHER METHOD AUXILIARS /////
395
	private Set getAllOperatorSymbols() {
396
		if (_operatorSymbols == null) {
397
			// Add some operations as example
398
			_operatorSymbols = new HashSet();
399
			_operatorSymbols.add("and");
400
//			operatorSymbols.add("Date");
401
			_operatorSymbols.add("<>"); // In SQL this is the formal operator
402
			_operatorSymbols.add("!="); // This operator is also supported
403
			_operatorSymbols.add("=");
404
			_operatorSymbols.add(">=");
405
			_operatorSymbols.add("<=");
406
			_operatorSymbols.add(">");
407
			_operatorSymbols.add("not");
408
			_operatorSymbols.add("or");
409
			_operatorSymbols.add("(");
410
			_operatorSymbols.add(")");
411
			_operatorSymbols.add("<");
412
		}
413
		
414
		return _operatorSymbols;
415
	}
416

  
417
	///// END OTHER METHOD AUXILIARS /////
418
}
trunk/extensions/extWFS2/src-test/com/iver/cit/gvsig/gui/panels/TestValidationOfFilter.java
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
}
0 600

  
trunk/extensions/extWFS2/src/com/iver/cit/gvsig/gui/panels/WFSFilterPanel.java
134 134
	private TreePath currentPath;
135 135
	private String featureName;
136 136
	private Map allFieldsAndValuesKnownOfCurrentLayer; // This will have all values (not repeated) known of all fields (not repeated)
137
	private short eventsReceived; // This attribute is necessary to avoid a bug produced by the reception duplicated of an event when a layer of a WFS service is selected.
137 138

  
138 139
	///// GUI METHODS ////
139 140

  
......
414 415
			super.getValuesJList().setEnabled(false);
415 416
			super.getValuesJList().setBackground(new Color(220, 220, 220)); // a grey color
416 417

  
418
			/*
419
			 * This attribute is necessary to avoid a bug produced by the reception duplicated of an event
420
			 *  when a layer of a WFS service is selected.
421
			 */ 
422
			if ((eventsReceived % 2) == 0)
423
				this.allFieldsAndValuesKnownOfCurrentLayer.clear();
424
			
425
			eventsReceived ++;
426

  
417 427
			this.allFieldsAndValuesKnownOfCurrentLayer.clear();
418 428
			getValidateFilterExpressionJCheckBox().setSelected(true);
419 429
		}
......
430 440

  
431 441
			this.getFieldsJTree().removeAll();
432 442
			this.getValuesJList().removeAll();
443
			
444
			/*
445
			 * This attribute is necessary to avoid a bug produced by the reception duplicated of an event
446
			 *  when a layer of a WFS service is selected.
447
			 */ 
448
			eventsReceived = 0;
433 449

  
434 450
			// Updates data associated to view with the new layer data
435 451
			this.setNewDataToTable();
......
727 743
		else
728 744
			return true; // No validation done because user selected that option
729 745
	}
730

  
746
	
731 747
	/**
732 748
	 * Returns true if there is a field with the same name as 'text'
733 749
	 *

Also available in: Unified diff