下面列出了java.util.zip.Inflater#inflate ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static String inflatePayload(byte[] compressed) {
Inflater inflater = new Inflater();
inflater.setInput(compressed);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
while (!inflater.finished()) {
try {
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
}
catch (DataFormatException e) {
throw new RuntimeException(e);
}
}
return new String(outputStream.toByteArray(), UTF_8);
}
/**
* Decompresses the remaining ByteBuf (after type has been read) using Snappy
*/
private void decompress() {
Inflater inflater = new Inflater();
try {
int len = readInt();
byte[] out = new byte[len];
inflater.setInput(array(), readerIndex(), readableBytes());
inflater.inflate(out);
clear();
writeByteArray(out);
} catch (Exception e) {
throw new EncoderException(e);
} finally {
inflater.end();
}
}
private void readChunkUnzip(Inflater inflater, byte[] buffer, int offset, int length) throws IOException {
try {
do {
int read = inflater.inflate(buffer, offset, length);
if(read <= 0) {
if(inflater.finished()) {
throw new EOFException();
}
if(inflater.needsInput()) {
refillInflater(inflater);
} else {
throw new IOException("Can't inflate " + length + " bytes");
}
} else {
offset += read;
length -= read;
}
} while(length > 0);
} catch (DataFormatException ex) {
throw (IOException)(new IOException("inflate error").initCause(ex));
}
}
/**
* 解压缩.
*
* @param inputByte
* byte[]数组类型的数据
* @return 解压缩后的数据
* @throws IOException
*/
public static byte[] inflater(final byte[] inputByte) throws IOException {
int compressedDataLength = 0;
Inflater compresser = new Inflater(false);
compresser.setInput(inputByte, 0, inputByte.length);
ByteArrayOutputStream o = new ByteArrayOutputStream(inputByte.length);
byte[] result = new byte[1024];
try {
while (!compresser.finished()) {
compressedDataLength = compresser.inflate(result);
if (compressedDataLength == 0) {
break;
}
o.write(result, 0, compressedDataLength);
}
} catch (Exception ex) {
System.err.println("Data format error!\n");
ex.printStackTrace();
} finally {
o.close();
}
compresser.end();
return o.toByteArray();
}
@Override
protected byte[] perform(byte[] input) throws Exception {
Inflater inflater = new Inflater();
inflater.setInput(input);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(input.length);
byte[] buffer = new byte[1024];
while( !inflater.finished() ) {
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
}
outputStream.close();
return outputStream.toByteArray();
}
/**
* Decompress the zlib-compressed bytes and return an array of decompressed bytes
*
*/
public static byte[] decompress(byte compressedBytes[]) throws DataFormatException {
Inflater decompresser = new Inflater();
decompresser.setInput(compressedBytes);
byte[] resultBuffer = new byte[compressedBytes.length * 2];
byte[] resultTotal = new byte[0];
int resultLength = decompresser.inflate(resultBuffer);
while (resultLength > 0) {
byte previousResult[] = resultTotal;
resultTotal = new byte[resultTotal.length + resultLength];
System.arraycopy(previousResult, 0, resultTotal, 0, previousResult.length);
System.arraycopy(resultBuffer, 0, resultTotal, previousResult.length, resultLength);
resultLength = decompresser.inflate(resultBuffer);
}
decompresser.end();
return resultTotal;
}
public int uncompress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset) throws IOException
{
Inflater inf = inflater.get();
inf.reset();
inf.setInput(input, inputOffset, inputLength);
if (inf.needsInput())
return 0;
// We assume output is big enough
try
{
return inf.inflate(output, outputOffset, output.length - outputOffset);
}
catch (DataFormatException e)
{
throw new IOException(e);
}
}
public static byte[] inflate(byte[] data) throws DataFormatException, IOException {
Inflater inflater = new Inflater();
inflater.setInput(data);
ByteArrayOutputStream o = new ByteArrayOutputStream(data.length);
byte[] buf = new byte[1024];
try {
while (!inflater.finished()) {
int i = 0;
i = inflater.inflate(buf);
o.write(buf, 0, i);
}
} finally {
inflater.end();
}
return o.toByteArray();
}
public static byte[] inflater(byte[] inputByte) throws IOException {
boolean compressedDataLength = false;
Inflater compresser = new Inflater(false);
compresser.setInput(inputByte, 0, inputByte.length);
ByteArrayOutputStream o = new ByteArrayOutputStream(inputByte.length);
byte[] result = new byte[1024];
try {
while(!compresser.finished()) {
int compressedDataLength1 = compresser.inflate(result);
if(compressedDataLength1 == 0) {
break;
}
o.write(result, 0, compressedDataLength1);
}
} catch (Exception var9) {
System.err.println("Data format error!\n");
var9.printStackTrace();
} finally {
o.close();
}
compresser.end();
return o.toByteArray();
}
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();
}
@Test
public void testLogoutOneLogoutRequestNotAttempted() throws Exception {
final String FAKE_URL = "http://url";
LogoutRequest logoutRequest = new LogoutRequest(TICKET_ID, new SimpleWebApplicationServiceImpl(FAKE_URL));
WebUtils.putLogoutRequests(this.requestContext, Arrays.asList(logoutRequest));
this.requestContext.getFlowScope().put(FrontChannelLogoutAction.LOGOUT_INDEX, 0);
final Event event = this.frontChannelLogoutAction.doExecute(this.requestContext);
assertEquals(FrontChannelLogoutAction.REDIRECT_APP_EVENT, event.getId());
List<LogoutRequest> list = WebUtils.getLogoutRequests(this.requestContext);
assertEquals(1, list.size());
final String url = (String) event.getAttributes().get("logoutUrl");
assertTrue(url.startsWith(FAKE_URL + "?SAMLRequest="));
final byte[] samlMessage = Base64.decodeBase64(URLDecoder.decode(StringUtils.substringAfter(url, "?SAMLRequest="), "UTF-8"));
final Inflater decompresser = new Inflater();
decompresser.setInput(samlMessage);
final byte[] result = new byte[1000];
decompresser.inflate(result);
decompresser.end();
final String message = new String(result);
assertTrue(message.startsWith("<samlp:LogoutRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" ID=\""));
assertTrue(message.indexOf("<samlp:SessionIndex>" + TICKET_ID + "</samlp:SessionIndex>") >= 0);
}
/**
* zlib decompress 2 byte
*
* @param bytesToDecompress byte[]
* @return byte[]
*/
public static byte[] decompressForZlib(byte[] bytesToDecompress) {
byte[] returnValues = null;
Inflater inflater = new Inflater();
int numberOfBytesToDecompress = bytesToDecompress.length;
inflater.setInput(bytesToDecompress, 0, numberOfBytesToDecompress);
int numberOfBytesDecompressedSoFar = 0;
List<Byte> bytesDecompressedSoFar = new ArrayList<>();
try {
while (!inflater.needsInput()) {
byte[] bytesDecompressedBuffer = new byte[numberOfBytesToDecompress];
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;
}
private void expand(Inflater inflater, byte[] inBuf, int inCount,
byte[] outBuf) throws DataFormatException {
int inPosn;
int outPosn;
inPosn = outPosn = 0;
//System.out.println("### starting expand, inCount is " + inCount);
while (!inflater.finished()) {
int want = -1, got;
// only read if the input buffer is empty
if (inflater.needsInput() && inCount != 0) {
want = (inCount < LOCAL_BUF_SIZE) ? inCount : LOCAL_BUF_SIZE;
inflater.setInput(inBuf, inPosn, want);
inCount -= want;
inPosn += want;
}
// inflate to current position in output buffer
int compCount;
compCount = inflater.inflate(outBuf, outPosn, LOCAL_BUF_SIZE);
outPosn += compCount;
//System.out.println("Expanded " + want + ", output " + compCount);
}
}
private static void decompress(InputStream in, OutputStream out) throws IOException, DataFormatException
{
byte[] buf = new byte[2048];
int read = in.read(buf);
if (read > 0)
{
Inflater inflater = new Inflater();
inflater.setInput(buf,0,read);
byte[] res = new byte[2048];
while (true)
{
int resRead = inflater.inflate(res);
if (resRead != 0)
{
out.write(res,0,resRead);
continue;
}
if (inflater.finished() || inflater.needsDictionary() || in.available() == 0)
{
break;
}
read = in.read(buf);
inflater.setInput(buf,0,read);
}
}
out.flush();
}
/**
* Decompresses a block which was compressed using the multi compression method.
*
* @param block block to be decompressed
* @param outSize size of the decompressed data
* @param dest buffer to copy the decompressed data
* @param destPos position in the destination buffer to copy the decompressed data
* @throws InvalidMpqArchiveException if unsupported compression is found or the decompression of the block fails
*/
public static void decompressMultiBlock( byte[] block, final int outSize, final byte[] dest, final int destPos ) throws InvalidMpqArchiveException {
// Check if block is really compressed, some blocks have set the compression flag, but are not compressed.
if ( block.length >= outSize ) {
// Copy block
System.arraycopy( block, 0, dest, destPos, outSize );
}
else {
final byte compressionFlag = block[ 0 ];
switch ( compressionFlag ) {
case FLAG_COMPRESSION_ZLIB : {
// Handle deflated code (compressionFlag = 0x02)
final Inflater inflater = new Inflater();
inflater.setInput( block, 1, block.length - 1 );
try {
inflater.inflate( dest, destPos, outSize );
inflater.end();
} catch ( final DataFormatException dfe ) {
throw new InvalidMpqArchiveException( "Data format exception, failed to decompressed block!", dfe );
}
break;
// End of inflating
}
case FLAG_COMPRESSION_BZIP2 : {
try {
new CBZip2InputStream( new ByteArrayInputStream( block, 3, block.length - 3 ) ).read( dest );
} catch ( final IOException ie ) {
throw new InvalidMpqArchiveException( "Data format exception, failed to decompressed block!", ie );
}
break;
}
default :
throw new InvalidMpqArchiveException( "Compression (" + compressionFlag + ") not supported!" );
}
}
}
/**
* java.util.zip.Deflater#finish()
*/
public void test_finish() throws Exception {
// This test already here, its the same as test_deflate()
byte byteArray[] = { 5, 2, 3, 7, 8 };
byte outPutBuf[] = new byte[100];
byte outPutInf[] = new byte[100];
int x = 0;
Deflater defl = new Deflater();
defl.setInput(byteArray);
defl.finish();
// needsInput should never return true after finish() is called
if (System.getProperty("java.vendor").startsWith("IBM")) {
assertFalse("needsInput() should return false after finish() is called", defl
.needsInput());
}
while (!defl.finished()) {
x += defl.deflate(outPutBuf);
}
int totalOut = defl.getTotalOut();
int totalIn = defl.getTotalIn();
assertEquals(x, totalOut);
assertEquals(byteArray.length, totalIn);
defl.end();
Inflater infl = new Inflater();
infl.setInput(outPutBuf);
while (!infl.finished()) {
infl.inflate(outPutInf);
}
assertEquals(totalIn, infl.getTotalOut());
assertEquals(totalOut, infl.getTotalIn());
for (int i = 0; i < byteArray.length; i++) {
assertEquals(byteArray[i], outPutInf[i]);
}
assertEquals("Final decompressed data contained more bytes than original",
0, outPutInf[byteArray.length]);
infl.end();
}
private void simpleTest()
throws UnsupportedEncodingException, DataFormatException {
// Encode a String into bytes
String inputString = "blahblahblah??";
byte[] input = inputString.getBytes("UTF-8");
// Compress the bytes
byte[] output = new byte[100];
Deflater compresser = new Deflater();
compresser.setInput(input);
compresser.finish();
int compressedDataLength = compresser.deflate(output);
// Decompress the bytes
Inflater decompresser = new Inflater();
decompresser.setInput(output, 0, compressedDataLength);
byte[] result = new byte[100];
int resultLength = decompresser.inflate(result);
// Decode the bytes into a String
String outputString = new String(result, 0, resultLength, "UTF-8");
assertEquals(inputString, outputString);
assertEquals(compresser.getAdler(), decompresser.getAdler());
decompresser.end();
}
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 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;
}
@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;
}