1 17 package org.apache.servicemix.wsn.client; 18 19 import java.io.StringWriter ; 20 21 import javax.jbi.messaging.MessageExchange; 22 import javax.jbi.messaging.MessagingException; 23 import javax.jbi.messaging.NormalizedMessage; 24 import javax.xml.bind.JAXBContext; 25 import javax.xml.transform.Source ; 26 27 import org.apache.servicemix.jbi.jaxp.StringSource; 28 import org.apache.servicemix.jbi.messaging.DefaultMarshaler; 29 30 public class JAXBMarshaler extends DefaultMarshaler { 31 32 private JAXBContext context; 33 34 public JAXBMarshaler(JAXBContext context) { 35 this.context = context; 36 } 37 38 public JAXBContext getContext() { 39 return context; 40 } 41 42 public void setContext(JAXBContext context) { 43 this.context = context; 44 } 45 46 protected Object defaultUnmarshal(MessageExchange exchange, NormalizedMessage message) { 47 try { 48 Source content = message.getContent(); 49 return context.createUnmarshaller().unmarshal(content); 50 } catch (Exception e) { 51 throw new RuntimeException (e); 52 } 53 } 54 55 protected Source asContent(NormalizedMessage message, Object body) { 56 try { 57 StringWriter writer = new StringWriter (); 58 context.createMarshaller().marshal(body, writer); 59 return new StringSource(writer.toString()); 60 } catch (Exception e) { 61 throw new RuntimeException (e); 62 } 63 } 64 65 @Override  66 public void marshal(MessageExchange exchange, NormalizedMessage message, Object body) throws MessagingException { 67 if (body instanceof Source ) { 68 message.setContent((Source ) body); 69 } 70 else { 71 Source content = asContent(message, body); 72 message.setContent(content); 73 } 74 } 75 } 76 | Popular Tags |