1 /*
2 * This file is part of *** M y C o R e ***
3 * See http://www.mycore.de/ for details.
4 *
5 * MyCoRe is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * MyCoRe is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with MyCoRe. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 package org.mycore.common.content.streams;
20
21 import java.io.IOException;
22 import java.io.InputStream;
23
24 import org.mycore.common.MCRException;
25
26 /**
27 * Provides the header of the stream that is read.
28 * This may be useful for content type detection purposes.
29 * Immediately after stream construction, getHeader() can be called.
30 *
31 * @author Frank L\u00FCtzenkirchen
32 */
33 public class MCRHeaderInputStream extends MCRBlockingInputStream {
34
35 /** The number of bytes that will be read for content type detection */
36 public static final int MAX_HEADER_SIZE = 65536;
37
38 /** The header of the stream read */
39 protected byte[] header;
40
41 public MCRHeaderInputStream(InputStream in) throws IOException, MCRException {
42 super(in, MAX_HEADER_SIZE);
43 super.mark(MAX_HEADER_SIZE);
44
45 byte[] buffer = new byte[MAX_HEADER_SIZE];
46
47 try {
48 int num = read(buffer, 0, buffer.length);
49 header = new byte[Math.max(0, num)];
50
51 if (num > 0) {
52 System.arraycopy(buffer, 0, header, 0, num);
53 }
54 } catch (IOException ex) {
55 String msg = "Error while reading content input stream header";
56 throw new MCRException(msg, ex);
57 }
58 super.reset();
59 }
60
61 /**
62 * Returns the header of the underlying input stream, at maximum
63 * MAX_HEADER_SIZE bytes.
64 */
65 public byte[] getHeader() {
66 return header;
67 }
68 }