Add ability to see raw response from server when something goes wrong. (OC Transpo...
[frank.git] / prod / net / jaekl / qd / util / InputStreamWrapper.java
1 // Copyright (C) 2014 Christian Jaekl
2
3 // Wrap an inputstream, keeping a copy of the first few bytes that are read from it.
4 // This is useful when passing an inputstream directly to the SAX parser, 
5 // because we may want to do a post-mortem examination of the input being parsed
6 // if parsing fails.
7
8 package net.jaekl.qd.util;
9
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.util.Arrays;
13
14 public class InputStreamWrapper extends InputStream {
15         final static int HEAD_MAX = 1024;
16         
17         InputStream m_is;       // the stream being wrapped
18         byte[] m_head;          // the first (up to HEAD_MAX) bytes that were read from the wrapped stream
19         int    m_headBytes;     // number of bytes stored in m_head
20         
21         public InputStreamWrapper(InputStream is)
22         {
23                 super();
24                 
25                 m_is = is;
26                 m_head = new byte[HEAD_MAX];
27                 m_headBytes = 0;
28         }
29         
30         @Override
31         public int read() throws IOException {
32                 int b = m_is.read();
33                 if ((-1) == b) {
34                         // end-of-stream
35                         return b;
36                 }
37                 if (m_headBytes < HEAD_MAX) {
38                         m_head[m_headBytes] = (byte)b;
39                         m_headBytes++;
40                 }
41                 return b;
42         }
43         
44         public byte[] getHeadBytes() {
45                 return Arrays.copyOf(m_head, m_headBytes);
46         }
47 }