Example usage for java.util.zip InflaterInputStream InflaterInputStream

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

Introduction

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

Prototype

public InflaterInputStream(InputStream in) 

Source Link

Document

Creates a new input stream with a default decompressor and buffer size.

Usage

From source file:org.bimserver.plugins.classloaders.JarClassLoader.java

@Override
protected URL findResource(final String name) {
    if (map.containsKey(name)) {
        try {//  w  w  w  .j a  v  a2s.  co m
            return new URL(new URL("jar:" + jarFile.toURI().toURL() + "!/" + name), name,
                    new URLStreamHandler() {
                        @Override
                        protected URLConnection openConnection(URL u) throws IOException {
                            return new URLConnection(u) {
                                @Override
                                public void connect() throws IOException {
                                }

                                @Override
                                public InputStream getInputStream() throws IOException {
                                    return new InflaterInputStream(new ByteArrayInputStream(map.get(name)));
                                }
                            };
                        }
                    });
        } catch (MalformedURLException e) {
            LOGGER.error("", e);
        }
    }
    return null;
}

From source file:auth.ProcessResponseServlet.java

private String decodeAuthnRequestXML(String encodedRequestXmlString) throws SamlException {
    try {//from   w  w  w .j  a va 2 s.  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.bimserver.plugins.classloaders.MemoryJarClassLoader.java

@Override
public URL findResource(final String name) {
    if (map.containsKey(name)) {
        try {/*  w  w w .  java 2  s.  c o m*/
            return new URL(new URL("jar:" + jarFile.toURI().toURL() + "!/" + name), name,
                    new URLStreamHandler() {
                        @Override
                        protected URLConnection openConnection(URL u) throws IOException {
                            return new URLConnection(u) {
                                @Override
                                public void connect() throws IOException {
                                }

                                @Override
                                public InputStream getInputStream() throws IOException {
                                    return new InflaterInputStream(new ByteArrayInputStream(map.get(name)));
                                }
                            };
                        }
                    });
        } catch (MalformedURLException e) {
            LOGGER.error("", e);
        }
    }
    return null;
}

From source file:org.jasig.cas.util.CompressionUtils.java

/**
 * Decode the byte[] in base64 to a string.
 *
 * @param bytes the data to encode/*from  w  w  w .j  a v  a 2  s  . c  o  m*/
 * @return the new string in {@link #UTF8_ENCODING}.
 */
public static String decodeByteArrayToString(final byte[] bytes) {
    final ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final byte[] buf = new byte[bytes.length];
    try (final InflaterInputStream iis = new InflaterInputStream(bais)) {
        int count = iis.read(buf);
        while (count != -1) {
            baos.write(buf, 0, count);
            count = iis.read(buf);
        }
        return new String(baos.toByteArray(), Charset.forName(UTF8_ENCODING));
    } catch (final Exception e) {
        LOGGER.error("Base64 decoding failed", e);
        return null;
    }
}

From source file:com.evilisn.DAO.CertMapper.java

public static byte[] httpGetBin(URI uri, boolean bActiveCheckUnknownHost) throws Exception

{

    InputStream is = null;//from   w w w . j a  va 2s  . c o m

    InputStream is_temp = null;

    try {

        if (uri == null)
            return null;

        URL url = uri.toURL();

        if (bActiveCheckUnknownHost) {

            url.getProtocol();

            String host = url.getHost();

            int port = url.getPort();

            if (port == -1)

                port = url.getDefaultPort();

            InetSocketAddress isa = new InetSocketAddress(host, port);

            if (isa.isUnresolved()) {

                //fix JNLP popup error issue

                throw new UnknownHostException("Host Unknown:" + isa.toString());

            }

        }

        HttpURLConnection uc = (HttpURLConnection) url.openConnection();

        uc.setDoInput(true);

        uc.setAllowUserInteraction(false);

        uc.setInstanceFollowRedirects(true);

        setTimeout(uc);

        String contentEncoding = uc.getContentEncoding();

        int len = uc.getContentLength();

        // is = uc.getInputStream();

        if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("gzip") != -1)

        {

            is_temp = uc.getInputStream();

            is = new GZIPInputStream(is_temp);

        }

        else if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("deflate") != -1)

        {

            is_temp = uc.getInputStream();

            is = new InflaterInputStream(is_temp);

        }

        else

        {

            is = uc.getInputStream();

        }

        if (len != -1) {

            int ch = 0, i = 0;

            byte[] res = new byte[len];

            while ((ch = is.read()) != -1) {

                res[i++] = (byte) (ch & 0xff);

            }

            return res;

        } else {

            ArrayList<byte[]> buffer = new ArrayList<byte[]>();

            int buf_len = 1024;

            byte[] res = new byte[buf_len];

            int ch = 0, i = 0;

            while ((ch = is.read()) != -1) {

                res[i++] = (byte) (ch & 0xff);

                if (i == buf_len) {

                    //rotate

                    buffer.add(res);

                    i = 0;

                    res = new byte[buf_len];

                }

            }

            int total_len = buffer.size() * buf_len + i;

            byte[] buf = new byte[total_len];

            for (int j = 0; j < buffer.size(); j++) {

                System.arraycopy(buffer.get(j), 0, buf, j * buf_len, buf_len);

            }

            if (i > 0) {

                System.arraycopy(res, 0, buf, buffer.size() * buf_len, i);

            }

            return buf;

        }

    } catch (Exception e) {

        e.printStackTrace();

        return null;

    } finally {

        closeInputStream(is_temp);

        closeInputStream(is);

    }

}

From source file:org.ozsoft.xantippe.Document.java

/**
 * Returns the document's content.//  ww w  .  ja v a  2s  .  c o m
 * 
 * @return  an InputStream to read the content from
 * 
 * @throws  XmldbException  if the contents could not be retrieved
 */
public InputStream getContent() throws XmldbException {
    FileStore fileStore = database.getFileStore();

    database.getLockManager().lockRead(this);

    InputStream is = null;
    try {
        is = fileStore.retrieve(id);
        if (compressionMode == CompressionMode.DEFLATE) {
            is = new InflaterInputStream(is);
        }
    } catch (FileStoreException e) {
        String msg = String.format("Could not retrieve document '%s': %s", this, e.getMessage());
        LOG.error(msg, e);
        throw new XmldbException(msg, e);
    } finally {
        database.getLockManager().unlockRead(this);
    }

    return is;
}

From source file:org.bimserver.plugins.classloaders.JarClassLoader.java

@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
    String fileName = name.replace(".", "/") + ".class";
    if (loadedClasses.containsKey(fileName)) {
        return loadedClasses.get(fileName);
    }/* w w  w.j av  a2 s.c o  m*/
    if (map.containsKey(fileName)) {
        byte[] bs = map.get(fileName);
        InflaterInputStream inflaterInputStream = new InflaterInputStream(new ByteArrayInputStream(bs));
        ByteArrayOutputStream uncompressed = new ByteArrayOutputStream();
        try {
            IOUtils.copy(inflaterInputStream, uncompressed);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] byteArray = uncompressed.toByteArray();
        Class<?> defineClass = defineClass(name, byteArray, 0, byteArray.length);
        loadedClasses.put(fileName, defineClass);

        /*
         * This is a fix to actually load the package-info.class file with
         * the annotations about for example namespaces required for JAXB to
         * work. Found this code here:
         * https://issues.jboss.org/browse/JBPM-1404
         */
        if (defineClass != null) {
            final int packageIndex = name.lastIndexOf('.');
            if (packageIndex != -1) {
                final String packageName = name.substring(0, packageIndex);
                final Package classPackage = getPackage(packageName);
                if (classPackage == null) {
                    definePackage(packageName, null, null, null, null, null, null, null);
                }
            }
        }

        // The original class file cannot be loaded for other purposes after this (would be strange), this saves memory
        map.remove(fileName);

        return defineClass;
    }
    throw new ClassNotFoundException(name);
}

