1   package com.atlassian.core.spool;
2   
3   import java.io.IOException;
4   import java.io.InputStream;
5   import java.io.BufferedInputStream;
6   
7   import org.apache.commons.io.IOUtils;
8   
9   /**
10   * Thresholding spool that uses a DeferredSpoolFileOutputStream for spooling, allowing for a balance between memory
11   * usage and speed.
12   */
13  public class DeferredSpool implements FileSpool, ThresholdingSpool
14  {
15      private int maxMemorySpool;
16      private FileFactory fileFactory = DefaultSpoolFileFactory.getInstance();
17  
18      public FileFactory getFileFactory()
19      {
20          return fileFactory;
21      }
22  
23      public void setFileFactory(FileFactory fileFactory)
24      {
25          this.fileFactory = fileFactory;
26      }
27  
28      public void setThresholdBytes(int bytes)
29      {
30          this.maxMemorySpool = bytes;
31      }
32  
33      public int getThresholdBytes()
34      {
35          return maxMemorySpool;
36      }
37  
38      public InputStream spool(InputStream is) throws IOException
39      {
40          DeferredSpoolFileOutputStream deferredStream = getNewDeferredSpoolFileOutputStream();
41          IOUtils.copy(is, deferredStream);
42          deferredStream.close();
43          return new BufferedInputStream(deferredStream.getInputStream());
44      }
45  
46      /**
47       * @return a new DeferredSpoolFileOutputStream
48       */
49      protected DeferredSpoolFileOutputStream getNewDeferredSpoolFileOutputStream()
50      {
51          return new DeferredSpoolFileOutputStream(maxMemorySpool, getFileFactory());
52      }
53  }