KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > providers > jms > JmsMessageUtils


1 /*
2  * $Id: JmsMessageUtils.java 3798 2006-11-04 04:07:14Z aperepel $
3  * --------------------------------------------------------------------------------------
4  * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
5  *
6  * The software in this package is published under the terms of the MuleSource MPL
7  * license, a copy of which has been included with this distribution in the
8  * LICENSE.txt file.
9  */

10
11 package org.mule.providers.jms;
12
13 import java.io.IOException JavaDoc;
14 import java.io.InputStream JavaDoc;
15 import java.io.ObjectOutputStream JavaDoc;
16 import java.io.Serializable JavaDoc;
17 import java.util.Enumeration JavaDoc;
18 import java.util.Hashtable JavaDoc;
19 import java.util.Iterator JavaDoc;
20 import java.util.Map JavaDoc;
21 import java.util.Vector JavaDoc;
22
23 import javax.jms.BytesMessage JavaDoc;
24 import javax.jms.Destination JavaDoc;
25 import javax.jms.JMSException JavaDoc;
26 import javax.jms.MapMessage JavaDoc;
27 import javax.jms.Message JavaDoc;
28 import javax.jms.MessageEOFException JavaDoc;
29 import javax.jms.ObjectMessage JavaDoc;
30 import javax.jms.Queue JavaDoc;
31 import javax.jms.Session JavaDoc;
32 import javax.jms.StreamMessage JavaDoc;
33 import javax.jms.TextMessage JavaDoc;
34 import javax.jms.Topic JavaDoc;
35
36 import org.apache.commons.io.output.ByteArrayOutputStream;
37 import org.mule.util.ArrayUtils;
38
39 /**
40  * <code>JmsMessageUtils</code> contains helper method for dealing with JMS
41  * messages in Mule.
42  */

