View Javadoc

1   /*
2    * $Id: ProtocolStream.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.transport.tcp.protocols;
12  
13  import org.mule.transport.tcp.TcpProtocol;
14  import org.mule.util.ClassUtils;
15  
16  import java.io.IOException;
17  import java.io.OutputStream;
18  
19  public class ProtocolStream extends OutputStream
20  {
21  
22      private boolean streamOk;
23      private TcpProtocol protocol;
24      private OutputStream os;
25  
26      public ProtocolStream(TcpProtocol protocol, boolean streamOk, OutputStream os)
27      {
28          this.protocol = protocol;
29          this.streamOk = streamOk;
30          this.os = os;
31      }
32  
33      private void assertStreamOk()
34      {
35          if (!streamOk)
36          {
37               throw new IllegalArgumentException("TCP protocol " + ClassUtils.getSimpleName(protocol.getClass()) +
38                       " does not support streaming output");
39          }
40      }
41  
42      public void write(byte b[]) throws IOException
43      {
44          assertStreamOk();
45          protocol.write(os, b);
46      }
47  
48      public void write(byte b[], int off, int len) throws IOException
49      {
50          assertStreamOk();
51          byte[] buffer = new byte[len];
52          System.arraycopy(b, off, buffer, 0, len);
53          protocol.write(os, buffer);
54      }
55  
56      public void flush() throws IOException
57      {
58          assertStreamOk();
59          os.flush();
60      }
61  
62      public void write(int b) throws IOException
63      {
64          write(new byte[]{(byte) b});
65      }
66  
67      public void close() throws IOException
68      {
69          assertStreamOk();
70          os.close();
71      }
72  
73  }