1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 package org.osjava.sj.loader.convert;
34
35 import java.util.Properties;
36 import java.util.Iterator;
37 import java.util.List;
38
39 import java.lang.reflect.Method;
40 import java.lang.reflect.InvocationTargetException;
41
42 /***
43 * Create an object using its empty constructor, then
44 * call setXxx for each pseudo property. Only String
45 * properties are supported.
46 *
47 * <pre>
48 * Foo.name=Arthur
49 * Foo.answer=42
50 * Foo.type=com.example.Person
51 * Foo.converter=org.osjava.sj.loader.convert.BeanConverter
52 * </pre>
53 */
54 public class BeanConverter implements Converter {
55
56 public Object convert(Properties properties, String type) {
57 String value = properties.getProperty("");
58
59 if(value != null) {
60 throw new RuntimeException("Specify the value as a pseudo property as Beans have empty constructors");
61 }
62
63 String methodName = null;
64
65 try {
66 Class c = Class.forName(type);
67 Object bean = c.newInstance();
68 Iterator itr = properties.keySet().iterator();
69 while(itr.hasNext()) {
70 String key = (String) itr.next();
71 if("converter".equals(key) || "type".equals(key)) {
72 continue;
73 }
74 Object property = properties.get(key);
75 if(property instanceof String) {
76 methodName = "set" + Character.toTitleCase(key.charAt(0)) + key.substring(1);
77 Method m = c.getMethod(methodName, new Class[] { String.class });
78 m.invoke(bean, new Object[] { (String) property });
79 } else
80 if(property instanceof List) {
81 List list = (List) property;
82 int sz = list.size();
83 key = "add" + Character.toTitleCase(key.charAt(0)) + key.substring(1);
84 Method m = c.getMethod(key, new Class[] { Integer.TYPE, String.class });
85 for(int i=0; i<sz; i++) {
86 Object item = list.get(i);
87 if(item instanceof String) {
88 m.invoke(bean, new Object[] { new Integer(i), (String) item });
89 } else {
90 throw new RuntimeException("Only Strings and Lists of String are supported");
91 }
92 }
93 } else {
94 throw new RuntimeException("Only Strings and Lists of Strings are supported");
95 }
96 }
97 return bean;
98 } catch(ClassNotFoundException cnfe) {
99 throw new RuntimeException("Unable to find class: "+type, cnfe);
100 } catch(NoSuchMethodException nsme) {
101 throw new RuntimeException("Unable to find method " + methodName + " on class: "+type, nsme);
102 } catch(InstantiationException ie) {
103 throw new RuntimeException("Unable to instantiate class: "+type, ie);
104 } catch(IllegalAccessException ie) {
105 throw new RuntimeException("Unable to access class: "+type, ie);
106 } catch(IllegalArgumentException iae) {
107 throw new RuntimeException("Unable to pass argument to class: "+type, iae);
108 } catch(InvocationTargetException ite) {
109 throw new RuntimeException("Unable to invoke (String) constructor on class: "+type, ite);
110 }
111
112 }
113
114 }