Example usage for java.util.zip Inflater Inflater

List of usage examples for java.util.zip Inflater Inflater

Introduction

In this page you can find the example usage for java.util.zip Inflater Inflater.

Prototype

public Inflater(boolean nowrap) 

Source Link

Document

Creates a new decompressor.

Usage

From source file:auth.ProcessResponseServlet.java

private String decodeAuthnRequestXML(String encodedRequestXmlString) throws SamlException {
    try {//w  w w .ja v  a 2s.c o  m
        // URL decode
        // No need to URL decode: auto decoded by request.getParameter() method

        // Base64 decode
        Base64 base64Decoder = new Base64();
        byte[] xmlBytes = encodedRequestXmlString.getBytes("UTF-8");
        byte[] base64DecodedByteArray = base64Decoder.decode(xmlBytes);

        //Uncompress the AuthnRequest data
        //First attempt to unzip the byte array according to DEFLATE (rfc 1951)
        try {

            Inflater inflater = new Inflater(true);
            inflater.setInput(base64DecodedByteArray);
            // since we are decompressing, it's impossible to know how much space we
            // might need; hopefully this number is suitably big
            byte[] xmlMessageBytes = new byte[5000];
            int resultLength = inflater.inflate(xmlMessageBytes);

            if (!inflater.finished()) {
                throw new RuntimeException("didn't allocate enough space to hold " + "decompressed data");
            }

            inflater.end();
            return new String(xmlMessageBytes, 0, resultLength, "UTF-8");

        } catch (DataFormatException e) {

            // if DEFLATE fails, then attempt to unzip the byte array according to
            // zlib (rfc 1950)
            ByteArrayInputStream bais = new ByteArrayInputStream(base64DecodedByteArray);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            InflaterInputStream iis = new InflaterInputStream(bais);
            byte[] buf = new byte[1024];
            int count = iis.read(buf);
            while (count != -1) {
                baos.write(buf, 0, count);
                count = iis.read(buf);
            }
            iis.close();
            return new String(baos.toByteArray());
        }

    } catch (UnsupportedEncodingException e) {
        throw new SamlException("Error decoding AuthnRequest: " + "Check decoding scheme - " + e.getMessage());
    } catch (IOException e) {
        throw new SamlException("Error decoding AuthnRequest: " + "Check decoding scheme - " + e.getMessage());
    }
}

From source file:org.resthub.rpc.AMQPHessianProxy.java

/**
 * Handles the object invocation.//from  ww w. j a  va 2s .  c  o  m
 *
 * @param proxy  the proxy object to invoke
 * @param method the method to call
 * @param args   the arguments to the proxy object
 */
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String methodName = method.getName();
    Class<?>[] params = method.getParameterTypes();

    // equals and hashCode are special cased
    if (methodName.equals("equals") && params.length == 1 && params[0].equals(Object.class)) {
        Object value = args[0];
        if (value == null || !Proxy.isProxyClass(value.getClass())) {
            return Boolean.FALSE;
        }

        AMQPHessianProxy handler = (AMQPHessianProxy) Proxy.getInvocationHandler(value);

        return _factory.equals(handler._factory);
    } else if (methodName.equals("hashCode") && params.length == 0) {
        return _factory.hashCode();
    } else if (methodName.equals("toString") && params.length == 0) {
        return "[HessianProxy " + proxy.getClass() + "]";
    }

    ConnectionFactory connectionFactory = _factory.getConnectionFactory();

    try {
        Message response = sendRequest(connectionFactory, method, args);

        if (response == null) {
            throw new TimeoutException();
        }

        MessageProperties props = response.getMessageProperties();
        boolean compressed = "deflate".equals(props.getContentEncoding());

        AbstractHessianInput in;

        InputStream is = new ByteArrayInputStream(response.getBody());
        if (compressed) {
            is = new InflaterInputStream(is, new Inflater(true));
        }

        int code = is.read();

        if (code == 'H') {
            int major = is.read();
            int minor = is.read();

            in = _factory.getHessian2Input(is);

            return in.readReply(method.getReturnType());
        } else if (code == 'r') {
            int major = is.read();
            int minor = is.read();

            in = _factory.getHessianInput(is);

            in.startReplyBody();

            Object value = in.readObject(method.getReturnType());

            in.completeReply();

            return value;
        } else {
            throw new HessianProtocolException("'" + (char) code + "' is an unknown code");
        }
    } catch (HessianProtocolException e) {
        throw new HessianRuntimeException(e);
    }
}

