KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * Copyright 2001-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.apache.axis.encoding.ser;
18
19 import org.apache.axis.AxisFault;
20 import org.apache.axis.Constants;
21 import org.apache.axis.description.FieldDesc;
22 import org.apache.axis.description.TypeDesc;
23 import org.apache.axis.encoding.SerializationContext;
24 import org.apache.axis.encoding.SimpleValueSerializer;
25 import org.apache.axis.encoding.SimpleType;
26 import org.apache.axis.utils.BeanPropertyDescriptor;
27 import org.apache.axis.utils.BeanUtils;
28 import org.apache.axis.utils.Messages;
29 import org.apache.axis.utils.JavaUtils;
30 import org.apache.axis.wsdl.fromJava.Types;
31 import org.w3c.dom.Element JavaDoc;
32 import org.xml.sax.Attributes JavaDoc;
33 import org.xml.sax.helpers.AttributesImpl JavaDoc;
34
35 import javax.xml.namespace.QName JavaDoc;
36 import java.io.IOException JavaDoc;
37
38 /**
39  * Serializer for primitives and anything simple whose value is obtained with toString()
40  *
41  * @author Rich Scheuerle <dims@yahoo.com>
42  */

43 public class SimpleSerializer implements SimpleValueSerializer {
44     public QName JavaDoc xmlType;
45     public Class JavaDoc javaType;
46
47     private BeanPropertyDescriptor[] propertyDescriptor = null;
48     private TypeDesc typeDesc = null;
49     public static final String JavaDoc VALUE_PROPERTY = "_value";
50
51     public SimpleSerializer(Class JavaDoc javaType, QName JavaDoc xmlType) {
52         this.xmlType = xmlType;
53         this.javaType = javaType;
54         init();
55     }
56     public SimpleSerializer(Class JavaDoc javaType, QName JavaDoc xmlType, TypeDesc typeDesc) {
57         this.xmlType = xmlType;
58         this.javaType = javaType;
59         this.typeDesc = typeDesc;
60         init();
61     }
62
63    /**
64     * Initialize the typeDesc and propertyDescriptor array.
65     */

66     private void init() {
67         // Set the typeDesc if not already set
68
if (typeDesc == null) {
69             typeDesc = TypeDesc.getTypeDescForClass(javaType);
70         }
71         // Get the cached propertyDescriptor from the type or
72
// generate a fresh one.
73
if (typeDesc != null) {
74             propertyDescriptor = typeDesc.getPropertyDescriptors();
75         } else if (!JavaUtils.isBasic(javaType)) {
76             propertyDescriptor = BeanUtils.getPd(javaType, null);
77         }
78     }
79
80     /**
81      * Serialize a primitive or simple value.
82      * If the object to serialize is a primitive, the Object value below
83      * is the associated java.lang class.
84      * To determine if the original value is a java.lang class or a primitive, consult
85      * the javaType class.
86      */

87     public void serialize(QName JavaDoc name, Attributes JavaDoc attributes,
88                           Object JavaDoc value, SerializationContext context)
89         throws IOException JavaDoc
90     {
91         if (value != null && value.getClass() == java.lang.Object JavaDoc.class) {
92             throw new IOException JavaDoc(Messages.getMessage("cantSerialize02"));
93         }
94
95         // get any attributes
96
attributes = getObjectAttributes(value, attributes, context);
97
98         String JavaDoc valueStr = null;
99         if (value != null) {
100             valueStr = getValueAsString(value, context);
101         }
102         context.startElement(name, attributes);
103         if (valueStr != null) {
104             context.writeSafeString(valueStr);
105         }
106         context.endElement();
107     }
108
109     public String JavaDoc getValueAsString(Object JavaDoc value, SerializationContext context) {
110         // We could have separate serializers/deserializers to take
111
// care of Float/Double cases, but it makes more sence to
112
// put them here with the rest of the java lang primitives.
113
if (value instanceof Float JavaDoc ||
114             value instanceof Double JavaDoc) {
115             double data = 0.0;
116             if (value instanceof Float JavaDoc) {
117                 data = ((Float JavaDoc) value).doubleValue();
118             } else {
119                 data = ((Double JavaDoc) value).doubleValue();
120             }
121             if (Double.isNaN(data)) {
122                 return "NaN";
123             } else if (data == Double.POSITIVE_INFINITY) {
124                 return "INF";
125             } else if (data == Double.NEGATIVE_INFINITY) {
126                 return "-INF";
127             }
128         } else if (value instanceof QName JavaDoc) {
129             return context.qName2String((QName JavaDoc)value);
130         }
131
132         if (propertyDescriptor != null && !(value instanceof SimpleType)) {
133             BeanPropertyDescriptor pd = BeanUtils.getSpecificPD(propertyDescriptor, "_value");
134             if(pd != null) {
135                 try {
136                     return pd.get(value).toString();
137                 } catch (Exception JavaDoc e) {
138                 }
139             }
140         }
141         return value.toString();
142     }
143
144     private Attributes JavaDoc getObjectAttributes(Object JavaDoc value,
145                                            Attributes JavaDoc attributes,
146                                            SerializationContext context) {
147         if (typeDesc != null && !typeDesc.hasAttributes())
148             return attributes;
149
150         AttributesImpl JavaDoc attrs;
151         if (attributes == null) {
152             attrs = new AttributesImpl JavaDoc();
153         } else if (attributes instanceof AttributesImpl JavaDoc) {
154             attrs = (AttributesImpl JavaDoc)attributes;
155         } else {
156             attrs = new AttributesImpl JavaDoc(attributes);
157         }
158
159         try {
160             // Find each property that is an attribute
161
// and add it to our attribute list
162
for (int i = 0;
163                  propertyDescriptor != null && i < propertyDescriptor.length;
164                  i++) {
165                 String JavaDoc propName = propertyDescriptor[i].getName();
166                 if (propName.equals("class"))
167                     continue;
168
169                 QName JavaDoc qname = null;
170                 if(typeDesc != null) {
171                     FieldDesc field = typeDesc.getFieldByName(propName);
172                     // skip it if its not an attribute
173
if (field == null || field.isElement())
174                         continue;
175                     qname = field.getXmlName();
176                 } else {
177                     if(propName.equals(VALUE_PROPERTY))
178                         continue;
179                 }
180                 if (qname == null) {
181                     qname = new QName JavaDoc("", propName);
182                 }
183
184                 if (propertyDescriptor[i].isReadable() &&
185                     !propertyDescriptor[i].isIndexed()) {
186                     // add to our attributes
187
Object JavaDoc propValue = propertyDescriptor[i].get(value);
188                     // If the property value does not exist, don't serialize
189
// the attribute. In the future, the decision to serializer
190
// the attribute may be more sophisticated. For example, don't
191
// serialize if the attribute matches the default value.
192
if (propValue != null) {
193                         String JavaDoc propString = getValueAsString(propValue, context);
194
195                         String JavaDoc namespace = qname.getNamespaceURI();
196                         String JavaDoc localName = qname.getLocalPart();
197
198                         attrs.addAttribute(namespace,
199                                            localName,
200                                            context.qName2String(qname),
201                                            "CDATA",
202                                            propString);
203                     }
204                 }
205             }
206         } catch (Exception JavaDoc e) {
207             // no attributes
208
return attrs;
209         }
210
211         return attrs;
212     }
213
214     public String JavaDoc getMechanismType() { return Constants.AXIS_SAX; }
215
216     /**
217      * Return XML schema for the specified type, suitable for insertion into
218      * the &lt;types&gt; element of a WSDL document, or underneath an
219      * &lt;element&gt; or &lt;attribute&gt; declaration.
220      *
221      * @param javaType the Java Class we're writing out schema for
222      * @param types the Java2WSDL Types object which holds the context
223      * for the WSDL being generated.
224      * @return a type element containing a schema simpleType/complexType
225      * @see org.apache.axis.wsdl.fromJava.Types
226      */

227     public Element JavaDoc writeSchema(Class JavaDoc javaType, Types types) throws Exception JavaDoc {
228         // ComplexType representation of SimpleType bean class
229
Element JavaDoc complexType = types.createElement("complexType");
230         types.writeSchemaTypeDecl(xmlType, complexType);
231         complexType.setAttribute("name", xmlType.getLocalPart());
232
233         // Produce simpleContent extending base type.
234
Element JavaDoc simpleContent = types.createElement("simpleContent");
235         complexType.appendChild(simpleContent);
236         Element JavaDoc extension = types.createElement("extension");
237         simpleContent.appendChild(extension);
238
239         // Get the base type from the "value" element of the bean
240
String JavaDoc base = "string";
241         for (int i=0; propertyDescriptor != null && i<propertyDescriptor.length; i++) {
242             String JavaDoc propName = propertyDescriptor[i].getName();
243             if (!propName.equals("value")) {
244                 if (typeDesc != null) {
245                     FieldDesc field = typeDesc.getFieldByName(propName);
246                     if (field != null) {
247                         if (field.isElement()) {
248                             // throw?
249
}
250                         QName JavaDoc qname = field.getXmlName();
251                         if (qname == null) {
252                             // Use the default...
253
qname = new QName JavaDoc("", propName);
254                         }
255
256                         // write attribute element
257
Class JavaDoc fieldType = propertyDescriptor[i].getType();
258
259                         // Attribute must be a simple type, enum or SimpleType
260
if (!types.isAcceptableAsAttribute(fieldType)) {
261                             throw new AxisFault(Messages.getMessage("AttrNotSimpleType00",
262                                     propName,
263                                     fieldType.getName()));
264                         }
265
266                         // write attribute element
267
// TODO the attribute name needs to be preserved from the XML
268
Element JavaDoc elem = types.createAttributeElement(propName,
269                                 fieldType,
270                                 field.getXmlType(),
271                                 false,
272                                 extension.getOwnerDocument());
273                         extension.appendChild(elem);
274                     }
275                 }
276                 continue;
277             }
278
279             BeanPropertyDescriptor bpd = propertyDescriptor[i];
280             Class JavaDoc type = bpd.getType();
281             // Attribute must extend a simple type, enum or SimpleType
282
if (!types.isAcceptableAsAttribute(type)) {
283                 throw new AxisFault(Messages.getMessage("AttrNotSimpleType01",
284                         type.getName()));
285             }
286             base = types.writeType(type);
287             extension.setAttribute("base", base);
288         }
289
290         // done
291
return complexType;
292
293     }
294 }
295
Popular Tags