View Javadoc

1   /*
2    * $Id: MuleRESTReceiverServlet.java 19191 2010-08-25 21:05:23Z tcarlson $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.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.transport.servlet;
12  
13  import org.mule.api.MuleEvent;
14  import org.mule.api.MuleException;
15  import org.mule.api.MuleMessage;
16  import org.mule.api.endpoint.InboundEndpoint;
17  import org.mule.api.transport.MessageReceiver;
18  
19  import java.io.IOException;
20  
21  import javax.servlet.ServletException;
22  import javax.servlet.http.HttpServletRequest;
23  import javax.servlet.http.HttpServletResponse;
24  
25  
26  /**
27   * <code>MuleRESTReceiverServlet</code> is used for sending and receiving events from
28   * the Mule server via a servlet container. The servlet uses the REST style of request
29   * processing. <p/>
30   * GET METHOD will do a request from an endpoint if an endpoint parameter is set otherwise 
31   * it behaves the same way as POST. You can either specify the endpoint URL REST-style, 
32   * e.g., to read from jms://orders.queue <p/>
33   * http://www.mycompany.com/rest/jms/orders/queue <p/> or a logical Mule endpoint name, 
34   * e.g., this would get the first email message received by the orderEmailInbox endpoint. <p/>
35   * http://www.mycompany.com/rest/ordersEmailInbox <p/> 
36   * POST METHOD Do a synchronous call and return a result 
37   * http://www.clientapplication.com/service/clientquery?custId=1234 <p/> 
38   * PUT METHOD Do an asynchronous call without returning a result (other than an http
39   * status code) http://www.clientapplication.com/service/orders?payload=<order>more
40   * beer</order> <p/> 
41   * DELETE METHOD Same as GET only without returning a result
42   */
43  
44  public class MuleRESTReceiverServlet extends MuleReceiverServlet
45  {
46      /**
47       * Serial version
48       */
49      private static final long serialVersionUID = -2395763805839859649L;
50  
51      @Override
52      protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
53          throws ServletException, IOException
54      {
55          try
56          {
57              InboundEndpoint endpoint = getEndpointForURI(httpServletRequest);
58              if (endpoint != null)
59              {
60                  String timeoutString = httpServletRequest.getParameter("timeout");
61                  long to = timeout;
62  
63                  if (timeoutString != null)
64                  {
65                      to = Long.parseLong(timeoutString);
66                  }
67  
68                  if (logger.isDebugEnabled())
69                  {
70                      logger.debug("Making request using endpoint: " + endpoint.toString() + " timeout is: "
71                                   + to);
72                  }
73  
74                  MuleMessage returnMessage = endpoint.request(to);
75                  writeResponse(httpServletResponse, returnMessage);
76              }
77              else
78              {
79                  MessageReceiver receiver = getReceiverForURI(httpServletRequest);
80              
81                  httpServletRequest.setAttribute(PAYLOAD_PARAMETER_NAME, payloadParameterName);
82                  
83                  MuleMessage message = receiver.createMuleMessage(httpServletRequest);
84                  MuleEvent event = receiver.routeMessage(message);
85                  MuleMessage returnMessage = event == null ? null : event.getMessage();
86                  writeResponse(httpServletResponse, returnMessage);
87              }
88          }
89          catch (Exception e)
90          {
91              handleException(e, "Failed to route event through Servlet Receiver", httpServletResponse);
92          }
93      }
94  
95      @Override
96      protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
97          throws ServletException, IOException
98      {
99          try
100         {
101             MessageReceiver receiver = getReceiverForURI(httpServletRequest);
102 
103             httpServletRequest.setAttribute(PAYLOAD_PARAMETER_NAME, payloadParameterName);
104 
105             MuleMessage message = receiver.createMuleMessage(httpServletRequest, 
106                 receiver.getEndpoint().getEncoding());
107             
108             MuleEvent event = receiver.routeMessage(message);
109             MuleMessage returnMessage = event == null ? null : event.getMessage();
110             writeResponse(httpServletResponse, returnMessage);
111         }
112         catch (Exception e)
113         {
114             handleException(e, "Failed to Post event to Mule", httpServletResponse);
115         }
116     }
117 
118     @Override
119     protected void doPut(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
120         throws ServletException, IOException
121     {
122         try
123         {
124             MessageReceiver receiver = getReceiverForURI(httpServletRequest);
125 
126             httpServletRequest.setAttribute(PAYLOAD_PARAMETER_NAME, payloadParameterName);
127 
128             MuleMessage message = receiver.createMuleMessage(httpServletRequest, 
129                 receiver.getEndpoint().getEncoding());
130             receiver.routeMessage(message);
131 
132             httpServletResponse.setStatus(HttpServletResponse.SC_CREATED);
133             if (feedback)
134             {
135                 httpServletResponse.getWriter().write(
136                     "Item was created at endpointUri: " + receiver.getEndpointURI());
137             }
138         }
139         catch (Exception e)
140         {
141             handleException(e, "Failed to Post event to Mule" + e.getMessage(), httpServletResponse);
142         }
143     }
144 
145     @Override
146     protected void doDelete(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
147         throws ServletException, IOException
148     {
149         try
150         {
151             InboundEndpoint endpoint = getEndpointForURI(httpServletRequest);
152             String timeoutString = httpServletRequest.getParameter("timeout");
153             long to = timeout;
154 
155             if (timeoutString != null)
156             {
157                 to = new Long(timeoutString).longValue();
158             }
159 
160             if (logger.isDebugEnabled())
161             {
162                 logger.debug("Making request using endpoint: " + endpoint.toString() + " timeout is: " + to);
163             }
164 
165             MuleMessage returnMessage = endpoint.request(to);
166             if (returnMessage != null)
167             {
168                 httpServletResponse.setStatus(HttpServletResponse.SC_OK);
169             }
170             else
171             {
172                 httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT);
173             }
174         }
175         catch (Exception e)
176         {
177             handleException(e, "Failed to Delete mule event via receive using uri: "
178                                + httpServletRequest.getPathInfo(), httpServletResponse);
179         }
180     }
181 
182     protected InboundEndpoint getEndpointForURI(HttpServletRequest httpServletRequest)
183         throws MuleException
184     {
185         String endpointName = httpServletRequest.getParameter("endpoint");
186         if (endpointName == null)
187         {
188             // Let's try stripping the path and only use the last path element
189             String uri = httpServletRequest.getPathInfo();
190             int i = uri.lastIndexOf("/");
191             if (i > -1)
192             {
193                 endpointName = uri.substring(i + 1);
194             }
195         }
196 
197         InboundEndpoint endpoint = muleContext.getRegistry().lookupEndpointFactory().getInboundEndpoint(endpointName);
198         if (endpoint == null)
199         {
200             // if we dont find an endpoint for the given name, lets check the
201             // servlet receivers
202             MessageReceiver receiver = getReceivers().get(endpointName);
203             
204             if (receiver != null)
205             {
206                 endpoint = receiver.getEndpoint();
207             }
208         }
209         return endpoint;
210     }
211 }