KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > providers > http > servlet > HttpRequestMessageAdapter


1 /*
2  * $Id: HttpRequestMessageAdapter.java 3982 2006-11-22 14:28:01Z lajos $
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 MuleSource MPL
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 java.io.BufferedReader JavaDoc;
14 import java.io.IOException JavaDoc;
15 import java.util.Enumeration JavaDoc;
16 import java.util.Iterator JavaDoc;
17 import java.util.Map JavaDoc;
18
19 import javax.servlet.http.HttpServletRequest JavaDoc;
20 import javax.servlet.http.HttpSession JavaDoc;
21
22 import org.apache.commons.io.IOUtils;
23 import org.apache.commons.io.output.ByteArrayOutputStream;
24 import org.apache.commons.lang.SystemUtils;
25 import org.mule.config.MuleProperties;
26 import org.mule.config.i18n.Message;
27 import org.mule.config.i18n.Messages;
28 import org.mule.providers.AbstractMessageAdapter;
29 import org.mule.providers.http.HttpConstants;
30 import org.mule.umo.MessagingException;
31 import org.mule.umo.provider.MessageTypeNotSupportedException;
32 import org.mule.umo.provider.UniqueIdNotSupportedException;
33
34 /**
35  * <code>HttpRequestMessageAdapter</code> is a Mule message adapter for
36  * javax.servletHttpServletRequest objects.
37  */