43 public class JmsMessageUtils
44 {
45
46     public static Message JavaDoc toMessage(Object JavaDoc object, Session JavaDoc session) throws JMSException JavaDoc
47     {
48         if (object instanceof Message JavaDoc)
49         {
50             return (Message JavaDoc)object;
51         }
52         else if (object instanceof String JavaDoc)
53         {
54             return session.createTextMessage((String JavaDoc)object);
55         }
56         else if (object instanceof Map JavaDoc)
57         {
58             MapMessage JavaDoc mMsg = session.createMapMessage();
59             Map JavaDoc src = (Map JavaDoc)object;
60
61             for (Iterator JavaDoc i = src.entrySet().iterator(); i.hasNext();)
62             {
63                 Map.Entry JavaDoc entry = (Map.Entry JavaDoc)i.next();
64                 mMsg.setObject(entry.getKey().toString(), entry.getValue());
65             }
66
67             return mMsg;
68         }
69         else if (object instanceof InputStream JavaDoc)
70         {
71             StreamMessage JavaDoc sMsg = session.createStreamMessage();
72             InputStream JavaDoc temp = (InputStream JavaDoc)object;
73
74             byte[] buffer = new byte[4096];
75             int len;
76
77             try
78             {
79                 while ((len = temp.read(buffer)) != -1)
80                 {
81                     sMsg.writeBytes(buffer, 0, len);
82                 }
83             }
84             catch (IOException JavaDoc e)
85             {
86                 throw new JMSException JavaDoc("Failed to read input stream to create a stream message: " + e);
87             }
88
89             return sMsg;
90         }
91         else if (object instanceof byte[])
92         {
93             BytesMessage JavaDoc bMsg = session.createBytesMessage();
94             bMsg.writeBytes((byte[])object);
95             return bMsg;
96         }
97         else if (object instanceof Serializable JavaDoc)
98         {
99             ObjectMessage JavaDoc oMsg = session.createObjectMessage();
100             oMsg.setObject((Serializable JavaDoc)object);
101             return oMsg;
102         }
103         else
104         {
105             throw new JMSException JavaDoc(
106                 "Source was not a supported type, data must be Serializable, String, byte[], Map or InputStream");
107         }
108     }
109
110     public static Object JavaDoc toObject(Message JavaDoc source, String JavaDoc jmsSpec) throws JMSException JavaDoc, IOException JavaDoc
111     {
112         if (source instanceof ObjectMessage JavaDoc)
113         {
114             return ((ObjectMessage JavaDoc)source).getObject();
115         }
116         else if (source instanceof MapMessage JavaDoc)
117         {
118             Hashtable JavaDoc map = new Hashtable JavaDoc();
119             MapMessage JavaDoc m = (MapMessage JavaDoc)source;
120
121             for (Enumeration JavaDoc e = m.getMapNames(); e.hasMoreElements();)
122             {
123                 String JavaDoc name = (String JavaDoc)e.nextElement();
124                 Object JavaDoc obj = m.getObject(name);
125                 map.put(name, obj);
126             }
127
128             return map;
129         }
130         else if (source instanceof TextMessage JavaDoc)
131         {
132             return ((TextMessage JavaDoc)source).getText();
133         }
134         else if (source instanceof BytesMessage JavaDoc)
135         {
136             return toByteArray(source, jmsSpec);
137         }
138         else if (source instanceof StreamMessage JavaDoc)
139         {
140             try
141             {
142                 StreamMessage JavaDoc sMsg = (StreamMessage JavaDoc)source;
143                 Vector JavaDoc result = new Vector JavaDoc();
144                 Object JavaDoc obj;
145                 while ((obj = sMsg.readObject()) != null)
146                 {
147                     result.addElement(obj);
148                 }
149                 return result;
150             }
151             catch (MessageEOFException JavaDoc eof)
152             {
153                 // ignored
154
}
155             catch (Exception JavaDoc e)
156             {
157                 throw new JMSException JavaDoc("Failed to extract information from JMS Stream Message: " + e);
158             }
159         }
160
161         // what else is there to do?
162
return source;
163     }
164
165     /**
166      * @param message the message to receive the bytes from. Note this only works for
167      * TextMessge, ObjectMessage, StreamMessage and BytesMessage.
168      * @param jmsSpec indicates the JMS API version, either
169      * {@link JmsConstants#JMS_SPECIFICATION_102B} or
170      * {@link JmsConstants#JMS_SPECIFICATION_11}. Any other value
171      * including <code>null</code> is treated as fallback to
172      * {@link JmsConstants#JMS_SPECIFICATION_102B}.
173      * @return a byte array corresponding with the message payload
174      * @throws JMSException if the message can't be read or if the message passed is
175      * a MapMessage
176      * @throws java.io.IOException if a failure occurs while reading the stream and
177      * converting the message data
178      */

179     public static byte[] toByteArray(Message JavaDoc message, String JavaDoc jmsSpec) throws JMSException JavaDoc, IOException JavaDoc
180     {
181         if (message instanceof BytesMessage JavaDoc)
182         {
183             BytesMessage JavaDoc bMsg = (BytesMessage JavaDoc)message;
184             bMsg.reset();
185
186             if (JmsConstants.JMS_SPECIFICATION_11.equals(jmsSpec))
187             {
188                 long bmBodyLength = bMsg.getBodyLength();
189                 if (bmBodyLength > Integer.MAX_VALUE)
190                 {
191                     throw new JMSException JavaDoc("Size of BytesMessage exceeds Integer.MAX_VALUE; "
192                                            + "please consider using JMS StreamMessage instead");
193                 }
194
195                 if (bmBodyLength > 0)
196                 {
197                     byte[] bytes = new byte[(int)bmBodyLength];
198                     bMsg.readBytes(bytes);
199                     return bytes;
200                 }
201                 else
202                 {
203                     return ArrayUtils.EMPTY_BYTE_ARRAY;
204                 }
205             }
206             else
207             {
208                 ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
209                 byte[] buffer = new byte[4096];
210                 int len;
211
212                 while ((len = bMsg.readBytes(buffer)) != -1)
213                 {
214                     baos.write(buffer, 0, len);
215                 }
216
217                 if (baos.size() > 0)
218                 {
219                     return baos.toByteArray();
220                 }
221                 else
222                 {
223                     return ArrayUtils.EMPTY_BYTE_ARRAY;
224                 }
225             }
226         }
227         else if (message instanceof StreamMessage JavaDoc)
228         {
229             StreamMessage JavaDoc sMsg = (StreamMessage JavaDoc)message;
230             sMsg.reset();
231
232             ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
233             byte[] buffer = new byte[4096];
234             int len;
235
236             while ((len = sMsg.readBytes(buffer)) != -1)
237             {
238                 baos.write(buffer, 0, len);
239             }
240
241             return baos.toByteArray();
242         }
243         else if (message instanceof ObjectMessage JavaDoc)
244         {
245             ObjectMessage JavaDoc oMsg = (ObjectMessage JavaDoc)message;
246             ByteArrayOutputStream baos = new ByteArrayOutputStream();
247             ObjectOutputStream JavaDoc os = new ObjectOutputStream JavaDoc(baos);
248             os.writeObject(oMsg.getObject());
249             os.flush();
250             os.close();
251             return baos.toByteArray();
252         }
253         else if (message instanceof TextMessage JavaDoc)
254         {
255             TextMessage JavaDoc tMsg = (TextMessage JavaDoc)message;
256             String JavaDoc tMsgText = tMsg.getText();
257
258             if (null == tMsgText)
259             {
260                 // Avoid creating new instances of byte arrays, even empty ones. The
261
// load on this part of the code can be high.
262
return ArrayUtils.EMPTY_BYTE_ARRAY;
263             }
264             else
265             {
266                 return tMsgText.getBytes();
267             }
268         }
269         else
270         {
271             throw new JMSException JavaDoc("Cannot get bytes from Map Message");
272         }
273     }
274
275     public static String JavaDoc getNameForDestination(Destination JavaDoc dest) throws JMSException JavaDoc
276     {
277         if (dest instanceof Queue JavaDoc)
278         {
279             return ((Queue JavaDoc)dest).getQueueName();
280         }
281         else if (dest instanceof Topic JavaDoc)
282         {
283             return ((Topic JavaDoc)dest).getTopicName();
284         }
285         else
286         {
287             return null;
288         }
289     }
290
291     public static Message JavaDoc copyJMSProperties(Message JavaDoc from, Message JavaDoc to, JmsConnector connector)
292         throws JMSException JavaDoc
293     {
294         if (connector.supportsProperty(JmsConstants.JMS_CORRELATION_ID))
295         {
296             to.setJMSCorrelationID(from.getJMSCorrelationID());
297         }
298         if (connector.supportsProperty(JmsConstants.JMS_DELIVERY_MODE))
299         {
300             to.setJMSDeliveryMode(from.getJMSDeliveryMode());
301         }
302         if (connector.supportsProperty(JmsConstants.JMS_DESTINATION))
303         {
304             to.setJMSDestination(from.getJMSDestination());
305         }
306         if (connector.supportsProperty(JmsConstants.JMS_EXPIRATION))
307         {
308             to.setJMSExpiration(from.getJMSExpiration());
309         }
310         if (connector.supportsProperty(JmsConstants.JMS_MESSAGE_ID))
311         {
312             to.setJMSMessageID(from.getJMSMessageID());
313         }
314         if (connector.supportsProperty(JmsConstants.JMS_PRIORITY))
315         {
316             to.setJMSPriority(from.getJMSPriority());
317         }
318         if (connector.supportsProperty(JmsConstants.JMS_REDELIVERED))
319         {
320             to.setJMSRedelivered(from.getJMSRedelivered());
321         }
322         if (connector.supportsProperty(JmsConstants.JMS_REPLY_TO))
323         {
324             to.setJMSReplyTo(from.getJMSReplyTo());
325         }
326         if (connector.supportsProperty(JmsConstants.JMS_TIMESTAMP))
327         {
328             to.setJMSTimestamp(from.getJMSTimestamp());
329         }
330         if (connector.supportsProperty(JmsConstants.JMS_TYPE))
331         {
332             to.setJMSType(from.getJMSType());
333         }
334         return to;
335     }
336 }
337
Popular Tags