Example usage for java.util.zip DeflaterOutputStream DeflaterOutputStream

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

Introduction

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

Prototype

public DeflaterOutputStream(OutputStream out, boolean syncFlush) 

Source Link

Document

Creates a new output stream with a default compressor, a default buffer size and the specified flush mode.

Usage

From source file:org.diorite.nbt.NbtOutputStream.java

/**
 * Create new deflated nbt output stream for given stream.
 *
 * @param outputStream stream to be used.
 * @param def          deflated to be used.
 *
 * @return created NbtOutputStream./*from   ww w  . j  av a2 s.  co m*/
 */
public static NbtOutputStream getDeflated(final OutputStream outputStream, final Deflater def) {
    return new NbtOutputStream(new DeflaterOutputStream(outputStream, def));
}

From source file:org.apache.tez.common.TezCommonUtils.java

@Private
public static ByteString compressByteArrayToByteString(byte[] inBytes, Deflater deflater) throws IOException {
    deflater.reset();//from   ww  w  . java  2 s  . c o m
    ByteString.Output os = ByteString.newOutput();
    DeflaterOutputStream compressOs = null;
    try {
        compressOs = new DeflaterOutputStream(os, deflater);
        compressOs.write(inBytes);
        compressOs.finish();
        ByteString byteString = os.toByteString();
        return byteString;
    } finally {
        if (compressOs != null) {
            compressOs.close();
        }
    }
}

From source file:org.diorite.nbt.NbtOutputStream.java

/**
 * Create new deflated nbt output stream for given file.
 *
 * @param file file to be used./*from w  w  w .java  2  s  .  c o  m*/
 * @param def  deflater to be used.
 *
 * @return created NbtOutputStream.
 *
 * @throws IOException if any file operation failed.
 */
public static NbtOutputStream getDeflated(final File file, final Deflater def) throws IOException {
    createFile(file);
    return new NbtOutputStream(new DeflaterOutputStream(new FileOutputStream(file, false), def));
}

From source file:org.apache.oozie.workflow.lite.LiteWorkflowAppParser.java

/**
 * Write the GlobalSectionData to a Base64 string.
 * @param globalSectionData/*w w w.j a v  a  2 s .c om*/
 * @return String
 * @throws WorkflowException
 */
private String getGlobalString(GlobalSectionData globalSectionData) throws WorkflowException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream oos = null;
    try {
        Deflater def = new Deflater();
        oos = new DataOutputStream(new DeflaterOutputStream(baos, def));
        globalSectionData.write(oos);
        oos.close();
    } catch (IOException e) {
        throw new WorkflowException(ErrorCode.E0700, "Error while processing global section conf");
    }
    return Base64.encodeBase64String(baos.toByteArray());
}

From source file:org.wso2.carbon.identity.saml.inbound.util.SAMLSSOUtil.java

/**
 * Compresses the response String//from  w w  w .j a v a2s .co m
 *
 * @param response
 * @return
 * @throws IOException
 */
public static String compressResponse(String response) throws IOException {

    Deflater deflater = new Deflater(Deflater.DEFLATED, true);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
    try {
        deflaterOutputStream.write(response.getBytes(StandardCharsets.UTF_8));
    } finally {
        deflaterOutputStream.close();
    }
    return Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);
}

From source file:com.tremolosecurity.proxy.auth.SAML2Auth.java