38
39 public class HttpRequestMessageAdapter extends AbstractMessageAdapter
40 {
41     /**
42      * Serial version
43      */

44     private static final long serialVersionUID = -4238448252206941125L;
45
46     private Object JavaDoc message = null;
47
48     private HttpServletRequest JavaDoc request;
49
50     public HttpRequestMessageAdapter(Object JavaDoc message) throws MessagingException
51     {
52         if (message instanceof HttpServletRequest JavaDoc)
53         {
54             setPayload((HttpServletRequest JavaDoc)message);
55             final Map JavaDoc parameterMap = request.getParameterMap();
56             if (parameterMap != null && parameterMap.size() > 0)
57             {
58                 for (Iterator JavaDoc iterator = parameterMap.entrySet().iterator(); iterator.hasNext();)
59                 {
60                     Map.Entry JavaDoc entry = (Map.Entry JavaDoc)iterator.next();
61                     String JavaDoc key = (String JavaDoc)entry.getKey();
62                     Object JavaDoc value = entry.getValue();
63                     if (value != null)
64                     {
65                         if (value.getClass().isArray() && ((Object JavaDoc[])value).length == 1)
66                         {
67                             setProperty(key, ((Object JavaDoc[])value)[0]);
68                         }
69                         else
70                         {
71                             setProperty(key, value);
72                         }
73                     }
74                 }
75             }
76             String JavaDoc key;
77             for (Enumeration JavaDoc e = request.getAttributeNames(); e.hasMoreElements();)
78             {
79                 key = (String JavaDoc)e.nextElement();
80                 properties.put(key, request.getAttribute(key));
81             }
82             String JavaDoc realKey;
83             for (Enumeration JavaDoc e = request.getHeaderNames(); e.hasMoreElements();)
84             {
85                 key = (String JavaDoc)e.nextElement();
86                 realKey = key;
87                 if (key.startsWith(HttpConstants.X_PROPERTY_PREFIX))
88                 {
89                     realKey = key.substring(2);
90                 }
91                 setProperty(realKey, request.getHeader(key));
92             }
93         }
94         else
95         {
96             throw new MessageTypeNotSupportedException(message, getClass());
97         }
98     }
99
100     /*
101      * (non-Javadoc)
102      *
103      * @see org.mule.umo.providers.UMOMessageAdapter#getMessage()
104      */

105     public Object JavaDoc getPayload()
106     {
107         return message;
108     }
109
110     public boolean isBinary()
111     {
112         return message instanceof byte[];
113     }
114
115     /*
116      * (non-Javadoc)
117      *
118      * @see org.mule.umo.providers.UMOMessageAdapter#getMessageAsBytes()
119      */

120     public byte[] getPayloadAsBytes() throws Exception JavaDoc
121     {
122         if (isBinary())
123         {
124             return (byte[])message;
125         }
126         else
127         {
128             return ((String JavaDoc)message).getBytes();
129         }
130     }
131
132     /**
133      * Converts the message implementation into a String representation
134      *
135      * @param encoding The encoding to use when transforming the message (if
136      * necessary). The parameter is used when converting from a byte array
137      * @return String representation of the message payload
138      * @throws Exception Implementation may throw an endpoint specific exception
139      */

140     public String JavaDoc getPayloadAsString(String JavaDoc encoding) throws Exception JavaDoc
141     {
142         if (isBinary())
143         {
144             return new String JavaDoc((byte[])message, encoding);
145         }
146         else
147         {
148             return (String JavaDoc)message;
149         }
150     }
151
152     /*
153      * (non-Javadoc)
154      *
155      * @see org.mule.umo.providers.UMOMessageAdapter#setMessage(java.lang.Object)
156      */

157     private void setPayload(HttpServletRequest JavaDoc message) throws MessagingException
158     {
159         try
160         {
161
162             request = message;
163             // String httpRequest = null;
164
// httpRequest = request.getScheme() + "://" + request.getServerName() +
165
// ":" + request.getServerPort() + request.getServletPath();
166
// httpRequest += request.getPathInfo();
167
// if(StringUtils.isNotBlank(request.getQueryString())) {
168
// httpRequest += "?" + request.getQueryString();
169
// }
170
// setProperty(HttpConnector.HTTP_REQUEST_PROPERTY, httpRequest);
171
// this.message = httpRequest;
172

173             // Check if a payload parameter has been set, if so use it
174
// otherwise we'll use the request payload
175
String JavaDoc payloadParam = (String JavaDoc)request
176                 .getAttribute(AbstractReceiverServlet.PAYLOAD_PARAMETER_NAME);
177
178             if (payloadParam == null)
179             {
180                 payloadParam = AbstractReceiverServlet.DEFAULT_PAYLOAD_PARAMETER_NAME;
181             }
182             String JavaDoc payload = request.getParameter(payloadParam);
183             if (payload == null)
184             {
185                 if (isText(request.getContentType()))
186                 {
187                     BufferedReader JavaDoc reader = request.getReader();
188                     StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(8192);
189                     String JavaDoc line = reader.readLine();
190                     while (line != null)
191                     {
192                         buffer.append(line);
193                         line = reader.readLine();
194                         if (line != null) buffer.append(SystemUtils.LINE_SEPARATOR);
195                     }
196                     this.message = buffer.toString();
197                 }
198                 else
199                 {
200                     ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
201                     IOUtils.copy(request.getInputStream(), baos);
202                     this.message = baos.toByteArray();
203                 }
204             }
205             else
206             {
207                 this.message = payload;
208             }
209         }
210         catch (IOException JavaDoc e)
211         {
212             throw new MessagingException(new Message("servlet", 3, request.getRequestURL().toString()), e);
213         }
214     }
215
216     public HttpServletRequest JavaDoc getRequest()
217     {
218         return request;
219     }
220
221     public String JavaDoc getUniqueId()
222     {
223         HttpSession JavaDoc session = null;
224
225         try
226         {
227             // We wrap this call as on some App Servers (Websfear) it can cause an
228
// NPE
229
session = getRequest().getSession();
230         }
231         catch (Exception JavaDoc e)
232         {
233             throw new UniqueIdNotSupportedException(this, new Message(Messages.X_IS_NULL, "Http session"));
234         }
235         if (session == null)
236         {
237             throw new UniqueIdNotSupportedException(this, new Message(Messages.X_IS_NULL, "Http session"));
238         }
239         return session.getId();
240     }
241
242     protected boolean isText(String JavaDoc contentType)
243     {
244         if (contentType == null)
245         {
246             return true;
247         }
248         return (contentType.startsWith("text/"));
249     }
250
251     /**
252      * Sets a replyTo address for this message. This is useful in an asynchronous
253      * environment where the caller doesn't wait for a response and the response
254      * needs to be routed somewhere for further processing. The value of this field
255      * can be any valid endpointUri url.
256      *
257      * @param replyTo the endpointUri url to reply to
258      */

259     public void setReplyTo(Object JavaDoc replyTo)
260     {
261         if (replyTo != null && replyTo.toString().startsWith("http"))
262         {
263             setProperty(HttpConstants.HEADER_LOCATION, replyTo);
264         }
265         setProperty(MuleProperties.MULE_CORRELATION_ID_PROPERTY, replyTo);
266     }
267
268     /**
269      * Sets a replyTo address for this message. This is useful in an asynchronous
270      * environment where the caller doesn't wait for a response and the response
271      * needs to be routed somewhere for further processing. The value of this field
272      * can be any valid endpointUri url.
273      *
274      * @return the endpointUri url to reply to or null if one has not been set
275      */

276     public Object JavaDoc getReplyTo()
277     {
278         String JavaDoc replyto = (String JavaDoc)getProperty(MuleProperties.MULE_REPLY_TO_PROPERTY);
279         if (replyto == null)
280         {
281             replyto = (String JavaDoc)getProperty(HttpConstants.HEADER_LOCATION);
282         }
283         return replyto;
284     }
285 }
286
Popular Tags