View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.transport.servlet.transformers;
8   
9   import org.mule.api.transformer.TransformerException;
10  import org.mule.transformer.AbstractDiscoverableTransformer;
11  import org.mule.transformer.types.DataTypeFactory;
12  
13  import java.io.IOException;
14  
15  import javax.servlet.http.HttpServletRequest;
16  
17  import org.apache.commons.io.IOUtils;
18  import org.apache.commons.io.output.ByteArrayOutputStream;
19  
20  /**
21   * Converts an {@link javax.servlet.http.HttpServletRequest} into an array of bytes by extracting
22   * the payload of the request.
23   */
24  public class HttpRequestToByteArray extends AbstractDiscoverableTransformer
25  {
26      public HttpRequestToByteArray()
27      {
28          registerSourceType(DataTypeFactory.create(HttpServletRequest.class));
29          setReturnDataType(DataTypeFactory.BYTE_ARRAY);
30      }
31  
32      @Override
33      protected Object doTransform(Object src, String outputEncoding) throws TransformerException
34      {
35          ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
36          try
37          {
38              IOUtils.copy(((HttpServletRequest) src).getInputStream(), baos);
39          }
40          catch (IOException e)
41          {
42              throw new TransformerException(this, e);
43          }
44          return baos.toByteArray();
45      }
46  }