KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > providers > http > transformers > ObjectToHttpClientMethodRequest


1 /*
2  * $Id: ObjectToHttpClientMethodRequest.java 3798 2006-11-04 04:07:14Z aperepel $
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.transformers;
12
13 import org.apache.commons.httpclient.HttpMethod;
14 import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
15 import org.apache.commons.httpclient.methods.GetMethod;
16 import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
17 import org.apache.commons.httpclient.methods.PostMethod;
18 import org.apache.commons.httpclient.methods.StringRequestEntity;
19 import org.apache.commons.lang.StringUtils;
20 import org.mule.MuleManager;
21 import org.mule.config.MuleProperties;
22 import org.mule.config.i18n.Message;
23 import org.mule.config.i18n.Messages;
24 import org.mule.providers.NullPayload;
25 import org.mule.providers.http.HttpConnector;
26 import org.mule.providers.http.HttpConstants;
27 import org.mule.transformers.AbstractEventAwareTransformer;
28 import org.mule.transformers.simple.SerializableToByteArray;
29 import org.mule.umo.UMOEventContext;
30 import org.mule.umo.UMOMessage;
31 import org.mule.umo.transformer.TransformerException;
32
33 import java.io.InputStream JavaDoc;
34 import java.net.URI JavaDoc;
35 import java.util.Iterator JavaDoc;
36
37 /**
38  * <code>ObjectToHttpClientMethodRequest</code> transforms a UMOMessage into a
39  * HttpClient HttpMethod that represents an HttpRequest.
40  *
41  * @author <a HREF="mailto:ross.mason@symphonysoft.com">Ross Mason</a>
42  * @version $Revision: 3798 $
43  */

