1 18 package org.apache.activemq.util.xstream; 19 20 import com.thoughtworks.xstream.XStream; 21 import com.thoughtworks.xstream.io.HierarchicalStreamReader; 22 import com.thoughtworks.xstream.io.HierarchicalStreamWriter; 23 import com.thoughtworks.xstream.io.xml.PrettyPrintWriter; 24 import com.thoughtworks.xstream.io.xml.XppReader; 25 import org.apache.activemq.MessageTransformerSupport; 26 27 import javax.jms.JMSException ; 28 import javax.jms.Message ; 29 import javax.jms.MessageConsumer ; 30 import javax.jms.MessageProducer ; 31 import javax.jms.ObjectMessage ; 32 import javax.jms.Session ; 33 import javax.jms.TextMessage ; 34 import java.io.Serializable ; 35 import java.io.StringReader ; 36 import java.io.StringWriter ; 37 38 43 public class XStreamMessageTransformer extends MessageTransformerSupport { 44 private XStream xStream; 45 46 47 public Message producerTransform(Session session, MessageProducer producer, Message message) throws JMSException { 48 if (message instanceof ObjectMessage ) { 49 TextMessage answer = session.createTextMessage(marshall(session, producer, (ObjectMessage ) message)); 50 copyProperties(message, answer); 51 return answer; 52 } 53 return message; 54 } 55 56 57 public Message consumerTransform(Session session, MessageConsumer consumer, Message message) throws JMSException { 58 if (message instanceof TextMessage ) { 59 TextMessage textMessage = (TextMessage ) message; 60 Object object = unmarshall(session, consumer, textMessage); 61 if (object instanceof Serializable ) { 62 ObjectMessage answer = session.createObjectMessage((Serializable ) object); 63 copyProperties(message, answer); 64 return answer; 65 } 66 else { 67 throw new JMSException ("Object is not serializable: " + object); 68 } 69 } 70 return message; 71 } 72 73 74 public XStream getXStream() { 77 if (xStream == null) { 78 xStream = createXStream(); 79 } 80 return xStream; 81 } 82 83 public void setXStream(XStream xStream) { 84 this.xStream = xStream; 85 } 86 87 protected XStream createXStream() { 90 return new XStream(); 91 } 92 93 96 protected String marshall(Session session, MessageProducer producer, ObjectMessage objectMessage) throws JMSException { 97 Serializable object = objectMessage.getObject(); 98 StringWriter buffer = new StringWriter (); 99 HierarchicalStreamWriter out = new PrettyPrintWriter(buffer); 100 getXStream().marshal(object, out); 101 return buffer.toString(); 102 } 103 104 107 protected Object unmarshall(Session session, MessageConsumer consumer, TextMessage textMessage) throws JMSException { 108 HierarchicalStreamReader in = new XppReader(new StringReader (textMessage.getText())); 109 return getXStream().unmarshal(in); 110 } 111 112 } 113 | Popular Tags |