Example usage for java.util.zip DeflaterOutputStream write

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

Introduction

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

Prototype

public void write(int b) throws IOException 

Source Link

Document

Writes a byte to the compressed output stream.

Usage

From source file:com.tremolosecurity.idp.providers.OpenIDConnectIdP.java

private void postResponse(OpenIDConnectTransaction transaction, HttpServletRequest request,
        HttpServletResponse response, AuthInfo authInfo, UrlHolder holder) throws Exception {
    //first generate a lastmile token
    OpenIDConnectTrust trust = trusts.get(transaction.getClientID());

    ConfigManager cfgMgr = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);

    DateTime now = new DateTime();
    DateTime notBefore = now.minus(trust.getCodeTokenTimeToLive());
    DateTime notAfter = now.plus(trust.getCodeTokenTimeToLive());

    com.tremolosecurity.lastmile.LastMile lmreq = new com.tremolosecurity.lastmile.LastMile(
            request.getRequestURI(), notBefore, notAfter, authInfo.getAuthLevel(), authInfo.getAuthMethod());
    lmreq.getAttributes().add(new Attribute("dn", authInfo.getUserDN()));
    Attribute attr = new Attribute("scope");
    attr.getValues().addAll(transaction.getScope());
    lmreq.getAttributes().add(attr);//w w w . j  a  va2s.c o  m
    if (transaction.getNonce() != null) {
        lmreq.getAttributes().add(new Attribute("nonce", transaction.getNonce()));
    }
    SecretKey key = cfgMgr.getSecretKey(trust.getCodeLastmileKeyName());

    String codeToken = lmreq.generateLastMileToken(key);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    DeflaterOutputStream compressor = new DeflaterOutputStream(baos,
            new Deflater(Deflater.BEST_COMPRESSION, true));

    compressor.write(org.bouncycastle.util.encoders.Base64.decode(codeToken.getBytes("UTF-8")));
    compressor.flush();
    compressor.close();

    String b64 = new String(org.bouncycastle.util.encoders.Base64.encode(baos.toByteArray()));

    StringBuffer b = new StringBuffer();
    b.append(transaction.getRedirectURI()).append("?").append("code=").append(URLEncoder.encode(b64, "UTF-8"))
            .append("&state=").append(URLEncoder.encode(transaction.getState(), "UTF-8"));

    response.sendRedirect(b.toString());

}

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

private String encodeRequestMessage(RequestAbstractType requestMessage) {

    try {// w  w  w .ja  v a 2s.c  om
        DefaultBootstrap.bootstrap();
    } catch (ConfigurationException e) {
        log.error("Error while initializing opensaml library", e);
        return null;
    }
    Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(requestMessage);
    Element authDOM = null;
    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);
        return URLEncoder.encode(encodedRequestMessage, "UTF-8").trim();

    } catch (MarshallingException e) {
        log.error("Error occurred while encoding SAML request", e);
    } catch (UnsupportedEncodingException e) {
        log.error("Error occurred while encoding SAML request", e);
    } catch (IOException e) {
        log.error("Error occurred while encoding SAML request", e);
    }
    return null;
}

From source file:nl.nn.adapterframework.util.JdbcUtil.java

public static void putStringAsBlob(IDbmsSupport dbmsSupport, final ResultSet rs, int columnIndex,
        String content, String charset, boolean compressBlob) throws IOException, JdbcException, SQLException {
    if (content != null) {
        Object blobHandle = dbmsSupport.getBlobUpdateHandle(rs, columnIndex);
        OutputStream out = dbmsSupport.getBlobOutputStream(rs, columnIndex, blobHandle);
        if (charset == null) {
            charset = Misc.DEFAULT_INPUT_STREAM_ENCODING;
        }/*  ww w. j a v  a2  s . co  m*/
        if (compressBlob) {
            DeflaterOutputStream dos = new DeflaterOutputStream(out);
            dos.write(content.getBytes(charset));
            dos.close();
        } else {
            out.write(content.getBytes(charset));
        }
        out.close();
        dbmsSupport.updateBlob(rs, columnIndex, blobHandle);
    } else {
        log.warn("content to store in blob was null");
    }
}

