View Javadoc

1   /*
2    * $Id: ObjectToXml.java 7976 2007-08-21 14:26:13Z dirk.olmes $
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.transformers.xml;
12  
13  import org.mule.umo.UMOEventContext;
14  import org.mule.umo.UMOMessage;
15  import org.mule.umo.transformer.TransformerException;
16  
17  /**
18   * <code>ObjectToXml</code> converts any object to XML using Xstream. Xstream uses
19   * some clever tricks so objects that get marshalled to XML do not need to implement
20   * any interfaces including Serializable and you don't even need to specify a default
21   * constructor. If <code>UMOMessage</code> is configured as a source type on this
22   * transformer by calling <code>setAcceptUMOMessage(true)</code> then the UMOMessage
23   * will be serialised. This is useful for transports such as TCP where the message
24   * headers would normally be lost.
25   */
26  
27  public class ObjectToXml extends AbstractXStreamTransformer
28  {
29  
30      public ObjectToXml()
31      {
32          this.registerSourceType(Object.class);
33      }
34  
35      public boolean isAcceptUMOMessage()
36      {
37          return this.isSourceTypeSupported(UMOMessage.class, true);
38      }
39  
40      public void setAcceptUMOMessage(boolean value)
41      {
42          if (value)
43          {
44              this.registerSourceType(UMOMessage.class);
45          }
46          else
47          {
48              this.unregisterSourceType(UMOMessage.class);
49          }
50      }
51  
52      public Object transform(Object src, String encoding, UMOEventContext context) throws TransformerException
53      {
54          /*
55           * If the UMOMessage source type has been registered that we can assume that
56           * the whole message is to be serialised to Xml, not just the payload. This
57           * can be useful for protocols such as tcp where the protocol does not
58           * support headers, thus the whole messgae needs to be serialized
59           */
60          if (this.isAcceptUMOMessage() && context != null)
61          {
62              src = context.getMessage();
63          }
64  
65          return this.getXStream().toXML(src);
66      }
67  }