下面列出了java.util.zip.Inflater#setInput ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static byte[] uncompressZlib(byte[] bytes) throws IOException {
Inflater inflater = new Inflater();
inflater.setInput(bytes);
ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);
byte[] buf = new byte[1024];
while (!inflater.finished()) {
try {
int count = inflater.inflate(buf);
bos.write(buf, 0, count);
}
catch (DataFormatException e) {
}
}
bos.close();
inflater.end();
return bos.toByteArray();
}
@Override
public byte[] uncompress(byte[] data) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Inflater decompressor = new Inflater();
try {
decompressor.setInput(data);
final byte[] buf = new byte[2048];
while (!decompressor.finished()) {
int count = decompressor.inflate(buf);
bos.write(buf, 0, count);
}
} catch (DataFormatException e) {
e.printStackTrace();
} finally {
decompressor.end();
}
return bos.toByteArray();
}
private static byte[] getInputByCompress(byte[] toByteArray) throws DataFormatException{
TransferInputStream fis = new TransferInputStream(toByteArray);
int unCompressedLength = fis.readInt();
int compressedLength = fis.readInt();
byte[] input = new byte[compressedLength];
fis.readFully(input, 0, compressedLength);
byte[] output = new byte[unCompressedLength];
Inflater decompresser = new Inflater();
decompresser.setInput(input);
decompresser.inflate(output);
decompresser.end();
return getInputByNormal(output);
}
public byte[] decompress(byte[] data){
Inflater decompresser = new Inflater();
decompresser.setInput(data);
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] result = new byte[100000];
int length = 0;
try {
while (!decompresser.finished()) {
length = decompresser.inflate(result);
if (length > 0) {
os.write(result, 0, length);
} else {
break;
}
}
} catch (DataFormatException e) {
e.printStackTrace();
}
return os.toByteArray();
}
public int fillInflater(Inflater inflater) throws IOException {
// Makes sure we're expecting this call:
if(state != STATE_DEFLATING) {
throw new IOException("fillInflater called while not deflating!");
}
if(bufferSize <= 0) {
if(!fillBuffer()) {
return -1;
}
}
inflater.setInput(buffer, bufferPos, bufferSize);
bufferPos += bufferSize;
offset += bufferSize;
int oldSize = bufferSize;
bufferSize = 0;
return oldSize;
}
public static byte[] decompress(byte[] value) throws DataFormatException
{
ByteArrayOutputStream bos = new ByteArrayOutputStream(value.length);
Inflater decompressor = new Inflater();
try
{
decompressor.setInput(value);
final byte[] buf = new byte[1024];
while (!decompressor.finished())
{
int count = decompressor.inflate(buf);
bos.write(buf, 0, count);
}
} finally
{
decompressor.end();
}
return bos.toByteArray();
}
public static byte[] b(byte abyte0[])
{
int i = 0;
if (abyte0 == null || abyte0.length == 0)
{
return null;
}
Inflater inflater = new Inflater();
inflater.setInput(abyte0, 0, abyte0.length);
ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
byte abyte1[] = new byte[1024];
do
{
if (inflater.needsInput())
{
inflater.end();
return bytearrayoutputstream.toByteArray();
}
int j = inflater.inflate(abyte1);
bytearrayoutputstream.write(abyte1, i, j);
i += j;
} while (true);
}
@Override
public byte[] inflate(byte[] data, int maxSize) throws IOException {
Inflater inflater = new Inflater();
inflater.setInput(data);
inflater.finished();
FastByteArrayOutputStream bos = ThreadCache.fbaos.get();
bos.reset();
byte[] buffer = new byte[1024];
try {
int length = 0;
while (!inflater.finished()) {
int i = inflater.inflate(buffer);
length += i;
if (maxSize > 0 && length >= maxSize) {
throw new IOException("Inflated data exceeds maximum size");
}
bos.write(buffer, 0, i);
}
return bos.toByteArray();
} catch (DataFormatException e) {
throw new IOException("Unable to inflate zlib stream", e);
}
}
public static byte[] uncompress(byte[] input) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Inflater decompressor = new Inflater();
try {
decompressor.setInput(input);
final byte[] buf = new byte[2048];
while (!decompressor.finished()) {
int count = 0;
try {
count = decompressor.inflate(buf);
} catch (DataFormatException e) {
e.printStackTrace();
}
bos.write(buf, 0, count);
}
} finally {
decompressor.end();
}
return bos.toByteArray();
}
/**
* Compress the byte[] using ZLIB deflate decompression.
*
* @param bytes The bytes to decompress
* @param expectedSize The expected size of the decompressed byte[].
*
* @return The decompressed bytes.
* @throws ImageReadException if the bytes could not be decompressed.
* @see Inflater
*/
public static byte[] decompress(final byte[] bytes, final int expectedSize) throws ImageReadException {
try {
final Inflater inflater = new Inflater();
inflater.setInput(bytes);
final byte[] result = new byte[expectedSize];
inflater.inflate(result);
return result;
} catch (final DataFormatException e) {
throw new ImageReadException("Unable to decompress image", e);
}
}
@Override
public int decompress(byte[] input, int offset, int length, OutputBuffer output)
throws OrcCorruptionException
{
Inflater inflater = new Inflater(true);
try {
inflater.setInput(input, offset, length);
byte[] buffer = output.initialize(Math.min(length * EXPECTED_COMPRESSION_RATIO, maxBufferSize));
int uncompressedLength = 0;
while (true) {
uncompressedLength += inflater.inflate(buffer, uncompressedLength, buffer.length - uncompressedLength);
if (inflater.finished() || buffer.length >= maxBufferSize) {
break;
}
int oldBufferSize = buffer.length;
buffer = output.grow(Math.min(buffer.length * 2, maxBufferSize));
if (buffer.length <= oldBufferSize) {
throw new IllegalStateException(format("Buffer failed to grow. Old size %d, current size %d", oldBufferSize, buffer.length));
}
}
if (!inflater.finished()) {
throw new OrcCorruptionException(orcDataSourceId, "Could not decompress all input (output buffer too small?)");
}
return uncompressedLength;
}
catch (DataFormatException e) {
throw new OrcCorruptionException(e, orcDataSourceId, "Invalid compressed stream");
}
finally {
inflater.end();
}
}
private void refillInflater(Inflater inflater) throws IOException {
while(chunkRemaining == 0) {
closeChunk();
openChunk(IDAT);
}
int read = readChunk(buffer, 0, buffer.length);
inflater.setInput(buffer, 0, read);
}
private Object doInCompress(InputStream is) throws IOException, DataFormatException, SocketExecuteException {
// in
int unCompressedLength = TransferUtil.readInt(is);
int compressedLength = TransferUtil.readInt(is);
byte[] input = new byte[compressedLength];
is.read(input);
byte[] output = new byte[unCompressedLength];
Inflater decompresser = new Inflater();
decompresser.setInput(input);
decompresser.inflate(output);
decompresser.end();
InputStream istemp = new ByteArrayInputStream(output);
return TransferObject.convertReturnInputStream(istemp);
}
private int inflate(byte[] src, byte[] dest) {
Inflater inflater = (inflaterRef == null ? null : inflaterRef.get());
// construct the inflater object or reuse an existing one
if (inflater == null)
inflaterRef = new SoftReference<Inflater>(inflater = new Inflater(true));
inflater.reset();
inflater.setInput(src);
try {
return inflater.inflate(dest);
} catch (DataFormatException ex) {
return -1;
}
}
@Override
public ByteBuf decode(ByteBuf encoded, int uncompressedLength) throws IOException {
ByteBuf uncompressed = PulsarByteBufAllocator.DEFAULT.heapBuffer(uncompressedLength, uncompressedLength);
int len = encoded.readableBytes();
byte[] array;
int offset;
if (encoded.hasArray()) {
array = encoded.array();
offset = encoded.arrayOffset() + encoded.readerIndex();
} else {
array = new byte[len];
encoded.getBytes(encoded.readerIndex(), array);
offset = 0;
}
int resultLength;
Inflater inflater = this.inflater.get();
inflater.reset();
inflater.setInput(array, offset, len);
try {
resultLength = inflater.inflate(uncompressed.array(), uncompressed.arrayOffset(), uncompressedLength);
} catch (DataFormatException e) {
throw new IOException(e);
}
checkArgument(resultLength == uncompressedLength);
uncompressed.writerIndex(uncompressedLength);
return uncompressed;
}
@Override
public void unzip(byte[] bytes, OutputStream outputStream) {
try {
Inflater inflater = new Inflater();
inflater.setInput(bytes);
byte[] buffer = new byte[1024];
for (int length; !inflater.finished() && (length = inflater.inflate(buffer)) > -1; )
outputStream.write(buffer, 0, length);
inflater.end();
} catch (Exception e) {
logger.warn(e, "使用ZIP解压缩数据时发生异常!");
}
}
private Array readCompressedZlib(ucar.nc2.Variable v2, long dataPos, int nx, int ny, List<Range> ranges, int[] levels)
throws IOException, InvalidRangeException {
// Get to the proper offset and read in the rest of the compressed data
raf.seek(dataPos);
int data_size = (int) (raf.length() - dataPos); // or 5120 as read buffer size
byte[] data = new byte[data_size];
raf.readFully(data);
// Buffer for decompressing data
byte[] uncomp = new byte[nx * ny];
int offset = 0;
// Set-up zlib decompression (inflation)
Inflater inflater = new Inflater(false);
inflater.setInput(data);
// Loop while the inflater has data and we have space in final buffer
// This will end up ignoring the last few compressed bytes, which
// correspond to the end of file marker, which is a single row of pixels
// of alternating 0/255.
while (inflater.getRemaining() > 0 && offset < uncomp.length) {
// Try to decompress what's left, which ends up decompressing one block
try {
offset += inflater.inflate(uncomp, offset, uncomp.length - offset);
} catch (DataFormatException ex) {
throw new IOException(ex);
}
// If the last block finished...
if (inflater.finished()) {
// See if anything's left
int bytesLeft = inflater.getRemaining();
if (bytesLeft > 0) {
// Figure out where we are in the input data
int inputOffset = data_size - bytesLeft;
// Check if remaining data are zlib--if not copy out and bail
byte[] b2 = new byte[2];
System.arraycopy(data, inputOffset, b2, 0, b2.length);
if (!isZlibHed(b2)) {
System.arraycopy(data, inputOffset, uncomp, offset, bytesLeft);
break;
}
// Otherwise, set up for decompressing next block
inflater.reset();
inflater.setInput(data, inputOffset, bytesLeft);
}
}
}
inflater.end();
// Turn the decompressed data into an array, caching as appropriate
Array array = makeArray(uncomp, levels, v2.getShape());
if (levels == null && array.getSize() < Variable.defaultSizeToCache)
v2.setCachedData(array, false);
return array.sectionNoReduce(ranges);
}
@Override
public boolean verifyUserSig(String identifier, String sig)throws QCloudException {
try {
Security.addProvider(new BouncyCastleProvider());
//DeBaseUrl64 urlSig to json
Base64 decoder = new Base64();
byte [] compressBytes = Base64Url.base64DecodeUrl(sig.getBytes(Charset.forName("UTF-8")));
//Decompression
Inflater decompression = new Inflater();
decompression.setInput(compressBytes, 0, compressBytes.length);
byte [] decompressBytes = new byte [1024];
int decompressLength = decompression.inflate(decompressBytes);
decompression.end();
String jsonString = new String(Arrays.copyOfRange(decompressBytes, 0, decompressLength));
//Get TLS.Sig from json
JSONObject jsonObject= JSON.parseObject(jsonString);
String sigTLS = jsonObject.getString("TLS.sig");
//debase64 TLS.Sig to get serailString
byte[] signatureBytes = decoder.decode(sigTLS.getBytes(Charset.forName("UTF-8")));
String strSdkAppid = jsonObject.getString("TLS.sdk_appid");
String sigTime = jsonObject.getString("TLS.time");
String sigExpire = jsonObject.getString("TLS.expire_after");
if (!imConfig.getSdkAppId().equals(strSdkAppid))
{
return false;
}
if ( System.currentTimeMillis()/1000 - Long.parseLong(sigTime) > Long.parseLong(sigExpire)) {
return false;
}
//Get Serial String from json
String SerialString =
"TLS.appid_at_3rd:" + 0 + "\n" +
"TLS.account_type:" + 0 + "\n" +
"TLS.identifier:" + identifier + "\n" +
"TLS.sdk_appid:" + imConfig.getSdkAppId() + "\n" +
"TLS.time:" + sigTime + "\n" +
"TLS.expire_after:" + sigExpire + "\n";
Reader reader = new CharArrayReader(imConfig.getPublicKey().toCharArray());
PEMParser parser = new PEMParser(reader);
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
Object obj = parser.readObject();
parser.close();
PublicKey pubKeyStruct = converter.getPublicKey((SubjectPublicKeyInfo) obj);
Signature signature = Signature.getInstance("SHA256withECDSA","BC");
signature.initVerify(pubKeyStruct);
signature.update(SerialString.getBytes(Charset.forName("UTF-8")));
return signature.verify(signatureBytes);
}catch (Exception e) {
throw new QCloudException(e);
}
}
@Override
public BufferedImage getImage() {
int sizeUncompressed = 0;
int size8888 = 0;
int maxWriteBuf = 2;
int maxHeight = 3;
byte[] writeBuf = new byte[maxWriteBuf];
@SuppressWarnings ("unused")
byte[] rowPointers = new byte[maxHeight];
switch (getFormat()) {
case 1:
case 513:
sizeUncompressed = getHeight() * getWidth() * 4;
break;
case 2:
sizeUncompressed = getHeight() * getWidth() * 8;
break;
case 517:
sizeUncompressed = getHeight() * getWidth() / 128;
break;
}
size8888 = getHeight() * getWidth() * 8;
if (size8888 > maxWriteBuf) {
maxWriteBuf = size8888;
writeBuf = new byte[maxWriteBuf];
}
if (getHeight() > maxHeight) {
maxHeight = getHeight();
rowPointers = new byte[maxHeight];
}
Inflater dec = new Inflater();
dec.setInput(getData(), 0, dataLength);
int declen = 0;
byte[] uc = new byte[sizeUncompressed];
try {
declen = dec.inflate(uc);
} catch (DataFormatException ex) {
throw new RuntimeException("zlib fucks", ex);
}
dec.end();
if (getFormat() == 1) {
for (int i = 0; i < sizeUncompressed; i++) {
byte low = (byte) (uc[i] & 0x0F);
byte high = (byte) (uc[i] & 0xF0);
writeBuf[(i << 1)] = (byte) (((low << 4) | low) & 0xFF);
writeBuf[(i << 1) + 1] = (byte) (high | ((high >>> 4) & 0xF));
}
} else if (getFormat() == 2) {
writeBuf = uc;
} else if (getFormat() == 513) {
for (int i = 0; i < declen; i += 2) {
byte bBits = (byte) ((uc[i] & 0x1F) << 3);
byte gBits = (byte) (((uc[i + 1] & 0x07) << 5) | ((uc[i] & 0xE0) >> 3));
byte rBits = (byte) (uc[i + 1] & 0xF8);
writeBuf[(i << 1)] = (byte) (bBits | (bBits >> 5));
writeBuf[(i << 1) + 1] = (byte) (gBits | (gBits >> 6));
writeBuf[(i << 1) + 2] = (byte) (rBits | (rBits >> 5));
writeBuf[(i << 1) + 3] = (byte) 0xFF;
}
} else if (getFormat() == 517) {
byte b = 0x00;
int pixelIndex = 0;
for (int i = 0; i < declen; i++) {
for (int j = 0; j < 8; j++) {
b = (byte) (((uc[i] & (0x01 << (7 - j))) >> (7 - j)) * 255);
for (int k = 0; k < 16; k++) {
pixelIndex = (i << 9) + (j << 6) + k * 2;
writeBuf[pixelIndex] = b;
writeBuf[pixelIndex + 1] = b;
writeBuf[pixelIndex + 2] = b;
writeBuf[pixelIndex + 3] = (byte) 0xFF;
}
}
}
}
DataBufferByte imgData = new DataBufferByte(writeBuf, sizeUncompressed);
SampleModel sm = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, getWidth(), getHeight(), 4, getWidth() * 4, ZAHLEN);
WritableRaster imgRaster = Raster.createWritableRaster(sm, imgData, new Point(0, 0));
BufferedImage aa = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
aa.setData(imgRaster);
return aa;
}
/**
* zlib decompress 2 byte
*
* @param bytesToDecompress
* @return
*/
public static byte[] decompressForZlib(byte[] bytesToDecompress) {
byte[] returnValues = null;
Inflater inflater = new Inflater();
int numberOfBytesToDecompress = bytesToDecompress.length;
inflater.setInput
(
bytesToDecompress,
0,
numberOfBytesToDecompress
);
int bufferSizeInBytes = numberOfBytesToDecompress;
int numberOfBytesDecompressedSoFar = 0;
List<Byte> bytesDecompressedSoFar = new ArrayList<Byte>();
try {
while (inflater.needsInput() == false) {
byte[] bytesDecompressedBuffer = new byte[bufferSizeInBytes];
int numberOfBytesDecompressedThisTime = inflater.inflate
(
bytesDecompressedBuffer
);
numberOfBytesDecompressedSoFar += numberOfBytesDecompressedThisTime;
for (int b = 0; b < numberOfBytesDecompressedThisTime; b++) {
bytesDecompressedSoFar.add(bytesDecompressedBuffer[b]);
}
}
returnValues = new byte[bytesDecompressedSoFar.size()];
for (int b = 0; b < returnValues.length; b++) {
returnValues[b] = (byte) (bytesDecompressedSoFar.get(b));
}
} catch (DataFormatException dfe) {
dfe.printStackTrace();
}
inflater.end();
return returnValues;
}