Example usage for java.util.zip GZIPOutputStream write

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

Introduction

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

Prototype

public synchronized void write(byte[] buf, int off, int len) throws IOException 

Source Link

Document

Writes array of bytes to the compressed output stream.

Usage

From source file:org.makersoft.mvc.json.JSONUtil.java

public static void writeJSONToResponse(SerializationParams serializationParams) throws IOException {
    StringBuilder stringBuilder = new StringBuilder();
    if (StringUtils.isNotBlank(serializationParams.getSerializedJSON()))
        stringBuilder.append(serializationParams.getSerializedJSON());

    if (StringUtils.isNotBlank(serializationParams.getWrapPrefix()))
        stringBuilder.insert(0, serializationParams.getWrapPrefix());
    else if (serializationParams.isWrapWithComments()) {
        stringBuilder.insert(0, "/* ");
        stringBuilder.append(" */");
    } else if (serializationParams.isPrefix())
        stringBuilder.insert(0, "{}&& ");

    if (StringUtils.isNotBlank(serializationParams.getWrapSuffix()))
        stringBuilder.append(serializationParams.getWrapSuffix());

    String json = stringBuilder.toString();

    if (LOG.isDebugEnabled()) {
        LOG.debug("[JSON]" + json);
    }//from  w w w  .  j  a  v  a  2 s. co  m

    HttpServletResponse response = serializationParams.getResponse();

    // status or error code
    if (serializationParams.getStatusCode() > 0)
        response.setStatus(serializationParams.getStatusCode());
    else if (serializationParams.getErrorCode() > 0)
        response.sendError(serializationParams.getErrorCode());

    // content type
    //        response.setContentType(serializationParams.getContentType() + ";charset="
    //                + serializationParams.getEncoding());

    // character encoding  
    response.setCharacterEncoding(serializationParams.getEncoding());
    // content type
    response.setContentType(serializationParams.getContentType());

    if (serializationParams.isNoCache()) {
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Expires", "0");
        response.setHeader("Pragma", "No-cache");
    }

    if (serializationParams.isGzip()) {
        response.addHeader("Content-Encoding", "gzip");
        GZIPOutputStream out = null;
        InputStream in = null;
        try {
            out = new GZIPOutputStream(response.getOutputStream());
            in = new ByteArrayInputStream(json.getBytes(serializationParams.getEncoding()));
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            if (in != null)
                in.close();
            if (out != null) {
                out.finish();
                out.close();
            }
        }

    } else {
        response.setContentLength(json.getBytes(serializationParams.getEncoding()).length);
        PrintWriter out = response.getWriter();
        out.print(json);
    }
}

From source file:org.ofbiz.webapp.event.RestEventHandler.java

/** 
* ? /* ww  w.  jav  a 2  s .c o m*/
*  
* @param is 
* @param os 
* @throws Exception 
*/
public static void compress(InputStream is, OutputStream os) throws Exception {

    GZIPOutputStream gos = new GZIPOutputStream(os);

    int count;
    byte data[] = new byte[BUFFER];
    while ((count = is.read(data, 0, BUFFER)) != -1) {
        gos.write(data, 0, count);
    }

    gos.finish();

    gos.flush();
    gos.close();
}

From source file:com.sxit.crawler.utils.ArchiveUtils.java

/**
 * Gzip passed bytes.//from w ww. j a  v  a2 s.  c  o m
 * Use only when bytes is small.
 * @param bytes What to gzip.
 * @return A gzip member of bytes.
 * @throws IOException
 */
public static byte[] gzip(byte[] bytes) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzipOS = new GZIPOutputStream(baos);
    gzipOS.write(bytes, 0, bytes.length);
    gzipOS.close();
    return baos.toByteArray();
}

From source file:arena.utils.FileUtils.java

public static void gzip(File input, File outFile) {
    Log log = LogFactory.getLog(FileUtils.class);
    InputStream inStream = null;//from  ww  w .ja v a2 s.  c  o m
    OutputStream outStream = null;
    GZIPOutputStream gzip = null;
    try {
        long inFileLengthKB = input.length() / 1024L;

        // Open the out file
        if (outFile == null) {
            outFile = new File(input.getParentFile(), input.getName() + ".gz");
        }
        inStream = new FileInputStream(input);
        outStream = new FileOutputStream(outFile, true);
        gzip = new GZIPOutputStream(outStream);

        // Iterate through in buffers and write out to the gzipped output stream
        byte buffer[] = new byte[102400]; // 100k buffer
        int read = 0;
        long readSoFar = 0;
        while ((read = inStream.read(buffer)) != -1) {
            readSoFar += read;
            gzip.write(buffer, 0, read);
            log.debug("Gzipped " + (readSoFar / 1024L) + "KB / " + inFileLengthKB + "KB of logfile "
                    + input.getName());
        }

        // Close the streams
        inStream.close();
        inStream = null;
        gzip.close();
        gzip = null;
        outStream.close();
        outStream = null;

        // Delete the old file
        input.delete();
        log.debug("Gzip of logfile " + input.getName() + " complete");
    } catch (IOException err) {
        // Delete the gzip file
        log.error("Error during gzip of logfile " + input, err);
    } finally {
        if (inStream != null) {
            try {
                inStream.close();
            } catch (IOException err2) {
            }
        }
        if (gzip != null) {
            try {
                gzip.close();
            } catch (IOException err2) {
            }
        }
        if (outStream != null) {
            try {
                outStream.close();
            } catch (IOException err2) {
            }
        }
    }
}

