001    package com.nimbusds.jose.util;
002    
003    
004    import java.io.ByteArrayInputStream;
005    import java.io.ByteArrayOutputStream;
006    import java.io.InputStream;
007    import java.io.IOException;
008    import java.io.OutputStream;
009    
010    import java.util.zip.DeflaterInputStream;
011    import java.util.zip.DeflaterOutputStream;
012    
013    
014    /**
015     * Deflate (RFC 1951) utilities.
016     *
017     * @author Vladimir Dzhuvinov
018     * @version $version$ (2012-09-17)
019     */
020    public class DeflateUtils {
021    
022    
023            /**
024             * Compresses the specified byte array according to the DEFLATE 
025             * specification (RFC 1951).
026             *
027             * @param bytes The byte array to compress. Must not be {@code null}.
028             *
029             * @return The compressed bytes.
030             *
031             * @throws IOException If compression failed.
032             */
033            public static byte[] compress(final byte[] bytes)
034                    throws IOException {
035            
036                    ByteArrayOutputStream out = new ByteArrayOutputStream();
037                    
038                    DeflaterOutputStream def = new DeflaterOutputStream(out);
039                    def.write(bytes);
040                    def.close();
041                    
042                    return out.toByteArray();
043            }
044            
045            
046            /**
047             * Decompresses the specified byte array according to the DEFLATE
048             * specification (RFC 1951).
049             *
050             * @param bytes The byte array to decompress. Must not be {@code null}.
051             *
052             * @return The decompressed bytes.
053             *
054             * @throws IOException If decompression failed.
055             */
056            public static byte[] decompress(final byte[] bytes)
057                    throws IOException {
058                    
059                    DeflaterInputStream def = new DeflaterInputStream(new ByteArrayInputStream(bytes));
060                    ByteArrayOutputStream out = new ByteArrayOutputStream();
061                    
062                    // Transfer bytes from the compressed array to the output
063                    byte[] buf = new byte[1024];
064                    
065                    int len;
066                    
067                    while ((len = def.read(buf)) > 0)
068                            out.write(buf, 0, len);
069     
070                    def.close();
071                    out.close();
072                    
073                    return out.toByteArray();
074            }
075    
076    
077            /**
078             * Prevents instantiation.
079             */
080            private DeflateUtils() {
081            
082            }
083    }