From source file:com.gargoylesoftware.htmlunit.WebResponseData.java

private InputStream getStream(final DownloadedContent downloadedContent, final List<NameValuePair> headers)
        throws IOException {

    InputStream stream = downloadedContent_.getInputStream();
    if (stream == null) {
        return null;
    }//from   w  ww.  j  ava2  s  .c o  m

    if (downloadedContent.isEmpty()) {
        return stream;
    }

    final String encoding = getHeader(headers, "content-encoding");
    if (encoding != null) {
        if (StringUtils.contains(encoding, "gzip")) {
            stream = new GZIPInputStream(stream);
        } else if (StringUtils.contains(encoding, "deflate")) {
            boolean zlibHeader = false;
            if (stream.markSupported()) { // should be always the case as the content is in a byte[] or in a file
                stream.mark(2);
                final byte[] buffer = new byte[2];
                stream.read(buffer, 0, 2);
                zlibHeader = (((buffer[0] & 0xff) << 8) | (buffer[1] & 0xff)) == 0x789c;
                stream.reset();
            }
            if (zlibHeader) {
                stream = new InflaterInputStream(stream);
            } else {
                stream = new InflaterInputStream(stream, new Inflater(true));
            }
        }
    }
    return stream;
}

From source file:ZipUtil.java

public static void unzipFileToFile(File flSource, File flTarget) throws IOException {
    Inflater oInflate = new Inflater(false);
    FileInputStream stmFileIn = new FileInputStream(flSource);
    FileOutputStream stmFileOut = new FileOutputStream(flTarget);
    InflaterInputStream stmInflateIn = new InflaterInputStream(stmFileIn, oInflate);

    try {/*w w w . j a  v a2 s .  com*/
        inflaterInputStmToFileOutputStm(stmInflateIn, stmFileOut);
    } //end try
    finally {
        stmFileOut.flush();
        stmFileOut.close();
        stmInflateIn.close();
        stmFileIn.close();
    }
}

From source file:com.alibaba.citrus.service.requestcontext.session.encoder.AbstractSerializationEncoder.java

/** ? */
public Map<String, Object> decode(String encodedValue, StoreContext storeContext)
        throws SessionEncoderException {
    // 1. base64?
    byte[] cryptotext = null;

    try {//from  w  w  w .j  a v a 2 s  .com
        encodedValue = URLDecoder.decode(assertNotNull(encodedValue, "encodedValue is null"), "ISO-8859-1");
        cryptotext = Base64.decodeBase64(encodedValue.getBytes("ISO-8859-1"));

        if (isEmptyArray(cryptotext)) {
            throw new SessionEncoderException("Session state is empty: " + encodedValue);
        }
    } catch (Exception e) {
        throw new SessionEncoderException("Failed to decode session state: ", e);
    }

    // 2. 
    byte[] plaintext = decrypt(cryptotext);

    if (isEmptyArray(plaintext)) {
        throw new SessionEncoderException("Decrypted session state is empty: " + encodedValue);
    }

    // 3. 
    ByteArrayInputStream bais = new ByteArrayInputStream(plaintext);
    Inflater inf = new Inflater(false);
    InflaterInputStream iis = new InflaterInputStream(bais, inf);

    // 4. ???
    try {
        @SuppressWarnings("unchecked")
        Map<String, Object> attrs = (Map<String, Object>) serializer.deserialize(iis);
        return attrs;
    } catch (Exception e) {
        throw new SessionEncoderException("Failed to parse session state", e);
    } finally {
        try {
            iis.close();
        } catch (IOException e) {
        }

        inf.end();
    }
}

From source file:name.npetrovski.jphar.DataEntry.java

private InputStream getCompressorInputStream(final InputStream is, Compression.Type compression)
        throws IOException {
    switch (compression) {
    case ZLIB:/*from   w  ww .  j a  va2  s .c  o  m*/
        return new InflaterInputStream(is, new Inflater(true));
    case BZIP:
        return new BZip2CompressorInputStream(is, true);
    case NONE:
        return is;
    default:
        throw new IOException("Unsupported compression type.");
    }

}

From source file:org.codice.ddf.security.common.jaxrs.RestSecurityTest.java

