Example usage for java.util.zip GZIPOutputStream flush

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

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the compressed output stream.

Usage

From source file:org.xdi.service.ObjectSerializationService.java

public boolean saveObject(String path, Serializable obj, boolean append) {
    File file = new File(path);
    FileOutputStream fos;/*  w w  w .j  av a  2  s .co m*/
    try {
        fos = new FileOutputStream(file, append);
    } catch (FileNotFoundException ex) {
        log.error("Faield to serialize to file: '{0}'. Error: ", path, ex);

        return false;
    }

    BufferedOutputStream bos = new BufferedOutputStream(fos);
    try {
        GZIPOutputStream gos = new GZIPOutputStream(bos);
        SerializationUtils.serialize(obj, gos);
        gos.flush();
        IOUtils.closeQuietly(gos);
    } catch (IOException ex) {
        log.error("Faield to serialize to file: '{0}'. Error: ", path, ex);
        IOUtils.closeQuietly(bos);

        return false;
    }

    return true;
}

From source file:de.iai.ilcd.model.common.XmlFile.java

/**
 * Compress the content of XML file prior to persist/merge events in order to save database space and be compatible
 * with MySQL server default configurations
 * as long as possible (1MB max package size)
 * //w w  w . ja va2 s . c  o  m
 * @throws Exception
 *             if anything goes wrong, just in-memory IO operations, should not happen
 * @see #decompressContent()
 */
@PrePersist
protected void compressContent() throws Exception {
    if (this.content == null) {
        this.compressedContent = null;
    } else {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzipOut = new GZIPOutputStream(out);
        gzipOut.write(this.content.getBytes("UTF-8"));
        gzipOut.flush();
        gzipOut.close();
        this.compressedContent = out.toByteArray();
    }
}

From source file:au.org.ala.layers.web.ObjectsService.java

/**
 * This method returns all objects associated with a field
 *
 * @param id//from w ww .j a v a2  s. co  m
 * @return
 */
@RequestMapping(value = "/objects/csv/{id}", method = RequestMethod.GET)
public void fieldObjectAsCSV(@PathVariable("id") String id, HttpServletResponse resp) throws IOException {
    try {
        resp.setContentType("text/csv");
        resp.setHeader("Content-Disposition", "attachment; filename=\"objects-" + id + ".csv.gz\"");
        GZIPOutputStream gzipped = new GZIPOutputStream(resp.getOutputStream());
        objectDao.writeObjectsToCSV(gzipped, id);
        gzipped.flush();
        gzipped.close();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        resp.sendError(500, "Problem performing download");
    }
}

From source file:edu.cornell.med.icb.goby.algorithmic.data.WeightsInfo.java

/**
 * Save weights info to disk.//  w w  w.  j a v a2 s .  c o m
 *
 * @param filename The name of the file to save to
 * @throws IOException If the file cannot be written
 */
public void save(final String filename) throws IOException {
    GZIPOutputStream gzipOutputStream = null;
    try {
        gzipOutputStream = new GZIPOutputStream(new FileOutputStream(filename));
        BinIO.storeObject(this, gzipOutputStream);
        gzipOutputStream.flush();
        LOG.info("Saved " + filename);
    } finally {
        IOUtils.closeQuietly(gzipOutputStream);
    }
}

From source file:de.undercouch.gradle.tasks.download.CompressionTest.java

@Override
protected Handler[] makeHandlers() throws IOException {
    ContextHandler compressionHandler = new ContextHandler("/" + COMPRESSED) {
        @Override//  w ww .  j  a  v a  2 s  .c o  m
        public void handle(String target, HttpServletRequest request, HttpServletResponse response,
                int dispatch) throws IOException, ServletException {
            String acceptEncoding = request.getHeader("Accept-Encoding");
            boolean acceptGzip = "gzip".equals(acceptEncoding);

            response.setStatus(200);
            OutputStream os = response.getOutputStream();
            if (acceptGzip) {
                response.setHeader("Content-Encoding", "gzip");
                GZIPOutputStream gos = new GZIPOutputStream(os);
                OutputStreamWriter osw = new OutputStreamWriter(gos);
                osw.write("Compressed");
                osw.close();
                gos.flush();
                gos.close();
            } else {
                OutputStreamWriter osw = new OutputStreamWriter(os);
                osw.write("Uncompressed");
                osw.close();
            }
            os.close();
        }
    };
    return new Handler[] { compressionHandler };
}

From source file:com.orange.mmp.api.ws.jsonrpc.MMPJsonRpcServlet.java

