View Javadoc

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