KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > activemq > web > MessageServletSupport


1 /**
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one or more
4  * contributor license agreements. See the NOTICE file distributed with
5  * this work for additional information regarding copyright ownership.
6  * The ASF licenses this file to You under the Apache License, Version 2.0
7  * (the "License"); you may not use this file except in compliance with
8  * the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18
19 package org.apache.activemq.web;
20
21 import org.apache.activemq.command.ActiveMQDestination;
22 import org.apache.activemq.command.ActiveMQQueue;
23 import org.apache.activemq.command.ActiveMQTopic;
24 import org.apache.commons.logging.Log;
25 import org.apache.commons.logging.LogFactory;
26
27 import javax.jms.Destination JavaDoc;
28 import javax.jms.JMSException JavaDoc;
29 import javax.jms.TextMessage JavaDoc;
30 import javax.servlet.ServletConfig JavaDoc;
31 import javax.servlet.ServletException JavaDoc;
32 import javax.servlet.http.HttpServlet JavaDoc;
33 import javax.servlet.http.HttpServletRequest JavaDoc;
34 import java.io.BufferedReader JavaDoc;
35 import java.io.IOException JavaDoc;
36 import java.util.HashMap JavaDoc;
37 import java.util.Iterator JavaDoc;
38 import java.util.Map JavaDoc;
39
40 /**
41  * A useful base class for any JMS related servlet;
42  * there are various ways to map JMS operations to web requests
43  * so we put most of the common behaviour in a reusable base class.
44  *
45  * This servlet can be configured with the following init paramters <dl>
46  * <dt>topic</dt><dd>Set to 'true' if the servle should default to using topics rather than channels</dd>
47  * <dt>destination</dt><dd>The default destination to use if one is not specifiied</dd>
48  * <dt></dt><dd></dd>
49  * </dl>
50  * @version $Revision: 1.1.1.1 $
51  */