/**
 * Gzip something./*from   w  w w . j av  a 2  s  . c om*/
 * 
 * @param in
 *            original content
 * @return size gzipped content
 */
private byte[] gzip(byte[] in) throws IOException {
    if (in != null && in.length > 0) {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        GZIPOutputStream gout = new GZIPOutputStream(bout);
        gout.write(in);
        gout.flush();
        gout.close();
        return bout.toByteArray();
    }
    return new byte[0];
}

From source file:com.google.api.ads.adwords.awreporting.processors.onmemory.ReportProcessorOnMemoryTest.java

private byte[] getReporDatafromCsv(ReportDefinitionReportType reportType) throws Exception {
    byte[] reportData = reportDataMap.get(reportType);
    if (reportData == null) {
        FileInputStream fis = new FileInputStream(getReportDataFileName(reportType));
        ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);
        GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
        FileUtil.copy(fis, gzipOut);//from  ww w.ja v a 2s  .com
        gzipOut.flush();
        gzipOut.close();
        reportData = baos.toByteArray();
        reportDataMap.put(reportType, reportData);
        baos.flush();
        baos.close();
    }
    return reportData;
}

From source file:org.runnerup.export.GoogleFitSynchronizer.java

private Status sendData(StringWriter w, String suffix, RequestMethod method) throws IOException {
    Status status = Status.ERROR;//from  www .  j a v a  2s . c om
    for (int attempts = 0; attempts < MAX_ATTEMPTS; attempts++) {
        HttpURLConnection connect = getHttpURLConnection(suffix, method);
        GZIPOutputStream gos = new GZIPOutputStream(connect.getOutputStream());
        gos.write(w.toString().getBytes());
        gos.flush();
        gos.close();

        int code = connect.getResponseCode();
        try {
            if (code == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                continue;
            } else if (code != HttpStatus.SC_OK) {
                Log.i(getName(), SyncHelper.parse(new GZIPInputStream(connect.getErrorStream())).toString());
                status = Status.ERROR;
                break;
            } else {
                Log.i(getName(), SyncHelper.parse(new GZIPInputStream(connect.getInputStream())).toString());
                status = Status.OK;
                break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            connect.disconnect();
        }
    }
    return status;
}

From source file:halive.shootinoutside.common.core.game.map.GameMap.java

public byte[] serializeMapToCompressedByteArray() throws IOException {
    //Compress data
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gzipOut = new GZIPOutputStream(out);
    gzipOut.write(serializeMapToJSONString().getBytes());
    gzipOut.flush();
    gzipOut.finish();/*from   w  ww. jav  a  2  s  .  co m*/
    return out.toByteArray();
}

From source file:org.exist.replication.shared.MessageHelper.java

/**
 *  Serialize document to byte array as gzipped document.
 * /*from   www .j  a va2 s . c o m*/
 * @param broker
 * @param document
 * @return
 * @throws IOException 
 */
public static byte[] gzipSerialize(DBBroker broker, DocumentImpl document) throws IOException {

    // This is the weak spot, the data is serialized into
    // a byte array. Better to have an overloap to a file,
    byte[] payload;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gos = new GZIPOutputStream(baos);

    if (document.getResourceType() == DocumentImpl.XML_FILE) {

        // Stream XML document
        Serializer serializer = broker.getSerializer();
        serializer.reset();
        try {
            serializer.setProperties(OUTPUT_PROPERTIES);

            Writer w = new OutputStreamWriter(gos, "UTF-8");
            serializer.serialize(document, w);
            w.flush();
            w.close();

            payload = baos.toByteArray();

        } catch (SAXException e) {
            payload = new byte[0];
            LOG.error(e);
            throw new IOException("Error while serializing XML document: " + e.getMessage(), e);

        } catch (Throwable e) {
            payload = new byte[0];
            System.gc(); // recover from out of memory exception
            LOG.error(e);
            throw new IOException("Error while serializing XML document: " + e.getMessage(), e);
        }

    } else {
        // Stream NON-XML document

        try {
            broker.readBinaryResource((BinaryDocument) document, gos);
            gos.flush();
            gos.close();

            payload = baos.toByteArray();

        } catch (IOException e) {
            payload = new byte[0];
            LOG.error(e);
            throw new IOException("Error while serializing binary document: " + e.getMessage(), e);

        } catch (Throwable e) {
            payload = new byte[0];
            System.gc(); // recover from out of memory exception
            LOG.error(e);
            throw new IOException("Error while serializing binary document: " + e.getMessage(), e);
        }
    }

    return payload;

}