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 java.io.IOException;
10  import java.io.InputStream;
11  
12  import org.apache.commons.logging.Log;
13  import org.apache.commons.logging.LogFactory;
14  
15  /**
16   * Returns data one byte at a time.  By default the data are a 4 byte integer, value 1, and
17   * a single byte value -1.
18   */
19  public class SlowInputStream extends InputStream
20  {
21  
22      public static final int EOF = -1;
23      public static int PAYLOAD = 255;
24      public static int[] CONTENTS = new int[]{0, 0, 0, 1, PAYLOAD};
25      public static final int FULL_LENGTH = CONTENTS.length;
26      private static final Log logger = LogFactory.getLog(SlowInputStream.class);
27  
28      private int[] contents;
29      private int next = 0;
30      private int mark = 0;
31  
32      public SlowInputStream()
33      {
34          this(CONTENTS);
35      }
36  
37      public SlowInputStream(int[] contents)
38      {
39          this.contents = contents;
40      }
41  
42      public SlowInputStream(byte[] bytes)
43      {
44          contents = new int[bytes.length];
45          for (int i = 0; i < bytes.length; ++i)
46          {
47              contents[i] = bytes[i];
48          }
49      }
50  
51      public int available() throws IOException
52      {
53          int available = next < contents.length ? 1 : 0;
54          logger.debug("available: " + available);
55          return available;
56      }
57  
58      public int read() throws IOException
59      {
60          int value = available() > 0 ? contents[next++] : EOF;
61          logger.debug("read: " + value);
62          return value;
63      }
64  
65      public int read(byte b[], int off, int len) throws IOException
66      {
67          int value = read();
68          if (value != EOF)
69          {
70              b[off] = (byte) value;
71              return 1;
72          }
73          else
74          {
75              return EOF;
76          }
77      }
78  
79      public synchronized void reset() throws IOException
80      {
81          next = mark;
82      }
83  
84      public synchronized void mark(int readlimit)
85      {
86          mark = next;
87      }
88  
89      public boolean markSupported()
90      {
91          return true;
92      }
93  
94  }