--- /dev/null
+// Copyright (C) 2014 Christian Jaekl
+
+// Wrap an inputstream, keeping a copy of the first few bytes that are read from it.
+// This is useful when passing an inputstream directly to the SAX parser,
+// because we may want to do a post-mortem examination of the input being parsed
+// if parsing fails.
+
+package net.jaekl.qd.util;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Arrays;
+
+public class InputStreamWrapper extends InputStream {
+ final static int HEAD_MAX = 1024;
+
+ InputStream m_is; // the stream being wrapped
+ byte[] m_head; // the first (up to HEAD_MAX) bytes that were read from the wrapped stream
+ int m_headBytes; // number of bytes stored in m_head
+
+ public InputStreamWrapper(InputStream is)
+ {
+ super();
+
+ m_is = is;
+ m_head = new byte[HEAD_MAX];
+ m_headBytes = 0;
+ }
+
+ @Override
+ public int read() throws IOException {
+ int b = m_is.read();
+ if ((-1) == b) {
+ // end-of-stream
+ return b;
+ }
+ if (m_headBytes < HEAD_MAX) {
+ m_head[m_headBytes] = (byte)b;
+ m_headBytes++;
+ }
+ return b;
+ }
+
+ public byte[] getHeadBytes() {
+ return Arrays.copyOf(m_head, m_headBytes);
+ }
+}