Example usage for java.util.zip Deflater DEFLATED

List of usage examples for java.util.zip Deflater DEFLATED

Introduction

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

Prototype

int DEFLATED

To view the source code for java.util.zip Deflater DEFLATED.

Click Source Link

Document

Compression method for the deflate algorithm (the only one currently supported).

Usage

From source file:zipB64.java

protected static String encodeMessage(String messageStr) {
    try {// w  w w  . j  a va  2s. c  o m
        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
        Deflater deflater = new Deflater(Deflater.DEFLATED);
        DeflaterOutputStream deflaterStream = new DeflaterOutputStream(bytesOut, deflater);
        deflaterStream.write(messageStr.getBytes("UTF-8"));
        deflaterStream.finish();

        Base64 b = new Base64(-1);
        return new String(b.encode(bytesOut.toByteArray()));
    } catch (Exception e) {
        return "crotte";
    }
}

From source file:ZipUtil.java

/**
 * Deflates the file and returns the deflated file.
 *///from ww w . j a v  a 2  s.co m
public static byte[] zipByteArray(byte[] file) throws IOException {
    byte[] byReturn = null;
    Deflater oDeflate = new Deflater(Deflater.DEFLATED, false);
    oDeflate.setInput(file);
    oDeflate.finish();
    ByteArrayOutputStream oZipStream = new ByteArrayOutputStream();
    try {
        while (!oDeflate.finished()) {
            byte[] byRead = new byte[ZIP_BUFFER_SIZE];
            int iBytesRead = oDeflate.deflate(byRead);
            if (iBytesRead == byRead.length) {
                oZipStream.write(byRead);
            } else {
                oZipStream.write(byRead, 0, iBytesRead);
            }
        }
        oDeflate.end();
        byReturn = oZipStream.toByteArray();
    } finally {
        oZipStream.close();
    }
    return byReturn;
}

From source file:ch.cern.security.saml2.utils.xml.XMLUtils.java

/**
 * Compress the xml string and encodes it in Base64
 * /*from  w  w  w  .j  a va  2 s .c  o m*/
 * @param xmlString
 * @param isDebugEnabled 
 * @return xml string encoded
 * @throws IOException
 * @throws UnsupportedEncodingException
 */
public static String xmlDeflateAndEncode(String xmlString, boolean isDebugEnabled)
        throws IOException, UnsupportedEncodingException {

    if (isDebugEnabled)
        nc.notice(xmlString);

    // Deflate the SAMLResponse value
    ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
    Deflater deflater = new Deflater(Deflater.DEFLATED, true);
    DeflaterOutputStream deflaterStream = new DeflaterOutputStream(bytesOut, deflater);
    deflaterStream.write(xmlString.getBytes());
    deflaterStream.finish();

    // Encoded the deflatedResponse in base64
    Base64 base64encoder = new Base64();
    String base64response = new String(base64encoder.encode(bytesOut.toByteArray()), "UTF-8");

    if (isDebugEnabled)
        nc.notice(base64response);

    return base64response;
}

From source file:ZipUtil.java

public static void zipFileToFile(File flSource, File flTarget) throws IOException {
    Deflater oDeflate = new Deflater(Deflater.DEFLATED, false);

    FileInputStream stmFileIn = new FileInputStream(flSource);
    FileOutputStream stmFileOut = new FileOutputStream(flTarget);
    DeflaterOutputStream stmDeflateOut = new DeflaterOutputStream(stmFileOut, oDeflate);
    try {/*from w  ww  .  java 2s .com*/
        // FileUtil.inputStreamToOutputStream(stmFileIn, stmDeflateOut);
    } //end try
    finally {
        stmDeflateOut.finish();
        stmDeflateOut.flush();
        stmDeflateOut.close();
        stmFileOut.close();
        stmFileIn.close();
    }
}

From source file:divconq.ctp.stream.UngzipStream.java

