KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > axis > encoding > ser > SimpleSerializer


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 2001-2003 The Apache Software Foundation. All rights
6  * reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  * notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  * notice, this list of conditions and the following disclaimer in
17  * the documentation and/or other materials provided with the
18  * distribution.
19  *
20  * 3. The end-user documentation included with the redistribution,
21  * if any, must include the following acknowledgment:
22  * "This product includes software developed by the
23  * Apache Software Foundation (http://www.apache.org/)."
24  * Alternately, this acknowledgment may appear in the software itself,
25  * if and wherever such third-party acknowledgments normally appear.
26  *
27  * 4. The names "Axis" and "Apache Software Foundation" must
28  * not be used to endorse or promote products derived from this
29  * software without prior written permission. For written
30  * permission, please contact apache@apache.org.
31  *
32  * 5. Products derived from this software may not be called "Apache",
33  * nor may "Apache" appear in their name, without prior written
34  * permission of the Apache Software Foundation.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This software consists of voluntary contributions made by many
51  * individuals on behalf of the Apache Software Foundation. For more
52  * information on the Apache Software Foundation, please see
53  * <http://www.apache.org/>.
54  */

55
56 package org.jboss.axis.encoding.ser;
57
58 import org.jboss.axis.AxisFault;
59 import org.jboss.axis.Constants;
60 import org.jboss.axis.description.FieldDesc;
61 import org.jboss.axis.description.TypeDesc;
62 import org.jboss.axis.encoding.SerializationContext;
63 import org.jboss.axis.encoding.SimpleType;
64 import org.jboss.axis.encoding.SimpleValueSerializer;
65 import org.jboss.axis.utils.BeanPropertyDescriptor;
66 import org.jboss.axis.utils.BeanUtils;
67 import org.jboss.axis.utils.Messages;
68 import org.jboss.axis.wsdl.fromJava.Types;
69 import org.w3c.dom.Element JavaDoc;
70 import org.xml.sax.Attributes JavaDoc;
71 import org.xml.sax.helpers.AttributesImpl JavaDoc;
72
73 import javax.xml.namespace.QName JavaDoc;
74 import java.io.IOException JavaDoc;
75
76 /**
77  * Serializer for primitives and anything simple whose value is obtained with toString()
78  *
79  * @author Rich Scheuerle <dims@yahoo.com>
80  */

81 public class SimpleSerializer implements SimpleValueSerializer
82 {
83    public QName JavaDoc xmlType;
84    public Class JavaDoc javaType;
85
86    private BeanPropertyDescriptor[] propertyDescriptor = null;
87    private TypeDesc typeDesc = null;
88
89    public SimpleSerializer(Class JavaDoc javaType, QName JavaDoc xmlType)
90    {
91       this.xmlType = xmlType;
92       this.javaType = javaType;
93       init();
94    }
95
96    public SimpleSerializer(Class JavaDoc javaType, QName JavaDoc xmlType, TypeDesc typeDesc)
97    {
98       this.xmlType = xmlType;
99       this.javaType = javaType;
100       this.typeDesc = typeDesc;
101       init();
102    }
103
104    /**
105     * Initialize the typeDesc and propertyDescriptor array.
106     */

107    private void init()
108    {
109       // The typeDesc and propertyDescriptor array are only necessary
110
// if this class extends SimpleType.
111
if (SimpleType.class.isAssignableFrom(javaType))
112       {
113          // Set the typeDesc if not already set
114
if (typeDesc == null)
115          {
116             typeDesc = TypeDesc.getTypeDescForClass(javaType);
117          }
118          // Get the cached propertyDescriptor from the type or
119
// generate a fresh one.
120
if (typeDesc != null)
121          {
122             propertyDescriptor = typeDesc.getPropertyDescriptors();
123          }
124          else
125          {
126             propertyDescriptor = BeanUtils.getPd(javaType, null);
127          }
128       }
129    }
130
131    /**
132     * Serialize a primitive or simple value.
133     * If the object to serialize is a primitive, the Object value below
134     * is the associated java.lang class.
135     * To determine if the original value is a java.lang class or a primitive, consult
136     * the javaType class.
137     */

138    public void serialize(QName JavaDoc name, Attributes JavaDoc attributes,
139                          Object JavaDoc value, SerializationContext context)
140            throws IOException JavaDoc
141    {
142       if (value != null && value.getClass() == java.lang.Object JavaDoc.class)
143       {
144          throw new IOException JavaDoc(Messages.getMessage("cantSerialize02"));
145       }
146
147       // get any attributes
148
if (value instanceof SimpleType)
149          attributes = getObjectAttributes(value, attributes, context);
150
151
152       if (name != null)
153          context.startElement(name, attributes);
154
155       if (value != null)
156          context.writeSafeString(getValueAsString(value, context));
157
158       if (name != null)
159          context.endElement();
160    }
161
162    public String JavaDoc getValueAsString(Object JavaDoc value, SerializationContext context)
163    {
164       // We could have separate serializers/deserializers to take
165
// care of Float/Double cases, but it makes more sence to
166
// put them here with the rest of the java lang primitives.
167
if (value instanceof Float JavaDoc ||
168               value instanceof Double JavaDoc)
169       {
170          double data = 0.0;
171          if (value instanceof Float JavaDoc)
172          {
173             data = ((Float JavaDoc)value).doubleValue();
174          }
175          else
176          {
177             data = ((Double JavaDoc)value).doubleValue();
178          }
179          if (Double.isNaN(data))
180          {
181             return "NaN";
182          }
183          else if (data == Double.POSITIVE_INFINITY)
184          {
185             return "INF";
186          }
187          else if (data == Double.NEGATIVE_INFINITY)
188          {
189             return "-INF";
190          }
191       }
192
193       return value.toString();
194    }
195
196    private Attributes JavaDoc getObjectAttributes(Object JavaDoc value,
197                                           Attributes JavaDoc attributes,
198                                           SerializationContext context)
199    {
200       if (typeDesc == null || !typeDesc.hasAttributes())
201          return attributes;
202
203       AttributesImpl JavaDoc attrs;
204       if (attributes == null)
205       {
206          attrs = new AttributesImpl JavaDoc();
207       }
208       else if (attributes instanceof AttributesImpl JavaDoc)
209       {
210          attrs = (AttributesImpl JavaDoc)attributes;
211       }
212       else
213       {
214          attrs = new AttributesImpl JavaDoc(attributes);
215       }
216
217       try
218       {
219          // Find each property that is an attribute
220
// and add it to our attribute list
221
for (int i = 0; i < propertyDescriptor.length; i++)
222          {
223             String JavaDoc propName = propertyDescriptor[i].getName();
224             if (propName.equals("class"))
225                continue;
226
227             FieldDesc field = typeDesc.getFieldByName(propName);
228             // skip it if its not an attribute
229
if (field == null || field.isElement())
230                continue;
231
232             QName JavaDoc qname = field.getXmlName();
233             if (qname == null)
234             {
235                qname = new QName JavaDoc("", propName);
236             }
237
238             if (propertyDescriptor[i].isReadable() &&
239                     !propertyDescriptor[i].isIndexed())
240             {
241                // add to our attributes
242
Object JavaDoc propValue = propertyDescriptor[i].get(value);
243                // If the property value does not exist, don't serialize
244
// the attribute. In the future, the decision to serializer
245
// the attribute may be more sophisticated. For example, don't
246
// serialize if the attribute matches the default value.
247
if (propValue != null)
248                {
249                   String JavaDoc propString = getValueAsString(propValue, context);
250
251                   String JavaDoc namespace = qname.getNamespaceURI();
252                   String JavaDoc localName = qname.getLocalPart();
253
254                   attrs.addAttribute(namespace,
255                           localName,
256                           context.qName2String(qname),
257                           "CDATA",
258                           propString);
259                }
260             }
261          }
262       }
263       catch (Exception JavaDoc e)
264       {
265          // no attributes
266
return attrs;
267       }
268
269       return attrs;
270    }
271
272    public String JavaDoc getMechanismType()
273    {
274       return Constants.AXIS_SAX;
275    }
276
277    /**
278     * Return XML schema for the specified type, suitable for insertion into
279     * the &lt;types&gt; element of a WSDL document, or underneath an
280     * &lt;element&gt; or &lt;attribute&gt; declaration.
281     *
282     * @param javaType the Java Class we're writing out schema for
283     * @param types the Java2WSDL Types object which holds the context
284     * for the WSDL being generated.
285     * @return a type element containing a schema simpleType/complexType
286     * @see org.jboss.axis.wsdl.fromJava.Types
287     */

288    public Element JavaDoc writeSchema(Class JavaDoc javaType, Types types) throws Exception JavaDoc
289    {
290       // Let the caller generate WSDL if this is not a SimpleType
291
if (!SimpleType.class.isAssignableFrom(javaType))
292          return null;
293
294       // ComplexType representation of SimpleType bean class
295
Element JavaDoc complexType = types.createElement("complexType");
296       types.writeSchemaElement(xmlType, complexType);
297       complexType.setAttribute("name", xmlType.getLocalPart());
298
299       // Produce simpleContent extending base type.
300
Element JavaDoc simpleContent = types.createElement("simpleContent");
301       complexType.appendChild(simpleContent);
302       Element JavaDoc extension = types.createElement("extension");
303       simpleContent.appendChild(extension);
304
305       // Get the base type from the "value" element of the bean
306
String JavaDoc base = "string";
307       for (int i = 0; i < propertyDescriptor.length; i++)
308       {
309          String JavaDoc propName = propertyDescriptor[i].getName();
310          if (!propName.equals("value"))
311          {
312             if (typeDesc != null)
313             {
314                FieldDesc field = typeDesc.getFieldByName(propName);
315                if (field != null)
316                {
317                   if (field.isElement())
318                   {
319                      // throw?
320
}
321                   QName JavaDoc qname = field.getXmlName();
322                   if (qname == null)
323                   {
324                      // Use the default...
325
qname = new QName JavaDoc("", propName);
326                   }
327
328                   // write attribute element
329
Class JavaDoc fieldType = propertyDescriptor[i].getType();
330
331                   // Attribute must be a simple type, enums or SimpleType
332
if (!types.isAcceptableAsAttribute(fieldType))
333                   {
334                      throw new AxisFault(Messages.getMessage("AttrNotSimpleType00",
335                              propName,
336                              fieldType.getName()));
337                   }
338
339                   // write attribute element
340
// TODO the attribute name needs to be preserved from the XML
341
Element JavaDoc elem = types.createAttributeElement(propName,
342                           fieldType,
343                           field.getXmlType(),
344                           false,
345                           extension.getOwnerDocument());
346                   extension.appendChild(elem);
347                }
348             }
349             continue;
350          }
351
352          BeanPropertyDescriptor bpd = propertyDescriptor[i];
353          Class JavaDoc type = bpd.getType();
354          // Attribute must extend a simple type, enums or SimpleType
355
if (!types.isAcceptableAsAttribute(type))
356          {
357             throw new AxisFault(Messages.getMessage("AttrNotSimpleType01",
358                     type.getName()));
359          }
360          base = types.writeType(type);
361          extension.setAttribute("base", base);
362       }
363
364       // done
365
return complexType;
366
367    }
368 }
369
Popular Tags