View Javadoc

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