KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sapia > util > xml > idefix > serializer > DynamicSerializer


1 package org.sapia.util.xml.idefix.serializer;
2
3
4 //import org.apache.log4j.Logger;
5
import org.sapia.util.xml.Namespace;
6 import org.sapia.util.xml.idefix.SerializationContext;
7 import org.sapia.util.xml.idefix.SerializationException;
8 import org.sapia.util.xml.idefix.SerializerIF;
9 import org.sapia.util.xml.idefix.SerializerNotFoundException;
10
11 import java.lang.reflect.InvocationTargetException JavaDoc;
12 import java.lang.reflect.Method JavaDoc;
13 import java.lang.reflect.Modifier JavaDoc;
14
15 import java.util.ArrayList JavaDoc;
16 import java.util.Iterator JavaDoc;
17 import java.util.List JavaDoc;
18
19
20 /**
21  * this implementation of the <code>SerializerIF</code> interface uses reflection
22  * to serialize the object passed to it.
23  *
24  * @author <a HREF="mailto:jc@sapia-oss.org">Jean-Cedric Desrochers</a>
25  * <dl>
26  * <dt><b>Copyright:</b><dd>Copyright &#169; 2002-2003 <a HREF="http://www.sapia-oss.org">Sapia Open Source Software</a>. All Rights Reserved.</dd></dt>
27  * <dt><b>License:</b><dd>Read the license.txt file of the jar or visit the
28  * <a HREF="http://www.sapia-oss.org/license.html" target="sapia-license">license page</a> at the Sapia OSS web site</dd></dt>
29  * </dl>
30  */

