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: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 ww w  .j a  va 2s  .  c om
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();
    }
}

From source file:org.simbasecurity.core.saml.SAMLServiceImpl.java

protected String encodeSAMLRequest(byte[] pSAMLRequest) throws RuntimeException {
    Base64 base64Encoder = new Base64();

    try {//from   ww w. j a  va  2  s.  c  o m
        ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
        Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true);

        DeflaterOutputStream def = new DeflaterOutputStream(byteArray, deflater);
        def.write(pSAMLRequest);
        def.close();
        byteArray.close();

        String stream = new String(base64Encoder.encode(byteArray.toByteArray()));

        return stream.trim();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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 ww . j a v  a 2  s .  co  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");
}

From source file:org.socraticgrid.workbench.security.wso2.Saml2Util.java

/**
 * Compressing and Encoding the response
 *
 * @param xmlString String to be encoded
 * @return compressed and encoded String
 *//*from w w w . j  a  va2 s  . com*/
public static String encode(String xmlString) throws Exception {
    Deflater deflater = new Deflater(Deflater.DEFLATED, true);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);

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

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

From source file:org.socraticgrid.workbench.security.wso2.SamlConsumer.java

@SuppressWarnings("deprecation")
private String encodeAuthnRequest(AuthnRequest authnRequest) throws MarshallingException, IOException {
    String requestMessage;//from   w  w  w. ja v  a  2s . c  o  m
    // 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:org.wso2.carbon.apim.sso.Util.java

/**
 * @param xmlString String to be encoded
 * @return//from w w w .  j  a v  a 2s. c o m
 */
public static String deflateAndEncode(String xmlString) throws Exception {
    Deflater deflater = new Deflater(Deflater.DEFLATED, true);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);

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

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

}

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

/**
 * Returns the marshalled and encoded SAML request.
 *
 * @param request/*from   www.j a  v a2  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:org.wso2.carbon.identity.application.authenticator.samlsso.manager.DefaultSAML2SSOManager.java

private String encodeRequestMessage(RequestAbstractType requestMessage) throws SAMLSSOException {

    Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(requestMessage);
    Element authDOM = null;// www  .j  a  v a2 s  . com
    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());
        deflaterOutputStream.close();

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

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

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

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

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

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;/*w w  w  .j  av a 2s.  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:org.wso2.carbon.identity.saml.inbound.util.SAMLSSOUtil.java

/**
 * Compresses the response String//from   w w  w  .  j  a  v  a  2  s . c o 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);
}