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