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.DefaultMuleException;
10  import org.mule.transport.file.i18n.FileMessages;
11  import org.mule.util.FileUtils;
12  
13  import java.io.File;
14  import java.io.FileInputStream;
15  import java.io.FileNotFoundException;
16  import java.io.IOException;
17  
18  /**
19   * This implementation is used when streaming and will move or delete the source file
20   * when the stream is closed.
21   */
22  class ReceiverFileInputStream extends FileInputStream
23  {
24      private File currentFile;
25      private boolean deleteOnClose;
26      private File moveToOnClose;
27      private InputStreamCloseListener closeListener;
28  
29      public ReceiverFileInputStream(File currentFile, boolean deleteOnClose, File moveToOnClose)
30          throws FileNotFoundException
31      {
32          super(currentFile);
33          this.currentFile = currentFile;
34          this.deleteOnClose = deleteOnClose;
35          this.moveToOnClose = moveToOnClose;
36      }
37  
38      public ReceiverFileInputStream(File sourceFile, boolean deleteOnClose, File destinationFile, InputStreamCloseListener closeListener) throws FileNotFoundException
39      {
40          this(sourceFile, deleteOnClose, destinationFile);
41          this.closeListener = closeListener;
42      }
43  
44      @Override
45      public void close() throws IOException
46      {
47          super.close();
48  
49          if (moveToOnClose != null)
50          {
51              FileUtils.moveFileWithCopyFallback(currentFile, moveToOnClose);
52          }
53          else if (deleteOnClose)
54          {
55              if (!currentFile.delete())
56              {
57                  try
58                  {
59                      throw new DefaultMuleException(FileMessages.failedToDeleteFile(currentFile));
60                  }
61                  catch (DefaultMuleException e)
62                  {
63                      IOException e2 = new IOException();
64                      e2.initCause(e);
65                      throw e2;
66                  }
67              }
68          }
69          if (closeListener != null)
70          {
71              closeListener.fileClose(currentFile);
72          }
73      }
74  
75      public File getCurrentFile()
76      {
77          return currentFile;
78      }
79  }