public void initializeSSO(HttpServletRequest req, HttpServletResponse resp, HttpSession session, boolean isJump,
        String jumpPage) throws MalformedURLException, ServletException {
    {// w  ww. j  av  a 2  s  .  c om
        RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();

        HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session
                .getAttribute(ProxyConstants.AUTH_MECH_PARAMS);

        boolean isMultiIdp = authParams.get("isMultiIdP") != null
                && authParams.get("isMultiIdP").getValues().get(0).equalsIgnoreCase("true");

        String postAuthnReqTo = "";
        String redirAuthnReqTo = "";
        String assertionConsumerServiceURL = "";
        boolean signAuthnReq = false;

        String uri = (String) req.getAttribute(ProxyConstants.AUTH_REDIR_URI);
        if (uri == null) {
            uri = req.getRequestURI();
        }

        if (isMultiIdp) {

            URL url = new URL(req.getRequestURL().toString());
            String hostName = url.getHost();
            String dn = authParams.get("idpDir").getValues().get(0);

            try {
                StringBuffer b = new StringBuffer();

                LDAPSearchResults res = cfgMgr.getMyVD().search(dn, 2, equal("hostname", hostName).toString(),
                        new ArrayList<String>());
                if (!res.hasMore()) {
                    throw new ServletException("No IdP found");
                }

                LDAPEntry entry = res.next();
                postAuthnReqTo = entry.getAttribute("idpURL").getStringValue();

                redirAuthnReqTo = entry.getAttribute("idpRedirURL").getStringValue();

                assertionConsumerServiceURL = ProxyTools.getInstance().getFqdnUrl(uri, req);
                signAuthnReq = entry.getAttribute("signAuthnReq").getStringValue().equalsIgnoreCase("1");

            } catch (LDAPException e) {
                throw new ServletException("Could not load IdP data", e);
            }

        } else {
            postAuthnReqTo = authParams.get("idpURL").getValues().get(0);// "http://idp.partner.domain.com:8080/opensso/SSOPOST/metaAlias/testSaml2Idp";

            redirAuthnReqTo = authParams.get("idpRedirURL").getValues().get(0);

            assertionConsumerServiceURL = ProxyTools.getInstance().getFqdnUrl(uri, req);// "http://sp.localdomain.com:8080/SampleSP/echo";

            if (authParams.get("forceToSSL") != null
                    && authParams.get("forceToSSL").getValues().get(0).equalsIgnoreCase("true")) {
                if (!assertionConsumerServiceURL.startsWith("https")) {
                    assertionConsumerServiceURL = assertionConsumerServiceURL.replace("http://", "https://");
                }
            }

            signAuthnReq = authParams.get("signAuthnReq") != null
                    && authParams.get("signAuthnReq").getValues().get(0).equalsIgnoreCase("true");
        }

        ConfigManager cfg = (ConfigManager) req.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);

        AuthnRequestBuilder authnBuilder = new AuthnRequestBuilder();
        AuthnRequest authn = authnBuilder.buildObject();
        authn.setAssertionConsumerServiceURL(assertionConsumerServiceURL);
        authn.setProtocolBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
        //authn.setDestination(postAuthnReqTo);
        authn.setDestination(redirAuthnReqTo);
        DateTime dt = new DateTime();

        String authMechanism = authParams.get("authCtxRef").getValues().get(0);

        byte[] idBytes = new byte[20];
        random.nextBytes(idBytes);

        /*StringBuffer id = new StringBuffer();
        for (byte b : idBytes) {
           id.append(Hex.encode(idBytes));
        }*/

        StringBuffer b = new StringBuffer();
        b.append('f').append(Hex.encodeHexString(idBytes));

        String id = b.toString();

        authn.setIssueInstant(dt);
        //authn.setID(Long.toString(random.nextLong()));
        authn.setID(id.toString());
        session.setAttribute("AUTOIDM_SAML2_REQUEST", authn.getID());
        IssuerBuilder ib = new IssuerBuilder();
        Issuer issuer = ib.buildObject();
        issuer.setValue(assertionConsumerServiceURL);

        authn.setIssuer(issuer);
        //authn.setAssertionConsumerServiceIndex(0);
        //authn.setAttributeConsumingServiceIndex(0);

        NameIDPolicyBuilder nidbpb = new NameIDPolicyBuilder();
        NameIDPolicy nidp = nidbpb.buildObject();
        //nidp.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
        nidp.setFormat("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress");
        nidp.setAllowCreate(true);
        nidp.setSPNameQualifier(assertionConsumerServiceURL);
        //authn.setNameIDPolicy(nidp);

        authn.setIsPassive(false);
        //authn.setProviderName("tremolosecurity.com");

        if (!authMechanism.isEmpty() && !authMechanism.equalsIgnoreCase("none")) {
            AuthnContextClassRefBuilder accrb = new AuthnContextClassRefBuilder();
            AuthnContextClassRef accr = accrb.buildObject();

            accr.setAuthnContextClassRef(authMechanism);

            //accr.setAuthnContextClassRef("urn:federation:authentication:windows");
            //accr.setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");

            RequestedAuthnContextBuilder racb = new RequestedAuthnContextBuilder();
            RequestedAuthnContext rac = racb.buildObject();
            rac.getAuthnContextClassRefs().add(accr);
            rac.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
            authn.setRequestedAuthnContext(rac);
        }

        authn.setForceAuthn(false);

        try {
            // Get the Subject marshaller
            Marshaller marshaller = new AuthnRequestMarshaller();

            // Marshall the Subject
            //Element assertionElement = marshaller.marshall(authn);

            String xml = OpenSAMLUtils.xml2str(authn);
            xml = xml.substring(xml.indexOf("?>") + 2);

            if (logger.isDebugEnabled()) {
                logger.debug("=======AuthnRequest============");
                logger.debug(xml);
                logger.debug("=======AuthnRequest============");
            }

            byte[] bxml = xml.getBytes("UTF-8");

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            DeflaterOutputStream compressor = new DeflaterOutputStream(baos,
                    new Deflater(Deflater.BEST_COMPRESSION, true));

            compressor.write(bxml);
            compressor.flush();
            compressor.close();

            String b64 = new String(Base64.encodeBase64(baos.toByteArray()));
            StringBuffer redirURL = new StringBuffer();
            StringBuffer query = new StringBuffer();

            idBytes = new byte[20];
            random.nextBytes(idBytes);

            query.append("SAMLRequest=").append(URLEncoder.encode(b64, "UTF-8")).append("&RelayState=")
                    .append(URLEncoder.encode(Hex.encodeHexString(idBytes), "UTF-8"));

            if (signAuthnReq) {

                String sigAlg = authParams.get("sigAlg") != null ? authParams.get("sigAlg").getValues().get(0)
                        : "RSA-SHA1";

                String xmlSigAlg = SAML2Auth.xmlDigSigAlgs.get(sigAlg);
                String javaSigAlg = SAML2Auth.javaDigSigAlgs.get(sigAlg);

                //sb.append("SAMLRequest=").append(xml).append("&SigAlg=").append(URLEncoder.encode("http://www.w3.org/2000/09/xmldsig#rsa-sha1", "UTF-8"));
                query.append("&SigAlg=").append(URLEncoder.encode(xmlSigAlg, "UTF-8"));

                java.security.Signature signer = java.security.Signature.getInstance(javaSigAlg);

                if (authParams.get("spSigKey") == null) {
                    throw new ServletException("No signature certificate specified");
                }
                String spSigKey = authParams.get("spSigKey").getValues().get(0);

                signer.initSign(cfgMgr.getPrivateKey(spSigKey));
                signer.update(query.toString().getBytes("UTF-8"));
                String base64Sig = new String(Base64.encodeBase64(signer.sign()));
                query.append("&Signature=").append(URLEncoder.encode(base64Sig, "UTF-8"));
            }

            redirURL.append(redirAuthnReqTo).append("?").append(query.toString());

            if (isJump) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Redirecting to Jump Page");
                    logger.debug("SAML2_JUMPPAGE='" + req.getAttribute("TREMOLO_AUTH_REDIR_URI"));
                }

                session.setAttribute("SAML2_JUMPPAGE", redirURL.toString());
                resp.sendRedirect(jumpPage);
            } else {
                resp.sendRedirect(redirURL.toString());
            }

            /*String b64 = new String(
                  org.apache.directory.shared.ldap.util.Base64
                .encode(bxml));
                    
            req.setAttribute("postaction", postAuthnReqTo);
            req.setAttribute("postdata", b64);
            req.getRequestDispatcher("/auth/fed/postauthnreq.jsp").forward(
                  req, resp);*/

        } catch (Exception e) {
            throw new ServletException("Error generating new authn request", e);
        }
    }
}