44
45 public class ObjectToHttpClientMethodRequest extends AbstractEventAwareTransformer
46 {
47     /**
48      * Serial version
49      */

50     private static final long serialVersionUID = -5726306151419912371L;
51
52     private SerializableToByteArray serializableToByteArray;
53
54     public ObjectToHttpClientMethodRequest()
55     {
56         setReturnClass(HttpMethod.class);
57         serializableToByteArray = new SerializableToByteArray();
58     }
59
60     private int addParameters(String JavaDoc queryString, PostMethod postMethod)
61     {
62         // Parse the HTTP argument list and convert to a NameValuePair
63
// collection
64

65         if (StringUtils.isEmpty(queryString))
66         {
67             return 0;
68         }
69
70         String JavaDoc currentParam;
71         int equals;
72         equals = queryString.indexOf("&");
73         if (equals > -1)
74         {
75             currentParam = queryString.substring(0, equals);
76             queryString = queryString.substring(equals + 1);
77         }
78         else
79         {
80             currentParam = queryString;
81             queryString = StringUtils.EMPTY;
82         }
83         int parameterIndex = -1;
84         while (StringUtils.isNotBlank(currentParam))
85         {
86             String JavaDoc paramName, paramValue;
87             equals = currentParam.indexOf("=");
88             if (equals > -1)
89             {
90                 paramName = currentParam.substring(0, equals);
91                 paramValue = currentParam.substring(equals + 1);
92                 parameterIndex++;
93                 postMethod.addParameter(paramName, paramValue);
94             }
95             equals = queryString.indexOf("&");
96             if (equals > -1)
97             {
98                 currentParam = queryString.substring(0, equals);
99                 queryString = queryString.substring(equals + 1);
100             }
101             else
102             {
103                 currentParam = queryString;
104                 queryString = StringUtils.EMPTY;
105             }
106         }
107         return parameterIndex + 1;
108     }
109
110     public Object JavaDoc transform(Object JavaDoc src, String JavaDoc encoding, UMOEventContext context) throws TransformerException
111     {
112         UMOMessage msg = context.getMessage();
113
114         String JavaDoc endpoint = msg.getStringProperty(MuleProperties.MULE_ENDPOINT_PROPERTY, null);
115         if (endpoint == null)
116         {
117             throw new TransformerException(
118                 new Message(Messages.EVENT_PROPERTY_X_NOT_SET_CANT_PROCESS_REQUEST,
119                     MuleProperties.MULE_ENDPOINT_PROPERTY), this);
120         }
121
122         String JavaDoc method = msg.getStringProperty(HttpConnector.HTTP_METHOD_PROPERTY, "POST");
123         try
124         {
125             URI JavaDoc uri = new URI JavaDoc(endpoint);
126             HttpMethod httpMethod = null;
127
128             if (HttpConstants.METHOD_GET.equals(method))
129             {
130                 httpMethod = new GetMethod(uri.toString());
131                 setHeaders(httpMethod, context);
132                 String JavaDoc paramName = msg.getStringProperty(HttpConnector.HTTP_GET_BODY_PARAM_PROPERTY,
133                     HttpConnector.DEFAULT_HTTP_GET_BODY_PARAM_PROPERTY);
134                 String JavaDoc query = uri.getQuery();
135                 if (!(src instanceof NullPayload) && !StringUtils.EMPTY.equals(src))
136                 {
137                     if (query == null)
138                     {
139                         query = paramName + "=" + src.toString();
140                     }
141                     else
142                     {
143                         query += "&" + paramName + "=" + src.toString();
144                     }
145                 }
146                 httpMethod.setQueryString(query);
147
148             }
149             else
150             {
151                 PostMethod postMethod = new PostMethod(uri.toString());
152                 setHeaders(postMethod, context);
153                 String JavaDoc paramName = msg.getStringProperty(HttpConnector.HTTP_POST_BODY_PARAM_PROPERTY, null);
154                 // postMethod.setRequestContentLength(PostMethod.CONTENT_LENGTH_AUTO);
155
if (paramName == null)
156                 {
157                     // Call method to manage the parameter array
158
addParameters(uri.getQuery(), postMethod);
159                     // Dont set a POST payload if the body is a Null Payload.
160
// This way client calls
161
// can control if a POST body is posted explicitly
162
if (!(context.getMessage().getPayload() instanceof NullPayload))
163                     {
164                         // See if we have a MIME type set
165
String JavaDoc mimeType = msg.getStringProperty(HttpConstants.HEADER_CONTENT_TYPE, null);
166
167                         if (src instanceof String JavaDoc)
168                         {
169                             // Ensure that we strip the encoding information from the
170
// encoding type
171
if (mimeType != null)
172                             {
173                                 int parameterIndex = mimeType.indexOf(";");
174                                 if (parameterIndex > 0)
175                                 {
176                                     mimeType = mimeType.substring(0, parameterIndex);
177                                 }
178                             }
179                             if (mimeType == null) mimeType = HttpConstants.DEFAULT_CONTENT_TYPE;
180                             if (encoding == null) encoding = MuleManager.getConfiguration().getEncoding();
181                             postMethod.setRequestEntity(new StringRequestEntity(src.toString(), mimeType,
182                                 encoding));
183                         }
184                         else if (src instanceof InputStream JavaDoc)
185                         {
186                             // TODO Danger here! We don't know if the content is
187
// really text or not
188
if (mimeType == null) mimeType = HttpConstants.DEFAULT_CONTENT_TYPE;
189                             postMethod.setRequestEntity(new InputStreamRequestEntity((InputStream JavaDoc)src,
190                                 mimeType));
191                         }
192                         else
193                         {
194                             // TODO Danger here! We don't know if the content is
195
// really text or not
196
if (mimeType == null) mimeType = HttpConstants.DEFAULT_CONTENT_TYPE;
197                             byte[] buffer = (byte[])serializableToByteArray.doTransform(src, encoding);
198                             postMethod.setRequestEntity(new ByteArrayRequestEntity(buffer, mimeType));
199                         }
200                     }
201                 }
202                 else
203                 {
204                     postMethod.addParameter(paramName, src.toString());
205                 }
206
207                 httpMethod = postMethod;
208
209             }
210
211             return httpMethod;
212         }
213         catch (Exception JavaDoc e)
214         {
215             throw new TransformerException(this, e);
216         }
217     }
218
219     protected void setHeaders(HttpMethod httpMethod, UMOEventContext context)
220     {
221         // Standard requestHeaders
222
String JavaDoc headerValue;
223         String JavaDoc headerName;
224         UMOMessage msg = context.getMessage();
225         for (Iterator JavaDoc iterator = msg.getPropertyNames().iterator(); iterator.hasNext();)
226         {
227             headerName = (String JavaDoc)iterator.next();
228             headerValue = msg.getStringProperty(headerName, null);
229             if (HttpConstants.REQUEST_HEADER_NAMES.get(headerName) == null)
230             {
231                 if (headerName.startsWith(MuleProperties.PROPERTY_PREFIX))
232                 {
233                     headerName = new StringBuffer JavaDoc(30).append("X-").append(headerName).toString();
234                 }
235                 // Make sure we have a valid header name otherwise we will
236
// corrupt the request
237
// If it is Content-Length we should check the Response Headers
238
// before setting it
239
if (headerName.startsWith(HttpConstants.HEADER_CONTENT_LENGTH))
240                 {
241                     if (httpMethod.getResponseHeader(HttpConstants.HEADER_CONTENT_LENGTH) == null)
242                     {
243                         httpMethod.addRequestHeader(headerName, headerValue);
244                     }
245                 }
246                 else
247                 {
248                     httpMethod.addRequestHeader(headerName, headerValue);
249                 }
250             }
251         }
252
253         if (context.getMessage().getPayload() instanceof InputStream JavaDoc)
254         {
255             // must set this for receiver to properly parse attachments
256
httpMethod.addRequestHeader(HttpConstants.HEADER_CONTENT_TYPE, "multipart/related");
257         }
258     }
259 }
260
Popular Tags