Debian Codegraph @

src/org/apache/axis/encoding/SerializationContext.java

raw ◀ ▶
1 Debian patch touch this file
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;
18
19 import java.io.IOException;
20 import java.io.Writer;
21 import java.lang.reflect.InvocationTargetException;
22 import java.lang.reflect.Method;
23 import java.util.ArrayList;
24 import java.util.Calendar;
25 import java.util.Date;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.Iterator;
29 import java.util.Stack;
30
31 import javax.xml.namespace.QName;
32 import javax.xml.rpc.JAXRPCException;
33 import javax.xml.rpc.holders.QNameHolder;
34
35 import org.apache.axis.AxisEngine;
36 import org.apache.axis.AxisProperties;
37 import org.apache.axis.Constants;
38 import org.apache.axis.Message;
39 import org.apache.axis.MessageContext;
40 import org.apache.axis.attachments.Attachments;
41 import org.apache.axis.client.Call;
42 import org.apache.axis.components.encoding.XMLEncoder;
43 import org.apache.axis.components.encoding.XMLEncoderFactory;
44 import org.apache.axis.components.logger.LogFactory;
45 import org.apache.axis.constants.Use;
46 import org.apache.axis.description.OperationDesc;
47 import org.apache.axis.description.TypeDesc;
48 import org.apache.axis.encoding.ser.ArraySerializer;
49 import org.apache.axis.encoding.ser.BaseSerializerFactory;
50 import org.apache.axis.encoding.ser.SimpleListSerializerFactory;
51 import org.apache.axis.handlers.soap.SOAPService;
52 import org.apache.axis.schema.SchemaVersion;
53 import org.apache.axis.soap.SOAPConstants;
54 import org.apache.axis.types.HexBinary;
55 import org.apache.axis.utils.IDKey;
56 import org.apache.axis.utils.JavaUtils;
57 import org.apache.axis.utils.Mapping;
58 import org.apache.axis.utils.Messages;
59 import org.apache.axis.utils.NSStack;
60 import org.apache.axis.utils.XMLUtils;
61 import org.apache.axis.utils.cache.MethodCache;
62 import org.apache.axis.wsdl.symbolTable.SchemaUtils;
63 import org.apache.axis.wsdl.symbolTable.SymbolTable;
64 import org.apache.axis.wsdl.symbolTable.Utils;
65 import org.apache.commons.logging.Log;
66 import org.w3c.dom.Attr;
67 import org.w3c.dom.CDATASection;
68 import org.w3c.dom.CharacterData;
69 import org.w3c.dom.Comment;
70 import org.w3c.dom.Element;
71 import org.w3c.dom.NamedNodeMap;
72 import org.w3c.dom.Node;
73 import org.w3c.dom.NodeList;
74 import org.w3c.dom.Text;
75 import org.xml.sax.Attributes;
76 import org.xml.sax.helpers.AttributesImpl;
77
78 /** Manage a serialization, including keeping track of namespace mappings
79 * and element stacks.
80 *
81 * @author Glen Daniels ([email protected])
82 * @author Rich Scheuerle <[email protected]>
83 */
84 public class SerializationContext implements javax.xml.rpc.encoding.SerializationContext
85 {
86 protected static Log log =
87 LogFactory.getLog(SerializationContext.class.getName());
88
89 // invariant member variable to track low-level logging requirements
90 // we cache this once per instance lifecycle to avoid repeated lookups
91 // in heavily used code.
92 private final boolean debugEnabled = log.isDebugEnabled();
93
94 private NSStack nsStack = null;
95 private boolean writingStartTag = false;
96 private boolean onlyXML = true;
97 private int indent=0;
98 private Stack elementStack = new Stack();
99 private Writer writer;
100 private int lastPrefixIndex = 1;
101 private MessageContext msgContext;
102 private QName currentXMLType;
103 /** The item QName if we're serializing a literal array... */
104 private QName itemQName;
105 /** The item type if we're serializing a literal array... */
106 private QName itemType;
107
108 /** The SOAP context we're using */
109 private SOAPConstants soapConstants = SOAPConstants.SOAP11_CONSTANTS;
110
111 private static QName multirefQName = new QName("","multiRef");
112 private static Class[] SERIALIZER_CLASSES =
113 new Class[] {String.class, Class.class, QName.class};
114 private static final String SERIALIZER_METHOD = "getSerializer";
115
116 /**
117 * Should I write out objects as multi-refs?
118 *
119 * !!! For now, this is an all-or-nothing flag. Either ALL objects will
120 * be written in-place as hrefs with the full serialization at the end
121 * of the body, or we'll write everything inline (potentially repeating
122 * serializations of identical objects).
123 */
124 private boolean doMultiRefs = false;
125
126 /**
127 * Should I disable the pretty xml completely.
128 */
129 private boolean disablePrettyXML = false;
130
131
132 /**
133 * Should I disable the namespace prefix optimization.
134 */
135 private boolean enableNamespacePrefixOptimization = false;
136
137 /**
138 * current setting for pretty
139 */
140 private boolean pretty = false;
141
142 /**
143 * Should I send an XML declaration?
144 */
145 private boolean sendXMLDecl = true;
146
147 /**
148 * Should I send xsi:type attributes? By default, yes.
149 */
150 private boolean sendXSIType = true;
151
152 /**
153 * Send an element with an xsi:nil="true" attribute for null
154 * variables (if Boolean.TRUE), or nothing (if Boolean.FALSE).
155 */
156 private Boolean sendNull = Boolean.TRUE;
157
158 /**
159 * A place to hold objects we cache for multi-ref serialization, and
160 * remember the IDs we assigned them.
161 */
162 private HashMap multiRefValues = null;
163 private int multiRefIndex = -1;
164 private boolean noNamespaceMappings = true;
165 private QName writeXMLType;
166 private XMLEncoder encoder = null;
167
168 /** The flag whether the XML decl should be written */
169 protected boolean startOfDocument = true;
170
171 /** The encoding to serialize */
172 private String encoding = XMLEncoderFactory.DEFAULT_ENCODING;
173
174 class MultiRefItem {
175 String id;
176 QName xmlType;
177 Boolean sendType;
178 Object value;
179 MultiRefItem(String id,
180 QName xmlType,
181 Boolean sendType, Object value) {
182 this.id = id;
183 this.xmlType = xmlType;
184 this.sendType = sendType;
185 this.value = value;
186 }
187
188 }
189 /**
190 * These three variables are necessary to process
191 * multi-level object graphs for multi-ref serialization.
192 * While writing out nested multi-ref objects (via outputMultiRef), we
193 * will fill the secondLevelObjects vector
194 * with any new objects encountered.
195 * The outputMultiRefsFlag indicates whether we are currently within the
196 * outputMultiRef() method (so that serialization() knows to update the
197 * secondLevelObjects vector).
198 * The forceSer variable is the trigger to force actual serialization of the indicated object.
199 */
200 private HashSet secondLevelObjects = null;
201 private Object forceSer = null;
202 private boolean outputMultiRefsFlag = false;
203
204 /**
205 * Which schema version are we using?
206 */
207 SchemaVersion schemaVersion = SchemaVersion.SCHEMA_2001;
208
209 /**
210 * A list of particular namespace -> prefix mappings we should prefer.
211 * See getPrefixForURI() below.
212 */
213 HashMap preferredPrefixes = new HashMap();
214
215 /**
216 * Construct SerializationContext with associated writer
217 * @param writer java.io.Writer
218 */
219 public SerializationContext(Writer writer)
220 {
221 this.writer = writer;
222 initialize();
223 }
224
225 private void initialize() {
226 // These are the preferred prefixes we'll use instead of the "ns1"
227 // style defaults. MAKE SURE soapConstants IS SET CORRECTLY FIRST!
228 preferredPrefixes.put(soapConstants.getEncodingURI(),
229 Constants.NS_PREFIX_SOAP_ENC);
230 preferredPrefixes.put(Constants.NS_URI_XML,
231 Constants.NS_PREFIX_XML);
232 preferredPrefixes.put(schemaVersion.getXsdURI(),
233 Constants.NS_PREFIX_SCHEMA_XSD);
234 preferredPrefixes.put(schemaVersion.getXsiURI(),
235 Constants.NS_PREFIX_SCHEMA_XSI);
236 preferredPrefixes.put(soapConstants.getEnvelopeURI(),
237 Constants.NS_PREFIX_SOAP_ENV);
238 nsStack = new NSStack(enableNamespacePrefixOptimization);
239 }
240
241
242 /**
243 * Construct SerializationContext with associated writer and MessageContext
244 * @param writer java.io.Writer
245 * @param msgContext is the MessageContext
246 */
247 public SerializationContext(Writer writer, MessageContext msgContext)
248 {
249 this.writer = writer;
250 this.msgContext = msgContext;
251
252 if ( msgContext != null ) {
253 soapConstants = msgContext.getSOAPConstants();
254
255 // Use whatever schema is associated with this MC
256 schemaVersion = msgContext.getSchemaVersion();
257
258 Boolean shouldSendDecl = (Boolean)msgContext.getProperty(
259 AxisEngine.PROP_XML_DECL);
260 if (shouldSendDecl != null)
261 sendXMLDecl = shouldSendDecl.booleanValue();
262
263 Boolean shouldSendMultiRefs =
264 (Boolean)msgContext.getProperty(AxisEngine.PROP_DOMULTIREFS);
265 if (shouldSendMultiRefs != null)
266 doMultiRefs = shouldSendMultiRefs.booleanValue();
267
268 Boolean shouldDisablePrettyXML =
269 (Boolean)msgContext.getProperty(AxisEngine.PROP_DISABLE_PRETTY_XML);
270 if (shouldDisablePrettyXML != null)
271 disablePrettyXML = shouldDisablePrettyXML.booleanValue();
272
273 Boolean shouldDisableNamespacePrefixOptimization =
274 (Boolean)msgContext.getProperty(AxisEngine.PROP_ENABLE_NAMESPACE_PREFIX_OPTIMIZATION);
275 if (shouldDisableNamespacePrefixOptimization != null) {
276 enableNamespacePrefixOptimization = shouldDisableNamespacePrefixOptimization.booleanValue();
277 } else {
278 enableNamespacePrefixOptimization = JavaUtils.isTrue(AxisProperties.getProperty(AxisEngine.PROP_ENABLE_NAMESPACE_PREFIX_OPTIMIZATION,
279 "true"));
280 }
281 boolean sendTypesDefault = sendXSIType;
282
283 // A Literal use operation overrides the above settings. Don't
284 // send xsi:type, and don't do multiref in that case.
285 OperationDesc operation = msgContext.getOperation();
286 if (operation != null) {
287 if (operation.getUse() != Use.ENCODED) {
288 doMultiRefs = false;
289 sendTypesDefault = false;
290 }
291 } else {
292 // A Literal use service also overrides the above settings.
293 SOAPService service = msgContext.getService();
294 if (service != null) {
295 if (service.getUse() != Use.ENCODED) {
296 doMultiRefs = false;
297 sendTypesDefault = false;
298 }
299 }
300 }
301
302 // The SEND_TYPE_ATTR and PROP_SEND_XSI options indicate
303 // whether the elements should have xsi:type attributes.
304 // Only turn this off is the user tells us to
305 if ( !msgContext.isPropertyTrue(Call.SEND_TYPE_ATTR, sendTypesDefault ))
306 sendXSIType = false ;
307
308 // Don't need this since the above isPropertyTrue should walk up to the engine's
309 // properties...?
310 //
311 // Boolean opt = (Boolean)optionSource.getOption(AxisEngine.PROP_SEND_XSI);
312 // if (opt != null) {
313 // sendXSIType = opt.booleanValue();
314 // }
315 } else {
316 enableNamespacePrefixOptimization = JavaUtils.isTrue(AxisProperties.getProperty(AxisEngine.PROP_ENABLE_NAMESPACE_PREFIX_OPTIMIZATION,
317 "true"));
318 disablePrettyXML = JavaUtils.isTrue(AxisProperties.getProperty(AxisEngine.PROP_DISABLE_PRETTY_XML,
319 "true"));
320 }
321
322 // Set up preferred prefixes based on current schema, soap ver, etc.
323 initialize();
324 }
325
326 /**
327 * Get whether the serialization should be pretty printed.
328 * @return true/false
329 */
330 public boolean getPretty() {
331 return pretty;
332 }
333
334 /**
335 * Indicate whether the serialization should be pretty printed.
336 * @param pretty true/false
337 */
338 public void setPretty(boolean pretty) {
339 if(!disablePrettyXML) {
340 this.pretty = pretty;
341 }
342 }
343
344 /**
345 * Are we doing multirefs?
346 * @return true or false
347 */
348 public boolean getDoMultiRefs() {
349 return doMultiRefs;
350 }
351
352 /**
353 * Set whether we are doing multirefs
354 */
355 public void setDoMultiRefs (boolean shouldDo)
356 {
357 doMultiRefs = shouldDo;
358 }
359
360 /**
361 * Set whether or not we should write XML declarations.
362 * @param sendDecl true/false
363 */
364 public void setSendDecl(boolean sendDecl)
365 {
366 sendXMLDecl = sendDecl;
367 }
368
369 /**
370 * Get whether or not to write xsi:type attributes.
371 * @return true/false
372 */
373 public boolean shouldSendXSIType() {
374 return sendXSIType;
375 }
376
377 /**
378 * Get the TypeMapping we're using.
379 * @return TypeMapping or null
380 */
381 public TypeMapping getTypeMapping()
382 {
383 // Always allow the default mappings
384 if (msgContext == null)
385 return DefaultTypeMappingImpl.getSingletonDelegate();
386
387 String encodingStyle = msgContext.getEncodingStyle();
388 if (encodingStyle == null)
389 encodingStyle = soapConstants.getEncodingURI();
390 return (TypeMapping) msgContext.
391 getTypeMappingRegistry().getTypeMapping(encodingStyle);
392 }
393
394 /**
395 * Get the TypeMappingRegistry we're using.
396 * @return TypeMapping or null
397 */
398 public TypeMappingRegistry getTypeMappingRegistry() {
399 if (msgContext == null)
400 return null;
401 return msgContext.getTypeMappingRegistry();
402 }
403
404 /**
405 * Get a prefix for a namespace URI. This method will ALWAYS
406 * return a valid prefix - if the given URI is already mapped in this
407 * serialization, we return the previous prefix. If it is not mapped,
408 * we will add a new mapping and return a generated prefix of the form
409 * "ns<num>".
410 * @param uri is the namespace uri
411 * @return prefix
412 */
413 public String getPrefixForURI(String uri)
414 {
415 return getPrefixForURI(uri, null, false);
416 }
417
418 /**
419 * Get a prefix for the given namespace URI. If one has already been
420 * defined in this serialization, use that. Otherwise, map the passed
421 * default prefix to the URI, and return that. If a null default prefix
422 * is passed, use one of the form "ns<num>"
423 */
424 public String getPrefixForURI(String uri, String defaultPrefix)
425 {
426 return getPrefixForURI(uri, defaultPrefix, false);
427 }
428
429 /**
430 * Get a prefix for the given namespace URI. If one has already been
431 * defined in this serialization, use that. Otherwise, map the passed
432 * default prefix to the URI, and return that. If a null default prefix
433 * is passed, use one of the form "ns<num>"
434 */
435 public String getPrefixForURI(String uri, String defaultPrefix, boolean attribute)
436 {
437 if ((uri == null) || (uri.length() == 0))
438 return null;
439
440 // If we're looking for an attribute prefix, we shouldn't use the
441 // "" prefix, but always register/find one.
442 String prefix = nsStack.getPrefix(uri, attribute);
443
444 if (prefix == null) {
445 prefix = (String)preferredPrefixes.get(uri);
446
447 if (prefix == null) {
448 if (defaultPrefix == null) {
449 prefix = "ns" + lastPrefixIndex++;
450 while(nsStack.getNamespaceURI(prefix)!=null) {
451 prefix = "ns" + lastPrefixIndex++;
452 }
453 } else {
454 prefix = defaultPrefix;
455 }
456 }
457
458 registerPrefixForURI(prefix, uri);
459 }
460
461 return prefix;
462 }
463
464 /**
465 * Register prefix for the indicated uri
466 * @param prefix
467 * @param uri is the namespace uri
468 */
469 public void registerPrefixForURI(String prefix, String uri)
470 {
471 if (debugEnabled) {
472 log.debug(Messages.getMessage("register00", prefix, uri));
473 }
474
475 if ((uri != null) && (prefix != null)) {
476 if (noNamespaceMappings) {
477 nsStack.push();
478 noNamespaceMappings = false;
479 }
480 String activePrefix = nsStack.getPrefix(uri,true);
481 if(activePrefix == null || !activePrefix.equals(prefix)) {
482 nsStack.add(uri, prefix);
483 }
484 }
485 }
486
487 /**
488 * Return the current message
489 */
490 public Message getCurrentMessage()
491 {
492 if (msgContext == null)
493 return null;
494 return msgContext.getCurrentMessage();
495 }
496
497 /**
498 * Get the MessageContext we're operating with
499 */
500 public MessageContext getMessageContext() {
501 return msgContext;
502 }
503
504 /**
505 * Returns this context's encoding style. If we've got a message
506 * context then we'll get the style from that; otherwise we'll
507 * return a default.
508 *
509 * @return a <code>String</code> value
510 */
511 public String getEncodingStyle() {
512 return msgContext == null ? Use.DEFAULT.getEncoding() : msgContext.getEncodingStyle();
513 }
514
515 /**
516 * Returns whether this context should be encoded or not.
517 *
518 * @return a <code>boolean</code> value
519 */
520 public boolean isEncoded() {
521 return Constants.isSOAP_ENC(getEncodingStyle());
522 }
523
524 /**
525 * Convert QName to a string of the form <prefix>:<localpart>
526 * @param qName
527 * @return prefixed qname representation for serialization.
528 */
529 public String qName2String(QName qName, boolean writeNS)
530 {
531 String prefix = null;
532 String namespaceURI = qName.getNamespaceURI();
533 String localPart = qName.getLocalPart();
534
535 if(localPart != null && localPart.length() > 0) {
536 int index = localPart.indexOf(':');
537 if(index!=-1){
538 prefix = localPart.substring(0,index);
539 if(prefix.length()>0 && !prefix.equals("urn")){
540 registerPrefixForURI(prefix, namespaceURI);
541 localPart = localPart.substring(index+1);
542 } else {
543 prefix = null;
544 }
545 }
546 localPart = Utils.getLastLocalPart(localPart);
547 }
548
549 if (namespaceURI.length() == 0) {
550 if (writeNS) {
551 // If this is unqualified (i.e. prefix ""), set the default
552 // namespace to ""
553 String defaultNS = nsStack.getNamespaceURI("");
554 if (defaultNS != null && defaultNS.length() > 0) {
555 registerPrefixForURI("", "");
556 }
557 }
558 } else {
559 prefix = getPrefixForURI(namespaceURI);
560 }
561
562 if ((prefix == null) || (prefix.length() == 0))
563 return localPart;
564
565 return prefix + ':' + localPart;
566 }
567
568 public String qName2String(QName qName)
569 {
570 return qName2String(qName, false);
571 }
572
573 /**
574 * Convert attribute QName to a string of the form <prefix>:<localpart>
575 * There are slightly different rules for attributes:
576 * - There is no default namespace
577 * - any attribute in a namespace must have a prefix
578 *
579 * @param qName QName
580 * @return prefixed qname representation for serialization.
581 */
582 public String attributeQName2String(QName qName) {
583 String prefix = null;
584 String uri = qName.getNamespaceURI();
585 if (uri.length() > 0) {
586 prefix = getPrefixForURI(uri, null, true);
587 }
588
589 if ((prefix == null) || (prefix.length() == 0))
590 return qName.getLocalPart();
591
592 return prefix + ':' + qName.getLocalPart();
593 }
594
595 /**
596 * Get the QName associated with the specified class.
597 * @param cls Class of an object requiring serialization.
598 * @return appropriate QName associated with the class.
599 */
600 public QName getQNameForClass(Class cls)
601 {
602 return getTypeMapping().getTypeQName(cls);
603 }
604
605 /**
606 * Indicates whether the object should be interpretted as a primitive
607 * for the purposes of multi-ref processing. A primitive value
608 * is serialized directly instead of using id/href pairs. Thus
609 * primitive serialization/deserialization is slightly faster.
610 * @param value to be serialized
611 * @return true/false
612 */
613 public boolean isPrimitive(Object value)
614 {
615 if (value == null) return true;
616
617 Class javaType = value.getClass();
618
619 if (javaType.isPrimitive()) return true;
620
621 if (javaType == String.class) return true;
622 if (Calendar.class.isAssignableFrom(javaType)) return true;
623 if (Date.class.isAssignableFrom(javaType)) return true;
624 if (HexBinary.class.isAssignableFrom(javaType)) return true;
625 if (Element.class.isAssignableFrom(javaType)) return true;
626 if (javaType == byte[].class) return true;
627
628 // There has been discussion as to whether arrays themselves should
629 // be regarded as multi-ref.
630 // Here are the three options:
631 // 1) Arrays are full-fledged Objects and therefore should always be
632 // multi-ref'd (Pro: This is like java. Con: Some runtimes don't
633 // support this yet, and it requires more stuff to be passed over the wire.)
634 // 2) Arrays are not full-fledged Objects and therefore should
635 // always be passed as single ref (note the elements of the array
636 // may be multi-ref'd.) (Pro: This seems reasonable, if a user
637 // wants multi-referencing put the array in a container. Also
638 // is more interop compatible. Con: Not like java serialization.)
639 // 3) Arrays of primitives should be single ref, and arrays of
640 // non-primitives should be multi-ref. (Pro: Takes care of the
641 // looping case. Con: Seems like an obtuse rule.)
642 //
643 // Changing the code from (1) to (2) to see if interop fairs better.
644 if (javaType.isArray()) return true;
645
646 // Note that java.lang wrapper classes (i.e. java.lang.Integer) are
647 // not primitives unless the corresponding type is an xsd type.
648 // (If the wrapper maps to a soap encoded primitive, it can be nillable
649 // and multi-ref'd).
650 QName qName = getQNameForClass(javaType);
651 if (qName != null && Constants.isSchemaXSD(qName.getNamespaceURI())) {
652 if (SchemaUtils.isSimpleSchemaType(qName)) {
653 return true;
654 }
655 }
656
657 return false;
658 }
659
660 /**
661 * Serialize the indicated value as an element with the name
662 * indicated by elemQName.
663 * The attributes are additional attribute to be serialized on the element.
664 * The value is the object being serialized. (It may be serialized
665 * directly or serialized as an mult-ref'd item)
666 * The value is an Object, which may be a wrapped primitive, the
667 * javaType is the actual unwrapped object type.
668 * xsi:type is set by using the javaType to
669 * find an appopriate xmlType from the TypeMappingRegistry.
670 * Null values and the xsi:type flag will be sent or not depending
671 * on previous configuration of this SerializationContext.
672 * @param elemQName is the QName of the element
673 * @param attributes are additional attributes
674 * @param value is the object to serialize
675 */
676 public void serialize(QName elemQName,
677 Attributes attributes,
678 Object value)
679 throws IOException {
680 serialize(elemQName, attributes, value, null, null, null, null);
681 }
682
683 /**
684 * Serialize the indicated value as an element with the name
685 * indicated by elemQName.
686 * The attributes are additional attribute to be serialized on the element.
687 * The value is the object being serialized. (It may be serialized
688 * directly or serialized as an mult-ref'd item)
689 * The value is an Object, which may be a wrapped primitive, the
690 * javaType is the actual unwrapped object type.
691 * The xmlType is the QName of the type that is used to set
692 * xsi:type. If not specified, xsi:type is set by using the javaType to
693 * find an appopriate xmlType from the TypeMappingRegistry.
694 * Null values and the xsi:type flag will be sent or not depending
695 * on previous configuration of this SerializationContext.
696 * @param elemQName is the QName of the element
697 * @param attributes are additional attributes
698 * @param value is the object to serialize
699 * @param xmlType is the qname of the type or null.
700 * @deprecated use serialize(QName, Attributes, Object, QName, Class) instead
701 */
702 public void serialize(QName elemQName,
703 Attributes attributes,
704 Object value,
705 QName xmlType)
706 throws IOException {
707 serialize(elemQName, attributes, value, xmlType, null, null, null);
708 }
709
710 /**
711 * Serialize the indicated value as an element with the name
712 * indicated by elemQName.
713 * The attributes are additional attribute to be serialized on the element.
714 * The value is the object being serialized. (It may be serialized
715 * directly or serialized as an mult-ref'd item)
716 * The value is an Object, which may be a wrapped primitive, the
717 * javaType is the actual unwrapped object type.
718 * The xmlType is the QName of the type that is used to set
719 * xsi:type. If not specified, xsi:type is set by using the javaType to
720 * find an appopriate xmlType from the TypeMappingRegistry.
721 * Null values and the xsi:type flag will be sent or not depending
722 * on previous configuration of this SerializationContext.
723 * @param elemQName is the QName of the element
724 * @param attributes are additional attributes
725 * @param value is the object to serialize
726 * @param xmlType is the qname of the type or null.
727 * @param javaType is the java type of the value
728 */
729 public void serialize(QName elemQName,
730 Attributes attributes,
731 Object value,
732 QName xmlType, Class javaType)
733 throws IOException {
734 serialize(elemQName, attributes, value, xmlType, javaType, null, null);
735 }
736
737 /**
738 * Serialize the indicated value as an element with the name
739 * indicated by elemQName.
740 * The attributes are additional attribute to be serialized on the element.
741 * The value is the object being serialized. (It may be serialized
742 * directly or serialized as an mult-ref'd item)
743 * The value is an Object, which may be a wrapped primitive.
744 * The xmlType (if specified) is the QName of the type that is used to set
745 * xsi:type.
746 * The sendNull flag indicates whether null values should be sent over the
747 * wire (default is to send such values with xsi:nil="true").
748 * The sendType flag indicates whether the xsi:type flag should be sent
749 * (default is true).
750 * @param elemQName is the QName of the element
751 * @param attributes are additional attributes
752 * @param value is the object to serialize
753 * @param xmlType is the qname of the type or null.
754 * @param sendNull determines whether to send null values.
755 * @param sendType determines whether to set xsi:type attribute.
756 *
757 * @deprecated use serialize(QName, Attributes, Object, QName,
758 * Boolean, Boolean) instead.
759 */
760 public void serialize(QName elemQName,
761 Attributes attributes,
762 Object value,
763 QName xmlType,
764 boolean sendNull,
765 Boolean sendType)
766 throws IOException
767 {
768 serialize( elemQName, attributes, value, xmlType, null,
769 (sendNull) ? Boolean.TRUE : Boolean.FALSE,
770 sendType);
771 }
772
773 /**
774 * Serialize the indicated value as an element with the name
775 * indicated by elemQName.
776 * The attributes are additional attribute to be serialized on the element.
777 * The value is the object being serialized. (It may be serialized
778 * directly or serialized as an mult-ref'd item)
779 * The value is an Object, which may be a wrapped primitive.
780 * The xmlType (if specified) is the QName of the type that is used to set
781 * xsi:type.
782 * The sendNull flag indicates whether to end an element with an xsi:nil="true" attribute for null
783 * variables (if Boolean.TRUE), or nothing (if Boolean.FALSE).
784 * The sendType flag indicates whether the xsi:type flag should be sent
785 * (default is true).
786 * @param elemQName is the QName of the element
787 * @param attributes are additional attributes
788 * @param value is the object to serialize
789 * @param xmlType is the qname of the type or null.
790 * @param sendNull determines whether to send null values.
791 * @param sendType determines whether to set xsi:type attribute.
792 */
793 public void serialize(QName elemQName,
794 Attributes attributes,
795 Object value,
796 QName xmlType,
797 Boolean sendNull,
798 Boolean sendType)
799 throws IOException
800 {
801 serialize(elemQName, attributes, value, xmlType, null, sendNull, sendType);
802
803 }
804
805 /**
806 * Serialize the indicated value as an element with the name
807 * indicated by elemQName.
808 * The attributes are additional attribute to be serialized on the element.
809 * The value is the object being serialized. (It may be serialized
810 * directly or serialized as an mult-ref'd item)
811 * The value is an Object, which may be a wrapped primitive.
812 * The xmlType (if specified) is the QName of the type that is used to set
813 * xsi:type.
814 * The sendNull flag indicates whether to end an element with an xsi:nil="true" attribute for null
815 * variables (if Boolean.TRUE), or nothing (if Boolean.FALSE).
816 * The sendType flag indicates whether the xsi:type flag should be sent
817 * (default is true).
818 * @param elemQName is the QName of the element
819 * @param attributes are additional attributes
820 * @param value is the object to serialize
821 * @param xmlType is the qname of the type or null.
822 * @param javaType is the java type of the value
823 * @param sendNull determines whether to send null values.
824 * @param sendType determines whether to set xsi:type attribute.
825 */
826 public void serialize(QName elemQName,
827 Attributes attributes,
828 Object value,
829 QName xmlType,
830 Class javaClass,
831 Boolean sendNull,
832 Boolean sendType)
833 throws IOException
834 {
835 boolean sendXSITypeCache = sendXSIType;
836 if (sendType != null) {
837 sendXSIType = sendType.booleanValue();
838 }
839 boolean shouldSendType = shouldSendXSIType();
840
841 try {
842 Boolean sendNullCache = this.sendNull;
843 if (sendNull != null) {
844 this.sendNull = sendNull;
845 } else {
846 sendNull = this.sendNull;
847 }
848
849 if (value == null) {
850 // If the value is null, the element is
851 // passed with xsi:nil="true" to indicate that no object is present.
852 if (this.sendNull.booleanValue()) {
853 AttributesImpl attrs = new AttributesImpl();
854 if (attributes != null && 0 < attributes.getLength())
855 attrs.setAttributes(attributes);
856 if (shouldSendType)
857 attrs = (AttributesImpl) setTypeAttribute(attrs, xmlType);
858 String nil = schemaVersion.getNilQName().getLocalPart();
859 attrs.addAttribute(schemaVersion.getXsiURI(), nil, "xsi:" + nil,
860 "CDATA", "true");
861 startElement(elemQName, attrs);
862 endElement();
863 }
864 this.sendNull = sendNullCache;
865 return;
866 }
867
868 Message msg= getCurrentMessage();
869 if(null != msg){
870 //Get attachments. returns null if no attachment support.
871 Attachments attachments= getCurrentMessage().getAttachmentsImpl();
872
873 if( null != attachments && attachments.isAttachment(value)){
874 //Attachment support and this is an object that should be treated as an attachment.
875
876 //Allow an the attachment to do its own serialization.
877 serializeActual(elemQName, attributes, value,
878 xmlType, javaClass, sendType);
879
880 //No need to add to mulitRefs. Attachment data stream handled by
881 // the message;
882 this.sendNull = sendNullCache;
883 return;
884 }
885 }
886
887 // If multi-reference is enabled and this object value is not a primitive
888 // and we are not forcing serialization of the object, then generate
889 // an element href (and store the object for subsequent outputMultiRef
890 // processing).
891
892 // NOTE : you'll notice that everywhere we register objects in the
893 // multiRefValues and secondLevelObjects collections, we key them
894 // using getIdentityKey(value) instead of the Object reference itself.
895 // THIS IS IMPORTANT, and please make sure you understand what's
896 // going on if you change any of this code. It's this way to make
897 // sure that individual Objects are serialized separately even if the
898 // hashCode() and equals() methods have been overloaded to make two
899 // Objects appear equal.
900
901 if (doMultiRefs && isEncoded() &&
902 (value != forceSer) && !isPrimitive(value)) {
903 if (multiRefIndex == -1)
904 multiRefValues = new HashMap();
905
906 String id;
907
908 // Look for a multi-ref descriptor for this Object.
909 MultiRefItem mri = (MultiRefItem)multiRefValues.get(
910 getIdentityKey(value));
911 if (mri == null) {
912 // Didn't find one, so create one, give it a new ID, and store
913 // it for next time.
914 multiRefIndex++;
915 id = "id" + multiRefIndex;
916 mri = new MultiRefItem (id, xmlType, sendType, value);
917 multiRefValues.put(getIdentityKey(value), mri);
918
919 /**
920 * If we're SOAP 1.2, we can "inline" the serializations,
921 * so put it out now, with it's ID.
922 */
923 if (soapConstants == SOAPConstants.SOAP12_CONSTANTS) {
924 AttributesImpl attrs = new AttributesImpl();
925 if (attributes != null && 0 < attributes.getLength())
926 attrs.setAttributes(attributes);
927 attrs.addAttribute("", Constants.ATTR_ID, "id", "CDATA",
928 id);
929 serializeActual(elemQName, attrs, value, xmlType, javaClass, sendType);
930 this.sendNull = sendNullCache;
931 return;
932 }
933
934
935 /** If we're in the middle of writing out
936 * the multi-refs, we've already cloned the list of objects
937 * and so even though we add a new one to multiRefValues,
938 * it won't get serialized this time around.
939 *
940 * To deal with this, we maintain a list of "second level"
941 * Objects - ones that need serializing as a result of
942 * serializing the first level. When outputMultiRefs() is
943 * nearly finished, it checks to see if secondLevelObjects
944 * is empty, and if not, it goes back and loops over those
945 * Objects. This can happen N times depending on how deep
946 * the Object graph goes.
947 */
948 if (outputMultiRefsFlag) {
949 if (secondLevelObjects == null)
950 secondLevelObjects = new HashSet();
951 secondLevelObjects.add(getIdentityKey(value));
952 }
953 } else {
954 // Found one, remember it's ID
955 id = mri.id;
956 }
957
958 // Serialize an HREF to our object
959 AttributesImpl attrs = new AttributesImpl();
960 if (attributes != null && 0 < attributes.getLength())
961 attrs.setAttributes(attributes);
962 attrs.addAttribute("", soapConstants.getAttrHref(), soapConstants.getAttrHref(),
963 "CDATA", '#' + id);
964
965 startElement(elemQName, attrs);
966 endElement();
967 this.sendNull = sendNullCache;
968 return;
969 }
970
971 // The forceSer variable is set by outputMultiRefs to force
972 // serialization of this object via the serialize(...) call
973 // below. However, if the forced object contains a self-reference, we
974 // get into an infinite loop..which is why it is set back to null
975 // before the actual serialization.
976 if (value == forceSer)
977 forceSer = null;
978
979 // Actually serialize the value. (i.e. not an href like above)
980 serializeActual(elemQName, attributes, value, xmlType, javaClass, sendType);
981 } finally {
982 sendXSIType = sendXSITypeCache;
983 }
984 }
985
986 /**
987 * Get an IDKey that represents the unique identity of the object.
988 * This is used as a unique key into a HashMap which will
989 * not give false hits on other Objects where hashCode() and equals()
990 * have been overriden to match.
991 *
992 * @param value the Object to hash
993 * @return a unique IDKey for the identity
994 */
995 private IDKey getIdentityKey(Object value) {
996 return new IDKey(value);
997 }
998
999 /**
1000 * The serialize method uses hrefs to reference all non-primitive
1001 * values. These values are stored and serialized by calling
1002 * outputMultiRefs after the serialize method completes.
1003 */
1004 public void outputMultiRefs() throws IOException
1005 {
1006 if (!doMultiRefs || (multiRefValues == null) ||
1007 soapConstants == SOAPConstants.SOAP12_CONSTANTS)
1008 return;
1009 outputMultiRefsFlag = true;
1010 AttributesImpl attrs = new AttributesImpl();
1011 attrs.addAttribute("","","","","");
1012
1013 String encodingURI = soapConstants.getEncodingURI();
1014 // explicitly state that this attribute is not a root
1015 String prefix = getPrefixForURI(encodingURI);
1016 String root = prefix + ":root";
1017 attrs.addAttribute(encodingURI, Constants.ATTR_ROOT, root,
1018 "CDATA", "0");
1019
1020 // Make sure we put the encodingStyle on each multiref element we
1021 // output.
1022 String encodingStyle;
1023 if (msgContext != null) {
1024 encodingStyle = msgContext.getEncodingStyle();
1025 } else {
1026 encodingStyle = soapConstants.getEncodingURI();
1027 }
1028 String encStyle = getPrefixForURI(soapConstants.getEnvelopeURI()) +
1029 ':' + Constants.ATTR_ENCODING_STYLE;
1030 attrs.addAttribute(soapConstants.getEnvelopeURI(),
1031 Constants.ATTR_ENCODING_STYLE,
1032 encStyle,
1033 "CDATA",
1034 encodingStyle);
1035
1036 // Make a copy of the keySet because it could be updated
1037 // during processing
1038 HashSet keys = new HashSet();
1039 keys.addAll(multiRefValues.keySet());
1040 Iterator i = keys.iterator();
1041 while (i.hasNext()) {
1042 while (i.hasNext()) {
1043 AttributesImpl attrs2 = new AttributesImpl(attrs);
1044 Object val = i.next();
1045 MultiRefItem mri = (MultiRefItem) multiRefValues.get(val);
1046 attrs2.setAttribute(0, "", Constants.ATTR_ID, "id", "CDATA",
1047 mri.id);
1048
1049 forceSer = mri.value;
1050
1051 // Now serialize the value.
1052 // The sendType parameter is defaulted for interop purposes.
1053 // Some of the remote services do not know how to
1054 // ascertain the type in these circumstances (though Axis does).
1055 serialize(multirefQName, attrs2, mri.value,
1056 mri.xmlType,
1057 null,
1058 this.sendNull,
1059 Boolean.TRUE); // mri.sendType
1060 }
1061
1062 // Done processing the iterated values. During the serialization
1063 // of the values, we may have run into new nested values. These
1064 // were placed in the secondLevelObjects map, which we will now
1065 // process by changing the iterator to locate these values.
1066 if (secondLevelObjects != null) {
1067 i = secondLevelObjects.iterator();
1068 secondLevelObjects = null;
1069 }
1070 }
1071
1072 // Reset maps and flags
1073 forceSer = null;
1074 outputMultiRefsFlag = false;
1075 multiRefValues = null;
1076 multiRefIndex = -1;
1077 secondLevelObjects = null;
1078 }
1079
1080 public void writeXMLDeclaration() throws IOException {
1081 writer.write("<?xml version=\"1.0\" encoding=\"");
1082 writer.write(encoding);
1083 writer.write("\"?>");
1084 startOfDocument = false;
1085 }
1086
1087 /**
1088 * Writes (using the Writer) the start tag for element QName along with the
1089 * indicated attributes and namespace mappings.
1090 * @param qName is the name of the element
1091 * @param attributes are the attributes to write
1092 */
1093 public void startElement(QName qName, Attributes attributes)
1094 throws IOException
1095 {
1096 java.util.ArrayList vecQNames = null;
1097 if (debugEnabled) {
1098 log.debug(Messages.getMessage("startElem00",
1099 "[" + qName.getNamespaceURI() + "]:" + qName.getLocalPart()));
1100 }
1101
1102 if (startOfDocument && sendXMLDecl) {
1103 writeXMLDeclaration();
1104 }
1105
1106 if (writingStartTag) {
1107 writer.write('>');
1108 if (pretty) writer.write('\n');
1109 indent++;
1110 }
1111
1112 if (pretty) for (int i=0; i<indent; i++) writer.write(' ');
1113 String elementQName = qName2String(qName, true);
1114 writer.write('<');
1115
1116 writer.write(elementQName);
1117
1118 if (writeXMLType != null) {
1119 attributes = setTypeAttribute(attributes, writeXMLType);
1120 writeXMLType = null;
1121 }
1122
1123 if (attributes != null) {
1124 for (int i = 0; i < attributes.getLength(); i++) {
1125 String qname = attributes.getQName(i);
1126 writer.write(' ');
1127
1128 String prefix = "";
1129 String uri = attributes.getURI(i);
1130 if (uri != null && uri.length() > 0) {
1131 if (qname.length() == 0) {
1132 // If qname isn't set, generate one
1133 prefix = getPrefixForURI(uri);
1134 } else {
1135 // If it is, make sure the prefix looks reasonable.
1136 int idx = qname.indexOf(':');
1137 if (idx > -1) {
1138 prefix = qname.substring(0, idx);
1139 prefix = getPrefixForURI(uri,
1140 prefix, true);
1141 }
1142 }
1143 if (prefix.length() > 0) {
1144 qname = prefix + ':' + attributes.getLocalName(i);
1145 } else {
1146 qname = attributes.getLocalName(i);
1147 }
1148 } else {
1149 qname = attributes.getQName(i);
1150 if(qname.length() == 0)
1151 qname = attributes.getLocalName(i);
1152 }
1153
1154 if (qname.startsWith("xmlns")) {
1155 if (vecQNames == null) vecQNames = new ArrayList();
1156 vecQNames.add(qname);
1157 }
1158 writer.write(qname);
1159 writer.write("=\"");
1160
1161 getEncoder().writeEncoded(writer, attributes.getValue(i));
1162
1163 writer.write('"');
1164 }
1165 }
1166
1167 if (noNamespaceMappings) {
1168 nsStack.push();
1169 } else {
1170 for (Mapping map=nsStack.topOfFrame(); map!=null; map=nsStack.next()) {
1171 if (!(map.getNamespaceURI().equals(Constants.NS_URI_XMLNS) && map.getPrefix().equals("xmlns")) &&
1172 !(map.getNamespaceURI().equals(Constants.NS_URI_XML) && map.getPrefix().equals("xml")))
1173 {
1174 StringBuffer sb = new StringBuffer("xmlns");
1175 if (map.getPrefix().length() > 0) {
1176 sb.append(':');
1177 sb.append(map.getPrefix());
1178 }
•1179 String qname = sb.toString();
1180 if ((vecQNames==null) || (vecQNames.indexOf(qname)==-1)) {
1181 writer.write(' ');
•1182 writer.write(qname);
1183 writer.write("=\"");
1184 getEncoder().writeEncoded(writer, map.getNamespaceURI());
1185 writer.write('"');
1186 }
1187 }
1188 }
1189
1190 noNamespaceMappings = true;
1191 }
1192
1193 writingStartTag = true;
1194
1195 elementStack.push(elementQName);
1196
1197 onlyXML=true;
1198 }
1199
1200 /**
1201 * Writes the end element tag for the open element.
1202 **/
1203 public void endElement()
1204 throws IOException
1205 {
1206 String elementQName = (String)elementStack.pop();
1207
1208 if (debugEnabled) {
1209 log.debug(Messages.getMessage("endElem00", "" + elementQName));
1210 }
1211
1212 nsStack.pop();
1213
1214 if (writingStartTag) {
1215 writer.write("/>");
1216 if (pretty) writer.write('\n');
1217 writingStartTag = false;
1218 return;
1219 }
1220
1221 if (onlyXML) {
1222 indent--;
1223 if (pretty) for (int i=0; i<indent; i++) writer.write(' ');
1224 }
1225 writer.write("</");
1226 writer.write(elementQName);
1227 writer.write('>');
1228 if (pretty) if (indent>0) writer.write('\n');
1229 onlyXML=true;
1230 }
1231
1232 /**
1233 * Convenience operation to write out (to Writer) the characters
1234 * in p1 starting at index p2 for length p3.
1235 * @param p1 character array to write
1236 * @param p2 starting index in array
1237 * @param p3 length to write
1238 */
1239 public void writeChars(char [] p1, int p2, int p3)
1240 throws IOException
1241 {
1242 if (startOfDocument && sendXMLDecl) {
1243 writeXMLDeclaration();
1244 }
1245
1246 if (writingStartTag) {
1247 writer.write('>');
1248 writingStartTag = false;
1249 }
1250 writeSafeString(String.valueOf(p1,p2,p3));
1251 onlyXML=false;
1252 }
1253
1254 /**
1255 * Convenience operation to write out (to Writer) the String
1256 * @param string is the String to write.
1257 */
1258 public void writeString(String string)
1259 throws IOException
1260 {
1261 if (startOfDocument && sendXMLDecl) {
1262 writeXMLDeclaration();
1263 }
1264
1265 if (writingStartTag) {
1266 writer.write('>');
1267 writingStartTag = false;
1268 }
1269 writer.write(string);
1270 onlyXML=false;
1271 }
1272
1273 /**
1274 * Convenience operation to write out (to Writer) the String
1275 * properly encoded with xml entities (like &amp)
1276 * @param string is the String to write.
1277 */
1278 public void writeSafeString(String string)
1279 throws IOException
1280 {
1281 if (startOfDocument && sendXMLDecl) {
1282 writeXMLDeclaration();
1283 }
1284
1285 if (writingStartTag) {
1286 writer.write('>');
1287 writingStartTag = false;
1288 }
1289
1290 getEncoder().writeEncoded(writer, string);
1291 onlyXML=false;
1292 }
1293
1294 /**
1295 * Output a DOM representation to a SerializationContext
1296 * @param el is a DOM Element
1297 */
1298 public void writeDOMElement(Element el)
1299 throws IOException
1300 {
1301 if (startOfDocument && sendXMLDecl) {
1302 writeXMLDeclaration();
1303 }
1304
1305 // If el is a Text element, write the text and exit
1306 if (el instanceof org.apache.axis.message.Text) {
1307 writeSafeString(((Text)el).getData());
1308 return;
1309 }
1310
1311 AttributesImpl attributes = null;
1312 NamedNodeMap attrMap = el.getAttributes();
1313
1314 if (attrMap.getLength() > 0) {
1315 attributes = new AttributesImpl();
1316 for (int i = 0; i < attrMap.getLength(); i++) {
1317 Attr attr = (Attr)attrMap.item(i);
1318 String tmp = attr.getNamespaceURI();
1319 if ( tmp != null && tmp.equals(Constants.NS_URI_XMLNS) ) {
1320 String prefix = attr.getLocalName();
1321 if (prefix != null) {
1322 if (prefix.equals("xmlns"))
1323 prefix = "";
1324 String nsURI = attr.getValue();
1325 registerPrefixForURI(prefix, nsURI);
1326 }
1327 continue;
1328 }
1329
1330 attributes.addAttribute(attr.getNamespaceURI(),
1331 attr.getLocalName(),
1332 attr.getName(),
1333 "CDATA", attr.getValue());
1334 }
1335 }
1336
1337 String namespaceURI = el.getNamespaceURI();
1338 String localPart = el.getLocalName();
1339 if(namespaceURI == null || namespaceURI.length()==0)
1340 localPart = el.getNodeName();
1341 QName qName = new QName(namespaceURI, localPart);
1342
1343 startElement(qName, attributes);
1344
1345 NodeList children = el.getChildNodes();
1346 for (int i = 0; i < children.getLength(); i++) {
1347 Node child = children.item(i);
1348 if (child instanceof Element) {
1349 writeDOMElement((Element)child);
1350 } else if (child instanceof CDATASection) {
1351 writeString("<![CDATA[");
1352 writeString(((Text)child).getData());
1353 writeString("]]>");
1354 } else if (child instanceof Comment) {
1355 writeString("<!--");
1356 writeString(((CharacterData)child).getData());
1357 writeString("-->");
1358 } else if (child instanceof Text) {
1359 writeSafeString(((Text)child).getData());
1360 }
1361 }
1362
1363 endElement();
1364 }
1365
1366 /**
1367 * Convenience method to get the Serializer for a specific
1368 * java type
1369 * @param javaType is Class for a type to serialize
1370 * @return Serializer
1371 */
1372 public final Serializer getSerializerForJavaType(Class javaType) {
1373 SerializerFactory serF = null;
1374 Serializer ser = null;
1375 try {
1376 serF = (SerializerFactory) getTypeMapping().getSerializer(javaType);
1377 if (serF != null) {
1378 ser = (Serializer) serF.getSerializerAs(Constants.AXIS_SAX);
1379 }
1380 } catch (JAXRPCException e) {
1381 }
1382
1383 return ser;
1384 }
1385
1386 /**
1387 * Obtains the type attribute that should be serialized and returns the new list of Attributes
1388 * @param attributes of the qname
1389 * @param type is the qname of the type
1390 * @return new list of Attributes
1391 */
1392 public Attributes setTypeAttribute(Attributes attributes, QName type)
1393 {
1394 SchemaVersion schema = SchemaVersion.SCHEMA_2001;
1395 if (msgContext != null) {
1396 schema = msgContext.getSchemaVersion();
1397 }
1398
1399 if (type == null ||
1400 type.getLocalPart().indexOf(SymbolTable.ANON_TOKEN) >= 0 ||
1401 ((attributes != null) &&
1402 (attributes.getIndex(schema.getXsiURI(),
1403 "type") != -1)))
1404 return attributes;
1405
1406 AttributesImpl attrs = new AttributesImpl();
1407 if (attributes != null && 0 < attributes.getLength() )
1408 attrs.setAttributes(attributes);
1409
1410 String prefix = getPrefixForURI(schema.getXsiURI(),
1411 "xsi");
1412
1413 attrs.addAttribute(schema.getXsiURI(),
1414 "type",
1415 prefix + ":type",
1416 "CDATA", attributeQName2String(type));
1417 return attrs;
1418 }
1419
1420 /**
1421 * Invoked to do the actual serialization of the qName (called by serialize above).
1422 * additional attributes that will be serialized with the qName.
1423 * @param elemQName is the QName of the element
1424 * @param attributes are additional attributes
1425 * @param value is the object to serialize
1426 * @param xmlType (optional) is the desired type QName.
1427 * @param sendType indicates whether the xsi:type attribute should be set.
1428 */
1429 private void serializeActual(QName elemQName,
1430 Attributes attributes,
1431 Object value,
1432 QName xmlType,
1433 Class javaClass,
1434 Boolean sendType)
1435 throws IOException
1436 {
1437 boolean shouldSendType = (sendType == null) ? shouldSendXSIType() :
1438 sendType.booleanValue();
1439
1440 if (value != null) {
1441 TypeMapping tm = getTypeMapping();
1442
1443 if (tm == null) {
1444 throw new IOException(
1445 Messages.getMessage("noSerializer00",
1446 value.getClass().getName(),
1447 "" + this));
1448 }
1449
1450 // Set currentXMLType to the one desired one.
1451 // Note for maxOccurs usage this xmlType is the
1452 // type of the component not the type of the array.
1453 currentXMLType = xmlType;
1454
1455 // if we're looking for xsd:anyType, accept anything...
1456 if (Constants.equals(Constants.XSD_ANYTYPE,xmlType)){
1457 xmlType = null;
1458 shouldSendType = true;
1459 }
1460
1461 // Try getting a serializer for the prefered xmlType
1462 QNameHolder actualXMLType = new QNameHolder();
1463
1464 Class javaType = getActualJavaClass(xmlType, javaClass, value);
1465
1466 Serializer ser = getSerializer(javaType, xmlType,
1467 actualXMLType);
1468
1469 if ( ser != null ) {
1470 // Send the xmlType if indicated or if
1471 // the actual xmlType is different than the
1472 // prefered xmlType
1473 if (shouldSendType ||
1474 (xmlType != null &&
1475 (!xmlType.equals(actualXMLType.value)))) {
1476
1477 if(!isEncoded()) {
1478 if (Constants.isSOAP_ENC(actualXMLType.value.getNamespaceURI())) {
1479 // Don't write SOAP_ENC types (i.e. Array) if we're not using encoding
1480 } else if (javaType.isPrimitive() && javaClass != null && JavaUtils.getWrapperClass(javaType) == javaClass) {
1481 // Don't write xsi:type when serializing primitive wrapper value as primitive type.
1482 }
1483 else {
1484 if(!(javaType.isArray() && xmlType != null && Constants.isSchemaXSD(xmlType.getNamespaceURI())) ) {
1485 writeXMLType = actualXMLType.value;
1486 }
1487 }
1488 } else {
1489 writeXMLType = actualXMLType.value;
1490 }
1491 }
1492
1493 // -----------------
1494 // NOTE: I have seen doc/lit tests that use
1495 // the type name as the element name in multi-ref cases
1496 // (for example <soapenc:Array ... >)
1497 // In such cases the xsi:type is not passed along.
1498 // -----------------
1499 // The multiref QName is our own fake name.
1500 // It may be beneficial to set the name to the
1501 // type name, but I didn't see any improvements
1502 // in the interop tests.
1503 //if (name.equals(multirefQName) && type != null)
1504 // name = type;
1505 ser.serialize(elemQName, attributes, value, this);
1506 return;
1507 }
1508 throw new IOException(Messages.getMessage("noSerializer00",
1509 value.getClass().getName(), "" + tm));
1510 }
1511 // !!! Write out a generic null, or get type info from somewhere else?
1512 }
1513
1514 /**
1515 * Returns the java class for serialization.
1516 * If the xmlType is xsd:anyType or javaType is array or javaType is java.lang.Object
1517 * the java class for serialization is the class of obj.
1518 * If the obj is not array and the obj's class does not match with the javaType,
1519 * the java class for serialization is the javaType.
1520 * Otherwise, the java class for serialization is the obj's class.
1521 *
1522 * @param xmlType the qname of xml type
1523 * @param javaType the java class from serializer
1524 * @param obj the object to serialize
1525 * @return the java class for serialization
1526 */
1527 private Class getActualJavaClass(QName xmlType, Class javaType, Object obj) {
1528 Class cls = obj.getClass();
1529
1530 if ((xmlType != null
1531 && Constants.isSchemaXSD(xmlType.getNamespaceURI()) && "anyType".equals(xmlType.getLocalPart()))
1532 || (javaType != null
1533 && (javaType.isArray() || javaType == Object.class))) {
1534 return cls;
1535 }
1536
1537 if (javaType != null && !javaType.isAssignableFrom(cls) && !cls.isArray()) {
1538 return javaType;
1539 }
1540
1541 return cls;
1542 }
1543
1544 private Serializer getSerializerFromClass(Class javaType, QName qname) {
1545
1546 Serializer serializer = null;
1547 try {
1548 Method method =
1549 MethodCache.getInstance().getMethod(javaType,
1550 SERIALIZER_METHOD,
1551 SERIALIZER_CLASSES);
1552 if (method != null) {
1553 serializer = (Serializer) method.invoke(null,
1554 new Object[] {getEncodingStyle(), javaType, qname});
1555 }
1556 } catch (NoSuchMethodException e) {
1557 } catch (IllegalAccessException e) {
1558 } catch (InvocationTargetException e) {
1559 }
1560 return serializer;
1561 }
1562
1563 /**
1564 * Get the currently prefered xmlType
1565 * @return QName of xmlType or null
1566 */
1567 public QName getCurrentXMLType() {
1568 return currentXMLType;
1569 }
1570
1571 /**
1572 * Walk the interfaces of a class looking for a serializer for that
1573 * interface. Include any parent interfaces in the search also.
1574 *
1575 */
1576 private SerializerFactory getSerializerFactoryFromInterface(Class javaType,
1577 QName xmlType,
1578 TypeMapping tm)
1579 {
1580 SerializerFactory serFactory = null ;
1581 Class [] interfaces = javaType.getInterfaces();
1582 if (interfaces != null) {
1583 for (int i = 0; i < interfaces.length; i++) {
1584 Class iface = interfaces[i];
1585 serFactory = (SerializerFactory) tm.getSerializer(iface,
1586 xmlType);
1587 if (serFactory == null)
1588 serFactory = getSerializerFactoryFromInterface(iface, xmlType, tm);
1589 if (serFactory != null)
1590 break;
1591
1592 }
1593 }
1594 return serFactory;
1595 }
1596
1597 /**
1598 * getSerializer
1599 * Attempts to get a serializer for the indicated javaType and xmlType.
1600 * @param javaType is the type of the object
1601 * @param xmlType is the preferred qname type.
1602 * @param actualXMLType is set to a QNameHolder or null.
1603 * If a QNameHolder, the actual xmlType is returned.
1604 * @return found class/serializer or null
1605 **/
1606 private Serializer getSerializer(Class javaType, QName xmlType,
1607 QNameHolder actualXMLType) {
1608 SerializerFactory serFactory = null ;
1609 TypeMapping tm = getTypeMapping();
1610 if (actualXMLType != null) {
1611 actualXMLType.value = null;
1612 }
1613
1614 while (javaType != null) {
1615 // check type mapping
1616 serFactory = (SerializerFactory) tm.getSerializer(javaType, xmlType);
1617 if (serFactory != null) {
1618 break;
1619 }
1620
1621 // check the class for serializer
1622 Serializer serializer = getSerializerFromClass(javaType, xmlType);
1623 if (serializer != null) {
1624 if (actualXMLType != null) {
1625 TypeDesc typedesc = TypeDesc.getTypeDescForClass(javaType);
1626 if (typedesc != null) {
1627 actualXMLType.value = typedesc.getXmlType();
1628 }
1629 }
1630 return serializer;
1631 }
1632
1633 // Walk my interfaces...
1634 serFactory = getSerializerFactoryFromInterface(javaType, xmlType, tm);
1635 if (serFactory != null) {
1636 break;
1637 }
1638
1639 // Finally, head to my superclass
1640 javaType = javaType.getSuperclass();
1641 }
1642
1643 // Using the serialization factory, create a serializer
1644 Serializer ser = null;
1645 if ( serFactory != null ) {
1646 ser = (Serializer) serFactory.getSerializerAs(Constants.AXIS_SAX);
1647
1648 if (actualXMLType != null) {
1649 // Get the actual qname xmlType from the factory.
1650 // If not found via the factory, fall back to a less
1651 // performant solution.
1652 if (serFactory instanceof BaseSerializerFactory) {
1653 actualXMLType.value =
1654 ((BaseSerializerFactory) serFactory).getXMLType();
1655 }
1656 boolean encoded = isEncoded();
1657 if (actualXMLType.value == null ||
1658 (!encoded &&
1659 (actualXMLType.value.equals(Constants.SOAP_ARRAY) ||
1660 actualXMLType.value.equals(Constants.SOAP_ARRAY12)))) {
1661 actualXMLType.value = tm.getXMLType(javaType,
1662 xmlType,
1663 encoded);
1664 }
1665 }
1666 }
1667
1668 return ser;
1669 }
1670
1671 public String getValueAsString(Object value, QName xmlType, Class javaClass) throws IOException {
1672 Class cls = value.getClass();
1673 cls = getActualJavaClass(xmlType, javaClass, value);
1674
1675 Serializer ser = getSerializer(cls, xmlType, null);
1676
1677 // The java type is an array, but we need a simple type.
1678 if (ser instanceof ArraySerializer)
1679 {
1680 SimpleListSerializerFactory factory =
1681 new SimpleListSerializerFactory(cls, xmlType);
1682 ser = (Serializer)
1683 factory.getSerializerAs(getEncodingStyle());
1684 }
1685
1686 if (!(ser instanceof SimpleValueSerializer)) {
1687 throw new IOException(
1688 Messages.getMessage("needSimpleValueSer",
1689 ser.getClass().getName()));
1690 }
1691 SimpleValueSerializer simpleSer = (SimpleValueSerializer)ser;
1692 return simpleSer.getValueAsString(value, this);
1693 }
1694
1695 public void setWriteXMLType(QName type) {
1696 writeXMLType = type;
1697 }
1698
1699 public XMLEncoder getEncoder() {
1700 if(encoder == null) {
1701 encoder = XMLUtils.getXMLEncoder(encoding);
1702 }
1703 return encoder;
1704 }
1705
1706 /**
1707 * get the encoding for the serialization
1708 * @return
1709 */
1710 public String getEncoding() {
1711 return encoding;
1712 }
1713
1714 /**
1715 * set the encoding for the serialization
1716 */
1717 public void setEncoding(String encoding) {
1718 this.encoding = encoding;
1719 }
1720
1721 public QName getItemQName() {
1722 return itemQName;
1723 }
1724
1725 public void setItemQName(QName itemQName) {
1726 this.itemQName = itemQName;
1727 }
1728
1729 public QName getItemType() {
1730 return itemType;
1731 }
1732
1733 public void setItemType(QName itemType) {
1734 this.itemType = itemType;
1735 }
1736 }