Alachisoft.NCache.Common.CompressionUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of nc-common Show documentation
Show all versions of nc-common Show documentation
Internal package of Alachisoft.
package Alachisoft.NCache.Common;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
//C# TO JAVA CONVERTER TODO TASK: There is no preprocessor in Java:
//#if VS2003
//#endif
/**
* Util class that compress and decompress values uing GZip provided solution
*/
public class CompressionUtil {
private static final int Compressed = BitSetConstants.Compressed;
///
/// Compress value only if its greater then threshold
///
/// value to be compressed
/// flag to be set if compression is successful
/// threshold limit
/// resultant value
public static byte[] Compress(byte[] value, Alachisoft.NCache.Common.BitSet flag, long threshold) {
if (value == null) return value;
if (flag == null) return value;
if (value.length <= threshold) return value;
try {
return Compress(value, flag);
} catch (IOException ioe) {
return value;
} catch (Exception ex) {
return value;
}
}
public static byte[] Compress(byte[] value, Alachisoft.NCache.Common.BitSet flag) throws IOException {
GZIPOutputStream ZippedObject = null;
ByteArrayOutputStream memStream = null;
try {
memStream = new ByteArrayOutputStream();
ZippedObject = new GZIPOutputStream(memStream);
ZippedObject.write((byte[]) value, 0, ((byte[]) value).length);
if (flag == null) flag = new BitSet();
flag.SetBit((byte) BitSetConstants.Compressed);
ZippedObject.close();
ZippedObject.finish();
memStream.close();
return memStream.toByteArray();
} catch (Exception ex) {
flag.UnsetBit((byte) BitSetConstants.Compressed);
return value;
}
}
///
/// Decompress the value
///
/// value to be decomrpessed
/// flag
/// decompressed value
public static byte[] Decompress(byte[] value, Alachisoft.NCache.Common.BitSet flag) throws Exception {
if (value == null) return value;
if (flag == null) return value;
if (flag.IsBitSet((byte) BitSetConstants.Compressed) == true) {
try {
return Decompress(value);
} catch (Exception e) {
throw e;
}
}
return value;
}
///
/// Decompress the value
///
/// value to be decomrpessed
/// decompressed value
public static byte[] Decompress(byte[] value) throws IOException {
GZIPInputStream uncompressedValue = null;
ByteArrayOutputStream result = null;
uncompressedValue = new GZIPInputStream(new ByteArrayInputStream(value));
result = new ByteArrayOutputStream();
int count;
byte[] tmp = new byte[2048];
// Un-compress byte-array 2048 bytes at a time (in case it is large)
while ((count = uncompressedValue.read(tmp, 0, tmp.length)) > 0) {
result.write(tmp, 0, count);
}
result.close();
uncompressedValue.close();
return result.toByteArray();
}
}