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