31 public class DynamicSerializer implements SerializerIF {
32   /** Defines an empty immutable list. */
33   private static final List JavaDoc EMPTY_LIST = new ArrayList JavaDoc(0);
34
35   /** Defines an empty Class array. */
36   private static final Class JavaDoc[] EMPTY_CLASS_ARRAY = new Class JavaDoc[0];
37
38   /** Define the logger instance of this class. */
39
40   /*private static final Logger _theLogger =
41           Logger.getLogger(DynamicSerializer.class);*/

42
43   /**
44    * Creates a new DynamicSerializer instance.
45    */

46   public DynamicSerializer() {
47     super();
48   }
49
50   /**
51    * Transforms the object passed in into an XML representation.
52    *
53    * @param anObject The object to serialize.
54    * @param aContext The serialization context to use.
55    * @exception SerializationException If an error occurs serializing the object.
56    */

57   public void serialize(Object JavaDoc anObject, SerializationContext aContext)
58     throws SerializationException {
59     // Define the name of the XML element
60
String JavaDoc aRootElementName = getObjectName(anObject.getClass());
61
62     // Define the namespace of the XML element
63
Namespace aRootNamespace = aContext.getNamespaceFactory().getNamespaceFor(anObject.getClass());
64
65     // Serialize the object with the extracted values
66
serialize(anObject, aRootNamespace, aRootElementName, aContext);
67   }
68
69   /**
70    * Transforms the object passed in into an XML representation. This method is called when the
71    * object to transform is nested inside another object.
72    *
73    * @param anObject The object to serialize.
74    * @param aNamespace The namespace of the object to serialize.
75    * @param anObjectName The name of the object to serialize.
76    * @param aContext The serialization context to use.
77    * @exception SerializationException If an error occurs serializing the object.
78    */

79   public void serialize(Object JavaDoc anObject, Namespace aNamespace,
80     String JavaDoc anObjectName, SerializationContext aContext)
81     throws SerializationException {
82     // Start the XML element
83
aContext.getXmlBuffer().addNamespace(aNamespace.getURI(),
84       aNamespace.getPrefix());
85     aContext.getXmlBuffer().startElement(aNamespace.getURI(), anObjectName);
86
87     Method JavaDoc aMethod = null;
88
89     try {
90       // Extract all the methods of the objects
91
List JavaDoc someMethods = getMatchingMethods(anObject);
92
93       // Walk though the object tree
94
for (Iterator JavaDoc it = someMethods.iterator(); it.hasNext();) {
95         aMethod = (Method JavaDoc) it.next();
96
97         // Extracting the value of the method
98
Object JavaDoc aMethodValue = aMethod.invoke(anObject, EMPTY_CLASS_ARRAY);
99
100         if (aMethodValue != null) {
101           // Define the object name
102
String JavaDoc aMethodName = getObjectName(aMethod);
103
104           // Define the namespace of the XML element
105
Namespace aMethodNamespace = aContext.getNamespaceFactory()
106                                                .getNamespaceFor(aMethodValue.getClass());
107
108           // Get a serializer for the object
109
SerializerIF aSerializer = aContext.getSerializerFactory()
110                                              .getSerializer(aMethodValue.getClass());
111
112           // Serialize the object
113
aSerializer.serialize(aMethodValue, aMethodNamespace, aMethodName,
114             aContext);
115         }
116       }
117     } catch (IllegalAccessException JavaDoc iae) {
118       String JavaDoc aMessage = "Unable to extract the value of the method: " +
119         aMethod;
120
121       //_theLogger.error(aMessage, iae);
122
throw new SerializationException(aMessage, iae);
123     } catch (InvocationTargetException JavaDoc ite) {
124       String JavaDoc aMessage = "Error calling the method: " + aMethod;
125
126       //_theLogger.error(aMessage, ite);
127
throw new SerializationException(aMessage, ite);
128     } catch (SerializerNotFoundException snfe) {
129       String JavaDoc aMessage = "Unable to found a serializer for the method: " +
130         aMethod;
131
132       //_theLogger.error(aMessage, snfe);
133
throw new SerializationException(aMessage, snfe);
134     }
135
136     // End the XML element
137
aContext.getXmlBuffer().endElement(aNamespace.getURI(), anObjectName);
138     aContext.getXmlBuffer().removeNamespace(aNamespace.getURI());
139   }
140
141   /**
142    * Returns the list of methods of the object passed in that should be
143    * introspected to perform the serialization of the object.
144    *
145    * @param anObject The object from which to retrieve the methods.
146    * @return A list of <code>Method</code> objects.
147    */

148   private List JavaDoc getMatchingMethods(Object JavaDoc anObject) {
149     if (anObject == null) {
150       return EMPTY_LIST;
151     }
152
153     Class JavaDoc aClass = anObject.getClass();
154     Method JavaDoc[] allMethods = aClass.getMethods(); // get all public methods
155
ArrayList JavaDoc someMatchingMethods = new ArrayList JavaDoc(allMethods.length);
156
157     for (int i = 0; i < allMethods.length; i++) {
158       Method JavaDoc aMethod = allMethods[i];
159
160       if ((aMethod.getName().startsWith("get") || // starts with 'get'
161
aMethod.getName().startsWith("is")) && // or 'is'
162
!aMethod.getName().equals("getClass") && // the method is not getClass()
163
!Modifier.isStatic(aMethod.getModifiers()) && // not static
164
(aMethod.getParameterTypes().length == 0) && // has no parameter
165
(aMethod.getReturnType() != Void.TYPE)) { // do not return void
166
someMatchingMethods.add(aMethod);
167       }
168     }
169
170     return someMatchingMethods;
171   }
172
173   /**
174    *
175    * @param aClass
176    * @return
177    */

178   private String JavaDoc getObjectName(Class JavaDoc aClass) {
179     String JavaDoc aQualifiedClassName = aClass.getName();
180     String JavaDoc aPackageName = aClass.getPackage().getName();
181     String JavaDoc aLocalClassName = aQualifiedClassName.substring(aPackageName.length() +
182         1);
183
184     return aLocalClassName;
185   }
186
187   /**
188    *
189    * @param aMethod
190    * @return
191    */

192   private String JavaDoc getObjectName(Method JavaDoc aMethod) {
193     int aPrefixLength = 0;
194     String JavaDoc aMethodName = aMethod.getName();
195
196     if (aMethodName.startsWith("get")) {
197       aPrefixLength = 3;
198     } else if (aMethodName.startsWith("is")) {
199       aPrefixLength = 2;
200     } else {
201       throw new IllegalArgumentException JavaDoc(
202         "The method name does not starts with \'get\' or \'is\'");
203     }
204
205     String JavaDoc anObjectName = SerializerHelper.firstToUpperFromIndex(aMethodName,
206         aPrefixLength);
207
208     return anObjectName;
209   }
210 }
211
Popular Tags