1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.oness.common.webapp.controller.util;
17
18 import org.apache.commons.beanutils.ConvertUtils;
19 import org.apache.commons.beanutils.Converter;
20
21 /***
22 * Converter that transforms empty strings in a <code>null</code> value and
23 * delegates to another converter otherwise.
24 *
25 * @author Carlos Sanchez
26 * @version $Revision: 1.1 $
27 */
28 public class NonEmptyStringConverter implements Converter {
29
30 private static final Class[] CLASSES = { String.class, Integer.class,
31 Long.class };
32
33 private Converter converter;
34
35 /***
36 * Register this converter in <code>ConvertUtils</code> using previous
37 * registered converter as delegated, for the following classes:
38 * <ul>
39 * <li><code>String</code></li>
40 * </ul>
41 */
42 public static void register() {
43 for (int i = 0; i < CLASSES.length; i++) {
44 Converter oldConverter = ConvertUtils.lookup(CLASSES[i]);
45 ConvertUtils.register(new NonEmptyStringConverter(oldConverter),
46 CLASSES[i]);
47 }
48 }
49
50 /***
51 * Deregister this converter in <code>ConvertUtils</code> and reset old
52 * converters.
53 */
54 public static void deregister() {
55 for (int i = 0; i < CLASSES.length; i++) {
56 Converter oldConverter = ConvertUtils.lookup(CLASSES[i]);
57 if (oldConverter instanceof NonEmptyStringConverter) {
58 NonEmptyStringConverter converter = (NonEmptyStringConverter) oldConverter;
59 ConvertUtils.register(converter.converter, CLASSES[i]);
60 }
61 }
62 }
63
64 /***
65 *
66 * @param converter
67 * Delegate converter
68 */
69 public NonEmptyStringConverter(Converter converter) {
70 this.converter = converter;
71 }
72
73 /***
74 * If the value is an empty String then <code>null</code> is returned,
75 * else the call is delegated to the converter specified at creation.
76 *
77 * @see org.apache.commons.beanutils.Converter#convert(java.lang.Class,
78 * java.lang.Object)
79 */
80 public Object convert(Class type, Object value) {
81 if (value instanceof String) {
82 String s = (String) value;
83 if (s.length() == 0)
84 return null;
85 }
86 return converter.convert(type, value);
87 }
88
89 }