From source file:org.droidparts.http.worker.HttpClientWorker.java

private static InputStream getUnpackedInputStream(HttpEntity entity) throws HTTPException {
    try {// w  ww . ja v  a  2s  .c o m
        InputStream is = entity.getContent();
        Header contentEncodingHeader = entity.getContentEncoding();
        if (contentEncodingHeader != null) {
            String contentEncoding = contentEncodingHeader.getValue();
            L.d("Content-Encoding: " + contentEncoding);
            if (isNotEmpty(contentEncoding)) {
                contentEncoding = contentEncoding.toLowerCase();
                if (contentEncoding.contains("gzip")) {
                    return new GZIPInputStream(is);
                } else if (contentEncoding.contains("deflate")) {
                    return new InflaterInputStream(is);
                }
            }
        }
        return is;
    } catch (Exception e) {
        throw new HTTPException(e);
    }
}

From source file:org.bimserver.plugins.classloaders.MemoryJarClassLoader.java

@Override
public Class<?> findClass(String name) throws ClassNotFoundException {
    String fileName = name.replace(".", "/") + ".class";
    if (loadedClasses.containsKey(fileName)) {
        return loadedClasses.get(fileName);
    }/*from ww  w  .ja  v  a 2 s  .c o m*/
    if (map.containsKey(fileName)) {
        byte[] bs = map.get(fileName);
        InflaterInputStream inflaterInputStream = new InflaterInputStream(new ByteArrayInputStream(bs));
        ByteArrayOutputStream uncompressed = new ByteArrayOutputStream();
        try {
            IOUtils.copy(inflaterInputStream, uncompressed);
        } catch (IOException e) {
            LOGGER.error("", e);
        }
        byte[] byteArray = uncompressed.toByteArray();
        Class<?> defineClass = defineClass(name, byteArray, 0, byteArray.length);
        loadedClasses.put(fileName, defineClass);

        /*
         * This is a fix to actually load the package-info.class file with
         * the annotations about for example namespaces required for JAXB to
         * work. Found this code here:
         * https://issues.jboss.org/browse/JBPM-1404
         */
        if (defineClass != null) {
            final int packageIndex = name.lastIndexOf('.');
            if (packageIndex != -1) {
                final String packageName = name.substring(0, packageIndex);
                final Package classPackage = getPackage(packageName);
                if (classPackage == null) {
                    definePackage(packageName, null, null, null, null, null, null, null);
                }
            }
        }

        // The original class file cannot be loaded for other purposes after this (would be strange), this saves memory
        map.remove(fileName);

        return defineClass;
    }
    throw new ClassNotFoundException(name);
}

