/*
Copyright 2012-2013 Helpers
https://github.com/provirus/Helpers
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ca.pgon.helpers;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;
import com.google.common.io.ByteStreams;
/**
* Some tools to help with common compressing tasks.
*
* @author Simon Levesque
*
*/
public class CompresserHelper {
private static final Logger logger = Logger.getLogger(CompresserHelper.class.getName());
/**
* Compress a content to BZip2.
*
* @param bytes
* @return the compressed bytes or null if an error occurred
*/
public static byte[] compressBZip2(byte[] bytes) {
try {
InputStream bytesIS = new ByteArrayInputStream(bytes);
ByteArrayOutputStream bytesCompressedOS = new ByteArrayOutputStream();
BZip2CompressorOutputStream bzip2CompressorOS = new BZip2CompressorOutputStream(bytesCompressedOS);
ByteStreams.copy(bytesIS, bzip2CompressorOS);
bzip2CompressorOS.close();
return bytesCompressedOS.toByteArray();
} catch (IOException e) {
logger.log(Level.SEVERE, "Error while compressing", e);
return null;
}
}
/**
* Extract a BZip2 content.
*
* @param bytes
* @return the uncompressed bytes or null if an error occurred
*/
public static byte[] extractBZip2(byte[] bytes) {
try {
InputStream bytesIS = new ByteArrayInputStream(bytes);
ByteArrayOutputStream bytesUncompressedOS = new ByteArrayOutputStream();
BZip2CompressorInputStream bzip2CompressorIS = new BZip2CompressorInputStream(bytesIS);
ByteStreams.copy(bzip2CompressorIS, bytesUncompressedOS);
bzip2CompressorIS.close();
return bytesUncompressedOS.toByteArray();
} catch (IOException e) {
logger.log(Level.SEVERE, "Error while uncompressing", e);
return null;
}
}
}