001 /** 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 018 package org.apache.activemq.util.oxm; 019 020 import javax.jms.JMSException; 021 import javax.jms.ObjectMessage; 022 import javax.jms.Session; 023 import javax.jms.TextMessage; 024 025 import org.springframework.oxm.AbstractMarshaller; 026 import org.springframework.oxm.Marshaller; 027 import org.springframework.oxm.Unmarshaller; 028 import org.springframework.xml.transform.StringResult; 029 import org.springframework.xml.transform.StringSource; 030 031 /** 032 * Transforms object messages to text messages and vice versa using {@link Spring OXM} 033 * 034 */ 035 public class OXMMessageTransformer extends AbstractXMLMessageTransformer { 036 037 /** 038 * OXM marshaller used to marshall/unmarshall messages 039 */ 040 private AbstractMarshaller marshaller; 041 042 public AbstractMarshaller getMarshaller() { 043 return marshaller; 044 } 045 046 public void setMarshaller(AbstractMarshaller marshaller) { 047 this.marshaller = marshaller; 048 } 049 050 /** 051 * Marshalls the Object in the {@link ObjectMessage} to a string using XML 052 * encoding 053 */ 054 protected String marshall(Session session, ObjectMessage objectMessage) 055 throws JMSException { 056 StringResult result = new StringResult(); 057 try { 058 marshaller.marshal(objectMessage.getObject(), result); 059 return result.toString(); 060 } catch (Exception e) { 061 throw new JMSException(e.getMessage()); 062 } 063 } 064 065 /** 066 * Unmarshalls the XML encoded message in the {@link TextMessage} to an 067 * Object 068 */ 069 protected Object unmarshall(Session session, TextMessage textMessage) 070 throws JMSException { 071 try { 072 return marshaller.unmarshal(new StringSource(textMessage.getText())); 073 } catch (Exception e) { 074 throw new JMSException(e.getMessage()); 075 } 076 } 077 078 }