001package com.nimbusds.jose.util;
002
003
004import java.io.ByteArrayInputStream;
005import java.io.ByteArrayOutputStream;
006import java.io.IOException;
007import java.util.zip.Deflater;
008import java.util.zip.DeflaterOutputStream;
009import java.util.zip.InflaterInputStream;
010import java.util.zip.Inflater;
011
012
013/**
014 * Deflate (RFC 1951) utilities.
015 *
016 * @author Vladimir Dzhuvinov
017 * @version $version$ (2013-04-16)
018 */
019public class DeflateUtils {
020
021
022        /**
023         * Omit headers and CRC fields from output, as specified by RFC 1950.
024         * Note that the Deflater JavaDocs are incorrect, see
025         * http://stackoverflow.com/questions/11076060/decompressing-gzipped-data-with-inflater-in-java
026         */
027        private static final boolean NOWRAP = true;
028
029
030        /**
031         * Compresses the specified byte array according to the DEFLATE 
032         * specification (RFC 1951).
033         *
034         * @param bytes The byte array to compress. Must not be {@code null}.
035         *
036         * @return The compressed bytes.
037         *
038         * @throws IOException If compression failed.
039         */
040        public static byte[] compress(final byte[] bytes)
041                throws IOException {
042
043                ByteArrayOutputStream out = new ByteArrayOutputStream();
044
045                DeflaterOutputStream def = new DeflaterOutputStream(out, new Deflater(Deflater.DEFLATED, NOWRAP));
046                def.write(bytes);
047                def.close();
048
049                return out.toByteArray();
050        }
051
052
053        /**
054         * Decompresses the specified byte array according to the DEFLATE
055         * specification (RFC 1951).
056         *
057         * @param bytes The byte array to decompress. Must not be {@code null}.
058         *
059         * @return The decompressed bytes.
060         *
061         * @throws IOException If decompression failed.
062         */
063        public static byte[] decompress(final byte[] bytes)
064                throws IOException {
065
066                InflaterInputStream inf = new InflaterInputStream(new ByteArrayInputStream(bytes), new Inflater(NOWRAP));
067                ByteArrayOutputStream out = new ByteArrayOutputStream();
068
069                // Transfer bytes from the compressed array to the output
070                byte[] buf = new byte[1024];
071
072                int len;
073
074                while ((len = inf.read(buf)) > 0) {
075
076                        out.write(buf, 0, len);
077                }
078
079                inf.close();
080                out.close();
081
082                return out.toByteArray();
083        }
084
085
086        /**
087         * Prevents public instantiation.
088         */
089        private DeflateUtils() {
090
091        }
092}