52 public abstract class MessageServletSupport extends HttpServlet JavaDoc {
53
54     private static final transient Log log = LogFactory.getLog(MessageServletSupport.class);
55
56     private boolean defaultTopicFlag = true;
57     private Destination defaultDestination;
58     private String JavaDoc destinationParameter = "destination";
59     private String JavaDoc typeParameter = "type";
60     private String JavaDoc bodyParameter = "body";
61     private boolean defaultMessagePersistent = true;
62     private int defaultMessagePriority = 5;
63     private long defaultMessageTimeToLive = 0;
64     private String JavaDoc destinationOptions;
65
66     public void init(ServletConfig JavaDoc servletConfig) throws ServletException JavaDoc {
67         super.init(servletConfig);
68
69         destinationOptions = servletConfig.getInitParameter("destinationOptions");
70         
71         String JavaDoc name = servletConfig.getInitParameter("topic");
72         if (name != null) {
73             defaultTopicFlag = asBoolean(name);
74         }
75
76         if (log.isDebugEnabled()) {
77             log.debug("Defaulting to use topics: " + defaultTopicFlag);
78         }
79
80         name = servletConfig.getInitParameter("destination");
81         if (name != null) {
82             if (defaultTopicFlag) {
83                 defaultDestination = new ActiveMQTopic(name);
84             }
85             else {
86                 defaultDestination = new ActiveMQQueue(name);
87             }
88         }
89
90         // lets check to see if there's a connection factory set
91
WebClient.initContext(getServletContext());
92     }
93
94     public static boolean asBoolean(String JavaDoc param) {
95         return asBoolean(param, false);
96     }
97     
98     public static boolean asBoolean(String JavaDoc param, boolean defaultValue) {
99         if (param == null) {
100             return defaultValue;
101         }
102         else {
103             return param.equalsIgnoreCase("true");
104         }
105     }
106
107
108     protected void appendParametersToMessage(HttpServletRequest JavaDoc request, TextMessage JavaDoc message) throws JMSException JavaDoc {
109         Map JavaDoc parameterMap = request.getParameterMap();
110         if (parameterMap == null) {
111             return;
112         }
113         Map JavaDoc parameters = new HashMap JavaDoc(parameterMap);
114         String JavaDoc correlationID = asString(parameters.remove("JMSCorrelationID"));
115         if (correlationID != null) {
116             message.setJMSCorrelationID(correlationID);
117         }
118         Long JavaDoc expiration = asLong(parameters.remove("JMSExpiration"));
119         if (expiration != null) {
120             message.setJMSExpiration(expiration.longValue());
121         }
122         Integer JavaDoc priority = asInteger(parameters.remove("JMSPriority"));
123         if (expiration != null) {
124             message.setJMSPriority(priority.intValue());
125         }
126         Destination replyTo = asDestination(parameters.remove("JMSReplyTo"));
127         if (replyTo != null) {
128             message.setJMSReplyTo(replyTo);
129         }
130         String JavaDoc type = (String JavaDoc) asString(parameters.remove("JMSType"));
131         if (correlationID != null) {
132             message.setJMSType(type);
133         }
134
135         for (Iterator JavaDoc iter = parameters.entrySet().iterator(); iter.hasNext();) {
136             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) iter.next();
137             String JavaDoc name = (String JavaDoc) entry.getKey();
138             if (!destinationParameter.equals(name) && !typeParameter.equals(name) && !bodyParameter.equals(name)) {
139                 Object JavaDoc value = entry.getValue();
140                 if (value instanceof Object JavaDoc[]) {
141                     Object JavaDoc[] array = (Object JavaDoc[]) value;
142                     if (array.length == 1) {
143                         value = array[0];
144                     }
145                     else {
146                         log.warn("Can't use property: " + name + " which is of type: " + value.getClass().getName() + " value");
147                         value = null;
148                         for (int i = 0, size = array.length; i < size; i++) {
149                             log.debug("value[" + i + "] = " + array[i]);
150                         }
151                     }
152                 }
153                 if (value != null) {
154                     message.setObjectProperty(name, value);
155                 }
156             }
157         }
158     }
159
160     protected long getSendTimeToLive(HttpServletRequest JavaDoc request) {
161         String JavaDoc text = request.getParameter("JMSTimeToLive");
162         if (text != null) {
163             return asLong(text);
164         }
165         return defaultMessageTimeToLive;
166     }
167
168     protected int getSendPriority(HttpServletRequest JavaDoc request) {
169         String JavaDoc text = request.getParameter("JMSPriority");
170         if (text != null) {
171             return asInt(text);
172         }
173         return defaultMessagePriority;
174     }
175
176     protected boolean isSendPersistent(HttpServletRequest JavaDoc request) {
177         return defaultMessagePersistent;
178     }
179
180     protected Destination asDestination(Object JavaDoc value) {
181         if (value instanceof Destination) {
182             return (Destination) value;
183         }
184         if (value instanceof String JavaDoc) {
185             String JavaDoc text = (String JavaDoc) value;
186             return ActiveMQDestination.createDestination(text, ActiveMQDestination.QUEUE_TYPE);
187         }
188         if (value instanceof String JavaDoc[]) {
189             String JavaDoc text = ((String JavaDoc[]) value)[0];
190             if (text == null) {
191                 return null;
192             }
193             return ActiveMQDestination.createDestination(text, ActiveMQDestination.QUEUE_TYPE);
194         }
195         return null;
196     }
197
198     protected Integer JavaDoc asInteger(Object JavaDoc value) {
199         if (value instanceof Integer JavaDoc) {
200             return (Integer JavaDoc) value;
201         }
202         if (value instanceof String JavaDoc) {
203             return Integer.valueOf((String JavaDoc) value);
204         }
205         if (value instanceof String JavaDoc[]) {
206             return Integer.valueOf(((String JavaDoc[]) value)[0]);
207         }
208         return null;
209     }
210
211     protected Long JavaDoc asLong(Object JavaDoc value) {
212         if (value instanceof Long JavaDoc) {
213             return (Long JavaDoc) value;
214         }
215         if (value instanceof String JavaDoc) {
216             return Long.valueOf((String JavaDoc) value);
217         }
218         if (value instanceof String JavaDoc[]) {
219             return Long.valueOf(((String JavaDoc[]) value)[0]);
220         }
221         return null;
222     }
223
224     protected long asLong(String JavaDoc name) {
225         return Long.parseLong(name);
226     }
227     
228     protected int asInt(String JavaDoc name) {
229         return Integer.parseInt(name);
230     }
231
232     protected String JavaDoc asString(Object JavaDoc value) {
233         if (value instanceof String JavaDoc[]) {
234             return ((String JavaDoc[])value)[0];
235         }
236
237         if (value != null) {
238             return value.toString();
239         }
240
241         return null;
242     }
243
244     /**
245      * @return the destination to use for the current request
246      */

