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: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);//ww  w .  jav a2 s .  c  o  m
            dos.close();
        } 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();
    String encodedRequestMessage = Base64.encodeBytes(byteArrayOutputStream.toByteArray(),
            Base64.DONT_BREAK_LINES);//from   w  w w .j  a  v a2s  . co m
    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 {/* ww  w . ja  va  2 s . 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.j a  v a 2s .  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.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 {/* w  w  w . ja va 2s .com*/
        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.pdfbox.filter.FlateFilter.java

/**
 * {@inheritDoc}/*  w  w  w . ja v  a2s  . c o m*/
 */
public void encode(InputStream rawData, OutputStream result, COSDictionary options, int filterIndex)
        throws IOException {
    DeflaterOutputStream out = new DeflaterOutputStream(result);
    int amountRead = 0;
    int mayRead = rawData.available();
    if (mayRead > 0) {
        byte[] buffer = new byte[Math.min(mayRead, BUFFER_SIZE)];
        while ((amountRead = rawData.read(buffer, 0, Math.min(mayRead, BUFFER_SIZE))) != -1) {
            out.write(buffer, 0, amountRead);
        }
    }
    out.close();
    result.flush();
}

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

@Private
public static ByteString compressByteArrayToByteString(byte[] inBytes, Deflater deflater) throws IOException {
    deflater.reset();//from  w w  w  .j a  v a 2  s.c o 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.apache.tez.common.TezUtils.java

/**
 * Convert a Configuration to compressed ByteString using Protocol buffer
 *
 * @param conf//from ww  w  .jav a  2s. c  om
 *          : Configuration to be converted
 * @return PB ByteString (compressed)
 * @throws java.io.IOException
 */
public static ByteString createByteStringFromConf(Configuration conf) throws IOException {
    Preconditions.checkNotNull(conf, "Configuration must be specified");
    ByteString.Output os = ByteString.newOutput();
    DeflaterOutputStream compressOs = new DeflaterOutputStream(os, new Deflater(Deflater.BEST_SPEED));
    try {
        writeConfInPB(compressOs, conf);
    } finally {
        if (compressOs != null) {
            compressOs.close();
        }
    }
    return os.toByteString();
}

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

/**
 * Get String with the SAML2 AuthnRequest message
 * @param format -1=plain, 1=base64// w  ww .java 2s.  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:org.openvpms.report.jasper.JRXMLDocumentHandler.java

/**
 * Creates a new {@link Document} from a stream.
 *
 * @param name     the document name//from   w w  w  . j  a v a2 s . c o  m
 * @param stream   a stream representing the document content
 * @param mimeType the mime type of the document. May be {@code null}
 * @param size     the size of stream
 * @return a new document
 * @throws DocumentException         if the document can't be created
 * @throws ArchetypeServiceException for any archetype service error
 * @throws JRXMLDocumentException    if the document version cannot be parsed
 */
public Document create(String name, InputStream stream, String mimeType, int size) {
    Document document;
    JasperDesign design;
    try {
        design = JRXmlLoader.load(stream);
    } catch (JRException exception) {
        if (ExceptionUtils.getRootCause(exception) instanceof SAXParseException) {
            if (name == null) {
                name = "file";
            }
            throw new JRXMLDocumentException(exception, JRXMLDocumentException.ErrorCode.ReadError, name);
        } else {
            throw new DocumentException(DocumentException.ErrorCode.ReadError, exception, name);
        }
    }
    try {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        DeflaterOutputStream output = new DeflaterOutputStream(bytes);
        JRXmlWriter.writeReport(design, output, "UTF-8");
        output.close();
        document = create(name, bytes.toByteArray(), "text/xml", size);
    } catch (Exception exception) {
        throw new DocumentException(DocumentException.ErrorCode.WriteError, exception, name);
    }
    return document;
}