Example usage for java.util.zip Inflater setInput

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

Introduction

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

Prototype

public void setInput(ByteBuffer input) 

Source Link

Document

Sets input data for decompression.

Usage

From source file:org.esupportail.publisher.security.CustomSingleSignOutHandler.java

/**
 * Uncompress a logout message (base64 + deflate).
 *
 * @param originalMessage the original logout message.
 * @return the uncompressed logout message.
 *///from   w  w  w.  java  2 s  . co m
private String uncompressLogoutMessage(final String originalMessage) {
    final byte[] binaryMessage = Base64.decodeBase64(originalMessage.getBytes());

    Inflater decompresser = null;
    try {
        // decompress the bytes
        decompresser = new Inflater();
        decompresser.setInput(binaryMessage);
        final byte[] result = new byte[binaryMessage.length * DECOMPRESSION_FACTOR];

        final int resultLength = decompresser.inflate(result);

        // decode the bytes into a String
        return new String(result, 0, resultLength, "UTF-8");
    } catch (final Exception e) {
        logger.error("Unable to decompress logout message", e);
        throw new RuntimeException(e);
    } finally {
        if (decompresser != null) {
            decompresser.end();
        }
    }
}

From source file:org.barcelonamedia.uima.reader.DBXMIReader.DBXMICollectionReader.java

public void getNext(CAS aCAS) throws IOException, CollectionException {

    try {/*from  w  w  w. j  av  a2 s.  c om*/

        if (this.do_decompression) {

            //Create the decompressor and give it the data to compress
            Inflater decompressor = new Inflater();
            byte[] documentDataByteArray = IOUtils.toByteArray(this.documentData);

            decompressor.setInput(documentDataByteArray);

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

            //Decompress the data
            byte[] buf = new byte[1024];

            while (!decompressor.finished()) {

                try {

                    int count = decompressor.inflate(buf);
                    bos.write(buf, 0, count);
                } catch (DataFormatException e) {

                    System.err.println("ERROR in Collection Reader " + e.getClass() + ": " + e.getMessage());
                    throw new IOException();
                }
            }

            try {

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

                System.err.println("ERROR in Collection Reader " + e.getClass() + ": " + e.getMessage());
                throw new IOException();
            }

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

            XmiCasDeserializer.deserialize(new ByteArrayInputStream(decompressedData), aCAS,
                    !this.mFailOnUnknownType);
        } else {

            XmiCasDeserializer.deserialize(this.documentData, aCAS, !this.mFailOnUnknownType);
        }

        this.currentIndex += 1;
    } catch (SAXException e) {

        System.err.println("ERROR in Collection Reader " + e.getClass() + ": " + e.getMessage());
        throw new CollectionException(e);
    }
}

From source file:org.exist.xmldb.RemoteResourceSet.java

@Override
public Resource getMembersAsResource() throws XMLDBException {
    final List<Object> params = new ArrayList<>();
    params.add(Integer.valueOf(handle));
    params.add(outputProperties);//from w ww .  ja v  a2s  .  c o  m

    try {

        final Path tmpfile = TemporaryFileManager.getInstance().getTemporaryFile();
        try (final OutputStream os = Files.newOutputStream(tmpfile)) {

            Map<?, ?> table = (Map<?, ?>) xmlRpcClient.execute("retrieveAllFirstChunk", params);

            long offset = ((Integer) table.get("offset")).intValue();
            byte[] data = (byte[]) table.get("data");
            final boolean isCompressed = "yes"
                    .equals(outputProperties.getProperty(EXistOutputKeys.COMPRESS_OUTPUT, "no"));
            // One for the local cached file
            Inflater dec = null;
            byte[] decResult = null;
            int decLength = 0;
            if (isCompressed) {
                dec = new Inflater();
                decResult = new byte[65536];
                dec.setInput(data);
                do {
                    decLength = dec.inflate(decResult);
                    os.write(decResult, 0, decLength);
                } while (decLength == decResult.length || !dec.needsInput());
            } else {
                os.write(data);
            }
            while (offset > 0) {
                params.clear();
                params.add(table.get("handle"));
                params.add(Long.toString(offset));
                table = (Map<?, ?>) xmlRpcClient.execute("getNextExtendedChunk", params);
                offset = Long.parseLong((String) table.get("offset"));
                data = (byte[]) table.get("data");
                // One for the local cached file
                if (isCompressed) {
                    dec.setInput(data);
                    do {
                        decLength = dec.inflate(decResult);
                        os.write(decResult, 0, decLength);
                    } while (decLength == decResult.length || !dec.needsInput());
                } else {
                    os.write(data);
                }
            }
            if (dec != null) {
                dec.end();
            }

            final RemoteXMLResource res = new RemoteXMLResource(leasableXmlRpcClient.lease(), collection,
                    handle, 0, XmldbURI.EMPTY_URI, Optional.empty());
            res.setContent(tmpfile);
            res.setProperties(outputProperties);
            return res;
        } catch (final XmlRpcException xre) {
            final byte[] data = (byte[]) xmlRpcClient.execute("retrieveAll", params);
            String content;
            try {
                content = new String(data, outputProperties.getProperty(OutputKeys.ENCODING, "UTF-8"));
            } catch (final UnsupportedEncodingException ue) {
                LOG.warn(ue);
                content = new String(data);
            }
            final RemoteXMLResource res = new RemoteXMLResource(leasableXmlRpcClient.lease(), collection,
                    handle, 0, XmldbURI.EMPTY_URI, Optional.empty());
            res.setContent(content);
            res.setProperties(outputProperties);
            return res;
        } catch (final IOException | DataFormatException ioe) {
            throw new XMLDBException(ErrorCodes.VENDOR_ERROR, ioe.getMessage(), ioe);
        }
    } catch (final IOException ioe) {
        throw new XMLDBException(ErrorCodes.VENDOR_ERROR, ioe.getMessage(), ioe);
    } catch (final XmlRpcException xre) {
        throw new XMLDBException(ErrorCodes.INVALID_RESOURCE, xre.getMessage(), xre);
    }
}

