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.wso2.carbon.identity.sso.saml.tomcat.agent.SSOManager.java

private String encodeRequestMessage(RequestAbstractType requestMessage)
        throws MarshallingException, IOException {

    Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(requestMessage);
    Element authDOM = marshaller.marshall(requestMessage);

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

    StringWriter rspWrt = new StringWriter();
    XMLHelper.writeNode(authDOM, rspWrt);
    deflaterOutputStream.write(rspWrt.toString().getBytes());
    deflaterOutputStream.close();//  www.ja v  a 2  s .  c  o m

    /* Encoding the compressed message */
    String encodedRequestMessage = Base64.encodeBytes(byteArrayOutputStream.toByteArray(),
            Base64.DONT_BREAK_LINES);
    return URLEncoder.encode(encodedRequestMessage, "UTF-8").trim();
}

From source file:org.apache.fop.render.pdf.ImageRawPNGAdapter.java

/** {@inheritDoc} */
public void outputContents(OutputStream out) throws IOException {
    InputStream in = ((ImageRawStream) image).createInputStream();

    try {// ww  w .  j a  va 2  s.  c  o  m
        if (numberOfInterleavedComponents == 1 || numberOfInterleavedComponents == 3) {
            // means we have Gray, RGB, or Palette
            IOUtils.copy(in, out);
        } else {
            // means we have Gray + alpha or RGB + alpha
            // TODO: since we have alpha here do this when the alpha channel is extracted
            int numBytes = numberOfInterleavedComponents - 1; // 1 for Gray, 3 for RGB
            int numColumns = image.getSize().getWidthPx();
            InflaterInputStream infStream = new InflaterInputStream(in, new Inflater());
            DataInputStream dataStream = new DataInputStream(infStream);
            int offset = 0;
            int bytesPerRow = numberOfInterleavedComponents * numColumns;
            int filter;
            // here we need to inflate the PNG pixel data, which includes alpha, separate the alpha
            // channel and then deflate the RGB channels back again
            DeflaterOutputStream dos = new DeflaterOutputStream(out, new Deflater());
            while ((filter = dataStream.read()) != -1) {
                byte[] bytes = new byte[bytesPerRow];
                dataStream.readFully(bytes, 0, bytesPerRow);
                dos.write((byte) filter);
                for (int j = 0; j < numColumns; j++) {
                    dos.write(bytes, offset, numBytes);
                    offset += numberOfInterleavedComponents;
                }
                offset = 0;
            }
            dos.close();
        }
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:org.wso2.carbon.identity.auth.saml2.common.SAML2AuthUtils.java

public static String encodeForRedirect(RequestAbstractType requestMessage) {

    Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(requestMessage);
    Element authDOM = null;//from w  ww.j  av a2s  . c  o m
    try {
        authDOM = marshaller.marshall(requestMessage);

        /* Compress the message */
        Deflater deflater = new Deflater(Deflater.DEFLATED, true);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
        StringWriter rspWrt = new StringWriter();
        XMLHelper.writeNode(authDOM, rspWrt);
        deflaterOutputStream.write(rspWrt.toString().getBytes(StandardCharsets.UTF_8));
        deflaterOutputStream.close();

        /* Encoding the compressed message */
        String encodedRequestMessage = Base64.encodeBytes(byteArrayOutputStream.toByteArray(),
                Base64.DONT_BREAK_LINES);

        byteArrayOutputStream.write(byteArrayOutputStream.toByteArray());
        byteArrayOutputStream.toString(StandardCharsets.UTF_8.toString());

        // logger saml
        if (logger.isDebugEnabled()) {
            logger.debug("SAML Request  :  " + rspWrt.toString());
        }

        return URLEncoder.encode(encodedRequestMessage, "UTF-8").trim();

    } catch (MarshallingException | IOException e) {
        throw new IdentityRuntimeException("Error occurred while encoding SAML request", e);
    }
}

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 w w. ja  va  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:org.socraticgrid.workbench.security.wso2.SamlConsumer.java

@SuppressWarnings("deprecation")
private String encodeAuthnRequest(AuthnRequest authnRequest) throws MarshallingException, IOException {
    String requestMessage;/*  www.  j av a 2  s  . com*/
    // Pass authnRequest object to a DOM element
    Marshaller marshaller = org.opensaml.Configuration.getMarshallerFactory().getMarshaller(authnRequest);
    org.w3c.dom.Element authDOM = null;

    authDOM = marshaller.marshall(authnRequest);

    // Get the string
    StringWriter rspWrt = new StringWriter();
    XMLHelper.writeNode(authDOM, rspWrt);
    requestMessage = rspWrt.toString();

    // DEFLATE compression of the message, byteArrayOutputStream will holds
    // the compressed bytes
    Deflater deflater = new Deflater(Deflater.DEFLATED, true);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);

    deflaterOutputStream.write(requestMessage.getBytes());
    deflaterOutputStream.close();

    // Encoding the compressed message
    String encodedRequestMessage = Base64.encodeBytes(byteArrayOutputStream.toByteArray(),
            Base64.DONT_BREAK_LINES);
    encodedRequestMessage = URLEncoder.encode(encodedRequestMessage).trim();

    return encodedRequestMessage;
}

From source file:PNGDecoder.java

/** main encoding method (stays blocked till encoding is finished).
 * @param image BufferedImage to encode/*from   w  w  w.  j  a  v  a2 s  .  c o  m*/
 * @throws IOException IOException
 */
public void encode(BufferedImage image) throws IOException {
    int width = image.getWidth(null);
    int height = image.getHeight(null);
    final byte id[] = { -119, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13 };
    write(id);
    crc.reset();
    write("IHDR".getBytes());
    write(width);
    write(height);
    byte head[] = null;
    switch (mode) {
    case BW_MODE:
        head = new byte[] { 1, 0, 0, 0, 0 };
        break;
    case GREYSCALE_MODE:
        head = new byte[] { 8, 0, 0, 0, 0 };
        break;
    case COLOR_MODE:
        head = new byte[] { 8, 2, 0, 0, 0 };
        break;
    }
    write(head);
    write((int) crc.getValue());
    ByteArrayOutputStream compressed = new ByteArrayOutputStream(65536);
    BufferedOutputStream bos = new BufferedOutputStream(new DeflaterOutputStream(compressed, new Deflater(9)));
    int pixel;
    int color;
    int colorset;
    switch (mode) {
    case BW_MODE:
        int rest = width % 8;
        int bytes = width / 8;
        for (int y = 0; y < height; y++) {
            bos.write(0);
            for (int x = 0; x < bytes; x++) {
                colorset = 0;
                for (int sh = 0; sh < 8; sh++) {
                    pixel = image.getRGB(x * 8 + sh, y);
                    color = ((pixel >> 16) & 0xff);
                    color += ((pixel >> 8) & 0xff);
                    color += (pixel & 0xff);
                    colorset <<= 1;
                    if (color >= 3 * 128)
                        colorset |= 1;
                }
                bos.write((byte) colorset);
            }
            if (rest > 0) {
                colorset = 0;
                for (int sh = 0; sh < width % 8; sh++) {
                    pixel = image.getRGB(bytes * 8 + sh, y);
                    color = ((pixel >> 16) & 0xff);
                    color += ((pixel >> 8) & 0xff);
                    color += (pixel & 0xff);
                    colorset <<= 1;
                    if (color >= 3 * 128)
                        colorset |= 1;
                }
                colorset <<= 8 - rest;
                bos.write((byte) colorset);
            }
        }
        break;
    case GREYSCALE_MODE:
        for (int y = 0; y < height; y++) {
            bos.write(0);
            for (int x = 0; x < width; x++) {
                pixel = image.getRGB(x, y);
                color = ((pixel >> 16) & 0xff);
                color += ((pixel >> 8) & 0xff);
                color += (pixel & 0xff);
                bos.write((byte) (color / 3));
            }
        }
        break;
    case COLOR_MODE:
        for (int y = 0; y < height; y++) {
            bos.write(0);
            for (int x = 0; x < width; x++) {
                pixel = image.getRGB(x, y);
                bos.write((byte) ((pixel >> 16) & 0xff));
                bos.write((byte) ((pixel >> 8) & 0xff));
                bos.write((byte) (pixel & 0xff));
            }
        }
        break;
    }
    bos.close();
    write(compressed.size());
    crc.reset();
    write("IDAT".getBytes());
    write(compressed.toByteArray());
    write((int) crc.getValue());
    write(0);
    crc.reset();
    write("IEND".getBytes());
    write((int) crc.getValue());
    out.close();
}

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

/**
 * Create new nbt output stream for given file, and write nbt tag to it.
 *
 * @param tag    nbt tag to write.//w  ww.  j  a v  a2 s  .  c  o m
 * @param file   data file to be used.
 * @param append if new data should be appended to existing one.
 * @param def    deflater to be used.
 *
 * @return created NbtOutputStream.
 *
 * @throws IOException if any write operation failed.
 */
public static NbtOutputStream writeDeflated(final NbtTag tag, final File file, final boolean append,
        final Deflater def) throws IOException {
    createFile(file);
    final NbtOutputStream out = new NbtOutputStream(
            new DeflaterOutputStream(new FileOutputStream(file, append), def));
    out.write(tag);
    return out;
}

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 a  va  2 s  .  co  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:org.slc.sli.api.security.saml.SamlHelper.java

/**
 * Converts plain-text xml to SAML-spec compliant string for HTTP-Redirect binding
 *
 * @param xml/*  w w w  . java  2s  . c  o m*/
 * @return
 * @throws IOException
 */
private String xmlToEncodedString(String xml) throws IOException {
    Deflater deflater = new Deflater(Deflater.DEFLATED, true);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
    deflaterOutputStream.write(xml.getBytes());
    deflaterOutputStream.close();
    String base64 = Base64.encodeBase64String(byteArrayOutputStream.toByteArray());
    return URLEncoder.encode(base64, "UTF-8");
}