Example usage for java.util.zip DeflaterOutputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Writes remaining compressed data to the output stream and closes the underlying stream.

Usage

From source file:com.cloud.agent.api.SecurityGroupRulesCmd.java

public String compressStringifiedRules() {
    StringBuilder ruleBuilder = new StringBuilder();
    for (SecurityGroupRulesCmd.IpPortAndProto ipPandP : getIngressRuleSet()) {
        ruleBuilder.append("I:").append(ipPandP.getProto()).append(":").append(ipPandP.getStartPort())
                .append(":").append(ipPandP.getEndPort()).append(":");
        for (String cidr : ipPandP.getAllowedCidrs()) {
            ruleBuilder.append(cidr).append(",");
        }//from   w ww.j av  a 2s  .  c  o m
        ruleBuilder.append("NEXT");
        ruleBuilder.append(" ");
    }
    for (SecurityGroupRulesCmd.IpPortAndProto ipPandP : getEgressRuleSet()) {
        ruleBuilder.append("E:").append(ipPandP.getProto()).append(":").append(ipPandP.getStartPort())
                .append(":").append(ipPandP.getEndPort()).append(":");
        for (String cidr : ipPandP.getAllowedCidrs()) {
            ruleBuilder.append(cidr).append(",");
        }
        ruleBuilder.append("NEXT");
        ruleBuilder.append(" ");
    }
    String stringified = ruleBuilder.toString();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        //Note : not using GZipOutputStream since that is for files
        //GZipOutputStream gives a different header, although the compression is the same
        DeflaterOutputStream dzip = new DeflaterOutputStream(out);
        dzip.write(stringified.getBytes());
        dzip.close();
    } catch (IOException e) {
        s_logger.warn("Exception while compressing security group rules");
        return null;
    }
    return Base64.encodeBase64String(out.toByteArray());
}

From source file:com.alibaba.citrus.service.requestcontext.session.valueencoder.AbstractSessionValueEncoder.java

private byte[] compress(byte[] data) throws SessionValueEncoderException {
    if (!doCompress()) {
        return data;
    }//from w w  w . ja  v  a  2  s.com

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Deflater def = new Deflater(Deflater.BEST_COMPRESSION, false);
    DeflaterOutputStream dos = new DeflaterOutputStream(baos, def);

    try {
        dos.write(data);
    } catch (Exception e) {
        throw new SessionValueEncoderException(e);
    } finally {
        try {
            dos.close();
        } catch (IOException e) {
        }

        def.end();
    }

    return baos.toByteArray();
}

From source file:de.tntinteractive.portalsammler.engine.SecureStore.java

private byte[] compress(final byte[] content) throws IOException {
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    final DeflaterOutputStream deflate = new DeflaterOutputStream(buffer);
    deflate.write(content);/*  w  w w .j a  v a 2  s .c om*/
    deflate.close();
    return buffer.toByteArray();
}

From source file:com.enonic.esl.xml.XMLTool.java

public static byte[] documentToDeflatedBytes(Document doc) {
    ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
    Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
    DeflaterOutputStream dos = new DeflaterOutputStream(out, deflater);
    printDocument(dos, doc, null, 0, false);
    try {/*w  w  w. j a v a 2  s. c om*/
        dos.close();
    } catch (IOException e) {
        throw new XMLToolException("Failed to close deflater output stream", e);
    }
    return out.toByteArray();
}

From source file:com.tremolosecurity.proxy.auth.saml2.Saml2SingleLogout.java

@Override
public void handleLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    if (request == null || response == null) {
        //do nothing
        return;/*from  w w  w  .  ja  va 2  s. co  m*/
    }

    String xmlAlg = SAML2Auth.xmlDigSigAlgs.get(digSigAlg);

    if (xmlAlg == null) {
        throw new ServletException("Unknown Signiture algorithm : '" + digSigAlg + "'");
    }

    String javaAlg = SAML2Auth.javaDigSigAlgs.get(digSigAlg);

    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);

    ConfigManager cfgMgr = holder.getConfig();

    LogoutRequestBuilder lrb = new LogoutRequestBuilder();
    LogoutRequest lr = lrb.buildObject();

    DateTime dt = new DateTime();
    lr.setIssueInstant(dt);

    lr.setDestination(logoutURL);

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

    String id = "f" + Hex.encodeHexString(idBytes);
    lr.setID(id);

    IssuerBuilder ib = new IssuerBuilder();
    Issuer issuer = ib.buildObject();
    issuer.setValue(assertionConsumerServiceURL);
    lr.setIssuer(issuer);

    NameIDBuilder nidbpb = new NameIDBuilder();
    NameID nid = nidbpb.buildObject();
    //nidp.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
    nid.setFormat(nameIDFormat);

    //nid.setSPNameQualifier(assertionConsumerServiceURL);
    nid.setValue(nameID);
    lr.setNameID(nid);

    SessionIndexBuilder sib = new SessionIndexBuilder();
    SessionIndex si = sib.buildObject();
    si.setSessionIndex(sessionIndex);
    lr.getSessionIndexes().add(si);

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

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

        String xml = OpenSAMLUtils.xml2str(lr);
        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"));

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

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

        PrivateKey sigKey = cfgMgr.getPrivateKey(signingKeyAlias);

        if (sigKey == null) {
            throw new ServletException("Signing Key : '" + signingKeyAlias + "' not found");
        }

        signer.initSign(sigKey);
        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(logoutURL).append("?").append(query.toString());

        if (logger.isDebugEnabled()) {
            logger.debug("Logout URL : '" + redirURL.toString() + "'");
        }

        //((ProxyResponse) response).removeHeader("Location");
        response.sendRedirect(redirURL.toString());

    } catch (Exception e) {
        throw new ServletException("Could not generate logout request", e);
    }

}