From source file:org.diorite.nbt.NbtOutputStream.java

/**
 * Create new deflated nbt output stream for given file.
 *
 * @param file   file to be used./*from   ww  w  .  j a va 2s.c o m*/
 * @param append if new data should be appended to existing one.
 * @param def    deflater to be used.
 *
 * @return created NbtOutputStream.
 *
 * @throws IOException if any file operation failed.
 */
public static NbtOutputStream getDeflated(final File file, final boolean append, final Deflater def)
        throws IOException {
    createFile(file);
    return new NbtOutputStream(new DeflaterOutputStream(new FileOutputStream(file, append), def));
}

From source file:PngEncoder.java

/**
 * Write the image data into the pngBytes array.
 * This will write one or more PNG "IDAT" chunks. In order
 * to conserve memory, this method grabs as many rows as will
 * fit into 32K bytes, or the whole image; whichever is less.
 *
 *
 * @return true if no errors; false if error grabbing pixels
 *//*  w ww . ja  v a  2 s  .c  o m*/
protected boolean writeImageData() {
    int rowsLeft = this.height; // number of rows remaining to write
    int startRow = 0; // starting row to process this time through
    int nRows; // how many rows to grab at a time

    byte[] scanLines; // the scan lines to be compressed
    int scanPos; // where we are in the scan lines
    int startPos; // where this line's actual pixels start (used
                  // for filtering)

    byte[] compressedLines; // the resultant compressed lines
    int nCompressed; // how big is the compressed area?

    //int depth;              // color depth ( handle only 8 or 32 )

    PixelGrabber pg;

    this.bytesPerPixel = (this.encodeAlpha) ? 4 : 3;

    Deflater scrunch = new Deflater(this.compressionLevel);
    ByteArrayOutputStream outBytes = new ByteArrayOutputStream(1024);

    DeflaterOutputStream compBytes = new DeflaterOutputStream(outBytes, scrunch);
    try {
        while (rowsLeft > 0) {
            nRows = Math.min(32767 / (this.width * (this.bytesPerPixel + 1)), rowsLeft);
            nRows = Math.max(nRows, 1);

            int[] pixels = new int[this.width * nRows];

            pg = new PixelGrabber(this.image, 0, startRow, this.width, nRows, pixels, 0, this.width);
            try {
                pg.grabPixels();
            } catch (Exception e) {
                System.err.println("interrupted waiting for pixels!");
                return false;
            }
            if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
                System.err.println("image fetch aborted or errored");
                return false;
            }

            /*
             * Create a data chunk. scanLines adds "nRows" for
             * the filter bytes.
             */
            scanLines = new byte[this.width * nRows * this.bytesPerPixel + nRows];

            if (this.filter == FILTER_SUB) {
                this.leftBytes = new byte[16];
            }
            if (this.filter == FILTER_UP) {
                this.priorRow = new byte[this.width * this.bytesPerPixel];
            }

            scanPos = 0;
            startPos = 1;
            for (int i = 0; i < this.width * nRows; i++) {
                if (i % this.width == 0) {
                    scanLines[scanPos++] = (byte) this.filter;
                    startPos = scanPos;
                }
                scanLines[scanPos++] = (byte) ((pixels[i] >> 16) & 0xff);
                scanLines[scanPos++] = (byte) ((pixels[i] >> 8) & 0xff);
                scanLines[scanPos++] = (byte) ((pixels[i]) & 0xff);
                if (this.encodeAlpha) {
                    scanLines[scanPos++] = (byte) ((pixels[i] >> 24) & 0xff);
                }
                if ((i % this.width == this.width - 1) && (this.filter != FILTER_NONE)) {
                    if (this.filter == FILTER_SUB) {
                        filterSub(scanLines, startPos, this.width);
                    }
                    if (this.filter == FILTER_UP) {
                        filterUp(scanLines, startPos, this.width);
                    }
                }
            }

            /*
             * Write these lines to the output area
             */
            compBytes.write(scanLines, 0, scanPos);

            startRow += nRows;
            rowsLeft -= nRows;
        }
        compBytes.close();

        /*
         * Write the compressed bytes
         */
        compressedLines = outBytes.toByteArray();
        nCompressed = compressedLines.length;

        this.crc.reset();
        this.bytePos = writeInt4(nCompressed, this.bytePos);
        this.bytePos = writeBytes(IDAT, this.bytePos);
        this.crc.update(IDAT);
        this.bytePos = writeBytes(compressedLines, nCompressed, this.bytePos);
        this.crc.update(compressedLines, 0, nCompressed);

        this.crcValue = this.crc.getValue();
        this.bytePos = writeInt4((int) this.crcValue, this.bytePos);
        scrunch.finish();
        scrunch.end();
        return true;
    } catch (IOException e) {
        System.err.println(e.toString());
        return false;
    }
}

