Example usage for java.util.zip GZIPOutputStream GZIPOutputStream

List of usage examples for java.util.zip GZIPOutputStream GZIPOutputStream

Introduction

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

Prototype

public GZIPOutputStream(OutputStream out) throws IOException 

Source Link

Document

Creates a new output stream with a default buffer size.

Usage

From source file:com.unilever.audit.services2.Sync_Down.java

/**
 * Retrieves representation of an instance of
 * com.unilever.audit.services2.AuditResource
 *
 * @param id//from   www.ja v a2  s  .  c  o  m
 * @param dataType
 * @return an instance of java.lang.String
 */
@GET
@Path("getSyncObject/{id}/{dataType}/{compress}")
@Produces("application/json")
public byte[] getSyncObject(@PathParam("id") int id, @PathParam("dataType") String dataType,
        @PathParam("compress") int compress) {

    GZIPOutputStream gzip = null;
    count++;
    ByteArrayOutputStream out = null;
    SyncDownObjects syncDownObjects = getObject(dataType, id);

    try {
        out = new ByteArrayOutputStream();
        gzip = new GZIPOutputStream(out);

        ObjectMapper mapper = new ObjectMapper();
        AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
        AnnotationIntrospector introspector1 = new JacksonAnnotationIntrospector();
        mapper.setAnnotationIntrospectors(introspector, introspector1);
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

        //String jsonString = mapper.writeValueAsString(syncDownObjects);
        //JSONObject jsonobject = (JSONObject) new JSONParser().parse(jsonString);
        //gzip.write(jsonobject.toString().getBytes("8859_1"));
        //gzip.write(jsonobject.toString().getBytes("UTF-8"));
        gzip.write(mapper.writeValueAsBytes(syncDownObjects));
        gzip.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    } //catch (ParseException ex) {
      // ex.printStackTrace();
      // }
    System.out.println("======================= count : " + count);
    return out.toByteArray();
}

From source file:com.nokia.helium.core.EmailDataSender.java

/**
 * GZipping a string.//from  w w w .j  ava 2 s .  c om
 * 
 * @param data the content to be gzipped.
 * @param filename the name for the file.
 * @return a ByteArrayDataSource.
 */
protected ByteArrayDataSource compressFile(File fileName) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gz = new GZIPOutputStream(out);
    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(fileName));
    byte[] dataBuffer = new byte[512];
    while ((bufferedInputStream.read(dataBuffer)) != -1) {
        gz.write(dataBuffer);
    }
    gz.close();
    bufferedInputStream.close();
    ByteArrayDataSource dataSrc = new ByteArrayDataSource(out.toByteArray(), "application/x-gzip");
    return dataSrc;
}

From source file:net.landora.video.info.file.FileInfoManager.java

private synchronized void writeCacheFile(File file, Map<String, FileInfo> infoMap) {
    OutputStream os = null;/*from   w  ww.ja v a 2  s. com*/
    try {
        os = new BufferedOutputStream(new FileOutputStream(file));
        if (COMPRESS_INFO_FILE) {
            os = new GZIPOutputStream(os);
        }

        XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(os);
        writer.writeStartDocument();

        writer.writeStartElement("files");
        writer.writeCharacters("\n");

        for (Map.Entry<String, FileInfo> entry : infoMap.entrySet()) {
            FileInfo info = entry.getValue();

            writer.writeStartElement("file");
            writer.writeAttribute("filename", entry.getKey());

            writer.writeAttribute("ed2k", info.getE2dkHash());
            writer.writeAttribute("length", String.valueOf(info.getFileSize()));
            writer.writeAttribute("lastmodified", String.valueOf(info.getLastModified()));

            if (info.getMetadataSource() != null) {
                writer.writeAttribute("metadatasource", info.getMetadataSource());
            }
            if (info.getMetadataId() != null) {
                writer.writeAttribute("metadataid", info.getMetadataId());
            }
            if (info.getVideoId() != null) {
                writer.writeAttribute("videoid", info.getVideoId());
            }

            writer.writeEndElement();
            writer.writeCharacters("\n");
        }

        writer.writeEndElement();
        writer.writeEndDocument();
        writer.close();

    } catch (Exception e) {
        log.error("Error writing file cache.", e);
    } finally {
        if (os != null) {
            IOUtils.closeQuietly(os);
        }
    }
}

From source file:hudson.plugins.project_inheritance.projects.view.InheritanceViewAction.java