From source file:com.alibaba.citrus.service.requestcontext.session.encoder.AbstractSerializationEncoder.java

/** ? */
public String encode(Map<String, Object> attrs, StoreContext storeContext) throws SessionEncoderException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // 1. ?//  w  w w. j a v a  2s  . com
    // 2. 
    Deflater def = new Deflater(Deflater.BEST_COMPRESSION, false);
    DeflaterOutputStream dos = new DeflaterOutputStream(baos, def);

    try {
        serializer.serialize(assertNotNull(attrs, "objectToEncode is null"), dos);
    } catch (Exception e) {
        throw new SessionEncoderException("Failed to encode session state", e);
    } finally {
        try {
            dos.close();
        } catch (IOException e) {
        }

        def.end();
    }

    byte[] plaintext = baos.toByteArray().toByteArray();

    // 3. 
    byte[] cryptotext = encrypt(plaintext);

    // 4. base64?
    try {
        String encodedValue = new String(Base64.encodeBase64(cryptotext, false), "ISO-8859-1");

        return URLEncoder.encode(encodedValue, "ISO-8859-1");
    } catch (UnsupportedEncodingException e) {
        throw new SessionEncoderException("Failed to encode session state", 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 !
 * /*from   w  w w .  j  av  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;
}

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

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

    try {// w  w  w.  j  a va 2  s .  c o 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:com.giri.target.svr.SeleniumTestRunner.java

private String toB64Text(final String text, final boolean compress) throws Exception {
    final byte[] inputbs = text.getBytes(Charset.forName("UTF-8"));

    final byte[] bytesToConvert;
    if (compress) {
        final ByteArrayOutputStream bout = new ByteArrayOutputStream();
        final Deflater d = new Deflater();
        final DeflaterOutputStream dout = new DeflaterOutputStream(bout, d);
        dout.write(inputbs);//from   w ww  .j  a  v a2 s. c  o m
        dout.close();
        bout.flush();
        bytesToConvert = bout.toByteArray();
    } else {
        bytesToConvert = inputbs;
    }

    final byte[] s64encBts = Base64.encodeBase64(bytesToConvert);

    return new String(s64encBts);
}

From source file:fr.mby.saml2.sp.opensaml.helper.OpenSamlHelper.java

/**
 * Encode a SAML2 request for the HTTP-redirect binding.
 * /*from w  w  w  .ja  v  a 2 s  . c o  m*/
 * @param request the request
 * @return the encoded request
 * @throws IOException
 */
public static String httpRedirectEncode(final SignableSAMLObject request) throws IOException {
    String urlEncodedRequest = null;
    ByteArrayOutputStream byteArrayOutputStream = null;
    DeflaterOutputStream deflaterOutputStream = null;

    if (request != null) {
        try {
            // Now we must build our representation to put into the html form to
            // be submitted to the idp
            Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(request);
            org.w3c.dom.Element authDOM = marshaller.marshall(request);

            //Signing the request
            Signature signature = request.getSignature();
            Assert.notNull(signature, "The request is not signed !");
            Signer.signObject(signature);

            StringWriter rspWrt = new StringWriter();
            XMLHelper.writeNode(authDOM, rspWrt);
            String messageXML = rspWrt.toString();

            // Encode XML message
            urlEncodedRequest = SamlHelper.httpRedirectEncode(messageXML);

        } catch (MarshallingException e) {
            OpenSamlHelper.LOGGER.error("Error while marshalling SAML 2.0 Request !", e);
        } catch (SignatureException e) {
            OpenSamlHelper.LOGGER.error("Error while signing SAML 2.0 Request !", e);
        } finally {
            if (byteArrayOutputStream != null) {
                byteArrayOutputStream.close();
            }
            if (deflaterOutputStream != null) {
                deflaterOutputStream.close();
            }
        }
    }

    return urlEncodedRequest;
}