View Javadoc

1   /*
2    * $Id: ResponseOutputStream.java 7976 2007-08-21 14:26:13Z dirk.olmes $
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.impl;
12  
13  import java.io.BufferedOutputStream;
14  import java.io.IOException;
15  import java.io.OutputStream;
16  import java.net.Socket;
17  
18  import org.apache.commons.io.output.ByteArrayOutputStream;
19  
20  /**
21   * <code>ResponseOutputStream</code> is an output stream associated with the
22   * currently received event. Note that if the stream is from a socket the socket is
23   * also available on this stream so that the socket state can be validated before
24   * writing.
25   */
26  
27  public class ResponseOutputStream extends BufferedOutputStream
28  {
29      private static ByteArrayOutputStream defaultStream = new ByteArrayOutputStream();
30  
31      private boolean used = false;
32      private boolean isDefault = false;
33      private Socket socket = null;
34  
35      public ResponseOutputStream()
36      {
37          super(defaultStream);
38          isDefault = true;
39      }
40  
41      public ResponseOutputStream(OutputStream stream)
42      {
43          super(stream);
44      }
45  
46      public ResponseOutputStream(Socket socket) throws IOException
47      {
48          super(socket.getOutputStream());
49          this.socket = socket;
50      }
51  
52      public void write(int b) throws IOException
53      {
54          super.write(b);
55          used = true;
56      }
57  
58      public byte[] getBytes() throws IOException
59      {
60          if (isDefault)
61          {
62              flush();
63              return defaultStream.toByteArray();
64          }
65          return null;
66      }
67  
68      public boolean isUsed()
69      {
70          return used;
71      }
72  
73      public Socket getSocket()
74      {
75          return socket;
76      }
77  }