protected void inflate(ByteBuf in) {
    switch (this.gzipState) {
    case HEADER_START:
        if (in.readableBytes() < 10)
            return;

        // read magic numbers
        int magic0 = in.readByte();
        int magic1 = in.readByte();

        if (magic0 != 31) {
            OperationContext.get().getTaskRun().kill("Input is not in the GZIP format");
            return;
        }/*from w w  w  . j  av  a  2  s  .  c o m*/

        this.crc.update(magic0);
        this.crc.update(magic1);

        int method = in.readUnsignedByte();

        if (method != Deflater.DEFLATED) {
            OperationContext.get().getTaskRun()
                    .kill("Unsupported compression method " + method + " in the GZIP header");
            return;
        }

        this.crc.update(method);

        this.flags = in.readUnsignedByte();
        this.crc.update(this.flags);

        if ((this.flags & FRESERVED) != 0) {
            OperationContext.get().getTaskRun().kill("Reserved flags are set in the GZIP header");
            return;
        }

        // mtime (int)
        this.crc.update(in.readByte());
        this.crc.update(in.readByte());
        this.crc.update(in.readByte());
        this.crc.update(in.readByte());

        this.crc.update(in.readUnsignedByte()); // extra flags
        this.crc.update(in.readUnsignedByte()); // operating system

        this.gzipState = GzipState.FLG_READ;
    case FLG_READ:
        if ((this.flags & FEXTRA) != 0) {
            if (in.readableBytes() < 2)
                return;

            int xlen1 = in.readUnsignedByte();
            int xlen2 = in.readUnsignedByte();

            this.crc.update(xlen1);
            this.crc.update(xlen2);

            this.xlen |= xlen1 << 8 | xlen2;
        }

        this.gzipState = GzipState.XLEN_READ;
    case XLEN_READ:
        if (this.xlen != -1) {
            if (in.readableBytes() < xlen)
                return;

            byte[] xtra = new byte[xlen];
            in.readBytes(xtra);
            this.crc.update(xtra);
        }

        this.gzipState = GzipState.SKIP_FNAME;
    case SKIP_FNAME:
        if ((this.flags & FNAME) != 0) {
            boolean gotend = false;

            while (in.isReadable()) {
                int b = in.readUnsignedByte();
                this.crc.update(b);

                if (b == 0x00) {
                    gotend = true;
                    break;
                }
            }

            if (!gotend)
                return;
        }

        this.gzipState = GzipState.SKIP_COMMENT;
    case SKIP_COMMENT:
        if ((this.flags & FCOMMENT) != 0) {
            boolean gotend = false;

            while (in.isReadable()) {
                int b = in.readUnsignedByte();
                this.crc.update(b);

                if (b == 0x00) {
                    gotend = true;
                    break;
                }
            }

            if (!gotend)
                return;
        }

        this.gzipState = GzipState.PROCESS_FHCRC;
    case PROCESS_FHCRC:
        if ((this.flags & FHCRC) != 0) {
            if (in.readableBytes() < 4)
                return;

            long crcValue = 0;

            for (int i = 0; i < 4; ++i)
                crcValue |= (long) in.readUnsignedByte() << i * 8;

            long readCrc = crc.getValue();

            if (crcValue != readCrc) {
                OperationContext.get().getTaskRun()
                        .kill("CRC value missmatch. Expected: " + crcValue + ", Got: " + readCrc);
                return;
            }
        }

        this.crc.reset();

        this.gzipState = GzipState.PRROCESS_CONTENT;
    case PRROCESS_CONTENT:
        int readableBytes = in.readableBytes();

        if (readableBytes < 1)
            return;

        if (in.hasArray()) {
            this.inflater.setInput(in.array(), in.arrayOffset() + in.readerIndex(), readableBytes);
        } else {
            byte[] array = new byte[readableBytes];
            in.getBytes(in.readerIndex(), array);
            this.inflater.setInput(array);
        }

        int maxOutputLength = this.inflater.getRemaining() << 1;
        ByteBuf decompressed = Hub.instance.getBufferAllocator().heapBuffer(maxOutputLength);

        boolean readFooter = false;
        byte[] outArray = decompressed.array();

        try {
            while (!this.inflater.needsInput()) {
                int writerIndex = decompressed.writerIndex();
                int outIndex = decompressed.arrayOffset() + writerIndex;
                int length = decompressed.writableBytes();

                if (length == 0) {
                    // completely filled the buffer allocate a new one and start to fill it
                    this.outlist.add(decompressed);
                    decompressed = Hub.instance.getBufferAllocator().heapBuffer(maxOutputLength);
                    outArray = decompressed.array();
                    continue;
                }

                int outputLength = this.inflater.inflate(outArray, outIndex, length);

                if (outputLength > 0) {
                    decompressed.writerIndex(writerIndex + outputLength);

                    this.crc.update(outArray, outIndex, outputLength);
                } else {
                    if (this.inflater.needsDictionary()) {
                        if (this.dictionary == null) {
                            OperationContext.get().getTaskRun().kill(
                                    "decompression failure, unable to set dictionary as non was specified");
                            return;
                        }

                        this.inflater.setDictionary(this.dictionary);
                    }
                }

                if (this.inflater.finished()) {
                    readFooter = true;
                    break;
                }
            }

            in.skipBytes(readableBytes - this.inflater.getRemaining());
        } catch (DataFormatException x) {
            OperationContext.get().getTaskRun().kill("decompression failure: " + x);
            return;
        } finally {
            if (decompressed.isReadable()) {
                this.outlist.add(decompressed);
            } else {
                decompressed.release();
            }
        }

        if (!readFooter)
            break;

        this.gzipState = GzipState.PROCESS_FOOTER;
    case PROCESS_FOOTER:
        if (in.readableBytes() < 8)
            return;

        long crcValue = 0;

        for (int i = 0; i < 4; ++i)
            crcValue |= (long) in.readUnsignedByte() << i * 8;

        long readCrc = this.crc.getValue();

        if (crcValue != readCrc) {
            OperationContext.get().getTaskRun()
                    .kill("CRC value missmatch. Expected: " + crcValue + ", Got: " + readCrc);
            return;
        }

        // read ISIZE and verify
        int dataLength = 0;

        for (int i = 0; i < 4; ++i)
            dataLength |= in.readUnsignedByte() << i * 8;

        int readLength = this.inflater.getTotalOut();

        if (dataLength != readLength) {
            OperationContext.get().getTaskRun()
                    .kill("Number of bytes mismatch. Expected: " + dataLength + ", Got: " + readLength);
            return;
        }

        this.gzipState = GzipState.DONE;
    case DONE:
        break;
    }
}

