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