001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *      http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.apache.oozie.compression;
020
021import java.io.ByteArrayOutputStream;
022import java.io.DataInputStream;
023import java.io.IOException;
024import java.util.zip.GZIPInputStream;
025import java.util.zip.GZIPOutputStream;
026import org.apache.commons.io.IOUtils;
027
028/**
029 * Class to compress and decompress data using Gzip codec
030 *
031 */
032public class GzipCompressionCodec implements CompressionCodec {
033
034    public static final String CODEC_NAME = "gz";
035
036    public byte[] compressBytes(byte[] header, byte[] data) throws IOException {
037        ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(2000);
038        byteOutput.write(header);
039        GZIPOutputStream gzipOut = new GZIPOutputStream(byteOutput);
040        gzipOut.write(data);
041        gzipOut.close();
042        return byteOutput.toByteArray();
043    }
044
045    public byte[] compressString(byte[] header, String data) throws IOException {
046        ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(1000);
047        byteOutput.write(header);
048        GZIPOutputStream gzipOut = new GZIPOutputStream(byteOutput);
049        gzipOut.write(data.getBytes(CodecFactory.UTF_8_ENCODING));
050        gzipOut.close();
051        return byteOutput.toByteArray();
052    }
053
054    public String decompressToString(DataInputStream dais) throws IOException {
055        GZIPInputStream gzipIn = new GZIPInputStream(dais);
056        String decompress = IOUtils.toString(gzipIn, CodecFactory.UTF_8_ENCODING);
057        gzipIn.close();
058        return decompress;
059    }
060
061    public byte[] decompressToBytes(DataInputStream dais) throws IOException {
062        GZIPInputStream gzipIn = new GZIPInputStream(dais);
063        byte[] decompress = IOUtils.toByteArray(gzipIn);
064        gzipIn.close();
065        return decompress;
066    }
067
068}