下面列出了java.awt.image.PixelInterleavedSampleModel#java.util.zip.Inflater 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static @Nullable ArrayList<Mesh> parseMshp(ParsableByteArray input) {
int version = input.readUnsignedByte();
if (version != 0) {
return null;
}
input.skipBytes(7); // flags + crc.
int encoding = input.readInt();
if (encoding == TYPE_DFL8) {
ParsableByteArray output = new ParsableByteArray();
Inflater inflater = new Inflater(true);
try {
if (!Util.inflate(input, output, inflater)) {
return null;
}
} finally {
inflater.end();
}
input = output;
} else if (encoding != TYPE_RAW) {
return null;
}
return parseRawMshpData(input);
}
public static byte[] decompress(byte[] data) throws IOException, DataFormatException {
long startTime = System.currentTimeMillis();
Inflater inflater = new Inflater();
inflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024];
while (!inflater.finished()) {
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
}
outputStream.close();
byte[] output = outputStream.toByteArray();
logger.debug("Original: " + data.length + " bytes. " + "Decompressed: " + output.length + " bytes. Time: " + (System.currentTimeMillis() - startTime));
return output;
}
private static byte[] uncompressBytesInflateDeflate(byte[] inBytes) throws IOException {
Inflater inflater = new Inflater();
inflater.setInput(inBytes);
ByteArrayOutputStream bos = new ByteArrayOutputStream(inBytes.length);
byte[] buffer = new byte[1024 * 8];
while (!inflater.finished()) {
int count;
try {
count = inflater.inflate(buffer);
} catch (DataFormatException e) {
throw new IOException(e);
}
bos.write(buffer, 0, count);
}
byte[] output = bos.toByteArray();
return output;
}
@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();
}
private static ByteSequence writeCompressedBytesType(final ByteSequence contents) throws IOException {
Inflater inflater = new Inflater();
try (org.apache.activemq.util.ByteArrayOutputStream decompressed = new org.apache.activemq.util.ByteArrayOutputStream()) {
int length = ByteSequenceData.readIntBig(contents);
contents.offset = 0;
byte[] data = Arrays.copyOfRange(contents.getData(), 4, contents.getLength());
inflater.setInput(data);
byte[] buffer = new byte[length];
int count = inflater.inflate(buffer);
decompressed.write(buffer, 0, count);
return decompressed.toByteSequence();
} catch (Exception e) {
throw new IOException(e);
} finally {
inflater.end();
}
}
/**
* java.util.zip.Inflater#end()
*/
public void test_end() throws Exception {
// test method of java.util.zip.inflater.end()
byte byteArray[] = { 5, 2, 3, 7, 8 };
int r = 0;
Inflater inflate = new Inflater();
inflate.setInput(byteArray);
inflate.end();
try {
inflate.reset();
} catch (NullPointerException expected) {
// Expected
}
Inflater i = new Inflater();
i.end();
// check for exception
i.end();
}
public static DeflaterInflaterData uncompressBytes(byte[] output, int compressedDataLength) throws DataFormatException {
Inflater decompresser = new Inflater();
decompresser.setInput(output, 0, compressedDataLength);
byte[] buffer = new byte[512];
byte[] result = new byte[0];
int bytesRead;
while (!decompresser.needsInput()) {
bytesRead = decompresser.inflate(buffer);
byte[] newResult = new byte[result.length + bytesRead];
System.arraycopy(result, 0, newResult, 0, result.length);
System.arraycopy(buffer, 0, newResult, result.length, bytesRead);
result = newResult;
}
// System.out.println(new String(result));
decompresser.end();
return new DeflaterInflaterData(result.length, result);
}
public static void checkValid(String fontData) throws IllegalArgumentException {
if (fontData == null || fontData.isEmpty()) {
return;
}
// Throws IllegalArgumentException if invalid
byte[] data = Base64.getDecoder().decode(fontData);
try {
int expectLen = ASCII_PNG_CHARS.length() >>> 1;
Inflater inflater = inflate(data, new byte[expectLen]);
long written = inflater.getBytesWritten();
checkArgument(inflater.finished(), "Font data larger than expected, expected %s", expectLen);
checkArgument(written == expectLen, "Font data not of expected size, expected %s got %s", expectLen, written);
} catch (DataFormatException e) {
throw new IllegalArgumentException("Corrupt font data", e);
}
}
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);
}
/**
* Base64 decodes the SAML message and then decompresses the message.
*
* @param message Base64 encoded, DEFALTE compressed, SAML message
*
* @return the SAML message
*
* @throws MessageDecodingException thrown if the message can not be decoded
*/
protected InputStream decodeMessage(String message) throws MessageDecodingException {
log.debug("Base64 decoding and inflating SAML message");
byte[] decodedBytes = Base64.decode(message);
if(decodedBytes == null){
log.error("Unable to Base64 decode incoming message");
throw new MessageDecodingException("Unable to Base64 decode incoming message");
}
try {
ByteArrayInputStream bytesIn = new ByteArrayInputStream(decodedBytes);
InflaterInputStream inflater = new InflaterInputStream(bytesIn, new Inflater(true));
return inflater;
} catch (Exception e) {
log.error("Unable to Base64 decode and inflate SAML message", e);
throw new MessageDecodingException("Unable to Base64 decode and inflate SAML message", e);
}
}
/**
* 解压缩.
*
* @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();
}
/**
* get the set of annotations of a vertex
* @param toDecode node ID
* @return the set of annotations as a String
* @throws DataFormatException
* @throws UnsupportedEncodingException
*/
public static String decodingVertex(Integer toDecode) throws DataFormatException, UnsupportedEncodingException {
Inflater decompresser = new Inflater();
/*DatabaseEntry key = new DatabaseEntry(toDecode.toString().getBytes("UTF-8"));
DatabaseEntry data = new DatabaseEntry();
annotationsDatabase.get(null, key, data, LockMode.DEFAULT);*/
//byte[] input = encoded.first().get(toDecode);
byte[] input = getBytes(annotationsDatabase, toDecode);
String outputString;
//if (data.getSize() == 0) {
if (input.length == 0) {
outputString = "Vertex " + toDecode + " does not exist.";
} else {
decompresser.setInput(input);
byte[] result = new byte[1000];
int resultLength = decompresser.inflate(result);
decompresser.end();
// Decode the bytes into a String
outputString = new String(result, 0, resultLength, "UTF-8");
}
//System.out.println(outputString);
return outputString;
}
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[] decompress(byte[] input) throws DataFormatException, IOException {
// Create the decompressor and give it the data to compress
Inflater decompressor = new Inflater();
decompressor.setInput(input);
// Create an expandable byte array to hold the decompressed data
ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
// Decompress the data
byte[] buf = new byte[1024];
while (!decompressor.finished()) {
int count = decompressor.inflate(buf);
bos.write(buf, 0, count);
}
bos.close();
// Get the decompressed data
return bos.toByteArray();
}
public static void main(String... args) throws Exception {
if (!new DefaultDeflateCompatibilityWindow().isCompatible()) {
System.err.println("zlib not compatible on this system");
System.exit(-1);
}
File oldFile = new File(args[0]); // must be a zip archive
Inflater uncompressor = new Inflater(true);
try (FileInputStream compressedPatchIn = new FileInputStream(args[1]);
InflaterInputStream patchIn =
new InflaterInputStream(compressedPatchIn, uncompressor, 32768);
FileOutputStream newFileOut = new FileOutputStream(args[2])) {
new FileByFileV1DeltaApplier().applyDelta(oldFile, patchIn, newFileOut);
} finally {
uncompressor.end();
}
}
protected void decompress(@Nonnull TransformState state, @Nullable StoreTimer timer) throws DataFormatException {
long startTime = System.nanoTime();
// At the moment, there is only one compression version, so
// we after we've verified it is in the right range, we
// can just move on. If we ever introduce a new format version,
// we will need to make this code more complicated.
int compressionVersion = state.data[state.offset];
if (compressionVersion < MIN_COMPRESSION_VERSION || compressionVersion > MAX_COMPRESSION_VERSION) {
throw new RecordSerializationException("unknown compression version")
.addLogInfo("compressionVersion", compressionVersion);
}
int decompressedLength = ByteBuffer.wrap(state.data, state.offset + 1, 4).order(ByteOrder.BIG_ENDIAN).getInt();
byte[] decompressed = new byte[decompressedLength];
Inflater decompressor = new Inflater();
decompressor.setInput(state.data, state.offset + 5, state.length - 5);
decompressor.inflate(decompressed);
decompressor.end();
state.setDataArray(decompressed);
if (timer != null) {
timer.recordSinceNanoTime(Events.DECOMPRESS_SERIALIZED_RECORD, startTime);
}
}
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();
}
private static byte[] uncompressBytesInflateDeflate(byte[] inBytes) throws IOException {
Inflater inflater = new Inflater();
inflater.setInput(inBytes);
NonSyncByteArrayOutputStream bos = new NonSyncByteArrayOutputStream(inBytes.length);
byte[] buffer = new byte[1024 * 8];
while (!inflater.finished()) {
int count;
try {
count = inflater.inflate(buffer);
} catch (DataFormatException e) {
throw new IOException(e);
}
bos.write(buffer, 0, count);
}
byte[] output = bos.toByteArray();
return output;
}
private byte[] decompress( byte [] compressedBytes ) {
Inflater inflater = new Inflater();
inflater.setInput( compressedBytes );
ByteArrayOutputStream outputStream = new ByteArrayOutputStream( compressedBytes.length);
byte[] buffer = new byte[1024];
try {
while (!inflater.finished()) {
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
}
outputStream.close();
}
catch (DataFormatException | IOException e) {
e.printStackTrace();
return compressedBytes;
}
return outputStream.toByteArray();
}
private void readChunkUnzip(Inflater inflater, byte[] buffer, int offset, int length) throws IOException {
assert (buffer != this.buffer);
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));
}
}
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();
}
/**
* Creates a new output stream with the specified decompressor and
* buffer size.
*
* @param out output stream to write the uncompressed data to
* @param infl decompressor ("inflater") for this stream
* @param bufLen decompression buffer size
* @throws IllegalArgumentException if {@code bufLen} is <= 0
* @throws NullPointerException if {@code out} or {@code infl} is null
*/
public RpcInflaterOutputStream(OutputStream out, Inflater infl, int bufLen, MD5Digester digester) {
super(out);
this.localDigester = digester;
// Sanity checks
if (out == null)
throw new NullPointerException("Null output");
if (infl == null)
throw new NullPointerException("Null inflater");
if (bufLen <= 0)
throw new IllegalArgumentException("Buffer size < 1");
// Initialize
inf = infl;
buf = new byte[bufLen];
}
public String decodeByteBuff(ByteBuf buf) throws IOException, DataFormatException {
byte[] temp = new byte[buf.readableBytes()];
ByteBufInputStream bis = new ByteBufInputStream(buf);
bis.read(temp);
bis.close();
Inflater decompresser = new Inflater(true);
decompresser.setInput(temp, 0, temp.length);
StringBuilder sb = new StringBuilder();
byte[] result = new byte[1024];
while (!decompresser.finished()) {
int resultLength = decompresser.inflate(result);
sb.append(new String(result, 0, resultLength, "UTF-8"));
}
decompresser.end();
return sb.toString();
}
/**
* java.util.zip.Inflater#needsInput()
*/
public void test_needsInput() {
// test method of java.util.zip.inflater.needsInput()
Inflater inflate = new Inflater();
assertTrue(
"needsInput give the wrong boolean value as a result of no input buffer",
inflate.needsInput());
byte byteArray[] = { 2, 3, 4, 't', 'y', 'u', 'e', 'w', 7, 6, 5, 9 };
inflate.setInput(byteArray);
assertFalse(
"methodNeedsInput returned true when the input buffer is full",
inflate.needsInput());
inflate.reset();
byte byteArrayEmpty[] = new byte[0];
inflate.setInput(byteArrayEmpty);
assertTrue(
"needsInput give wrong boolean value as a result of an empty input buffer",
inflate.needsInput());
inflate.end();
}
/**
* java.util.zip.Inflater#setInput(byte[], int, int)
*/
public void test_setInput$BII() {
// test method of java.util.zip.inflater.setInput(byte,int,int)
byte byteArray[] = { 2, 3, 4, 't', 'y', 'u', 'e', 'w', 7, 6, 5, 9 };
int offSet = 6;
int length = 6;
Inflater inflate = new Inflater();
inflate.setInput(byteArray, offSet, length);
assertEquals(
"setInputBII did not deliver the right number of bytes to the input buffer",
length, inflate.getRemaining());
// boundary check
inflate.reset();
int r = 0;
try {
inflate.setInput(byteArray, 100, 100);
} catch (ArrayIndexOutOfBoundsException e) {
r = 1;
}
inflate.end();
assertEquals("boundary check is not present for setInput", 1, r);
}
public void testInflateZero() throws Exception {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(
byteArrayOutputStream);
deflaterOutputStream.close();
byte[] input = byteArrayOutputStream.toByteArray();
Inflater inflater = new Inflater();
inflater.setInput(input);
byte[] buffer = new byte[0];
int numRead = 0;
while (!inflater.finished()) {
int inflatedChunkSize = inflater.inflate(buffer, numRead,
buffer.length - numRead);
numRead += inflatedChunkSize;
}
inflater.end();
}
@Test
public void verifyLogoutOneLogoutRequestNotAttempted() throws Exception {
final LogoutRequest logoutRequest = new DefaultLogoutRequest(TICKET_ID,
new SimpleWebApplicationServiceImpl(TEST_URL),
new URL(TEST_URL));
final Event event = getLogoutEvent(Arrays.asList(logoutRequest));
assertEquals(FrontChannelLogoutAction.REDIRECT_APP_EVENT, event.getId());
final List<LogoutRequest> list = WebUtils.getLogoutRequests(this.requestContext);
assertEquals(1, list.size());
final String url = (String) event.getAttributes().get(FrontChannelLogoutAction.DEFAULT_FLOW_ATTRIBUTE_LOGOUT_URL);
assertTrue(url.startsWith(TEST_URL + "?" + FrontChannelLogoutAction.DEFAULT_LOGOUT_PARAMETER + "="));
final byte[] samlMessage = CompressionUtils.decodeBase64ToByteArray(
URLDecoder.decode(StringUtils.substringAfter(url, "?" + FrontChannelLogoutAction.DEFAULT_LOGOUT_PARAMETER + "="), "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.contains("<samlp:SessionIndex>" + TICKET_ID + "</samlp:SessionIndex>"));
}
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;
}
}
public static Object deserialize(byte[] bytes) throws IOException {
if (bytes.length < 2) {
throw new IOException("Invalid bytes content");
}
InputStream in = new ByteArrayInputStream(bytes);
if (bytes[0] == 0) {
in.read(); // consume the marker;
if (in.read() != ZLIB_COMPRESSION) {
throw new IOException("Unknown compression type");
}
final Inflater inflater = new Inflater(true);
in = new InflaterInputStream(in, inflater) {
@Override public void close() throws IOException {
try {
super.close();
} finally {
inflater.end();
}
}
};
}
try (ObjectInputStream oin = new ObjectInputStream(in)) {
try {
return oin.readObject();
} catch (ClassNotFoundException e) {
throw new IOException("Exception while deserilaizing.", e);
}
}
}
/**
* Wrap response input stream if it is compressed, return input its self if not use compress
*/
private InputStream decompressBody() {
if (!decompress) {
return body;
}
// if has no body, some server still set content-encoding header,
// GZIPInputStream wrap empty input stream will cause exception. we should check this
if (method.equals(Methods.HEAD)
|| (statusCode >= 100 && statusCode < 200) || statusCode == NOT_MODIFIED || statusCode == NO_CONTENT) {
return body;
}
String contentEncoding = headers.getHeader(NAME_CONTENT_ENCODING);
if (contentEncoding == null) {
return body;
}
//we should remove the content-encoding header here?
switch (contentEncoding) {
case "gzip":
try {
return new GZIPInputStream(body);
} catch (IOException e) {
Closeables.closeQuietly(body);
throw new RequestsException(e);
}
case "deflate":
// Note: deflate implements may or may not wrap in zlib due to rfc confusing.
// here deal with deflate without zlib header
return new InflaterInputStream(body, new Inflater(true));
case "identity":
case "compress": //historic; deprecated in most applications and replaced by gzip or deflate
default:
return body;
}
}