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.model.streaming;
8   
9   import java.io.IOException;
10  import java.io.OutputStream;
11  
12  import org.apache.commons.logging.Log;
13  import org.apache.commons.logging.LogFactory;
14  
15  public class CallbackOutputStream extends OutputStream
16  {
17      private static final Log logger = LogFactory.getLog(CallbackOutputStream.class);
18  
19      public static interface Callback
20      {
21          public void onClose() throws Exception;
22      }
23  
24      private OutputStream delegate;
25      private Callback callback;
26  
27      public CallbackOutputStream(OutputStream delegate, Callback callback)
28      {
29          this.delegate = delegate;
30          this.callback = callback;
31      }
32  
33      @Override
34      public void write(int b) throws IOException
35      {
36          delegate.write(b);
37      }
38  
39      @Override
40      public void write(byte b[]) throws IOException
41      {
42          delegate.write(b);
43      }
44  
45      @Override
46      public void write(byte b[], int off, int len) throws IOException
47      {
48          delegate.write(b, off, len);
49      }
50  
51      @Override
52      public void close() throws IOException
53      {
54          try
55          {
56              delegate.close();
57          }
58          finally
59          {
60              closeCallback();
61          }
62      }
63  
64      private void closeCallback()
65      {
66          if (null != callback)
67          {
68              try
69              {
70                  callback.onClose();
71              }
72              catch(Exception e)
73              {
74                  logger.debug("Suppressing exception while releasing resources: " + e.getMessage());
75              }
76          }
77  
78      }
79  }