From source file:com.vmware.demo.SamlService.java

public String generateSAMLRequest(String assertionConsumerServiceURL, String nameIdFormat) {
    String samlRequest = "";

    try {/*from   w  ww  .  j av a 2s. co  m*/
        // Generate ID
        String randId = "A71AB3E13";

        // Create an issuer Object
        IssuerBuilder issuerBuilder = new IssuerBuilder();
        Issuer issuer = issuerBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:assertion", "Issuer", "samlp");
        issuer.setValue(issuerString);

        // Create NameIDPolicy
        NameIDPolicyBuilder nameIdPolicyBuilder = new NameIDPolicyBuilder();
        NameIDPolicy nameIdPolicy = nameIdPolicyBuilder.buildObject();
        if (StringUtils.isNotEmpty(nameIdFormat)) {
            nameIdPolicy.setFormat(nameIdFormat);
        }
        nameIdPolicy.setSPNameQualifier(issuerString);
        nameIdPolicy.setAllowCreate(true);

        // Create AuthnContextClassRef
        AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
        AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder
                .buildObject("urn:oasis:names:tc:SAML:2.0:assertion", "AuthnContextClassRef", "saml");
        authnContextClassRef
                .setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");

        // Create RequestedAuthnContext
        RequestedAuthnContextBuilder requestedAuthnContextBuilder = new RequestedAuthnContextBuilder();
        RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
        requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
        requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);

        AuthnRequestBuilder authRequestBuilder = new AuthnRequestBuilder();
        AuthnRequest authRequest = authRequestBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:protocol",
                "AuthnRequest", "samlp");
        authRequest.setForceAuthn(false);
        authRequest.setIsPassive(false);
        authRequest.setIssueInstant(new DateTime());
        authRequest.setProtocolBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
        authRequest.setAssertionConsumerServiceURL(assertionConsumerServiceURL);
        authRequest.setIssuer(issuer);
        authRequest.setNameIDPolicy(nameIdPolicy);
        authRequest.setRequestedAuthnContext(requestedAuthnContext);
        authRequest.setID(randId);
        authRequest.setVersion(SAMLVersion.VERSION_20);
        Marshaller marshaller = org.opensaml.Configuration.getMarshallerFactory().getMarshaller(authRequest);
        org.w3c.dom.Element authDOM = marshaller.marshall(authRequest);
        StringWriter rspWrt = new StringWriter();
        XMLHelper.writeNode(authDOM, rspWrt);
        String messageXML = rspWrt.toString();
        Deflater deflater = new Deflater(Deflater.DEFLATED, true);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
        deflaterOutputStream.write(messageXML.getBytes());
        deflaterOutputStream.close();
        samlRequest = Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);
        //samlRequest = URLEncoder.encode(samlRequest);

        logger.info("samlRequest: " + samlRequest);

    } catch (MarshallingException e) {
        logger.error("General Error", e);
    } catch (IOException e) {
        logger.error("General Error", e);
    }
    return samlRequest;
}

