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