MessageServletSupport xref

View Javadoc

    1   /***
    2    *
    3    * Copyright 2004 Protique Ltd
    4    *
    5    * Licensed under the Apache License, Version 2.0 (the "License");
    6    * you may not use this file except in compliance with the License.
    7    * You may obtain a copy of the License at
    8    *
    9    * http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   *
    17   **/
    18
    19  package org.codehaus.activemq.web;
    20
    21  import org.codehaus.activemq.message.ActiveMQQueue;
    22  import org.codehaus.activemq.message.ActiveMQTopic;
    23
    24  import javax.jms.Destination;
    25  import javax.jms.JMSException;
    26  import javax.jms.TextMessage;
    27  import javax.servlet.ServletConfig;
    28  import javax.servlet.ServletException;
    29  import javax.servlet.http.HttpServlet;
    30  import javax.servlet.http.HttpServletRequest;
    31  import javax.servlet.http.HttpSession;
    32  import java.io.BufferedReader;
    33  import java.io.IOException;
    34  import java.util.Iterator;
    35  import java.util.Map;
    36
    37  /***
    38   * A useful base class for any JMS related servlet;
    39   * there are various ways to map JMS operations to web requests
    40   * so we put most of the common behaviour in a reusable base class.
    41   *
    42   * @version $Revision: 1.9 $
    43   */
    44  public abstract class MessageServletSupport extends HttpServlet {
    45
    46      private boolean defaultTopicFlag = true;
    47      private Destination defaultDestination;
    48      private String destinationParameter = "destination";
    49      private String topicParameter = "topic";
    50      private String bodyParameter = "body";
    51
    52
    53      public void init(ServletConfig servletConfig) throws ServletException {
    54          super.init(servletConfig);
    55
    56          String name = servletConfig.getInitParameter("topic");
    57          if (name != null) {
    58              defaultTopicFlag = asBoolean(name);
    59          }
    60
    61          log("Defaulting to use topics: " + defaultTopicFlag);
    62
    63          name = servletConfig.getInitParameter("destination");
    64          if (name != null) {
    65              if (defaultTopicFlag) {
    66                  defaultDestination = new ActiveMQTopic(name);
    67              }
    68              else {
    69                  defaultDestination = new ActiveMQQueue(name);
    70              }
    71          }
    72
    73          // lets check to see if there's a connection factory set
    74          WebClient.initContext(getServletContext());
    75      }
    76
    77      protected WebClient createWebClient(HttpServletRequest request) {
    78          return new WebClient(getServletContext());
    79      }
    80
    81      public static boolean asBoolean(String param) {
    82          return param != null && param.equalsIgnoreCase("true");
    83      }
    84
    85      /***
    86       * Helper method to get the client for the current session
    87       *
    88       * @param request is the current HTTP request
    89       * @return the current client or a newly creates
    90       */
    91      protected WebClient getWebClient(HttpServletRequest request) {
    92          HttpSession session = request.getSession(true);
    93          WebClient client = WebClient.getWebClient(session);
    94          if (client == null) {
    95              client = createWebClient(request);
    96              session.setAttribute(WebClient.webClientAttribute, client);
    97          }
    98          return client;
    99      }
    100
    101
    102     protected void appendParametersToMessage(HttpServletRequest request, TextMessage message) throws JMSException {
    103         for (Iterator iter = request.getParameterMap().entrySet().iterator(); iter.hasNext();) {
    104             Map.Entry entry = (Map.Entry) iter.next();
    105             String name = (String) entry.getKey();
    106             if (!destinationParameter.equals(name) && !topicParameter.equals(name) && !bodyParameter.equals(name)) {
    107                 Object value = entry.getValue();
    108                 if (value instanceof Object[]) {
    109                     Object[] array = (Object[]) value;
    110                     if (array.length == 1) {
    111                         value = array[0];
    112                     }
    113                     else {
    114                         log("Can't use property: " + name + " which is of type: " + value.getClass().getName() + " value");
    115                         value = null;
    116                         for (int i = 0, size = array.length; i < size; i++) {
    117                             log("value[" + i + "] = " + array[i]);
    118                         }
    119                     }
    120                 }
    121                 if (value != null) {
    122                     message.setObjectProperty(name, value);
    123                 }
    124             }
    125         }
    126     }
    127
    128     /***
    129      * @return the destination to use for the current request
    130      */
    131     protected Destination getDestination(WebClient client, HttpServletRequest request) throws JMSException, NoDestinationSuppliedException {
    132         String destinationName = request.getParameter(destinationParameter);
    133         if (destinationName == null) {
    134             if (defaultDestination == null) {
    135                 return getDestinationFromURI(client, request);
    136             }
    137             else {
    138                 return defaultDestination;
    139             }
    140         }
    141
    142         return getDestination(client, request, destinationName);
    143     }
    144
    145     /***
    146      * @return the destination to use for the current request using the relative URI from
    147      *         where this servlet was invoked as the destination name
    148      */
    149     protected Destination getDestinationFromURI(WebClient client, HttpServletRequest request) throws NoDestinationSuppliedException, JMSException {
    150         String uri = request.getPathInfo();
    151         if (uri == null) {
    152             throw new NoDestinationSuppliedException();
    153         }
    154         // replace URI separator with JMS destination separator
    155         if (uri.startsWith("/")) {
    156             uri = uri.substring(1);
    157         }
    158         uri = uri.replace('/', '.');
    159         return getDestination(client, request, uri);
    160     }
    161
    162     /***
    163      * @return the Destination object for the given destination name
    164      */
    165     protected Destination getDestination(WebClient client, HttpServletRequest request, String destinationName) throws JMSException {
    166         if (isTopic(request)) {
    167             return client.getSession().createTopic(destinationName);
    168         }
    169         else {
    170             return client.getSession().createQueue(destinationName);
    171         }
    172     }
    173
    174     /***
    175      * @return true if the current request is for a topic destination, else false if its for a queue
    176      */
    177     protected boolean isTopic
    178             (HttpServletRequest
    179             request) {
    180         boolean aTopic = defaultTopicFlag;
    181         String aTopicText = request.getParameter(topicParameter);
    182         if (aTopicText != null) {
    183             aTopic = asBoolean(aTopicText);
    184         }
    185         return aTopic;
    186     }
    187
    188     protected long asLong(String name) {
    189         return Long.parseLong(name);
    190     }
    191
    192     /***
    193      * @return the text that was posted to the servlet which is used as the body
    194      *         of the message to be sent
    195      */
    196     protected String getPostedMessageBody(HttpServletRequest request) throws IOException {
    197         String answer = request.getParameter(bodyParameter);
    198         if (answer == null) {
    199             // lets read the message body instead
    200             BufferedReader reader = request.getReader();
    201             StringBuffer buffer = new StringBuffer();
    202             while (true) {
    203                 String line = reader.readLine();
    204                 if (line == null) {
    205                     break;
    206                 }
    207                 buffer.append(line);
    208                 buffer.append("\n");
    209             }
    210             return buffer.toString();
    211         }
    212         return answer;
    213     }
    214 }