01: package dinamica.validators;
02:
03: import java.util.HashMap;
04: import javax.servlet.http.HttpServletRequest;
05: import dinamica.*;
06:
07: /**
08: * This validator transforms the value (if not null) of the corresponding
09: * parameter, by appending a '%' at the end of the text or by enclosing the
10: * the value between '%' characters.<br>
11: * It is used to create search patterns for SQL queries like 'value starts with..' that can
12: * be used in sql LIKE expressions. Always returns TRUE.<br>
13: * As a preventtive measure, all occurrences of the '%' character in the parameter's value
14: * will be erased before applying the transformation.
15: * <br><br>
16: * Requires the following custom attributes:<br>
17: * <ul>
18: * <li> parameter: Name of the request parameter to transform. This parameter
19: * MUST be defined in validator.xml and must be of type VARCHAR.
20: * <li> rule: a string that denotes the possible transformation, accepted
21: * values are 'like' and 'contains'.
22: * </ul>
23: *
24: * (c) 2005 Martin Cordova<br>
25: * This code is released under the LGPL license<br>
26: * Dinamica Framework - http://www.martincordova.com<br>
27: * @author Martin Cordova (dinamica@martincordova.com)
28: * */
29: public class SQLPatternTransformer extends AbstractValidator {
30:
31: /* (non-Javadoc)
32: * @see dinamica.AbstractValidator#isValid(javax.servlet.http.HttpServletRequest, dinamica.Recordset, java.util.HashMap)
33: */
34: public boolean isValid(HttpServletRequest req,
35: Recordset inputParams, HashMap<String, String> attribs)
36: throws Throwable {
37:
38: boolean bParam = attribs.containsKey("parameter");
39: if (!bParam)
40: throw new Throwable(
41: "["
42: + this .getClass().getName()
43: + "] Missing attribute [parameter] in validator.xml");
44:
45: boolean bRule = attribs.containsKey("rule");
46: if (!bRule)
47: throw new Throwable("[" + this .getClass().getName()
48: + "] Missing attribute [rule] in validator.xml");
49:
50: String rule = (String) attribs.get("rule");
51:
52: if (!rule.equalsIgnoreCase("like")
53: && !rule.equalsIgnoreCase("contains"))
54: throw new Throwable(
55: "["
56: + this .getClass().getName()
57: + "] Invalid attribute value [rule] in validator.xml: "
58: + rule
59: + " - Accepted values are 'like' or 'contains'");
60:
61: String paramName = (String) attribs.get("parameter");
62: if (!inputParams.isNull(paramName)) {
63: String value = inputParams.getString(paramName);
64: value = StringUtil.replace(value, "%", "");
65: if (rule.equalsIgnoreCase("like"))
66: value = value + "%";
67: if (rule.equalsIgnoreCase("contains"))
68: value = "%" + value + "%";
69: inputParams.setValue(paramName, value);
70: } else {
71: boolean x = attribs.containsKey("ifnull");
72: if (x) {
73: String value = (String) attribs.get("ifnull");
74: inputParams.setValue(paramName, value);
75: }
76: }
77:
78: return true;
79: }
80:
81: }
|