View Javadoc
1   /*
2    * Copyright 2002-2012 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.jms.support.converter;
18  
19  import java.io.Serializable;
20  import java.util.Enumeration;
21  import java.util.HashMap;
22  import java.util.Map;
23  import javax.jms.BytesMessage;
24  import javax.jms.JMSException;
25  import javax.jms.MapMessage;
26  import javax.jms.Message;
27  import javax.jms.ObjectMessage;
28  import javax.jms.Session;
29  import javax.jms.TextMessage;
30  
31  import org.springframework.util.ObjectUtils;
32  
33  /**
34   * A simple message converter which is able to handle TextMessages, BytesMessages,
35   * MapMessages, and ObjectMessages. Used as default conversion strategy
36   * by {@link org.springframework.jms.core.JmsTemplate}, for
37   * {@code convertAndSend} and {@code receiveAndConvert} operations.
38   *
39   * <p>Converts a String to a {@link javax.jms.TextMessage}, a byte array to a
40   * {@link javax.jms.BytesMessage}, a Map to a {@link javax.jms.MapMessage}, and
41   * a Serializable object to a {@link javax.jms.ObjectMessage} (or vice versa).
42   *
43   * @author Juergen Hoeller
44   * @since 1.1
45   * @see org.springframework.jms.core.JmsTemplate#convertAndSend
46   * @see org.springframework.jms.core.JmsTemplate#receiveAndConvert
47   */
48  public class SimpleMessageConverter implements MessageConverter {
49  
50  	/**
51  	 * This implementation creates a TextMessage for a String, a
52  	 * BytesMessage for a byte array, a MapMessage for a Map,
53  	 * and an ObjectMessage for a Serializable object.
54  	 * @see #createMessageForString
55  	 * @see #createMessageForByteArray
56  	 * @see #createMessageForMap
57  	 * @see #createMessageForSerializable
58  	 */
59  	@Override
60  	public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
61  		if (object instanceof Message) {
62  			return (Message) object;
63  		}
64  		else if (object instanceof String) {
65  			return createMessageForString((String) object, session);
66  		}
67  		else if (object instanceof byte[]) {
68  			return createMessageForByteArray((byte[]) object, session);
69  		}
70  		else if (object instanceof Map) {
71  			return createMessageForMap((Map<? ,?>) object, session);
72  		}
73  		else if (object instanceof Serializable) {
74  			return createMessageForSerializable(((Serializable) object), session);
75  		}
76  		else {
77  			throw new MessageConversionException("Cannot convert object of type [" +
78  					ObjectUtils.nullSafeClassName(object) + "] to JMS message. Supported message " +
79  					"payloads are: String, byte array, Map<String,?>, Serializable object.");
80  		}
81  	}
82  
83  	/**
84  	 * This implementation converts a TextMessage back to a String, a
85  	 * ByteMessage back to a byte array, a MapMessage back to a Map,
86  	 * and an ObjectMessage back to a Serializable object. Returns
87  	 * the plain Message object in case of an unknown message type.
88  	 * @see #extractStringFromMessage
89  	 * @see #extractByteArrayFromMessage
90  	 * @see #extractMapFromMessage
91  	 * @see #extractSerializableFromMessage
92  	 */
93  	@Override
94  	public Object fromMessage(Message message) throws JMSException, MessageConversionException {
95  		if (message instanceof TextMessage) {
96  			return extractStringFromMessage((TextMessage) message);
97  		}
98  		else if (message instanceof BytesMessage) {
99  			return extractByteArrayFromMessage((BytesMessage) message);
100 		}
101 		else if (message instanceof MapMessage) {
102 			return extractMapFromMessage((MapMessage) message);
103 		}
104 		else if (message instanceof ObjectMessage) {
105 			return extractSerializableFromMessage((ObjectMessage) message);
106 		}
107 		else {
108 			return message;
109 		}
110 	}
111 
112 
113 	/**
114 	 * Create a JMS TextMessage for the given String.
115 	 * @param text the String to convert
116 	 * @param session current JMS session
117 	 * @return the resulting message
118 	 * @throws JMSException if thrown by JMS methods
119 	 * @see javax.jms.Session#createTextMessage
120 	 */
121 	protected TextMessage createMessageForString(String text, Session session) throws JMSException {
122 		return session.createTextMessage(text);
123 	}
124 
125 	/**
126 	 * Create a JMS BytesMessage for the given byte array.
127 	 * @param bytes the byyte array to convert
128 	 * @param session current JMS session
129 	 * @return the resulting message
130 	 * @throws JMSException if thrown by JMS methods
131 	 * @see javax.jms.Session#createBytesMessage
132 	 */
133 	protected BytesMessage createMessageForByteArray(byte[] bytes, Session session) throws JMSException {
134 		BytesMessage message = session.createBytesMessage();
135 		message.writeBytes(bytes);
136 		return message;
137 	}
138 
139 	/**
140 	 * Create a JMS MapMessage for the given Map.
141 	 * @param map the Map to convert
142 	 * @param session current JMS session
143 	 * @return the resulting message
144 	 * @throws JMSException if thrown by JMS methods
145 	 * @see javax.jms.Session#createMapMessage
146 	 */
147 	protected MapMessage createMessageForMap(Map<?, ?> map, Session session) throws JMSException {
148 		MapMessage message = session.createMapMessage();
149 		for (Map.Entry<?, ?> entry : map.entrySet()) {
150 			if (!(entry.getKey() instanceof String)) {
151 				throw new MessageConversionException("Cannot convert non-String key of type [" +
152 						ObjectUtils.nullSafeClassName(entry.getKey()) + "] to JMS MapMessage entry");
153 			}
154 			message.setObject((String) entry.getKey(), entry.getValue());
155 		}
156 		return message;
157 	}
158 
159 	/**
160 	 * Create a JMS ObjectMessage for the given Serializable object.
161 	 * @param object the Serializable object to convert
162 	 * @param session current JMS session
163 	 * @return the resulting message
164 	 * @throws JMSException if thrown by JMS methods
165 	 * @see javax.jms.Session#createObjectMessage
166 	 */
167 	protected ObjectMessage createMessageForSerializable(Serializable object, Session session) throws JMSException {
168 		return session.createObjectMessage(object);
169 	}
170 
171 
172 	/**
173 	 * Extract a String from the given TextMessage.
174 	 * @param message the message to convert
175 	 * @return the resulting String
176 	 * @throws JMSException if thrown by JMS methods
177 	 */
178 	protected String extractStringFromMessage(TextMessage message) throws JMSException {
179 		return message.getText();
180 	}
181 
182 	/**
183 	 * Extract a byte array from the given {@link BytesMessage}.
184 	 * @param message the message to convert
185 	 * @return the resulting byte array
186 	 * @throws JMSException if thrown by JMS methods
187 	 */
188 	protected byte[] extractByteArrayFromMessage(BytesMessage message) throws JMSException {
189 		byte[] bytes = new byte[(int) message.getBodyLength()];
190 		message.readBytes(bytes);
191 		return bytes;
192 	}
193 
194 	/**
195 	 * Extract a Map from the given {@link MapMessage}.
196 	 * @param message the message to convert
197 	 * @return the resulting Map
198 	 * @throws JMSException if thrown by JMS methods
199 	 */
200 	@SuppressWarnings("unchecked")
201 	protected Map<String, Object> extractMapFromMessage(MapMessage message) throws JMSException {
202 		Map<String, Object> map = new HashMap<String, Object>();
203 		Enumeration<String> en = message.getMapNames();
204 		while (en.hasMoreElements()) {
205 			String key = en.nextElement();
206 			map.put(key, message.getObject(key));
207 		}
208 		return map;
209 	}
210 
211 	/**
212 	 * Extract a Serializable object from the given {@link ObjectMessage}.
213 	 * @param message the message to convert
214 	 * @return the resulting Serializable object
215 	 * @throws JMSException if thrown by JMS methods
216 	 */
217 	protected Serializable extractSerializableFromMessage(ObjectMessage message) throws JMSException {
218 		return message.getObject();
219 	}
220 
221 }