View Javadoc

1   /*
2    * $Id: FileContentsMessageAdapter.java 11559 2008-04-10 18:16:04Z dfeist $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSource, Inc.  All rights reserved.  http://www.mulesource.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.MessagingException;
14  import org.mule.api.MuleRuntimeException;
15  import org.mule.api.ThreadSafeAccess;
16  import org.mule.config.i18n.CoreMessages;
17  import org.mule.util.IOUtils;
18  
19  import java.io.FileInputStream;
20  
21  /**
22   * <code>FileContentsMessageAdapter</code> provides a wrapper for file data. Users
23   * can obtain the contents of the message through the payload property and can get
24   * the filename and directory in the properties using PROPERTY_FILENAME and
25   * PROPERTY_DIRECTORY.
26   */
27  public class FileContentsMessageAdapter extends FileMessageAdapter
28  {
29      /**
30       * Serial version
31       */
32      private static final long serialVersionUID = 7368719494535568721L;
33  
34      private byte[] contents = null;
35  
36      public FileContentsMessageAdapter(Object message) throws MessagingException
37      {
38          super(message);
39          this.getPayload();
40      }
41  
42      public FileContentsMessageAdapter(FileContentsMessageAdapter template)
43      {
44          super(template);
45          contents = template.contents;
46          this.getPayload();
47      }
48  
49      public Object getPayload()
50      {
51          if (contents == null)
52          {
53              synchronized (this)
54              {
55                  try
56                  {
57                      if (fileInputStream == null)
58                      {
59                          fileInputStream = new FileInputStream(file);
60                      }
61                      contents = IOUtils.toByteArray(fileInputStream);
62                      fileInputStream.close();
63                  }
64                  catch (Exception noPayloadException)
65                  {
66                      throw new MuleRuntimeException(CoreMessages.failedToReadPayload(), noPayloadException);
67                  }
68              }
69          }
70          return contents;
71      }
72  
73      public ThreadSafeAccess newThreadCopy()
74      {
75          return new FileContentsMessageAdapter(this);
76      }
77  }