From source file:nl.nn.adapterframework.util.JdbcUtil.java

public static void putByteArrayAsBlob(IDbmsSupport dbmsSupport, final ResultSet rs, int columnIndex,
        byte content[], boolean compressBlob) throws IOException, JdbcException, SQLException {
    if (content != null) {
        Object blobHandle = dbmsSupport.getBlobUpdateHandle(rs, columnIndex);
        OutputStream out = dbmsSupport.getBlobOutputStream(rs, columnIndex, blobHandle);
        if (compressBlob) {
            DeflaterOutputStream dos = new DeflaterOutputStream(out);
            dos.write(content);
            dos.close();//from   ww  w .  j  av a2 s  .  c o  m
        } else {
            out.write(content);
        }
        out.close();
        dbmsSupport.updateBlob(rs, columnIndex, blobHandle);
    } else {
        log.warn("content to store in blob was null");
    }
}

From source file:org.apache.cloudstack.utils.auth.SAMLUtils.java

public static String encodeSAMLRequest(XMLObject authnRequest) throws MarshallingException, IOException {
    Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(authnRequest);
    Element authDOM = marshaller.marshall(authnRequest);
    StringWriter requestWriter = new StringWriter();
    XMLHelper.writeNode(authDOM, requestWriter);
    String requestMessage = requestWriter.toString();
    Deflater deflater = new Deflater(Deflater.DEFLATED, true);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
    deflaterOutputStream.write(requestMessage.getBytes());
    deflaterOutputStream.close();//w  ww  . j  av a2  s .c o  m
    String encodedRequestMessage = Base64.encodeBytes(byteArrayOutputStream.toByteArray(),
            Base64.DONT_BREAK_LINES);
    encodedRequestMessage = URLEncoder.encode(encodedRequestMessage, HttpUtils.UTF_8).trim();
    return encodedRequestMessage;
}

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

