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.codice.ddf.security.common.jaxrs.RestSecurity.java

/**
 * Deflates a value and Base64 encodes the result.
 *
 * @param value value to deflate and Base64 encode
 * @return String/*from  w w  w. j av  a2  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, GZIP_COMPATIBLE))) {
        tokenStream.write(value.getBytes(StandardCharsets.UTF_8));
        tokenStream.close();

        return Base64.getEncoder().encodeToString(valueBytes.toByteArray());
    }
}

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

private byte[] compress(byte[] data) throws SessionValueEncoderException {
    if (!doCompress()) {
        return data;
    }/*  www  .ja  v a 2 s .c om*/

    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:org.resthub.rpc.AMQPProxy.java

/**
 * Create the request message body//from  w  w w.j a  v a 2 s .co m
 *
 * @param method
 * @param args
 * @return
 * @throws IOException
 */
private byte[] createRequestBody(Method method, Object[] args) throws IOException {
    ByteArrayOutputStream payload = new ByteArrayOutputStream(256);
    OutputStream os;
    if (_factory.isCompressed()) {
        Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true);
        os = new DeflaterOutputStream(payload, deflater);
    } else {
        os = payload;
    }

    _factory.getSerializationHandler().writeMethodCall(method, args, os);

    return payload.toByteArray();
}

From source file:org.jbpm.bpel.persistence.db.type.ElementType.java

public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
    // easy way out: null value
    if (value == null) {
        st.setNull(index, SQL_TYPES[0]);
        if (log.isTraceEnabled())
            log.trace("binding null to parameter: " + index);
    } else {//from   w w w .  ja  v a 2s  . c  o m
        Element element = (Element) value;
        try {
            // create identity transformer
            Transformer idTransformer = XmlUtil.getTransformerFactory().newTransformer();

            // allocate memory result stream
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

            // deflate if requested
            Integer deflateLevel = getXmlDeflateLevel();
            if (deflateLevel != null) {
                // introduce deflater stream
                Deflater deflater = new Deflater(deflateLevel.intValue());
                OutputStream deflaterStream = new DeflaterOutputStream(byteStream, deflater);
                // write element to stream
                idTransformer.transform(new DOMSource(element), new StreamResult(deflaterStream));
                // release resources
                try {
                    deflaterStream.close();
                } catch (IOException e) {
                    // should not happen
                    throw new AssertionError(e);
                }
                deflater.end();
            } else {
                // write element to stream
                idTransformer.transform(new DOMSource(element), new StreamResult(byteStream));
                // noop
                // byteStream.close();
            }

            // extract contents of result stream
            st.setBytes(index, byteStream.toByteArray());
            if (log.isTraceEnabled())
                log.trace("binding '" + byteStream + "' to parameter: " + index);
        } catch (TransformerException e) {
            throw new HibernateException("could not transform to xml stream: " + element, e);
        }
    }
}

From source file:org.asimba.wa.integrationtest.saml2.model.AuthnRequest.java

/**
 * Get String with the SAML2 AuthnRequest message
 * @param format -1=plain, 1=base64/*from  w w w. j a v a  2  s  .c  o m*/
 * @return
 * @throws XMLStreamException
 * @throws IOException
 */