public void createTgzArchive(File dstFile, String srcDir, List<File> srcFiles) throws IOException {
    //Creating the output ZipFile
    FileOutputStream fos = new FileOutputStream(dstFile);
    GZIPOutputStream gzos = new GZIPOutputStream(fos);
    TarOutputStream tos = new TarOutputStream(gzos);

    try {/*from   w w  w.jav  a 2s .  c  o m*/
        byte[] buffer = new byte[8192];
        for (File srcFile : srcFiles) {
            if (!srcFile.exists()) {
                throw new IOException("No such file " + srcFile.getPath());
            }
            //Strip the prefix off the srcFile
            String relPath = PathMapping.getRelativePath(srcFile.getPath(), srcDir, File.separator);

            TarEntry entry = new TarEntry(relPath);
            entry.setMode(0777);
            entry.setSize(srcFile.length());
            //Put the entry into the ZIP file
            tos.putNextEntry(entry);
            //Dump the data
            FileInputStream fis = new FileInputStream(srcFile);
            try {
                while (true) {
                    int read = fis.read(buffer);
                    if (read <= 0) {
                        break;
                    }
                    tos.write(buffer, 0, read);
                }
            } finally {
                fis.close();
            }
            //Close the entry
            tos.closeEntry();
        }
    } finally {
        if (tos != null) {
            tos.close();
        }
    }
}

From source file:com.dotcms.publisher.myTest.PushPublisher.java

/**
 * Compress (tar.gz) the input files to the output file
 *
 * @param files The files to compress/*from   w  w w . j  a va2s.c o  m*/
 * @param output The resulting output file (should end in .tar.gz)
 * @param bundleRoot
 * @throws IOException
 */
private void compressFiles(Collection<File> files, File output, String bundleRoot) throws IOException {
    Logger.info(this.getClass(), "Compressing " + files.size() + " to " + output.getAbsoluteFile());
    // Create the output stream for the output file
    FileOutputStream fos = new FileOutputStream(output);
    // Wrap the output file stream in streams that will tar and gzip everything
    TarArchiveOutputStream taos = new TarArchiveOutputStream(
            new GZIPOutputStream(new BufferedOutputStream(fos)));

    // TAR originally didn't support long file names, so enable the support for it
    taos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);

    // Get to putting all the files in the compressed output file
    for (File f : files) {
        addFilesToCompression(taos, f, ".", bundleRoot);
    }

    // Close everything up
    taos.close();
    fos.close();
}

From source file:com.github.jasonruckman.gzip.AbstractBenchmark.java

