blob: 988f27f3489ac4bc202c115f508b70716e449a30 [file] [log] [blame]
Shuyi Chend7955ce2013-05-22 14:51:55 -07001/*
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
17package com.kenai.jbosh;
18
19import java.io.ByteArrayInputStream;
20import java.io.ByteArrayOutputStream;
21import java.io.IOException;
22import java.util.zip.GZIPInputStream;
23import java.util.zip.GZIPOutputStream;
24
25/**
26 * Codec methods for compressing and uncompressing using GZIP.
27 */
28final class GZIPCodec {
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 GZIPCodec() {
42 // Empty
43 }
44
45 /**
46 * Returns the name of the codec.
47 *
48 * @return string name of the codec (i.e., "gzip")
49 */
50 public static String getID() {
51 return "gzip";
52 }
53
54 /**
55 * Compress/encode the data provided using the GZIP 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 GZIPOutputStream gzOut = null;
64 try {
65 gzOut = new GZIPOutputStream(byteOut);
66 gzOut.write(data);
67 gzOut.close();
68 byteOut.close();
69 return byteOut.toByteArray();
70 } finally {
71 gzOut.close();
72 byteOut.close();
73 }
74 }
75
76 /**
77 * Uncompress/decode the data provided using the GZIP 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 GZIPInputStream gzIn = null;
87 try {
88 gzIn = new GZIPInputStream(byteIn);
89 int read;
90 byte[] buffer = new byte[BUFFER_SIZE];
91 do {
92 read = gzIn.read(buffer);
93 if (read > 0) {
94 byteOut.write(buffer, 0, read);
95 }
96 } while (read >= 0);
97 return byteOut.toByteArray();
98 } finally {
99 gzIn.close();
100 byteOut.close();
101 }
102 }
103
104}