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.file;
8   
9   import org.mule.api.MuleContext;
10  import org.mule.api.MuleMessage;
11  import org.mule.util.IOUtils;
12  
13  import java.io.File;
14  import java.io.FileInputStream;
15  import java.io.InputStream;
16  
17  /**
18   * <code>FileContentsMuleMessageFactory</code> converts the
19   * {@link InputStream}'s content into a <code>byte[]</code> as payload
20   * for the {@link MuleMessage}.
21   */
22  public class FileContentsMuleMessageFactory extends FileMuleMessageFactory
23  {
24      public FileContentsMuleMessageFactory(MuleContext context)
25      {
26          super(context);
27      }
28  
29      @Override
30      protected Class<?>[] getSupportedTransportMessageTypes()
31      {
32          return new Class[]{InputStream.class, File.class};
33      }
34  
35      @Override
36      protected Object extractPayload(Object transportMessage, String encoding) throws Exception
37      {
38          InputStream inputStream = convertToInputStream(transportMessage);
39          byte[] payload = IOUtils.toByteArray(inputStream);
40          inputStream.close();
41          return payload;
42      }
43  
44      private InputStream convertToInputStream(Object transportMessage) throws Exception
45      {
46          InputStream stream = null;
47  
48          if (transportMessage instanceof InputStream)
49          {
50              stream = (InputStream) transportMessage;
51          }
52          else if (transportMessage instanceof File)
53          {
54              stream = new FileInputStream((File) transportMessage);
55          }
56  
57          return stream;
58      }
59  }