View Javadoc

1   /*
2    * $Id: ObjectToXml.java 11236 2008-03-06 23:48:23Z tcarlson $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSource, Inc.  All rights reserved.  http://www.mulesource.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.module.xml.transformer;
12  
13  import org.mule.api.MuleMessage;
14  import org.mule.api.transformer.TransformerException;
15  
16  /**
17   * <code>ObjectToXml</code> converts any object to XML using Xstream. Xstream uses
18   * some clever tricks so objects that get marshalled to XML do not need to implement
19   * any interfaces including Serializable and you don't even need to specify a default
20   * constructor. If <code>MuleMessage</code> is configured as a source type on this
21   * transformer by calling <code>setAcceptUMOMessage(true)</code> then the MuleMessage
22   * will be serialised. This is useful for transports such as TCP where the message
23   * headers would normally be lost.
24   */
25  
26  public class ObjectToXml extends AbstractXStreamTransformer
27  {
28  
29      public ObjectToXml()
30      {
31          this.registerSourceType(Object.class);
32          this.setReturnClass(String.class);
33      }
34  
35      public boolean isAcceptUMOMessage()
36      {
37          return this.sourceTypes.contains(MuleMessage.class);
38      }
39  
40      public void setAcceptUMOMessage(boolean value)
41      {
42          if (value)
43          {
44              this.registerSourceType(MuleMessage.class);
45          }
46          else
47          {
48              this.unregisterSourceType(MuleMessage.class);
49          }
50      }
51  
52      public Object transform(MuleMessage message, String outputEncoding) throws TransformerException
53      {
54          Object src = message.getPayload();
55          /*
56           * If the MuleMessage source type has been registered that we can assume that
57           * the whole message is to be serialised to Xml, not just the payload. This
58           * can be useful for protocols such as tcp where the protocol does not
59           * support headers, thus the whole messgae needs to be serialized
60           */
61          if (this.isAcceptUMOMessage())
62          {
63              src = message;
64          }
65          return this.getXStream().toXML(src);
66      }
67  }