1 /*
   2  * Copyright 1996-2006 Sun Microsystems, Inc.  All Rights Reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Sun designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Sun in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  22  * CA 95054 USA or visit www.sun.com if you need additional information or
  23  * have any questions.
  24  */
  25 
  26 package java.util.zip;
  27 
  28 /**
  29  * This class provides support for general purpose compression using the
  30  * popular ZLIB compression library. The ZLIB compression library was
  31  * initially developed as part of the PNG graphics standard and is not
  32  * protected by patents. It is fully described in the specifications at
  33  * the <a href="package-summary.html#package_description">java.util.zip
  34  * package description</a>.
  35  *
  36  * <p>The following code fragment demonstrates a trivial compression
  37  * and decompression of a string using <tt>Deflater</tt> and
  38  * <tt>Inflater</tt>.
  39  *
  40  * <blockquote><pre>
  41  * try {
  42  *     // Encode a String into bytes
  43  *     String inputString = "blahblahblah\u20AC\u20AC";
  44  *     byte[] input = inputString.getBytes("UTF-8");
  45  *
  46  *     // Compress the bytes
  47  *     byte[] output = new byte[100];
  48  *     Deflater compresser = new Deflater();
  49  *     compresser.setInput(input);
  50  *     compresser.finish();
  51  *     int compressedDataLength = compresser.deflate(output);
  52  *     compresser.end();
  53  *
  54  *     // Decompress the bytes
  55  *     Inflater decompresser = new Inflater();
  56  *     decompresser.setInput(output, 0, compressedDataLength);
  57  *     byte[] result = new byte[100];
  58  *     int resultLength = decompresser.inflate(result);
  59  *     decompresser.end();
  60  *
  61  *     // Decode the bytes into a String
  62  *     String outputString = new String(result, 0, resultLength, "UTF-8");
  63  * } catch(java.io.UnsupportedEncodingException ex) {
  64  *     // handle
  65  * } catch (java.util.zip.DataFormatException ex) {
  66  *     // handle
  67  * }
  68  * </pre></blockquote>
  69  *
  70  * @see         Inflater
  71  * @author      David Connelly
  72  */
  73 public
  74 class Deflater {
  75     private long strm;
  76     private byte[] buf = new byte[0];
  77     private int off, len;
  78     private int level, strategy;
  79     private boolean setParams;
  80     private boolean finish, finished;
  81 
  82     /**
  83      * Compression method for the deflate algorithm (the only one currently
  84      * supported).
  85      */
  86     public static final int DEFLATED = 8;
  87 
  88     /**
  89      * Compression level for no compression.
  90      */
  91     public static final int NO_COMPRESSION = 0;
  92 
  93     /**
  94      * Compression level for fastest compression.
  95      */
  96     public static final int BEST_SPEED = 1;
  97 
  98     /**
  99      * Compression level for best compression.
 100      */
 101     public static final int BEST_COMPRESSION = 9;
 102 
 103     /**
 104      * Default compression level.
 105      */
 106     public static final int DEFAULT_COMPRESSION = -1;
 107 
 108     /**
 109      * Compression strategy best used for data consisting mostly of small
 110      * values with a somewhat random distribution. Forces more Huffman coding
 111      * and less string matching.
 112      */
 113     public static final int FILTERED = 1;
 114 
 115     /**
 116      * Compression strategy for Huffman coding only.
 117      */
 118     public static final int HUFFMAN_ONLY = 2;
 119 
 120     /**
 121      * Default compression strategy.
 122      */
 123     public static final int DEFAULT_STRATEGY = 0;
 124 
 125     static {
 126         /* Zip library is loaded from System.initializeSystemClass */
 127         initIDs();
 128     }
 129 
 130     /**
 131      * Creates a new compressor using the specified compression level.
 132      * If 'nowrap' is true then the ZLIB header and checksum fields will
 133      * not be used in order to support the compression format used in
 134      * both GZIP and PKZIP.
 135      * @param level the compression level (0-9)
 136      * @param nowrap if true then use GZIP compatible compression
 137      */
 138     public Deflater(int level, boolean nowrap) {
 139         this.level = level;
 140         this.strategy = DEFAULT_STRATEGY;
 141         strm = init(level, DEFAULT_STRATEGY, nowrap);
 142     }
 143 
 144     /**
 145      * Creates a new compressor using the specified compression level.
 146      * Compressed data will be generated in ZLIB format.
 147      * @param level the compression level (0-9)
 148      */
 149     public Deflater(int level) {
 150         this(level, false);
 151     }
 152 
 153     /**
 154      * Creates a new compressor with the default compression level.
 155      * Compressed data will be generated in ZLIB format.
 156      */
 157     public Deflater() {
 158         this(DEFAULT_COMPRESSION, false);
 159     }
 160 
 161     /**
 162      * Sets input data for compression. This should be called whenever
 163      * needsInput() returns true indicating that more input data is required.
 164      * @param b the input data bytes
 165      * @param off the start offset of the data
 166      * @param len the length of the data
 167      * @see Deflater#needsInput
 168      */
 169     public synchronized void setInput(byte[] b, int off, int len) {
 170         if (b== null) {
 171             throw new NullPointerException();
 172         }
 173         if (off < 0 || len < 0 || off > b.length - len) {
 174             throw new ArrayIndexOutOfBoundsException();
 175         }
 176         this.buf = b;
 177         this.off = off;
 178         this.len = len;
 179     }
 180 
 181     /**
 182      * Sets input data for compression. This should be called whenever
 183      * needsInput() returns true indicating that more input data is required.
 184      * @param b the input data bytes
 185      * @see Deflater#needsInput
 186      */
 187     public void setInput(byte[] b) {
 188         setInput(b, 0, b.length);
 189     }
 190 
 191     /**
 192      * Sets preset dictionary for compression. A preset dictionary is used
 193      * when the history buffer can be predetermined. When the data is later
 194      * uncompressed with Inflater.inflate(), Inflater.getAdler() can be called
 195      * in order to get the Adler-32 value of the dictionary required for
 196      * decompression.
 197      * @param b the dictionary data bytes
 198      * @param off the start offset of the data
 199      * @param len the length of the data
 200      * @see Inflater#inflate
 201      * @see Inflater#getAdler
 202      */
 203     public synchronized void setDictionary(byte[] b, int off, int len) {
 204         if (strm == 0 || b == null) {
 205             throw new NullPointerException();
 206         }
 207         if (off < 0 || len < 0 || off > b.length - len) {
 208             throw new ArrayIndexOutOfBoundsException();
 209         }
 210         setDictionary(strm, b, off, len);
 211     }
 212 
 213     /**
 214      * Sets preset dictionary for compression. A preset dictionary is used
 215      * when the history buffer can be predetermined. When the data is later
 216      * uncompressed with Inflater.inflate(), Inflater.getAdler() can be called
 217      * in order to get the Adler-32 value of the dictionary required for
 218      * decompression.
 219      * @param b the dictionary data bytes
 220      * @see Inflater#inflate
 221      * @see Inflater#getAdler
 222      */
 223     public void setDictionary(byte[] b) {
 224         setDictionary(b, 0, b.length);
 225     }
 226 
 227     /**
 228      * Sets the compression strategy to the specified value.
 229      * @param strategy the new compression strategy
 230      * @exception IllegalArgumentException if the compression strategy is
 231      *                                     invalid
 232      */
 233     public synchronized void setStrategy(int strategy) {
 234         switch (strategy) {
 235           case DEFAULT_STRATEGY:
 236           case FILTERED:
 237           case HUFFMAN_ONLY:
 238             break;
 239           default:
 240             throw new IllegalArgumentException();
 241         }
 242         if (this.strategy != strategy) {
 243             this.strategy = strategy;
 244             setParams = true;
 245         }
 246     }
 247 
 248     /**
 249      * Sets the current compression level to the specified value.
 250      * @param level the new compression level (0-9)
 251      * @exception IllegalArgumentException if the compression level is invalid
 252      */
 253     public synchronized void setLevel(int level) {
 254         if ((level < 0 || level > 9) && level != DEFAULT_COMPRESSION) {
 255             throw new IllegalArgumentException("invalid compression level");
 256         }
 257         if (this.level != level) {
 258             this.level = level;
 259             setParams = true;
 260         }
 261     }
 262 
 263     /**
 264      * Returns true if the input data buffer is empty and setInput()
 265      * should be called in order to provide more input.
 266      * @return true if the input data buffer is empty and setInput()
 267      * should be called in order to provide more input
 268      */
 269     public boolean needsInput() {
 270         return len <= 0;
 271     }
 272 
 273     /**
 274      * When called, indicates that compression should end with the current
 275      * contents of the input buffer.
 276      */
 277     public synchronized void finish() {
 278         finish = true;
 279     }
 280 
 281     /**
 282      * Returns true if the end of the compressed data output stream has
 283      * been reached.
 284      * @return true if the end of the compressed data output stream has
 285      * been reached
 286      */
 287     public synchronized boolean finished() {
 288         return finished;
 289     }
 290 
 291     /**
 292      * Fills specified buffer with compressed data. Returns actual number
 293      * of bytes of compressed data. A return value of 0 indicates that
 294      * needsInput() should be called in order to determine if more input
 295      * data is required.
 296      * @param b the buffer for the compressed data
 297      * @param off the start offset of the data
 298      * @param len the maximum number of bytes of compressed data
 299      * @return the actual number of bytes of compressed data
 300      */
 301     public synchronized int deflate(byte[] b, int off, int len) {
 302         if (b == null) {
 303             throw new NullPointerException();
 304         }
 305         if (off < 0 || len < 0 || off > b.length - len) {
 306             throw new ArrayIndexOutOfBoundsException();
 307         }
 308         return deflateBytes(b, off, len);
 309     }
 310 
 311     /**
 312      * Fills specified buffer with compressed data. Returns actual number
 313      * of bytes of compressed data. A return value of 0 indicates that
 314      * needsInput() should be called in order to determine if more input
 315      * data is required.
 316      * @param b the buffer for the compressed data
 317      * @return the actual number of bytes of compressed data
 318      */
 319     public int deflate(byte[] b) {
 320         return deflate(b, 0, b.length);
 321     }
 322 
 323     /**
 324      * Returns the ADLER-32 value of the uncompressed data.
 325      * @return the ADLER-32 value of the uncompressed data
 326      */
 327     public synchronized int getAdler() {
 328         ensureOpen();
 329         return getAdler(strm);
 330     }
 331 
 332     /**
 333      * Returns the total number of uncompressed bytes input so far.
 334      *
 335      * <p>Since the number of bytes may be greater than
 336      * Integer.MAX_VALUE, the {@link #getBytesRead()} method is now
 337      * the preferred means of obtaining this information.</p>
 338      *
 339      * @return the total number of uncompressed bytes input so far
 340      */
 341     public int getTotalIn() {
 342         return (int) getBytesRead();
 343     }
 344 
 345     /**
 346      * Returns the total number of uncompressed bytes input so far.</p>
 347      *
 348      * @return the total (non-negative) number of uncompressed bytes input so far
 349      * @since 1.5
 350      */
 351     public synchronized long getBytesRead() {
 352         ensureOpen();
 353         return getBytesRead(strm);
 354     }
 355 
 356     /**
 357      * Returns the total number of compressed bytes output so far.
 358      *
 359      * <p>Since the number of bytes may be greater than
 360      * Integer.MAX_VALUE, the {@link #getBytesWritten()} method is now
 361      * the preferred means of obtaining this information.</p>
 362      *
 363      * @return the total number of compressed bytes output so far
 364      */
 365     public int getTotalOut() {
 366         return (int) getBytesWritten();
 367     }
 368 
 369     /**
 370      * Returns the total number of compressed bytes output so far.</p>
 371      *
 372      * @return the total (non-negative) number of compressed bytes output so far
 373      * @since 1.5
 374      */
 375     public synchronized long getBytesWritten() {
 376         ensureOpen();
 377         return getBytesWritten(strm);
 378     }
 379 
 380     /**
 381      * Resets deflater so that a new set of input data can be processed.
 382      * Keeps current compression level and strategy settings.
 383      */
 384     public synchronized void reset() {
 385         ensureOpen();
 386         reset(strm);
 387         finish = false;
 388         finished = false;
 389         off = len = 0;
 390     }
 391 
 392     /**
 393      * Closes the compressor and discards any unprocessed input.
 394      * This method should be called when the compressor is no longer
 395      * being used, but will also be called automatically by the
 396      * finalize() method. Once this method is called, the behavior
 397      * of the Deflater object is undefined.
 398      */
 399     public synchronized void end() {
 400         if (strm != 0) {
 401             end(strm);
 402             strm = 0;
 403             buf = null;
 404         }
 405     }
 406 
 407     /**
 408      * Closes the compressor when garbage is collected.
 409      */
 410     protected void finalize() {
 411         end();
 412     }
 413 
 414     private void ensureOpen() {
 415         if (strm == 0)
 416             throw new NullPointerException();
 417     }
 418 
 419     private static native void initIDs();
 420     private native static long init(int level, int strategy, boolean nowrap);
 421     private native static void setDictionary(long strm, byte[] b, int off,
 422                                              int len);
 423     private native int deflateBytes(byte[] b, int off, int len);
 424     private native static int getAdler(long strm);
 425     private native static long getBytesRead(long strm);
 426     private native static long getBytesWritten(long strm);
 427     private native static void reset(long strm);
 428     private native static void end(long strm);
 429 }