1 /* 2 * Copyright 2009 Mike Cumings 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.kenai.jbosh; 18 19 import java.io.ByteArrayInputStream; 20 import java.io.ByteArrayOutputStream; 21 import java.io.IOException; 22 import java.util.zip.DeflaterOutputStream; 23 import java.util.zip.InflaterInputStream; 24 25 /** 26 * Codec methods for compressing and uncompressing using ZLIB. 27 */ 28 final class ZLIBCodec { 29 30 /** 31 * Size of the internal buffer when decoding. 32 */ 33 private static final int BUFFER_SIZE = 512; 34 35 /////////////////////////////////////////////////////////////////////////// 36 // Constructors: 37 38 /** 39 * Prevent construction. 40 */ 41 private ZLIBCodec() { 42 // Empty 43 } 44 45 /** 46 * Returns the name of the codec. 47 * 48 * @return string name of the codec (i.e., "deflate") 49 */ 50 public static String getID() { 51 return "deflate"; 52 } 53 54 /** 55 * Compress/encode the data provided using the ZLIB format. 56 * 57 * @param data data to compress 58 * @return compressed data 59 * @throws IOException on compression failure 60 */ 61 public static byte[] encode(final byte[] data) throws IOException { 62 ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); 63 DeflaterOutputStream deflateOut = null; 64 try { 65 deflateOut = new DeflaterOutputStream(byteOut); 66 deflateOut.write(data); 67 deflateOut.close(); 68 byteOut.close(); 69 return byteOut.toByteArray(); 70 } finally { 71 deflateOut.close(); 72 byteOut.close(); 73 } 74 } 75 76 /** 77 * Uncompress/decode the data provided using the ZLIB format. 78 * 79 * @param data data to uncompress 80 * @return uncompressed data 81 * @throws IOException on decompression failure 82 */ 83 public static byte[] decode(final byte[] compressed) throws IOException { 84 ByteArrayInputStream byteIn = new ByteArrayInputStream(compressed); 85 ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); 86 InflaterInputStream inflaterIn = null; 87 try { 88 inflaterIn = new InflaterInputStream(byteIn); 89 int read; 90 byte[] buffer = new byte[BUFFER_SIZE]; 91 do { 92 read = inflaterIn.read(buffer); 93 if (read > 0) { 94 byteOut.write(buffer, 0, read); 95 } 96 } while (read >= 0); 97 return byteOut.toByteArray(); 98 } finally { 99 inflaterIn.close(); 100 byteOut.close(); 101 } 102 } 103 104 } 105