public String getRequest(int format) throws XMLStreamException, IOException {
    _logger.info("For ID: " + this._id);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Deflater compresser = new Deflater(Deflater.BEST_COMPRESSION, true);
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(baos, compresser);
    StringWriter sw = new StringWriter();

    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    XMLStreamWriter writer = null;

    // ugly but effective:
    if (format == base64) {
        writer = factory.createXMLStreamWriter(deflaterOutputStream);
    } else {
        writer = factory.createXMLStreamWriter(sw);
    }

    writer.writeStartElement("samlp", "AuthnRequest", "urn:oasis:names:tc:SAML:2.0:protocol");
    writer.writeNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");

    writer.writeAttribute("ID", _id);
    writer.writeAttribute("Version", "2.0");
    writer.writeAttribute("IssueInstant", this._issueInstant);
    writer.writeAttribute("ProtocolBinding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    writer.writeAttribute("AssertionConsumerServiceURL", _acsUrl);

    writeIssuer(writer);

    writeNameIDPolicy(writer);

    writeRequestedAuthnContext(writer);

    writer.writeEndElement();
    writer.flush();

    if (format == base64) {
        deflaterOutputStream.close();
        byte[] bain = baos.toByteArray();
        byte[] encoded = Base64.encodeBase64(bain, false);
        String result = new String(encoded, Charset.forName("UTF-8"));

        return result;
    } else {
        return sw.toString();
    }

}

From source file:name.npetrovski.jphar.DataEntry.java

private OutputStream getCompressorOutputStream(final OutputStream os, Compression.Type compression)
        throws IOException {
    switch (compression) {
    case ZLIB:/*w  w  w . j  a v a  2s  .c o  m*/
        return new DeflaterOutputStream(os, new Deflater(Deflater.DEFAULT_COMPRESSION, true));
    case BZIP:
        return new BZip2CompressorOutputStream(os);
    case NONE:
        return os;
    default:
        throw new IOException("Unsupported compression type.");
    }
}

From source file:org.wso2.carbon.appmgt.gateway.handlers.security.saml2.SAMLUtils.java

/**
 * Returns the marshalled and encoded SAML request.
 *
 * @param request/*from   www  .ja v a 2  s. co  m*/
 * @return
 * @throws SAMLException
 */
public static String marshallAndEncodeSAMLRequest(RequestAbstractType request) throws SAMLException {

    try {
        String marshalledRequest = SAMLSSOUtil.marshall(request);

        Deflater deflater = new Deflater(Deflater.DEFLATED, true);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
        deflaterOutputStream.write(marshalledRequest.getBytes("UTF-8"));
        deflaterOutputStream.close();

        String encodedRequestMessage = Base64.encodeBytes(byteArrayOutputStream.toByteArray(),
                Base64.DONT_BREAK_LINES);
        return URLEncoder.encode(encodedRequestMessage, "UTF-8").trim();

    } catch (IdentityException e) {
        throw new SAMLException("Can't marshall and encode SAML response", e);
    } catch (IOException e) {
        throw new SAMLException("Can't marshall and encode SAML response", e);
    }
}

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;//w  w w .  j a  v  a  2s  .  com
    }

    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:org.apache.flex.compiler.internal.embedding.transcoders.JPEGTranscoder.java

public static byte[] deflate(byte[] buf) throws IOException {
    Deflater deflater = new Deflater(Deflater.BEST_SPEED);
    DAByteArrayOutputStream out = new DAByteArrayOutputStream();
    DeflaterOutputStream deflaterStream = new DeflaterOutputStream(out, deflater);
    try {/*from  w w  w .j av  a 2 s. co m*/
        deflaterStream.write(buf, 0, buf.length);
        deflaterStream.finish();
        deflater.end();
    } finally {
        IOUtils.closeQuietly(deflaterStream);
    }
    return out.getDirectByteArray();
}

From source file:prz.PRZ.java

/**
 *
 * @param bytes/*from  w w  w.  jav  a 2  s  .  c om*/
 * @return
 */
public static byte[] huffman_test(byte[] bytes) {
    Deflater d = new Deflater(9, true);
    d.setStrategy(Deflater.HUFFMAN_ONLY);
    DeflaterOutputStream dfos;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        dfos = new DeflaterOutputStream(baos, d);
        dfos.write(bytes);
        dfos.finish();
        byte[] y = baos.toByteArray();
        System.out.println("HUFF-> BitLength:" + (bytes.length * 8) + "| BestLength: " + (y.length * 8)
                + "| Ratio: " + ((double) y.length / (bytes.length)));
        return y;
    } catch (IOException ex) {
        Logger.getLogger(PRZ.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}