From source file:org.opentestsystem.authoring.testspecbank.service.impl.TestSpecificationServiceImpl.java

private final byte[] decompress(final byte[] testSpecificationXml) {
    final Inflater inflater = new Inflater();
    inflater.setInput(testSpecificationXml);
    final ByteArrayOutputStream baos = new ByteArrayOutputStream(testSpecificationXml.length);

    byte[] outBytes = null;

    try {/* w  w w . j a  v a2  s  .co m*/
        final byte[] buffer = new byte[BUFFER_SIZE];
        while (!inflater.finished()) {
            final int count = inflater.inflate(buffer);
            baos.write(buffer, 0, count);
        }
        baos.close();
        outBytes = baos.toByteArray();

    } catch (final IOException | DataFormatException e) {
        throw new LocalizedException("testspec.xml.compress.error", e);
    }

    return outBytes;
}

From source file:org.ajax4jsf.resource.ResourceBuilderImpl.java

protected byte[] decrypt(byte[] src) {
    try {/*w  w w .j a v  a 2s . c  o m*/
        byte[] zipsrc = codec.decode(src);
        Inflater decompressor = new Inflater();
        byte[] uncompressed = new byte[zipsrc.length * 5];
        decompressor.setInput(zipsrc);
        int totalOut = decompressor.inflate(uncompressed);
        byte[] out = new byte[totalOut];
        System.arraycopy(uncompressed, 0, out, 0, totalOut);
        decompressor.end();
        return out;
    } catch (Exception e) {
        throw new FacesException("Error decode resource data", e);
    }
}

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  w  w  w .  j  a  v a2 s.  c om*/
 *
 * @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));
    }
}

From source file:org.mcxiaoke.commons.http.impl.DeflateDecompressingEntity.java

/**
 * Returns the non-null InputStream that should be returned to by all
 * requests to {@link #getContent()}./* ww w  .  j av  a  2  s  .c  om*/
 * 
 * @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));
    }
}

From source file:com.fanfou.app.opensource.http.support.DeflateDecompressingEntity.java

/**
 * Returns the non-null InputStream that should be returned to by all
 * requests to {@link #getContent()}./*from www .  j a  va  2s.c om*/
 * 
 * @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. */
    final byte[] peeked = new byte[6];

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

    final int headerLength = pushback.read(peeked);

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

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

    final 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 (final 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));
    }
}

From source file:com.eryansky.common.utils.SysUtils.java

/**
  * // w ww  . j  av  a  2 s.  c  o  m
  * 
  * @param in
  *            ?
  * @return 
  */
 public static String unZip_Str(byte[] in) {
     Inflater decompresser = new Inflater();
     decompresser.setInput(in);
     ArrayList<Byte> al = new ArrayList<Byte>();
     byte[] result;
     int count = 0;
     for (; !decompresser.finished();) {
         result = new byte[100];
         try {
             count += decompresser.inflate(result);
         } catch (DataFormatException e) {
             e.printStackTrace();
         }
         for (int i = 0; i < result.length; i++) {
             al.add(new Byte(result[i]));
         }
     }
     result = new byte[al.size()];
     for (int i = 0; i < al.size(); i++) {
         result[i] = (al.get(i)).byteValue();
     }
     decompresser.end();

     try {
         return new String(result, 0, count, "UTF-8");
     } catch (UnsupportedEncodingException e) {
         return "";
     }
 }

