Example usage for java.util.zip InflaterInputStream read

List of usage examples for java.util.zip InflaterInputStream read

Introduction

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

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this input stream into an array of bytes.

Usage

From source file:PNGDecoder.java

public byte[] getImageData() {
    try {/*from   w w w. j  a v a2s.co m*/
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // Write all the IDAT data into the array.
        for (int i = 0; i < mNumberOfChunks; i++) {
            PNGChunk chunk = mChunks[i];
            if (chunk.getTypeString().equals("IDAT")) {
                out.write(chunk.getData());
            }
        }
        out.flush();
        // Now deflate the data.
        InflaterInputStream in = new InflaterInputStream(new ByteArrayInputStream(out.toByteArray()));
        ByteArrayOutputStream inflatedOut = new ByteArrayOutputStream();
        int readLength;
        byte[] block = new byte[8192];
        while ((readLength = in.read(block)) != -1)
            inflatedOut.write(block, 0, readLength);
        inflatedOut.flush();
        byte[] imageData = inflatedOut.toByteArray();
        // Compute the real length.
        int width = (int) getWidth();
        int height = (int) getHeight();
        int bitsPerPixel = getBitsPerPixel();
        int length = width * height * bitsPerPixel / 8;

        byte[] prunedData = new byte[length];

        // We can only deal with non-interlaced images.
        if (getInterlace() == 0) {
            int index = 0;
            for (int i = 0; i < length; i++) {
                if ((i * 8 / bitsPerPixel) % width == 0) {
                    index++; // Skip the filter byte.
                }
                prunedData[i] = imageData[index++];
            }
        } else
            System.out.println("Couldn't undo interlacing.");

        return prunedData;
    } catch (IOException ioe) {
    }
    return null;
}

From source file:auth.ProcessResponseServlet.java