From source file:ddf.security.samlp.SimpleSignTest.java

/**
 * Deflates a value and Base64 encodes the result. This code is copied from RestSecurity because it would cause a circular dependency to use it directly..
 *
 * @param value value to deflate and Base64 encode
 * @return String/*from w  ww  . j  av a  2  s .  c  o m*/
 * @throws IOException if the value cannot be converted
 */
public static String deflateAndBase64Encode(String value) throws IOException {
    ByteArrayOutputStream valueBytes = new ByteArrayOutputStream();
    try (OutputStream tokenStream = new DeflaterOutputStream(valueBytes,
            new Deflater(Deflater.DEFLATED, true))) {
        tokenStream.write(value.getBytes(StandardCharsets.UTF_8));
        tokenStream.close();

        return new String(Base64.encodeBase64(valueBytes.toByteArray()));
    }
}

From source file:com.xwiki.authentication.saml.XWikiSAMLAuthenticator.java

public void showLogin(XWikiContext context) throws XWikiException {
    XWikiRequest request = context.getRequest();
    XWikiResponse response = context.getResponse();

    try {// w  ww .java  2 s .co  m
        DefaultBootstrap.bootstrap();
    } catch (ConfigurationException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Failed to bootstrap saml module");
        }
        throw new XWikiException(XWikiException.MODULE_XWIKI_USER, XWikiException.ERROR_XWIKI_USER_INIT,
                "Failed to bootstrap saml module");
    }
    XMLObjectBuilderFactory builderFactory = org.opensaml.Configuration.getBuilderFactory();

    // Generate ID
    String randId = RandomStringUtils.randomAlphanumeric(42);
    if (LOG.isDebugEnabled())
        LOG.debug("Random ID: " + randId);

    String sourceurl = request.getParameter("xredirect");
    if (sourceurl == null) {
        if (context.getAction().startsWith("login"))
            sourceurl = context.getWiki().getURL("Main.WebHome", "view", context);
        else {
            context.getWiki();
            sourceurl = XWiki.getRequestURL(request).toString();
        }
    }

    request.getSession().setAttribute("saml_url", sourceurl);
    request.getSession().setAttribute("saml_id", randId);

    //Create an issuer Object
    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:assertion", "Issuer", "samlp");
    issuer.setValue(getSAMLIssuer(context));

    //Create NameIDPolicy
    NameIDPolicyBuilder nameIdPolicyBuilder = new NameIDPolicyBuilder();
    NameIDPolicy nameIdPolicy = nameIdPolicyBuilder.buildObject();
    nameIdPolicy.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent");
    nameIdPolicy.setSPNameQualifier(getSAMLNameQualifier(context));
    nameIdPolicy.setAllowCreate(true);

    //Create AuthnContextClassRef
    AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
    AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder
            .buildObject("urn:oasis:names:tc:SAML:2.0:assertion", "AuthnContextClassRef", "saml");
    authnContextClassRef
            .setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");

    //Create RequestedAuthnContext
    RequestedAuthnContextBuilder requestedAuthnContextBuilder = new RequestedAuthnContextBuilder();
    RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
    requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
    requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);

    DateTime issueInstant = new DateTime();
    AuthnRequestBuilder authRequestBuilder = new AuthnRequestBuilder();
    AuthnRequest authRequest = authRequestBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:protocol",
            "AuthnRequest", "samlp");
    authRequest.setForceAuthn(false);
    authRequest.setIsPassive(false);
    authRequest.setIssueInstant(issueInstant);
    authRequest.setProtocolBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    authRequest.setAssertionConsumerServiceURL(getSAMLAuthenticatorURL(context));
    authRequest.setIssuer(issuer);
    authRequest.setNameIDPolicy(nameIdPolicy);
    authRequest.setRequestedAuthnContext(requestedAuthnContext);
    authRequest.setID(randId);
    authRequest.setVersion(SAMLVersion.VERSION_20);
    String stringRep = authRequest.toString();

    if (LOG.isDebugEnabled()) {
        LOG.debug("New AuthnRequestImpl: " + stringRep);
        LOG.debug("Assertion Consumer Service URL: " + authRequest.getAssertionConsumerServiceURL());
    }

    // Now we must build our representation to put into the html form to be submitted to the idp
    MarshallerFactory mfact = org.opensaml.Configuration.getMarshallerFactory();
    Marshaller marshaller = (Marshaller) mfact.getMarshaller(authRequest);
    if (marshaller == null) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Failed to get marshaller for " + authRequest);
        }
        throw new XWikiException(XWikiException.MODULE_XWIKI_USER, XWikiException.ERROR_XWIKI_USER_INIT,
                "Failed to get marshaller for " + authRequest);
    } else {
        Element authDOM;
        String samlRequest = "";
        try {
            authDOM = marshaller.marshall(authRequest);
            StringWriter rspWrt = new StringWriter();
            XMLHelper.writeNode(authDOM, rspWrt);
            String messageXML = rspWrt.toString();
            Deflater deflater = new Deflater(Deflater.DEFLATED, true);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream,
                    deflater);
            deflaterOutputStream.write(messageXML.getBytes());
            deflaterOutputStream.close();
            samlRequest = Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);
            String outputString = new String(byteArrayOutputStream.toByteArray());
            samlRequest = URLEncoder.encode(samlRequest);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Converted AuthRequest: " + messageXML);
                // LOG.debug("samlRequest: " + samlRequest);
            }
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Failed to marshaller request for " + authRequest);
            }
            throw new XWikiException(XWikiException.MODULE_XWIKI_USER, XWikiException.ERROR_XWIKI_USER_INIT,
                    "Failed to marshaller request for " + authRequest);
        }

        String actionURL = getSAMLAuthenticatorURL(context);
        String url = actionURL + "?SAMLRequest=" + samlRequest;
        if (LOG.isInfoEnabled()) {
            LOG.info("Saml request sent to " + url);
        }
        try {
            response.sendRedirect(url);
            context.setFinished(true);
        } catch (IOException e) {
        }
    }
}