private void initializeKryo() {
    try {//  w  ww . ja va 2  s.co  m
        Kryo kryo = new Kryo();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        GZIPOutputStream gzos = new GZIPOutputStream(outputStream);
        Output o = output();
        o.setOutputStream(gzos);
        kryo.writeObject(o, sampleData);
        o.close();
        gzos.close();
        serializedKryoData = outputStream.toByteArray();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.esofthead.mycollab.community.ui.chart.JFreeChartWrapper.java

@Override
public Resource getSource() {
    if (res == null) {
        StreamSource streamSource = new StreamResource.StreamSource() {
            private ByteArrayInputStream bytestream = null;

            ByteArrayInputStream getByteStream() {
                if (chart != null && bytestream == null) {
                    int width = getGraphWidth();
                    int height = getGraphHeight();

                    if (mode == RenderingMode.SVG) {

                        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder docBuilder = null;
                        try {
                            docBuilder = docBuilderFactory.newDocumentBuilder();
                        } catch (ParserConfigurationException e1) {
                            throw new RuntimeException(e1);
                        }//from   w w w . j a v  a2  s . c  om
                        Document document = docBuilder.newDocument();
                        Element svgelem = document.createElement("svg");
                        document.appendChild(svgelem);

                        // Create an instance of the SVG Generator
                        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

                        // draw the chart in the SVG generator
                        chart.draw(svgGenerator, new Rectangle(width, height));
                        Element el = svgGenerator.getRoot();
                        el.setAttributeNS(null, "viewBox", "0 0 " + width + " " + height + "");
                        el.setAttributeNS(null, "style", "width:100%;height:100%;");
                        el.setAttributeNS(null, "preserveAspectRatio", getSvgAspectRatio());

                        // Write svg to buffer
                        ByteArrayOutputStream baoutputStream = new ByteArrayOutputStream();
                        Writer out;
                        try {
                            OutputStream outputStream = gzipEnabled ? new GZIPOutputStream(baoutputStream)
                                    : baoutputStream;
                            out = new OutputStreamWriter(outputStream, "UTF-8");
                            /*
                            * don't use css, FF3 can'd deal with the result
                            * perfectly: wrong font sizes
                            */
                            boolean useCSS = false;
                            svgGenerator.stream(el, out, useCSS, false);
                            outputStream.flush();
                            outputStream.close();
                            bytestream = new ByteArrayInputStream(baoutputStream.toByteArray());
                        } catch (Exception e) {
                            log.error("Error while generating SVG chart", e);
                        }
                    } else {
                        // Draw png to bytestream
                        try {
                            byte[] bytes = ChartUtilities.encodeAsPNG(chart.createBufferedImage(width, height));
                            bytestream = new ByteArrayInputStream(bytes);
                        } catch (Exception e) {
                            log.error("Error while generating PNG chart", e);
                        }

                    }

                } else {
                    bytestream.reset();
                }
                return bytestream;
            }

            @Override
            public InputStream getStream() {
                return getByteStream();
            }
        };

        res = new StreamResource(streamSource, String.format("graph%d", System.currentTimeMillis())) {

            @Override
            public int getBufferSize() {
                if (getStreamSource().getStream() != null) {
                    try {
                        return getStreamSource().getStream().available();
                    } catch (IOException e) {
                        log.warn("Error while get stream info", e);
                        return 0;
                    }
                } else {
                    return 0;
                }
            }

            @Override
            public long getCacheTime() {
                return 0;
            }

            @Override
            public String getFilename() {
                if (mode == RenderingMode.PNG) {
                    return super.getFilename() + ".png";
                } else {
                    return super.getFilename() + (gzipEnabled ? ".svgz" : ".svg");
                }
            }

            @Override
            public DownloadStream getStream() {
                DownloadStream downloadStream = new DownloadStream(getStreamSource().getStream(), getMIMEType(),
                        getFilename());
                if (gzipEnabled && mode == RenderingMode.SVG) {
                    downloadStream.setParameter("Content-Encoding", "gzip");
                }
                return downloadStream;
            }

            @Override
            public String getMIMEType() {
                if (mode == RenderingMode.PNG) {
                    return "image/png";
                } else {
                    return "image/svg+xml";
                }
            }
        };
    }
    return res;
}

From source file:gedi.util.io.text.LineOrientedFile.java

public Writer createWriter(boolean append) throws IOException {
    if (exists() && !append)
        delete();//  ww  w  .  j  a v  a2  s  .  c  o  m
    isGZIP();
    isBZIP2();

    OutputStream st = createOutputStream(append);
    if (isGZIP())
        st = new GZIPOutputStream(st);
    if (isBZIP2())
        st = new BZip2CompressorOutputStream(st);
    Writer re = new OutputStreamWriter(st, enc);
    if (isPipe())
        return re;
    return new BufferedWriter(re);
}

From source file:co.cask.cdap.internal.app.runtime.LocalizationUtilsTest.java

private File createTarGzFile(String tarGzFileName, File... filesToAdd) throws IOException {
    File target = TEMP_FOLDER.newFile(tarGzFileName + ".tar.gz");
    try (TarArchiveOutputStream tos = new TarArchiveOutputStream(
            new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(target))))) {
        addFilesToTar(tos, filesToAdd);/*  www  . j av  a  2 s. co m*/
    }
    return target;
}

From source file:eu.domibus.ebms3.common.CompressionService.java

/**
 * Compresses the given byte[]./*w ww. j av a  2s  .com*/
 *
 * @param uncompressed the byte[] to compress
 * @return the compressed byte[]
 * @throws java.lang.NullPointerException if the payload has no content a {@link java.lang.NullPointerException}
 *                                        is thrown
 * @throws java.io.IOException            if problem during gzip compression occurs a {@link java.io.IOException} is thrown
 */
private byte[] compress(byte[] uncompressed) throws IOException, NullPointerException {
    if (uncompressed == null) {
        throw new NullPointerException("Payload was null");
    }

    ByteArrayOutputStream compressedContent = new ByteArrayOutputStream();

    try {
        this.compress(new ByteArrayInputStream(uncompressed), new GZIPOutputStream(compressedContent));
    } catch (IOException e) {
        CompressionService.LOG.error("", e);
        throw e;
    }

    return compressedContent.toByteArray();
}