247     protected Destination getDestination(WebClient client, HttpServletRequest JavaDoc request) throws JMSException JavaDoc {
248         String JavaDoc destinationName = request.getParameter(destinationParameter);
249         if (destinationName == null) {
250             if (defaultDestination == null) {
251                 return getDestinationFromURI(client, request);
252             }
253             else {
254                 return defaultDestination;
255             }
256         }
257
258         return getDestination(client, request, destinationName);
259     }
260
261     /**
262      * @return the destination to use for the current request using the relative URI from
263      * where this servlet was invoked as the destination name
264      */

265     protected Destination getDestinationFromURI(WebClient client, HttpServletRequest JavaDoc request) throws JMSException JavaDoc {
266         String JavaDoc uri = request.getPathInfo();
267         if (uri == null)
268             return null;
269         
270         // replace URI separator with JMS destination separator
271
if (uri.startsWith("/")) {
272             uri = uri.substring(1);
273             if (uri.length()==0)
274                 return null;
275         }
276         
277         uri = uri.replace('/', '.');
278         System.err.println("destination uri="+uri);
279         return getDestination(client, request, uri);
280     }
281
282     /**
283      * @return the Destination object for the given destination name
284      */

285     protected Destination getDestination(WebClient client, HttpServletRequest JavaDoc request, String JavaDoc destinationName) throws JMSException JavaDoc {
286
287         // TODO cache destinations ???
288

289         boolean is_topic=defaultTopicFlag;
290         if (destinationName.startsWith("topic://"))
291         {
292             is_topic=true;
293             destinationName=destinationName.substring(8);
294         }
295         else if (destinationName.startsWith("channel://"))
296         {
297             is_topic=true;
298             destinationName=destinationName.substring(10);
299         }
300         else
301             is_topic=isTopic(request);
302         
303         if( destinationOptions!=null ) {
304             destinationName += "?" + destinationOptions;
305         }
306         
307         if (is_topic) {
308             return client.getSession().createTopic(destinationName);
309         }
310         else {
311             return client.getSession().createQueue(destinationName);
312         }
313     }
314
315     /**
316      * @return true if the current request is for a topic destination, else false if its for a queue
317      */

318     protected boolean isTopic(HttpServletRequest JavaDoc request) {
319         String JavaDoc typeText = request.getParameter(typeParameter);
320         if (typeText == null) {
321             return defaultTopicFlag;
322         }
323         return typeText.equalsIgnoreCase("topic");
324     }
325
326     /**
327      * @return the text that was posted to the servlet which is used as the body
328      * of the message to be sent
329      */

330     protected String JavaDoc getPostedMessageBody(HttpServletRequest JavaDoc request) throws IOException JavaDoc {
331         String JavaDoc answer = request.getParameter(bodyParameter);
332         if (answer == null && "text/xml".equals(request.getContentType())) {
333             // lets read the message body instead
334
BufferedReader JavaDoc reader = request.getReader();
335             StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
336             while (true) {
337                 String JavaDoc line = reader.readLine();
338                 if (line == null) {
339                     break;
340                 }
341                 buffer.append(line);
342                 buffer.append("\n");
343             }
344             return buffer.toString();
345         }
346         return answer;
347     }
348 }
349
Popular Tags