From source file:org.forgerock.openam.cts.utils.blob.strategies.CompressionStrategy.java

/**
 * Compress the Tokens binary object./*from w w w.j a  v  a 2 s .  c  o  m*/
 *
 * @param token Non null Token to modify.
 *
 * @throws org.forgerock.openam.cts.utils.blob.TokenStrategyFailedException {@inheritDoc}
 */
@Override
public void perform(Token token) throws TokenStrategyFailedException {
    bout.reset();
    try {
        GZIPOutputStream out = new GZIPOutputStream(bout);
        out.write(token.getBlob(), 0, token.getBlob().length);
        out.flush();
        out.close();
    } catch (IOException e) {
        throw new TokenStrategyFailedException(e);
    }
    token.setBlob(bout.toByteArray());
}

From source file:com.eucalyptus.blockstorage.PutMethodWithProgress.java

@Override
protected boolean writeRequestBody(HttpState state, HttpConnection conn) throws IOException {
    InputStream inputStream;/*from   ww  w .j a v  a  2s . c  o m*/
    if (outFile != null) {
        inputStream = new FileInputStream(outFile);

        ChunkedOutputStream chunkedOut = new ChunkedOutputStream(conn.getRequestOutputStream());
        byte[] buffer = new byte[StorageProperties.TRANSFER_CHUNK_SIZE];
        int bytesRead;
        long totalBytesProcessed = 0;
        while ((bytesRead = inputStream.read(buffer)) > 0) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            GZIPOutputStream zip = new GZIPOutputStream(out);
            zip.write(buffer, 0, bytesRead);
            zip.close();
            chunkedOut.write(out.toByteArray());
            totalBytesProcessed += bytesRead;
            callback.update(totalBytesProcessed);
        }
        if (totalBytesProcessed > 0) {
            callback.finish();
        } else {
            callback.failed();
        }
        chunkedOut.finish();
        inputStream.close();
    } else {
        return false;
    }
    return true;
}

From source file:edu.ucsb.eucalyptus.cloud.ws.PutMethodWithProgress.java

@Override
protected boolean writeRequestBody(HttpState state, HttpConnection conn) throws IOException {
    InputStream inputStream;/*from w w w. j  av a 2s. c  om*/
    if (outFile != null) {
        inputStream = new FileInputStream(outFile);

        ChunkedOutputStream chunkedOut = new ChunkedOutputStream(conn.getRequestOutputStream());
        byte[] buffer = new byte[StorageProperties.TRANSFER_CHUNK_SIZE];
        int bytesRead;
        int numberProcessed = 0;
        long totalBytesProcessed = 0;
        while ((bytesRead = inputStream.read(buffer)) > 0) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            GZIPOutputStream zip = new GZIPOutputStream(out);
            zip.write(buffer, 0, bytesRead);
            zip.close();
            chunkedOut.write(out.toByteArray());
            totalBytesProcessed += bytesRead;
            if (++numberProcessed >= callback.getUpdateThreshold()) {
                callback.run();
                numberProcessed = 0;
            }
        }
        if (totalBytesProcessed > 0) {
            callback.finish();
        } else {
            callback.failed();
        }
        chunkedOut.finish();
        inputStream.close();
    } else {
        return false;
    }
    return true;
}

From source file:gdt.data.entity.ArchiveHandler.java

private static void compressGzipFile(String tarFile$, String gzipFile$) {
    try {//from   ww w . j  a v  a2 s .  co m
        FileInputStream fis = new FileInputStream(tarFile$);
        FileOutputStream fos = new FileOutputStream(gzipFile$);
        GZIPOutputStream gzipOS = new GZIPOutputStream(fos);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1) {
            gzipOS.write(buffer, 0, len);
        }
        gzipOS.close();
        fos.close();
        fis.close();
    } catch (Exception e) {
        Logger.getLogger(ArchiveHandler.class.getName()).severe(e.toString());
    }

}

From source file:org.commoncrawl.util.ArcFileWriter.java

/**
 * Gzip passed bytes. Use only when bytes is small.
 * /*  w  w  w . jav  a 2s  .  c om*/
 * @param bytes
 *          What to gzip.
 * @return A gzip member of bytes.
 * @throws IOException
 */
private static byte[] gzip(byte[] bytes) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzipOS = new GZIPOutputStream(baos);
    gzipOS.write(bytes, 0, bytes.length);
    gzipOS.close();
    return baos.toByteArray();
}

From source file:z.hol.net.http.entity.compress.GzipCompressingEntity.java

@Override
public void writeTo(final OutputStream outstream) throws IOException {
    if (outstream == null) {
        throw new IllegalArgumentException("Output stream may not be null");
    }//from w  w  w .jav  a 2 s.  c o  m
    GZIPOutputStream gzip = new GZIPOutputStream(outstream);
    InputStream in = wrappedEntity.getContent();
    byte[] tmp = new byte[2048];
    int l;
    while ((l = in.read(tmp)) != -1) {
        gzip.write(tmp, 0, l);
    }
    gzip.close();
}