From source file:org.barcelonamedia.uima.tools.docanalyzer.DBAnnotationViewerDialog.java

public void launchThatViewer(String xmi_id, TypeSystem typeSystem, final String[] aTypesToDisplay,
        boolean javaViewerRBisSelected, boolean javaViewerUCRBisSelected, boolean xmlRBisSelected,
        File styleMapFile, File viewerDirectory) {

    try {/* w  w  w . ja  v a2s.  c o m*/

        InputStream xmiDocument = this.xmiDAO.getXMI(xmi_id);

        // create a new CAS
        CAS cas = CasCreationUtils.createCas(Collections.EMPTY_LIST, typeSystem,
                UIMAFramework.getDefaultPerformanceTuningProperties());

        if (this.med1.isUmcompress()) {

            //Descomprime el XMI

            //Create the decompressor and give it the data to compress
            Inflater decompressor = new Inflater();
            byte[] documentDataByteArray = IOUtils.toByteArray(xmiDocument);

            decompressor.setInput(documentDataByteArray);

            //Create an expandable byte array to hold the decompressed data
            ByteArrayOutputStream bos = new ByteArrayOutputStream(documentDataByteArray.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
            byte[] decompressedData = bos.toByteArray();

            XmiCasDeserializer.deserialize(new ByteArrayInputStream(decompressedData), cas, true);
        } else {

            XmlCasDeserializer.deserialize(xmiDocument, cas, true);
        }

        //get the specified view
        cas = cas.getView(this.defaultCasViewName);

        //launch appropriate viewer
        if (javaViewerRBisSelected || javaViewerUCRBisSelected) { // JMP

            // record preference for next time
            med1.setViewType(javaViewerRBisSelected ? "Java Viewer" : "JV User Colors");

            //create tree viewer component
            CasAnnotationViewer viewer = new CasAnnotationViewer();
            viewer.setDisplayedTypes(aTypesToDisplay);

            if (javaViewerUCRBisSelected)
                getColorsForTypesFromFile(viewer, styleMapFile);
            else
                viewer.setHiddenTypes(new String[] { "uima.cpm.FileLocation" });

            // launch viewer in a new dialog
            viewer.setCAS(cas);
            JDialog dialog = new JDialog(DBAnnotationViewerDialog.this,
                    "Annotation Results for " + xmi_id + " in " + inputDirPath); // JMP
            dialog.getContentPane().add(viewer);
            dialog.setSize(850, 630);
            dialog.pack();
            dialog.show();
        } else {

            CAS defaultView = cas.getView(CAS.NAME_DEFAULT_SOFA);

            if (defaultView.getDocumentText() == null) {
                displayError(
                        "The HTML and XML Viewers can only view the default text document, which was not found in this CAS.");
                return;
            }

            // generate inline XML
            File inlineXmlFile = new File(viewerDirectory, "inline.xml");
            String xmlAnnotations = new CasToInlineXml().generateXML(defaultView);
            FileOutputStream outStream = new FileOutputStream(inlineXmlFile);
            outStream.write(xmlAnnotations.getBytes("UTF-8"));
            outStream.close();

            if (xmlRBisSelected) // JMP passed in
            {
                // record preference for next time
                med1.setViewType("XML");

                BrowserUtil.openUrlInDefaultBrowser(inlineXmlFile.getAbsolutePath());
            } else
            // HTML view
            {
                med1.setViewType("HTML");
                // generate HTML view
                // first process style map if not done already
                if (!processedStyleMap) {
                    if (!styleMapFile.exists()) {
                        annotationViewGenerator.autoGenerateStyleMapFile(
                                promptForAE().getAnalysisEngineMetaData(), styleMapFile);
                    }
                    annotationViewGenerator.processStyleMap(styleMapFile);
                    processedStyleMap = true;
                }
                annotationViewGenerator.processDocument(inlineXmlFile);
                File genFile = new File(viewerDirectory, "index.html");
                // open in browser
                BrowserUtil.openUrlInDefaultBrowser(genFile.getAbsolutePath());
            }
        }

        // end LTV here

    } catch (Exception ex) {

        displayError(ex);
    }
}