From source file:PngEncoder.java

/**
 * Writes the IDAT (Image data) chunks to the output stream.
 *
 * @param out the OutputStream to write the chunk to
 * @param csum the Checksum that is updated as data is written
 *             to the passed-in OutputStream
 * @throws IOException if a problem is encountered writing the output
 *//*w  w w . java  2  s.c  o m*/
private void writeIdatChunks(OutputStream out, Checksum csum) throws IOException {
    int rowWidth = width * outputBpp; // size of image data in a row in bytes.

    int row = 0;

    Deflater deflater = new Deflater(compressionLevel);
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    DeflaterOutputStream defOut = new DeflaterOutputStream(byteOut, deflater);

    byte[] filteredPixelQueue = new byte[rowWidth];

    // Output Pixel Queues
    byte[][] outputPixelQueue = new byte[2][rowWidth];
    Arrays.fill(outputPixelQueue[1], (byte) 0);
    int outputPixelQueueRow = 0;
    int outputPixelQueuePrevRow = 1;

    while (row < height) {
        if (filter == null) {
            defOut.write(0);
            translator.translate(outputPixelQueue[outputPixelQueueRow], row);
            defOut.write(outputPixelQueue[outputPixelQueueRow], 0, rowWidth);
        } else {
            defOut.write(filter.getType());
            translator.translate(outputPixelQueue[outputPixelQueueRow], row);
            filter.filter(filteredPixelQueue, outputPixelQueue[outputPixelQueueRow],
                    outputPixelQueue[outputPixelQueuePrevRow], outputBpp);
            defOut.write(filteredPixelQueue, 0, rowWidth);
        }

        ++row;
        outputPixelQueueRow = row & 1;
        outputPixelQueuePrevRow = outputPixelQueueRow ^ 1;
    }
    defOut.finish();
    byteOut.close();

    writeInt(out, byteOut.size());
    csum.reset();
    out.write(IDAT);
    byteOut.writeTo(out);
    writeInt(out, (int) csum.getValue());
}

