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