View Javadoc

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