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.DefaultMuleMessage;
10  import org.mule.api.MuleContext;
11  import org.mule.api.MuleMessage;
12  import org.mule.transport.AbstractMuleMessageFactory;
13  
14  import java.io.File;
15  import java.io.InputStream;
16  
17  /**
18   * <code>FileMuleMessageFactory</code> creates a new {@link MuleMessage} with a
19   * {@link File} or {@link InputStream} payload. Users can obtain the filename and
20   * directory in the properties using <code>FileConnector.PROPERTY_FILENAME</code> and
21   * <code>FileConnector.PROPERTY_DIRECTORY</code>.
22   */
23  public class FileMuleMessageFactory extends AbstractMuleMessageFactory
24  {
25      public FileMuleMessageFactory(MuleContext context)
26      {
27          super(context);
28      }
29  
30      @Override
31      protected Class<?>[] getSupportedTransportMessageTypes()
32      {
33          return new Class[]{File.class, ReceiverFileInputStream.class};
34      }
35  
36      @Override
37      protected Object extractPayload(Object transportMessage, String encoding) throws Exception
38      {
39          return transportMessage;
40      }
41  
42      @Override
43      protected void addProperties(DefaultMuleMessage message, Object transportMessage) throws Exception
44      {
45          super.addProperties(message, transportMessage);
46          File file = convertToFile(transportMessage);
47          setPropertiesFromFile(message, file);
48      }
49  
50      protected File convertToFile(Object transportMessage)
51      {
52          File file = null;
53  
54          if (transportMessage instanceof File)
55          {
56              file = (File) transportMessage;
57          }
58          else if (transportMessage instanceof ReceiverFileInputStream)
59          {
60              file = ((ReceiverFileInputStream) transportMessage).getCurrentFile();
61          }
62  
63          return file;
64      }
65  
66      protected void setPropertiesFromFile(MuleMessage message, File file)
67      {
68          message.setOutboundProperty(FileConnector.PROPERTY_ORIGINAL_FILENAME, file.getName());
69          message.setOutboundProperty(FileConnector.PROPERTY_DIRECTORY, file.getParent());
70          message.setOutboundProperty(FileConnector.PROPERTY_FILE_SIZE, file.length());
71      }
72  }