Revision 9704

View differences:

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
	
215
	///// END TESTS /////
216
	
217
	///// METHODS RELATED WITH THE VALIDATION OF THE QUERY /////
218
	
219
	/**
220
	 * Checks the filter expression if it's correct
221
	 * 
222
	 * @param query The query expression to analyze
223
	 * @return True if it's valid or false if not
224
	 */	
225
	private boolean validateExpression(String query) {
226
		// If it's an empty query -> ok 
227
		if (query.trim().length() == 0)
228
			return true;
229
		
230
		// Replace all Date(dd-mmm-yyyy) format to ddd-mmm-yyyy (characters will replaced to spaces)
231
		int index = 0;
232
		String query_copy = new String(query);
233
		while ((index = query_copy.indexOf("Date(", index)) != -1) {
234
			if (index > 0) {
235
				if ((query_copy.charAt(index-1) != ' ') && (query_copy.charAt(index-1) != '('))
236
					break;
237
			}
238
			
239
			if (((index + 16) < query_copy.length()) && (query_copy.charAt(index + 16) == ')')) { // +17 is the length of Date(dd-mmm-yyyy)
240
				if ((index + 17) < query_copy.length()) {
241
					query_copy = query_copy.substring(0, index) + "     " + query_copy.substring(index+6, index+16) + " " + query_copy.substring(index+17);
242
				}
243
				else {
244
					query_copy = query_copy.substring(0, index) + "     " + query_copy.substring(index+6, index+16);
245
				}
246
			}
247
		}
248
		
249
		SQLQueryValidation sQLQueryValidation = new SQLQueryValidation(query_copy, true);
250

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

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

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

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

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

  
418
	///// END OTHER METHOD AUXILIARS /////
419
}
0 420

  

Also available in: Unified diff