001/* 002 * The contents of this file are subject to the terms of the Common Development and 003 * Distribution License (the License). You may not use this file except in compliance with the 004 * License. 005 * 006 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the 007 * specific language governing permission and limitations under the License. 008 * 009 * When distributing Covered Software, include this CDDL Header Notice in each file and include 010 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL 011 * Header, with the fields enclosed by brackets [] replaced by your own identifying 012 * information: "Portions copyright [year] [name of copyright owner]". 013 * 014 * Copyright 2013-2015 ForgeRock AS. 015 */ 016 017package org.forgerock.json.jose.jwe.handlers.compression; 018 019import java.io.ByteArrayInputStream; 020import java.io.ByteArrayOutputStream; 021import java.io.IOException; 022import java.util.zip.Deflater; 023import java.util.zip.DeflaterOutputStream; 024import java.util.zip.Inflater; 025import java.util.zip.InflaterInputStream; 026 027import org.forgerock.json.jose.exceptions.JweCompressionException; 028 029/** 030 * An implementation of the CompressionHandler for DEFLATE Compressed Data Format Specification. 031 * <p> 032 * @see <a href="http://tools.ietf.org/html/rfc1951">DEFLATE Compressed Data Format Specification version 1.3</a> 033 * 034 */ 035public class DeflateCompressionHandler implements CompressionHandler { 036 037 /** 038 * {@inheritDoc} 039 */ 040 @Override 041 public byte[] compress(byte[] bytes) { 042 ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); 043 try (DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteOutputStream, 044 new Deflater(Deflater.DEFLATED, true))) { 045 deflaterOutputStream.write(bytes); 046 } catch (IOException e) { 047 throw new JweCompressionException("Failed to apply compression algorithm.", e); 048 } 049 050 return byteOutputStream.toByteArray(); 051 } 052 053 /** 054 * {@inheritDoc} 055 */ 056 @Override 057 public byte[] decompress(byte[] bytes) { 058 ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); 059 try (InflaterInputStream inflaterInputStream = new InflaterInputStream(new ByteArrayInputStream(bytes), 060 new Inflater(true)); 061 ByteArrayOutputStream out = byteOutputStream) { 062 byte[] buffer = new byte[1024]; 063 int l; 064 while ((l = inflaterInputStream.read(buffer)) > 0) { 065 out.write(buffer, 0, l); 066 } 067 } catch (IOException e) { 068 throw new JweCompressionException("Failed to apply de-compression algorithm.", e); 069 } 070 071 return byteOutputStream.toByteArray(); 072 } 073}