@Test
public void testInflateDeflateWithTokenDuplication() throws Exception {
    String token = "valid_grant valid_grant valid_grant valid_grant valid_grant valid_grant";

    DeflateEncoderDecoder deflateEncoderDecoder = new DeflateEncoderDecoder();
    byte[] deflatedToken = deflateEncoderDecoder.deflateToken(token.getBytes());

    String cxfInflatedToken = IOUtils.toString(deflateEncoderDecoder.inflateToken(deflatedToken));

    String streamInflatedToken = IOUtils
            .toString(new InflaterInputStream(new ByteArrayInputStream(deflatedToken), new Inflater(true)));

    assertNotSame(cxfInflatedToken, token);
    assertEquals(streamInflatedToken, token);
}

From source file:org.commoncrawl.hadoop.io.deprecated.ArcFileReader.java

/**
 * Costructs a new ArcFileReader object with specified block size (for
 * allocations)/*ww w . jav a2s  . co m*/
 */
public ArcFileReader() {

    super(_dummyStream, new Inflater(true), _blockSize);
    // set up buffer queue ...
    _consumerQueue = new LinkedBlockingQueue<BufferItem>(_bufferQueueSize);
    // setup the proper stream...
    super.in = new PushbackInputStream(new InputStream() {

        ByteBuffer _activeBuffer = null;
        byte oneByteArray[] = new byte[1];

        @Override
        public int read() throws IOException {
            if (read(oneByteArray, 0, 1) != -1) {
                return oneByteArray[0] & 0xff;
            }
            return -1;
        }

        @Override
        public int read(byte b[], int off, int len) throws IOException {
            if (_activeBuffer == null || _activeBuffer.remaining() == 0) {
                BufferItem nextItem = null;
                try {
                    // when io timeout is not specified, block indefinitely...
                    if (_ioTimeoutValue == -1) {
                        nextItem = _consumerQueue.take();
                    }
                    // otherwise wait for specified time on io
                    else {
                        nextItem = _consumerQueue.poll(_ioTimeoutValue, TimeUnit.MILLISECONDS);

                        if (nextItem == null) {
                            throw new IOException("IO Timeout waiting for Buffer");
                        }
                    }

                } catch (InterruptedException e) {
                    throw new IOException("Thread Interrupted waiting for Buffer");
                }

                if (nextItem._buffer == null) {
                    _eosReached = true;
                    // EOF CONDITION ...
                    return -1;
                } else {
                    _activeBuffer = nextItem._buffer;
                }
            }
            final int sizeAvailable = _activeBuffer.remaining();
            final int readSize = Math.min(sizeAvailable, len);

            _activeBuffer.get(b, off, readSize);

            _streamPos += readSize;

            return readSize;
        }
    }, _blockSize);
}

From source file:org.pac4j.saml.client.RedirectSaml2ClientIT.java

private String getInflatedAuthnRequest(String location) throws Exception {
    List<NameValuePair> pairs = URLEncodedUtils.parse(URI.create(location), "UTF-8");
    Inflater inflater = new Inflater(true);
    byte[] decodedRequest = Base64.decodeBase64(pairs.get(0).getValue());
    ByteArrayInputStream is = new ByteArrayInputStream(decodedRequest);
    InflaterInputStream inputStream = new InflaterInputStream(is, inflater);
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    return reader.readLine();
}

From source file:de.hofuniversity.iisys.neo4j.websock.query.encoding.safe.TSafeDeflateJsonQueryHandler.java

@Override
public WebsockQuery decode(ByteBuffer buff) throws DecodeException {
    WebsockQuery query = null;// ww w  .  j ava 2  s  .c  o m

    try {
        //decompress
        final byte[] incoming = buff.array();
        final Inflater inflater = new Inflater(true);
        inflater.setInput(incoming);

        int read = 0;
        int totalSize = 0;
        final List<byte[]> buffers = new LinkedList<byte[]>();

        final byte[] buffer = new byte[BUFFER_SIZE];
        read = inflater.inflate(buffer);
        while (read > 0) {
            totalSize += read;
            buffers.add(Arrays.copyOf(buffer, read));
            read = inflater.inflate(buffer);
        }

        final byte[] data = fuse(buffers, totalSize).array();
        final JSONObject obj = new JSONObject(new String(data));

        if (fDebug) {
            fTotalBytesIn += incoming.length;
            fLogger.log(Level.FINEST, "received compressed JSON message: " + incoming.length + " bytes\n"
                    + "total bytes received: " + fTotalBytesIn);
        }

        query = JsonConverter.fromJson(obj);
    } catch (Exception e) {
        e.printStackTrace();
        throw new DecodeException(buff, "failed to decode JSON", e);
    }

    return query;
}