From source file:fr.mby.saml2.sp.impl.helper.SamlHelper.java

/**
 * Encode a SAML2 request for the HTTP-redirect binding. The encoded message is not URL encoded !
 * //ww w  .  j a v  a  2  s .c  o m
 * @param request
 *            the request
 * @return the encoded request
 * @throws IOException
 */
public static String httpRedirectEncode(final String samlMessage) throws IOException {
    String deflatedRequest = null;
    ByteArrayOutputStream byteArrayOutputStream = null;
    DeflaterOutputStream deflaterOutputStream = null;

    try {
        final Deflater deflater = new Deflater(Deflater.DEFLATED, true);
        byteArrayOutputStream = new ByteArrayOutputStream();
        deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);

        // Deflated then Base 64 encoded then Url Encoded for HTTP REDIRECT Binding
        deflaterOutputStream.write(samlMessage.getBytes());
        deflaterOutputStream.finish();
        deflater.finish();

        deflatedRequest = Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);

        if (SamlHelper.LOGGER.isDebugEnabled()) {
            SamlHelper.LOGGER.debug(String.format("SAML 2.0 Request: %s", samlMessage));
            SamlHelper.LOGGER.debug(String.format("Encoded HTTP-Redirect Request: %s", deflatedRequest));
        }
    } finally {
        if (byteArrayOutputStream != null) {
            byteArrayOutputStream.close();
        }
        if (deflaterOutputStream != null) {
            deflaterOutputStream.close();
        }
    }

    return deflatedRequest;
}