private String decodeAuthnRequestXML(String encodedRequestXmlString) throws SamlException {
    try {//  w w w  .j  a  v a2s  .c om
        // 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:fabiogentile.powertutor.ui.UMLogger.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case MENU_PREFERENCES:
        startActivity(new Intent(this, EditPreferences.class));
        return true;
    case MENU_SAVE_LOG:
        new Thread() {
            public void start() {
                File writeFile = new File(Environment.getExternalStorageDirectory(),
                        "PowerTrace" + System.currentTimeMillis() + ".log");

                try {
                    InflaterInputStream logIn = new InflaterInputStream(openFileInput("PowerTrace.log"));
                    BufferedOutputStream logOut = new BufferedOutputStream(new FileOutputStream(writeFile));

                    byte[] buffer = new byte[20480];
                    for (int ln = logIn.read(buffer); ln != -1; ln = logIn.read(buffer)) {
                        logOut.write(buffer, 0, ln);
                    }//from   w  w  w  . ja  v  a  2  s .  c  om
                    logIn.close();
                    logOut.close();
                    Toast.makeText(UMLogger.this, "Wrote log to " + writeFile.getAbsolutePath(),
                            Toast.LENGTH_SHORT).show();
                    return;

                } catch (EOFException e) {
                    Toast.makeText(UMLogger.this, "Wrote log to " + writeFile.getAbsolutePath(),
                            Toast.LENGTH_SHORT).show();
                    return;
                } catch (IOException e) {
                    Log.e(TAG, "failed to save log: " + e.getMessage());
                }
                Toast.makeText(UMLogger.this, "Failed to write log to sdcard", Toast.LENGTH_SHORT).show();
            }
        }.start();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

From source file:org.fastcatsearch.ir.document.DocumentWriter.java

public Document readDocument(int docNo) throws IOException, IRException {
    long prevPosPos = positionOutput.position();
    long docPos = -1;
    try {/*from w  ww  .  j a v  a  2  s .  c  om*/
        long positionOffset = ((long) docNo) * IOUtil.SIZE_OF_LONG;
        positionOutput.seek(positionOffset);
        docPos = IOUtil.readLong(positionOutput.getRaf());
    } finally {
        positionOutput.seek(prevPosPos);
    }

    // find a document block
    long prevDocPos = docOutput.position();
    try {
        docOutput.seek(docPos);
        RandomAccessFile raf = docOutput.getRaf();
        int len = IOUtil.readInt(raf);
        long n = raf.getFilePointer();
        InputStream docInput = Channels.newInputStream(docOutput.getRaf().getChannel().position(n));
        //2014-11-26 ?  working ?   ? ? GC ?? OOM ? ?.
        // Stream  .
        InflaterInputStream decompressInputStream = null;
        inflaterOutput.reset();
        int count = -1;
        try {
            BoundedInputStream boundedInputStream = new BoundedInputStream(docInput, len);
            boundedInputStream.setPropagateClose(false);// docInput  .
            decompressInputStream = new InflaterInputStream(boundedInputStream, new Inflater(), 512);
            while ((count = decompressInputStream.read(workingBuffer)) != -1) {
                inflaterOutput.write(workingBuffer, 0, count);
            }
        } finally {
            decompressInputStream.close();
        }
    } finally {
        docOutput.seek(prevDocPos);
    }

    BytesRef bytesRef = inflaterOutput.getBytesRef();
    DataInput bai = new BytesDataInput(bytesRef.bytes, 0, bytesRef.length);

    Document document = new Document(fields.size());
    for (int i = 0; i < fields.size(); i++) {
        FieldSetting fs = fields.get(i);
        Field f = null;
        boolean hasValue = bai.readBoolean();
        if (hasValue) {
            f = fs.createEmptyField();
            f.readRawFrom(bai);
        } else {
            f = fs.createEmptyField();
        }
        if (f != null) {
            String multiValueDelimiter = fs.getMultiValueDelimiter();
            try {
                f.parseIndexable(multiValueDelimiter);
            } catch (FieldDataParseException e) {
                throw new IOException(e);
            }
        }
        document.add(f);
    }
    document.setDocId(docNo);
    return document;
}

From source file:org.fastcatsearch.ir.document.DocumentReader.java

public Document readDocument(int docNo, boolean[] fieldSelectOption, boolean indexable) throws IOException {
    // if(docNo < baseDocNo) throw new
    // IOException("Request docNo cannot less than baseDocNo! docNo = "+docNo+", baseDocNo = "+baseDocNo);

    // baseDocNo?    .
    // docNo -= baseDocNo;

    DataInput bai = null;//from  w  ww.j  a v  a2  s.  c  o m

    if (docNo != lastDocNo) {
        long positionOffset = docNo * IOUtil.SIZE_OF_LONG;
        if (positionOffset >= positionLimit) {
            //.
            return null;
        }
        positionInput.seek(positionOffset);
        long pos = positionInput.readLong();
        // find a document block
        docInput.seek(pos);
        int len = docInput.readInt();

        //2014-11-26 ?  working ?   ? ? GC ?? OOM ? ?.
        // Stream  .
        InflaterInputStream decompressInputStream = null;
        inflaterOutput.reset();
        int count = -1;
        try {
            BoundedInputStream boundedInputStream = new BoundedInputStream(docInput, len);
            boundedInputStream.setPropagateClose(false);// docInput  .
            decompressInputStream = new InflaterInputStream(boundedInputStream, new Inflater(), 512);
            while ((count = decompressInputStream.read(workingBuffer)) != -1) {
                inflaterOutput.write(workingBuffer, 0, count);
            }
        } finally {
            decompressInputStream.close();
        }

        BytesRef bytesRef = inflaterOutput.getBytesRef();
        bai = new BytesDataInput(bytesRef.bytes, 0, bytesRef.length);

        lastDocNo = docNo;
        lastBai = bai;
    } else {
        lastBai.reset();
        bai = lastBai;
    }

    Document document = new Document(fields.size());
    for (int i = 0; i < fields.size(); i++) {
        FieldSetting fs = fields.get(i);
        Field f = null;
        boolean hasValue = bai.readBoolean();
        //         logger.debug("read hasValue={}, select={}, fs={} ", hasValue, fieldSelectOption, fs);
        if (hasValue) {
            //1. fieldSelectOption ?  ? ??.
            //2. ? , true? ? ?.
            if (fieldSelectOption == null || (fieldSelectOption != null && fieldSelectOption[i])) {
                f = fs.createEmptyField();
                f.readRawFrom(bai);
            } else {
                bai.skipVIntData();
            }
            //            logger.debug("fill {} >> {}", i, f);
        } else {
            //?  ?   .
            f = fs.createEmptyField();
            //            logger.debug("fill {} >> empty", i);
        }
        if (f != null && indexable) {
            String multiValueDelimiter = fs.getMultiValueDelimiter();
            try {
                f.parseIndexable(multiValueDelimiter);
            } catch (FieldDataParseException e) {
                throw new IOException(e);
            }
        }
        document.set(i, f);
    }

    document.setDocId(docNo + baseDocNo);

    return document;
}

From source file:com.tremolosecurity.idp.providers.Saml2Idp.java

private String inflate(String saml) throws Exception {
    byte[] compressedData = Base64.decodeBase64(saml);
    ByteArrayInputStream bin = new ByteArrayInputStream(compressedData);

    InflaterInputStream decompressor = new InflaterInputStream(bin, new Inflater(true));
    //decompressor.setInput(compressedData);

    // Create an expandable byte array to hold the decompressed data
    ByteArrayOutputStream bos = new ByteArrayOutputStream(compressedData.length);

    // Decompress the data
    byte[] buf = new byte[1024];
    int len;//from w  w w  .ja  va 2 s.  c o  m
    while ((len = decompressor.read(buf)) > 0) {

        bos.write(buf, 0, len);

    }
    try {
        bos.close();
    } catch (IOException e) {
    }

    // Get the decompressed data
    byte[] decompressedData = bos.toByteArray();

    String decoded = new String(decompressedData);

    return decoded;
}

From source file:com.tremolosecurity.idp.providers.OpenIDConnectIdP.java

private String inflate(String saml) throws Exception {
    byte[] compressedData = org.bouncycastle.util.encoders.Base64.decode(saml);
    ByteArrayInputStream bin = new ByteArrayInputStream(compressedData);

    InflaterInputStream decompressor = new InflaterInputStream(bin, new Inflater(true));
    //decompressor.setInput(compressedData);

    // Create an expandable byte array to hold the decompressed data
    ByteArrayOutputStream bos = new ByteArrayOutputStream(compressedData.length);

    // Decompress the data
    byte[] buf = new byte[1024];
    int len;/*ww  w  . j  a v a 2 s  .  c om*/
    while ((len = decompressor.read(buf)) > 0) {

        bos.write(buf, 0, len);

    }
    try {
        bos.close();
    } catch (IOException e) {
    }

    // Get the decompressed data
    byte[] decompressedData = bos.toByteArray();

    String decoded = new String(decompressedData);

    return decoded;
}

From source file:com.qut.middleware.esoe.sso.plugins.redirect.handler.impl.RedirectLogicImpl.java

private AuthnRequest getRedirectRequest(SSOProcessorData data, RedirectBindingData bindingData)
        throws RedirectBindingException {
    InflaterInputStream inflaterStream = null;
    ByteArrayOutputStream inflatedByteStream = null;
    byte[] chunk = new byte[TMP_BUFFER_SIZE];

    boolean signed = (bindingData.getSignature() != null && bindingData.getSignature().length() > 0);

    SSOProcessor ssoProcessor = data.getSSOProcessor();
    String remoteAddress = data.getRemoteAddress();

    try {/* w ww . j av  a 2s.c  o  m*/
        if (bindingData.getSAMLRequestString() == null || bindingData.getSAMLRequestString().length() <= 0) {
            ssoProcessor.createStatusAuthnResponse(data, StatusCodeConstants.requester, null,
                    "No AuthnRequest document was supplied to the Redirect binding.", true);
            this.logger.error(
                    "[SSO for {}] Redirect binding failed: No AuthnRequest document was supplied in the request.",
                    remoteAddress);
            throw new RedirectBindingException(
                    "Redirect binding failed as no AuthnRequest document was supplied in the request.");
        }

        if (bindingData.getRequestEncoding() != null
                && !bindingData.getRequestEncoding().equals(BindingConstants.deflateEncoding)) {
            ssoProcessor.createStatusAuthnResponse(data, StatusCodeConstants.requester, null,
                    "The given SAML Request encoding is not supported in this implementation.", true);
            this.logger.error(
                    "[SSO for {}] Redirect binding failed: SAML Request encoding '{}' is not supported in the current implementation.",
                    new Object[] { remoteAddress, bindingData.getRequestEncoding() });
            throw new RedirectBindingException(
                    "Redirect binding failed as the given SAML Request encoding is not supported in the current implementation.");
        }

        if (bindingData.getSignature() != null) {
            ssoProcessor.createStatusAuthnResponse(data, StatusCodeConstants.requester, null,
                    "Signed Redirect binding documents are not supported in this implementation.", true);
            this.logger.error(
                    "[SSO for {}] Redirect binding failed: Signed Redirect binding documents are not supported in the current implementation.",
                    remoteAddress);
            throw new RedirectBindingException(
                    "Redirect binding failed as Signed Redirect binding documents are not supported in the current implementation.");
        }
    } catch (SSOException e) {
        this.logger.error("[SSO for {}] Redirect binding failed to generate an error response. Error was: {}",
                new Object[] { remoteAddress, e.getMessage() });
        throw new RedirectBindingException(
                "Redirect binding failed to generate an error reponse. Original error follows", e);
    }

    try {
        /*
         * Retrieves the AuthnRequest from the encoded and compressed String extracted from the request of SAML HTTP
         * Redirect. The AuthnRequest XML is retrieved in the following order: 1. Base64 decode, 2. Inflate
         */
        byte[] decodedBytes = Base64.decodeBase64(bindingData.getSAMLRequestString().getBytes());
        ByteArrayInputStream decodedByteStream = new ByteArrayInputStream(decodedBytes);
        inflaterStream = new InflaterInputStream(decodedByteStream, new Inflater(true));
        inflatedByteStream = new ByteArrayOutputStream();

        int writeCount = 0;
        int count = 0;
        // Inflate and dump in the output stream to build a byte array.
        while ((count = inflaterStream.read(chunk)) >= 0) {
            inflatedByteStream.write(chunk, 0, count);
            writeCount = writeCount + count;
        }

        byte[] samlRequestDocument = inflatedByteStream.toByteArray();

        AuthnRequest authnRequest = ssoProcessor.unmarshallRequest(samlRequestDocument, signed);
        this.logger.debug("[SSO for {}] AuthnRequest was unmarshalled successfully by the SSO Processor",
                remoteAddress);

        return authnRequest;
    } catch (IOException e) {
        this.logger.error(
                "[SSO for {}] IO exception occurred while inflating the request document. Error was: {}",
                new Object[] { remoteAddress, e.getMessage() });
        throw new RedirectBindingException("IO exception occurred while inflating the request document.");
    } catch (SignatureValueException e) {
        this.logger.error(
                "[SSO for {}] Signature value exception occurred while trying to unmarshal the redirect request. Error was: {}",
                new Object[] { remoteAddress, e.getMessage() });
        this.logger.debug(
                "[SSO for {}] Signature value exception occurred while trying to unmarshal the redirect request. Exception follows",
                remoteAddress, e);
        throw new RedirectBindingException(
                "Signature value exception occurred while trying to unmarshal the redirect request.");
    } catch (ReferenceValueException e) {
        this.logger.error(
                "[SSO for {}] Reference value exception occurred while unmarshalling the redirect request. Error was: {}",
                new Object[] { remoteAddress, e.getMessage() });
        this.logger.debug(
                "[SSO for {}] Reference value exception occurred while unmarshalling the redirect request. Exception follows",
                remoteAddress, e);
        throw new RedirectBindingException(
                "Reference value exception occurred while unmarshalling the redirect request.");
    } catch (UnmarshallerException e) {
        this.logger.error(
                "[SSO for {}] Unmarshaller exception occurred while unmarshalling the redirect request. Error was: {}",
                new Object[] { remoteAddress, e.getMessage() });
        this.logger.debug(
                "[SSO for {}] Unmarshaller exception occurred while unmarshalling the redirect request. Exception follows",
                remoteAddress, e);
        throw new RedirectBindingException(
                "Unmarshaller exception occurred while unmarshalling the redirect request.");
    } finally {
        try {
            if (inflatedByteStream != null) {
                inflatedByteStream.reset();
                inflatedByteStream.close();
            }

            if (inflaterStream != null)
                inflaterStream.close();
        } catch (IOException e) {
            this.logger.error("Unable to close stream correctly - " + e.getLocalizedMessage());
            this.logger.debug(e.getLocalizedMessage(), e);
        }
    }
}