1 package net.sourceforge.jparam.output;
2
3 import java.io.PrintStream;
4 import java.lang.reflect.Method;
5 import java.lang.reflect.Modifier;
6 import java.util.Iterator;
7 import java.util.List;
8
9 import net.sourceforge.jparam.JParam;
10 import net.sourceforge.jparam.JParamException;
11 import net.sourceforge.jparam.typename.TypeNameRegistry;
12 import net.sourceforge.jparam.util.Utils;
13
14 public class OutputMethodSerializer implements ISerializer {
15 Method m;
16 Class supportedClass;
17
18 public OutputMethodSerializer(Method m) {
19 this.m = m;
20 String validationError = getMethodValidError(m);
21 Utils.assert(validationError == null, validationError);
22
23 supportedClass = m.getParameterTypes()[0];
24 }
25
26
27
28
29 public Class getSupportedClass() {
30 return supportedClass;
31 }
32
33 public void serialize(Object obj, PrintStream out) throws JParamException {
34 String typeName = null;
35 TypeNameRegistry tnr = TypeNameRegistry.getInstance();
36 typeName = tnr.getJParamTypeName(obj.getClass());
37
38 Utils.assert(typeName != null,
39 "Class not registered for JParam type, class: "
40 + obj.getClass().getName());
41 try {
42 out.print(typeName + "(");
43 List subObjects = getSubObjects(obj);
44
45 if (subObjects != null && subObjects.size() > 0) {
46 boolean first = true;
47 for (Iterator iter = subObjects.iterator(); iter.hasNext();) {
48 Object element = iter.next();
49
50 if (!first) {
51 out.print(", ");
52 } else {
53 first = false;
54 }
55
56 JParam.writeObject(element, out);
57 }
58 }
59 } catch (Exception e) {
60 throw new JParamException("Error serializing subobjects for: "
61 + obj, e);
62 }
63
64
65
66
67
68
69 out.print(")");
70 }
71
72 public List getSubObjects(Object obj) throws Exception {
73 Utils.assert(supportedClass.isAssignableFrom(obj.getClass()),
74 "Invalid object supplied to serialized, supported class: "
75 + supportedClass.getName() + " arguments type: "
76 + obj.getClass().getName());
77 List ret = (List) m.invoke(null, new Object[] { obj });
78 return ret;
79 }
80
81 public static String getMethodValidError(Method m) {
82 if (!m.getName().equals("output"))
83 return "Output method name must be \"output\", method: " + m;
84 if (!List.class.isAssignableFrom(m.getReturnType()))
85 return "Output method must return a List, method: " + m;
86 if (m.getParameterTypes().length != 1)
87 return "Output method parameter must be a single object, method: "
88 + m;
89 if (!Modifier.isStatic(m.getModifiers()))
90 return "Output method must be static, method: " + m;
91 return null;
92 }
93
94 public static boolean isMethodValid(Method m) {
95 return getMethodValidError(m) == null;
96 }
97
98 public String toString() {
99 return "Output method serializer for type: "
100 + getSupportedClass().getName() + " using method: " + m;
101 }
102
103 }