View Javadoc

1   /*
2    * $Id: HttpClientMethodResponseToObject.java 19250 2010-08-30 16:53:14Z dirk.olmes $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.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.http.transformers;
12  
13  import org.mule.DefaultMuleMessage;
14  import org.mule.api.transformer.TransformerException;
15  import org.mule.transformer.AbstractTransformer;
16  import org.mule.transformer.types.DataTypeFactory;
17  import org.mule.transport.NullPayload;
18  import org.mule.transport.http.HttpConstants;
19  import org.mule.transport.http.ReleasingInputStream;
20  
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.util.HashMap;
24  import java.util.Map;
25  
26  import org.apache.commons.httpclient.Header;
27  import org.apache.commons.httpclient.HttpMethod;
28  
29  /**
30   * <code>HttpClientMethodResponseToObject</code> transforms a http client response
31   * to a DefaultMuleMessage.
32   */
33  
34  public class HttpClientMethodResponseToObject extends AbstractTransformer
35  {
36  
37      public HttpClientMethodResponseToObject()
38      {
39          registerSourceType(DataTypeFactory.create(HttpMethod.class));
40          setReturnDataType(DataTypeFactory.MULE_MESSAGE);
41      }
42  
43      @Override
44      public Object doTransform(Object src, String encoding) throws TransformerException
45      {
46          Object msg;
47          HttpMethod httpMethod = (HttpMethod)src;
48          
49          InputStream is;
50          try
51          {
52              is = httpMethod.getResponseBodyAsStream();
53          }
54          catch (IOException e)
55          {
56              throw new TransformerException(this, e);
57          }
58          
59          if (is == null)
60          {
61              msg = NullPayload.getInstance();
62          }
63          else
64          {
65              msg = new ReleasingInputStream(is, httpMethod);
66          }
67          
68          // Standard headers
69          Map headerProps = new HashMap();
70          Header[] headers = httpMethod.getResponseHeaders();
71          String name;
72          for (int i = 0; i < headers.length; i++)
73          {
74              name = headers[i].getName();
75              if (name.startsWith(HttpConstants.X_PROPERTY_PREFIX))
76              {
77                  name = name.substring(2);
78              }
79              headerProps.put(name, headers[i].getValue());
80          }
81          // Set Mule Properties
82  
83          return new DefaultMuleMessage(msg, headerProps, muleContext);
84      }
85  }