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