View Javadoc

1   /*
2    * $Id: AbstractReceiverServlet.java 8560 2007-09-24 14:10:29Z marie.rizzo $
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 CPAL v1.0
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.http.servlet;
12  
13  import org.mule.providers.http.HttpConnector;
14  import org.mule.providers.http.HttpConstants;
15  import org.mule.providers.http.HttpResponse;
16  import org.mule.umo.UMOMessage;
17  
18  import java.io.ByteArrayInputStream;
19  import java.io.IOException;
20  
21  import javax.servlet.ServletConfig;
22  import javax.servlet.ServletException;
23  import javax.servlet.http.HttpServlet;
24  import javax.servlet.http.HttpServletResponse;
25  
26  import org.apache.commons.httpclient.Header;
27  import org.apache.commons.logging.Log;
28  import org.apache.commons.logging.LogFactory;
29  
30  /**
31   * A base servlet used to receive requests from a servlet container and route
32   * them into Mule
33   */
34  
35  public abstract class AbstractReceiverServlet extends HttpServlet
36  {
37      /**
38       * logger used by this class
39       */
40      protected transient Log logger = LogFactory.getLog(getClass());
41  
42      public static final String REQUEST_TIMEOUT_PROPERTY = "org.mule.servlet.timeout";
43      public static final String FEEDBACK_PROPERTY = "org.mule.servlet.feedback";
44      public static final String DEFAULT_CONTENT_TYPE_PROPERTY = "org.mule.servlet.default.content.type";
45  
46      /** The name of the servlet connector to use with this Servlet */
47      public static final String SERVLET_CONNECTOR_NAME_PROPERTY = "org.mule.servlet.connector.name";
48  
49      public static final String PAYLOAD_PARAMETER_NAME = "org.mule.servlet.payload.param";
50      public static final String DEFAULT_PAYLOAD_PARAMETER_NAME = "payload";
51  
52      public static final long DEFAULT_GET_TIMEOUT = 10000L;
53  
54      protected String payloadParameterName;
55      protected long timeout = DEFAULT_GET_TIMEOUT;
56      protected boolean feedback = true;
57      protected String defaultContentType = HttpConstants.DEFAULT_CONTENT_TYPE;
58  
59      public final void init() throws ServletException
60      {
61          doInit();
62      }
63  
64      public final void init(ServletConfig servletConfig) throws ServletException
65      {
66          String timeoutString = servletConfig.getInitParameter(REQUEST_TIMEOUT_PROPERTY);
67          if (timeoutString != null)
68          {
69              timeout = Long.parseLong(timeoutString);
70          }
71          logger.info("Default request timeout for GET methods is: " + timeout);
72  
73          String feedbackString = servletConfig.getInitParameter(FEEDBACK_PROPERTY);
74          if (feedbackString != null)
75          {
76              feedback = Boolean.valueOf(feedbackString).booleanValue();
77          }
78          logger.info("feedback is set to: " + feedback);
79  
80          String ct = servletConfig.getInitParameter(DEFAULT_CONTENT_TYPE_PROPERTY);
81          if (ct != null)
82          {
83              defaultContentType = ct;
84          }
85          logger.info("Default content type is: " + defaultContentType);
86  
87          payloadParameterName = servletConfig.getInitParameter(PAYLOAD_PARAMETER_NAME);
88          if (payloadParameterName == null)
89          {
90              payloadParameterName = DEFAULT_PAYLOAD_PARAMETER_NAME;
91          }
92          logger.info("Using payload param name: " + payloadParameterName);
93  
94          doInit(servletConfig);
95      }
96  
97      protected void doInit(ServletConfig servletConfig) throws ServletException
98      {
99          // nothing to do
100     }
101 
102     protected void doInit() throws ServletException
103     {
104         // nothing to do
105     }
106 
107     protected void writeResponse(HttpServletResponse servletResponse, UMOMessage message) throws Exception
108     {
109         if (message == null)
110         {
111             servletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT);
112             if (feedback)
113             {
114                 servletResponse.setStatus(HttpServletResponse.SC_OK);
115                 servletResponse.getWriter().write("Action was processed successfully. There was no result");
116             }
117         }
118         else
119         {
120             HttpResponse httpResponse;
121 
122             if (message.getPayload() instanceof HttpResponse)
123             {
124                 httpResponse = (HttpResponse)message.getPayload();
125             }
126             else
127             {
128                 httpResponse = new HttpResponse();
129                 httpResponse.setBody(new ByteArrayInputStream(message.getAdapter().getPayloadAsBytes()));
130                 String ct = message.getStringProperty(HttpConstants.HEADER_CONTENT_TYPE, null);
131                 if(ct!=null)
132                 {
133                     httpResponse.setHeader(new Header(HttpConstants.HEADER_CONTENT_TYPE, ct));
134                 }
135                 httpResponse.setStatusLine(httpResponse.getHttpVersion(), 
136                     message.getIntProperty(HttpConnector.HTTP_STATUS_PROPERTY, HttpServletResponse.SC_OK));
137             }
138 
139             Header contentTypeHeader = httpResponse.getFirstHeader(HttpConstants.HEADER_CONTENT_TYPE);
140             String contentType = null;
141             if (contentTypeHeader == null)
142             {
143                 contentType = defaultContentType;
144             }
145             else
146             {
147                 contentType = contentTypeHeader.getValue();
148             }
149 
150             if (!servletResponse.isCommitted())
151             {
152                 servletResponse.setStatus(httpResponse.getStatusCode());
153             }
154             if (!contentType.startsWith("text"))
155             {
156                 servletResponse.setContentType(contentType);
157                 servletResponse.getOutputStream().write(httpResponse.getBodyBytes());
158             }
159             else
160             {
161 
162                 servletResponse.setContentType(contentType);
163                 // Encoding: this method will check the charset on the content type
164                 servletResponse.getWriter().write(httpResponse.getBodyString());
165             }
166         }
167         servletResponse.flushBuffer();
168     }
169 
170     protected void handleException(Throwable exception, String message, HttpServletResponse response)
171     {
172         logger.error("message: " + exception.getMessage(), exception);
173         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
174         try
175         {
176             response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message + ": "
177                                                                              + exception.getMessage());
178         }
179         catch (IOException e)
180         {
181             logger.error("Failed to sendError on response: " + e.getMessage(), e);
182         }
183     }
184 }