X-Git-Url: http://jaekl.net/gitweb/?p=frank.git;a=blobdiff_plain;f=prod%2Fnet%2Fjaekl%2Fqd%2Futil%2FInputStreamWrapper.java;fp=prod%2Fnet%2Fjaekl%2Fqd%2Futil%2FInputStreamWrapper.java;h=f78cf613be42faed0597a3f90cebbf46a48e902c;hp=0000000000000000000000000000000000000000;hb=418e4d229a8b607b022cfb867bb702bec1765d13;hpb=d870b8b1ca2e633b0f2b58969cc042888d07db6e diff --git a/prod/net/jaekl/qd/util/InputStreamWrapper.java b/prod/net/jaekl/qd/util/InputStreamWrapper.java new file mode 100644 index 0000000..f78cf61 --- /dev/null +++ b/prod/net/jaekl/qd/util/InputStreamWrapper.java @@ -0,0 +1,47 @@ +// 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); + } +}