Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame^] | 1 | package aQute.libg.gzip; |
| 2 | |
| 3 | import java.io.BufferedInputStream; |
| 4 | import java.io.EOFException; |
| 5 | import java.io.IOException; |
| 6 | import java.io.InputStream; |
| 7 | import java.util.zip.GZIPInputStream; |
| 8 | |
| 9 | public class GZipUtils { |
| 10 | |
| 11 | /** |
| 12 | * Determines whether the specified stream contains gzipped data, by |
| 13 | * checking for the GZIP magic number, and returns a stream capable of |
| 14 | * reading those data. |
| 15 | * |
| 16 | * @throws IOException |
| 17 | */ |
| 18 | public static InputStream detectCompression(InputStream stream) throws IOException { |
| 19 | InputStream buffered; |
| 20 | if (stream.markSupported()) |
| 21 | buffered = stream; |
| 22 | else |
| 23 | buffered = new BufferedInputStream(stream); |
| 24 | |
| 25 | buffered.mark(2); |
| 26 | int magic = readUShort(buffered); |
| 27 | buffered.reset(); |
| 28 | |
| 29 | InputStream result; |
| 30 | if (magic == GZIPInputStream.GZIP_MAGIC) |
| 31 | result = new GZIPInputStream(buffered); |
| 32 | else |
| 33 | result = buffered; |
| 34 | return result; |
| 35 | } |
| 36 | |
| 37 | /* |
| 38 | * Reads unsigned short in Intel byte order. |
| 39 | */ |
| 40 | private static int readUShort(InputStream in) throws IOException { |
| 41 | int b = readUByte(in); |
| 42 | return (readUByte(in) << 8) | b; |
| 43 | } |
| 44 | |
| 45 | /* |
| 46 | * Reads unsigned byte. |
| 47 | */ |
| 48 | private static int readUByte(InputStream in) throws IOException { |
| 49 | int b = in.read(); |
| 50 | if (b == -1) { |
| 51 | throw new EOFException(); |
| 52 | } |
| 53 | if (b < -1 || b > 255) { |
| 54 | // Report on this.in, not argument in; see read{Header, Trailer}. |
| 55 | throw new IOException(in.getClass().getName() + ".read() returned value out of range -1..255: " + b); |
| 56 | } |
| 57 | return b; |
| 58 | } |
| 59 | |
| 60 | } |