View Javadoc

1   /*
2    * $Id: HttpRequestToByteArray.java 12238 2008-07-06 22:13:50Z rossmason $
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  package org.mule.transport.servlet;
11  
12  import org.mule.api.transformer.TransformerException;
13  import org.mule.transformer.AbstractDiscoverableTransformer;
14  
15  import java.io.IOException;
16  
17  import javax.servlet.http.HttpServletRequest;
18  
19  import org.apache.commons.io.IOUtils;
20  import org.apache.commons.io.output.ByteArrayOutputStream;
21  
22  /**
23   * Converts an {@link javax.servlet.http.HttpServletRequest} into an array of bytes by extracting the payload of
24   * the request.
25   */
26  public class HttpRequestToByteArray extends AbstractDiscoverableTransformer
27  {
28  
29      public HttpRequestToByteArray()
30      {
31          registerSourceType(HttpServletRequest.class);
32          setReturnClass(byte[].class);
33      }
34  
35      protected Object doTransform(Object src, String encoding) throws TransformerException
36      {
37          ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
38          try
39          {
40              IOUtils.copy(((HttpServletRequest) src).getInputStream(), baos);
41          }
42          catch (IOException e)
43          {
44              throw new TransformerException(this, e);
45          }
46          return baos.toByteArray();
47      }
48  
49  }