View Javadoc

1   /*
2    * $Id: HttpClientMethodResponseToObject.java 7963 2007-08-21 08:53:15Z dirk.olmes $
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.providers.http.transformers;
12  
13  import org.mule.impl.MuleMessage;
14  import org.mule.providers.http.HttpConstants;
15  import org.mule.transformers.AbstractTransformer;
16  import org.mule.umo.UMOMessage;
17  import org.mule.umo.transformer.TransformerException;
18  
19  import java.io.IOException;
20  import java.util.HashMap;
21  import java.util.Map;
22  
23  import org.apache.commons.httpclient.Header;
24  import org.apache.commons.httpclient.HttpMethod;
25  import org.apache.commons.io.IOUtils;
26  
27  /**
28   * <code>HttpClientMethodResponseToObject</code> transforms a http client response
29   * to a MuleMessage.
30   */
31  
32  public class HttpClientMethodResponseToObject extends AbstractTransformer
33  {
34  
35      public HttpClientMethodResponseToObject()
36      {
37          registerSourceType(HttpMethod.class);
38          setReturnClass(UMOMessage.class);
39      }
40  
41      public Object doTransform(Object src, String encoding) throws TransformerException
42      {
43          Object msg;
44          HttpMethod httpMethod = (HttpMethod)src;
45          Header contentType = httpMethod.getResponseHeader(HttpConstants.HEADER_CONTENT_TYPE);
46          try
47          {
48              if (contentType != null && !contentType.getValue().startsWith("text/"))
49              {
50                  // TODO properly do streaming
51                  msg = IOUtils.toByteArray(httpMethod.getResponseBodyAsStream());
52              }
53              else
54              {
55                  msg = httpMethod.getResponseBodyAsString();
56              }
57          }
58          catch (IOException e)
59          {
60              throw new TransformerException(this, e);
61          }
62          // Standard headers
63          Map headerProps = new HashMap();
64          Header[] headers = httpMethod.getRequestHeaders();
65          String name;
66          for (int i = 0; i < headers.length; i++)
67          {
68              name = headers[i].getName();
69              if (name.startsWith(HttpConstants.X_PROPERTY_PREFIX))
70              {
71                  name = name.substring(2);
72              }
73              headerProps.put(name, headers[i].getValue());
74          }
75          // Set Mule Properties
76  
77          return new MuleMessage(msg, headerProps);
78      }
79  }