1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.dbutils.wrappers;
18
19 import java.lang.reflect.InvocationHandler;
20 import java.lang.reflect.Method;
21 import java.sql.ResultSet;
22
23 import org.apache.commons.dbutils.ProxyFactory;
24
25 /**
26 * Wraps a <code>ResultSet</code> to trim strings returned by the
27 * <code>getString()</code> and <code>getObject()</code> methods.
28 *
29 * <p>
30 * Usage Example:
31 * This example shows how to decorate ResultSets so processing continues as
32 * normal but all Strings are trimmed before being returned from the
33 * <code>ResultSet</code>.
34 * </p>
35 *
36 * <pre>
37 * ResultSet rs = // somehow get a ResultSet;
38 *
39 * // Substitute wrapped ResultSet with additional behavior for real ResultSet
40 * rs = StringTrimmedResultSet.wrap(rs);
41 *
42 * // Pass wrapped ResultSet to processor
43 * List list = new BasicRowProcessor().toBeanList(rs);
44 * </pre>
45 */
46 public class StringTrimmedResultSet implements InvocationHandler {
47
48 /**
49 * The factory to create proxies with.
50 */
51 private static final ProxyFactory factory = ProxyFactory.instance();
52
53 /**
54 * Wraps the <code>ResultSet</code> in an instance of this class. This is
55 * equivalent to:
56 * <pre>
57 * ProxyFactory.instance().createResultSet(new StringTrimmedResultSet(rs));
58 * </pre>
59 *
60 * @param rs The <code>ResultSet</code> to wrap.
61 * @return wrapped ResultSet
62 */
63 public static ResultSet wrap(ResultSet rs) {
64 return factory.createResultSet(new StringTrimmedResultSet(rs));
65 }
66
67 /**
68 * The wrapped result.
69 */
70 private final ResultSet rs;
71
72 /**
73 * Constructs a new instance of <code>StringTrimmedResultSet</code>
74 * to wrap the specified <code>ResultSet</code>.
75 * @param rs ResultSet to wrap
76 */
77 public StringTrimmedResultSet(ResultSet rs) {
78 super();
79 this.rs = rs;
80 }
81
82 /**
83 * Intercept calls to the <code>getString()</code> and
84 * <code>getObject()</code> methods and trim any Strings before they're
85 * returned.
86 *
87 * @throws Throwable
88 * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
89 */
90 public Object invoke(Object proxy, Method method, Object[] args)
91 throws Throwable {
92
93 Object result = method.invoke(this.rs, args);
94
95 if (method.getName().equals("getObject")
96 || method.getName().equals("getString")) {
97
98 if (result instanceof String) {
99 result = ((String) result).trim();
100 }
101 }
102
103 return result;
104 }
105
106 }