/** {@inheritDoc} */
public void setup(PDFDocument doc) {
    super.setup(doc);
    ColorModel cm = ((ImageRawPNG) this.image).getColorModel();
    if (cm instanceof IndexColorModel) {
        numberOfInterleavedComponents = 1;
    } else {//from w  ww  . ja v  a2s . c  om
        // this can be 1 (gray), 2 (gray + alpha), 3 (rgb) or 4 (rgb + alpha)
        // numberOfInterleavedComponents = (cm.hasAlpha() ? 1 : 0) + cm.getNumColorComponents();
        numberOfInterleavedComponents = cm.getNumComponents();
    }

    // set up image compression for non-alpha channel
    FlateFilter flate;
    try {
        flate = new FlateFilter();
        flate.setApplied(true);
        flate.setPredictor(FlateFilter.PREDICTION_PNG_OPT);
        if (numberOfInterleavedComponents < 3) {
            // means palette (1) or gray (1) or gray + alpha (2)
            flate.setColors(1);
        } else {
            // means rgb (3) or rgb + alpha (4)
            flate.setColors(3);
        }
        flate.setColumns(image.getSize().getWidthPx());
        flate.setBitsPerComponent(this.getBitsPerComponent());
    } catch (PDFFilterException e) {
        throw new RuntimeException("FlateFilter configuration error", e);
    }
    this.pdfFilter = flate;
    this.disallowMultipleFilters();

    // Handle transparency channel if applicable; note that for palette images the transparency is
    // not TRANSLUCENT
    if (cm.hasAlpha() && cm.getTransparency() == ColorModel.TRANSLUCENT) {
        doc.getProfile().verifyTransparencyAllowed(image.getInfo().getOriginalURI());
        // TODO: Implement code to combine image with background color if transparency is not allowed
        // here we need to inflate the PNG pixel data, which includes alpha, separate the alpha channel
        // and then deflate it back again
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DeflaterOutputStream dos = new DeflaterOutputStream(baos, new Deflater());
        InputStream in = ((ImageRawStream) image).createInputStream();
        try {
            InflaterInputStream infStream = new InflaterInputStream(in, new Inflater());
            DataInputStream dataStream = new DataInputStream(infStream);
            // offset is the byte offset of the alpha component
            int offset = numberOfInterleavedComponents - 1; // 1 for GA, 3 for RGBA
            int numColumns = image.getSize().getWidthPx();
            int bytesPerRow = numberOfInterleavedComponents * numColumns;
            int filter;
            // read line by line; the first byte holds the filter
            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, 1);
                    offset += numberOfInterleavedComponents;
                }
                offset = numberOfInterleavedComponents - 1;
            }
            dos.close();
        } catch (IOException e) {
            throw new RuntimeException("Error processing transparency channel:", e);
        } finally {
            IOUtils.closeQuietly(in);
        }
        // set up alpha channel compression
        FlateFilter transFlate;
        try {
            transFlate = new FlateFilter();
            transFlate.setApplied(true);
            transFlate.setPredictor(FlateFilter.PREDICTION_PNG_OPT);
            transFlate.setColors(1);
            transFlate.setColumns(image.getSize().getWidthPx());
            transFlate.setBitsPerComponent(this.getBitsPerComponent());
        } catch (PDFFilterException e) {
            throw new RuntimeException("FlateFilter configuration error", e);
        }
        BitmapImage alphaMask = new BitmapImage("Mask:" + this.getKey(), image.getSize().getWidthPx(),
                image.getSize().getHeightPx(), baos.toByteArray(), null);
        alphaMask.setPDFFilter(transFlate);
        alphaMask.disallowMultipleFilters();
        alphaMask.setColorSpace(new PDFDeviceColorSpace(PDFDeviceColorSpace.DEVICE_GRAY));
        softMask = doc.addImage(null, alphaMask).makeReference();
    }
}

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

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

    try {/*from  ww w. ja  v a2s  .  c om*/
        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.apache.fop.render.ps.ImageEncoderPNG.java

/** {@inheritDoc} */
public void writeTo(OutputStream out) throws IOException {
    // TODO: refactor this code with equivalent PDF code
    InputStream in = ((ImageRawStream) image).createInputStream();
    try {//ww w .ja  v a  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
            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
            // TODO: not using the baos below and using the original out instead (as happens in PDF)
            // would be preferable but that does not work with the rest of the postscript code; this
            // needs to be revisited
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DeflaterOutputStream dos = new DeflaterOutputStream(/* out */baos, 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();
            IOUtils.copy(new ByteArrayInputStream(baos.toByteArray()), out);
        }
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:org.apache.tez.common.TezCommonUtils.java

@Private
public static ByteString compressByteArrayToByteString(byte[] inBytes, Deflater deflater) throws IOException {
    deflater.reset();//  w  w w.  ja  v a  2  s . co m
    ByteString.Output os = ByteString.newOutput();
    DeflaterOutputStream compressOs = null;
    try {
        compressOs = new DeflaterOutputStream(os, deflater);
        compressOs.write(inBytes);
        compressOs.finish();
        ByteString byteString = os.toByteString();
        return byteString;
    } finally {
        if (compressOs != null) {
            compressOs.close();
        }
    }
}

From source file:org.fejoa.library.messages.ZipEnvelope.java

static public byte[] zip(byte[] data, boolean isRawData) throws JSONException, IOException {
    JSONObject object = new JSONObject();
    object.put(Envelope.PACK_TYPE_KEY, ZIP_TYPE);
    if (isRawData)
        object.put(Envelope.CONTAINS_DATA_KEY, 1);
    object.put(ZIP_FORMAT_KEY, ZIP_FORMAT);
    String header = object.toString() + "\n";

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    outStream.write(header.getBytes());//from w w  w  .  jav  a 2s  .com
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(outStream);
    deflaterOutputStream.write(data);
    deflaterOutputStream.finish();
    outStream.close();
    return outStream.toByteArray();
}