From source file:org.pentaho.reporting.libraries.base.util.PngEncoder.java

/**
 * Write the image data into the pngBytes array. This will write one or more PNG "IDAT" chunks. In order to conserve
 * memory, this method grabs as many rows as will fit into 32K bytes, or the whole image; whichever is less.
 *
 * @return true if no errors; false if error grabbing pixels
 *///from  w w  w  . j  a  v  a 2 s  .c o m
protected boolean writeImageData() {

    this.bytesPerPixel = (this.encodeAlpha) ? 4 : 3;

    final Deflater scrunch = new Deflater(this.compressionLevel);
    final ByteArrayOutputStream outBytes = new ByteArrayOutputStream(1024);
    final DeflaterOutputStream compBytes = new DeflaterOutputStream(outBytes, scrunch);
    try {
        int startRow = 0; // starting row to process this time through
        //noinspection SuspiciousNameCombination
        int rowsLeft = this.height; // number of rows remaining to write
        while (rowsLeft > 0) {
            final int nRows = Math.max(Math.min(32767 / (this.width * (this.bytesPerPixel + 1)), rowsLeft), 1);

            final int[] pixels = new int[this.width * nRows];

            final PixelGrabber pg = new PixelGrabber(this.image, 0, startRow, this.width, nRows, pixels, 0,
                    this.width);
            try {
                pg.grabPixels();
            } catch (Exception e) {
                logger.error("interrupted waiting for pixels!", e);
                return false;
            }
            if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
                logger.error("image fetch aborted or errored");
                return false;
            }

            /*
            * Create a data chunk. scanLines adds "nRows" for
            * the filter bytes.
            */
            final byte[] scanLines = new byte[this.width * nRows * this.bytesPerPixel + nRows];

            if (this.filter == PngEncoder.FILTER_SUB) {
                this.leftBytes = new byte[16];
            }
            if (this.filter == PngEncoder.FILTER_UP) {
                this.priorRow = new byte[this.width * this.bytesPerPixel];
            }

            int scanPos = 0;
            int startPos = 1;
            for (int i = 0; i < this.width * nRows; i++) {
                if (i % this.width == 0) {
                    scanLines[scanPos++] = (byte) this.filter;
                    startPos = scanPos;
                }
                scanLines[scanPos++] = (byte) ((pixels[i] >> 16) & 0xff);
                scanLines[scanPos++] = (byte) ((pixels[i] >> 8) & 0xff);
                scanLines[scanPos++] = (byte) ((pixels[i]) & 0xff);
                if (this.encodeAlpha) {
                    scanLines[scanPos++] = (byte) ((pixels[i] >> 24) & 0xff);
                }
                if ((i % this.width == this.width - 1) && (this.filter != PngEncoder.FILTER_NONE)) {
                    if (this.filter == PngEncoder.FILTER_SUB) {
                        filterSub(scanLines, startPos, this.width);
                    }
                    if (this.filter == PngEncoder.FILTER_UP) {
                        filterUp(scanLines, startPos, this.width);
                    }
                }
            }

            /*
            * Write these lines to the output area
            */
            compBytes.write(scanLines, 0, scanPos);

            startRow += nRows;
            rowsLeft -= nRows;
        }
        compBytes.close();

        /*
        * Write the compressed bytes
        */
        final byte[] compressedLines = outBytes.toByteArray();
        final int nCompressed = compressedLines.length;

        this.crc.reset();
        this.bytePos = writeInt4(nCompressed, this.bytePos);
        this.bytePos = writeBytes(PngEncoder.IDAT, this.bytePos);
        this.crc.update(PngEncoder.IDAT);
        this.bytePos = writeBytes(compressedLines, nCompressed, this.bytePos);
        this.crc.update(compressedLines, 0, nCompressed);

        this.crcValue = this.crc.getValue();
        this.bytePos = writeInt4((int) this.crcValue, this.bytePos);
        return true;
    } catch (IOException e) {
        logger.error("Failed to write PNG Data", e);
        return false;
    } finally {
        scrunch.finish();
        scrunch.end();
    }
}