View Javadoc

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