From source file:z.hol.net.http.entity.DeflateDecompressingEntity.java

/**
 * Returns the non-null InputStream that should be returned to by all requests to
 * {@link #getContent()}.//from  www  .  j a  v  a2  s  .c o  m
 *
 * @return a non-null InputStream
 * @throws IOException if there was a problem
 */
@Override
InputStream getDecompressingInputStream(final InputStream wrapped) throws IOException {
    /*
     * A zlib stream will have a header.
     *
     * CMF | FLG [| DICTID ] | ...compressed data | ADLER32 |
     *
     * * CMF is one byte.
     *
     * * FLG is one byte.
     *
     * * DICTID is four bytes, and only present if FLG.FDICT is set.
     *
     * Sniff the content. Does it look like a zlib stream, with a CMF, etc? c.f. RFC1950,
     * section 2.2. http://tools.ietf.org/html/rfc1950#page-4
     *
     * We need to see if it looks like a proper zlib stream, or whether it is just a deflate
     * stream. RFC2616 calls zlib streams deflate. Confusing, isn't it? That's why some servers
     * implement deflate Content-Encoding using deflate streams, rather than zlib streams.
     *
     * We could start looking at the bytes, but to be honest, someone else has already read
     * the RFCs and implemented that for us. So we'll just use the JDK libraries and exception
     * handling to do this. If that proves slow, then we could potentially change this to check
     * the first byte - does it look like a CMF? What about the second byte - does it look like
     * a FLG, etc.
     */

    /* We read a small buffer to sniff the content. */
    byte[] peeked = new byte[6];

    PushbackInputStream pushback = new PushbackInputStream(wrapped, peeked.length);

    int headerLength = pushback.read(peeked);

    if (headerLength == -1) {
        throw new IOException("Unable to read the response");
    }

    /* We try to read the first uncompressed byte. */
    byte[] dummy = new byte[1];

    Inflater inf = new Inflater();

    try {
        int n;
        while ((n = inf.inflate(dummy)) == 0) {
            if (inf.finished()) {

                /* Not expecting this, so fail loudly. */
                throw new IOException("Unable to read the response");
            }

            if (inf.needsDictionary()) {

                /* Need dictionary - then it must be zlib stream with DICTID part? */
                break;
            }

            if (inf.needsInput()) {
                inf.setInput(peeked);
            }
        }

        if (n == -1) {
            throw new IOException("Unable to read the response");
        }

        /*
         * We read something without a problem, so it's a valid zlib stream. Just need to reset
         * and return an unused InputStream now.
         */
        pushback.unread(peeked, 0, headerLength);
        return new InflaterInputStream(pushback);
    } catch (DataFormatException e) {

        /* Presume that it's an RFC1951 deflate stream rather than RFC1950 zlib stream and try
         * again. */
        pushback.unread(peeked, 0, headerLength);
        return new InflaterInputStream(pushback, new Inflater(true));
    }
}