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:com.tremolosecurity.unison.u2f.util.U2fUtil.java

public static String encode(List<SecurityKeyData> devices, String encyrptionKeyName) throws Exception {
    ArrayList<KeyHolder> keys = new ArrayList<KeyHolder>();
    for (SecurityKeyData dr : devices) {
        KeyHolder kh = new KeyHolder();
        kh.setCounter(dr.getCounter());/*from   w  w  w  . j  a  va2 s  . c om*/
        kh.setEnrollmentTime(dr.getEnrollmentTime());
        kh.setKeyHandle(dr.getKeyHandle());
        kh.setPublicKey(dr.getPublicKey());
        kh.setTransports(dr.getTransports());
        keys.add(kh);
    }

    String json = gson.toJson(keys);
    EncryptedMessage msg = new EncryptedMessage();

    SecretKey key = GlobalEntries.getGlobalEntries().getConfigManager().getSecretKey(encyrptionKeyName);
    if (key == null) {
        throw new Exception("Queue message encryption key not found");
    }

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    msg.setMsg(cipher.doFinal(json.getBytes("UTF-8")));
    msg.setIv(cipher.getIV());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

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

    compressor.write(gson.toJson(msg).getBytes("UTF-8"));
    compressor.flush();
    compressor.close();

    String b64 = new String(Base64.encodeBase64(baos.toByteArray()));

    return b64;

}

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. ?/*from  w  w  w  .j  a  va2 s  .  c om*/
    // 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:com.aliyun.odps.commons.proto.ProtobufRecordStreamWriter.java

public ProtobufRecordStreamWriter(TableSchema schema, OutputStream out, CompressOption option)
        throws IOException {
    columns = schema.getColumns().toArray(new Column[0]);
    OutputStream tmpOut;/*w  w w .  j ava2s . c om*/
    if (option != null) {
        if (option.algorithm.equals(CompressOption.CompressAlgorithm.ODPS_ZLIB)) {
            def = new Deflater();
            def.setLevel(option.level);
            def.setStrategy(option.strategy);
            tmpOut = new DeflaterOutputStream(out, def);
        } else if (option.algorithm.equals(CompressOption.CompressAlgorithm.ODPS_SNAPPY)) {
            tmpOut = new SnappyFramedOutputStream(out);
        } else if (option.algorithm.equals(CompressOption.CompressAlgorithm.ODPS_RAW)) {
            tmpOut = out;
        } else {
            throw new IOException("invalid compression option.");
        }
    } else {
        tmpOut = out;
    }
    bou = new CountingOutputStream(tmpOut);
    this.out = CodedOutputStream.newInstance(bou);
}

From source file:ch.cern.security.saml2.utils.xml.XMLUtils.java

/**
 * Compress the xml string and encodes it in Base64
 * //from w w w. ja v a2  s  . co  m
 * @param xmlString
 * @param isDebugEnabled 
 * @return xml string encoded
 * @throws IOException
 * @throws UnsupportedEncodingException
 */
public static String xmlDeflateAndEncode(String xmlString, boolean isDebugEnabled)
        throws IOException, UnsupportedEncodingException {

    if (isDebugEnabled)
        nc.notice(xmlString);

    // Deflate the SAMLResponse value
    ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
    Deflater deflater = new Deflater(Deflater.DEFLATED, true);
    DeflaterOutputStream deflaterStream = new DeflaterOutputStream(bytesOut, deflater);
    deflaterStream.write(xmlString.getBytes());
    deflaterStream.finish();

    // Encoded the deflatedResponse in base64
    Base64 base64encoder = new Base64();
    String base64response = new String(base64encoder.encode(bytesOut.toByteArray()), "UTF-8");

    if (isDebugEnabled)
        nc.notice(base64response);

    return base64response;
}

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 {//from   ww w.j  a  v  a  2 s.co  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:ZipUtil.java

public static void zipFileToFile(File flSource, File flTarget) throws IOException {
    Deflater oDeflate = new Deflater(Deflater.DEFLATED, false);

    FileInputStream stmFileIn = new FileInputStream(flSource);
    FileOutputStream stmFileOut = new FileOutputStream(flTarget);
    DeflaterOutputStream stmDeflateOut = new DeflaterOutputStream(stmFileOut, oDeflate);
    try {/*from w  w  w  . j a  v a2s  .  com*/
        // FileUtil.inputStreamToOutputStream(stmFileIn, stmDeflateOut);
    } //end try
    finally {
        stmDeflateOut.finish();
        stmDeflateOut.flush();
        stmDeflateOut.close();
        stmFileOut.close();
        stmFileIn.close();
    }
}

From source file:org.squale.welcom.struts.webServer.WebEngine.java

/**
 * gzip / deflate / none// w w w. ja  v  a2  s .co  m
 * 
 * @return OutPuStream en focntion de la configuration
 * @throws IOException IOException
 */
public OutputStream getOutputStream() throws IOException {
    OutputStream out;
    if ((request.getHeader("Accept-Encoding") != null) && (request.getHeader("Accept-Encoding").indexOf(
            WelcomConfigurator.getMessage(WelcomConfigurator.OPTIFLUX_COMPRESSION_MODE).toLowerCase()) > -1)) {
        response.setHeader("Content-Encoding",
                WelcomConfigurator.getMessage(WelcomConfigurator.OPTIFLUX_COMPRESSION_MODE).toLowerCase());

        if (Util.isEqualsIgnoreCase(WelcomConfigurator.getMessage(WelcomConfigurator.OPTIFLUX_COMPRESSION_MODE),
                "deflate")) {
            out = new DeflaterOutputStream(response.getOutputStream(), new Deflater(COMPRESSION_LEVEL, true));
        } else {
            out = new GZIPOutputStream(response.getOutputStream());
        }
    } else {
        out = response.getOutputStream();
    }
    return out;
}

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

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

    try {/* www  .  j  a  va  2s  .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.diorite.nbt.NbtOutputStream.java

/**
 * Create new compressed nbt output stream for given stream, and write nbt tag to it.
 *
 * @param tag          nbt tag to write.
 * @param outputStream output stream to be used.
 * @param def          deflater to be used.
 *
 * @return created NbtOutputStream./*from  ww  w  .jav  a  2s .com*/
 *
 * @throws IOException if any write operation failed.
 */
public static NbtOutputStream writeDeflated(final NbtTag tag, final OutputStream outputStream,
        final Deflater def) throws IOException {
    final NbtOutputStream out = new NbtOutputStream(new DeflaterOutputStream(outputStream, def));
    out.write(tag);
    return out;
}

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 w  w  . j  av a2s .c  o  m
        // 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();
    }
}