Example usage for java.util.zip GZIPOutputStream finish

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

Introduction

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

Prototype

public void finish() throws IOException 

Source Link

Document

Finishes writing compressed data to the output stream without closing the underlying stream.

Usage

From source file:com.kolich.common.util.io.GZIPCompressor.java

/**
 * Given an uncompressed InputStream, compress it and return the
 * result as new byte array./*from www .j  a  v  a2s  .com*/
 * @return
 */
public static final byte[] compress(final InputStream is, final int outputBufferSize) {
    GZIPOutputStream gzos = null;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        gzos = new GZIPOutputStream(baos, outputBufferSize) {
            // Ugly anonymous constructor hack to set the compression
            // level on the underlying Deflater to "max compression".
            {
                def.setLevel(Deflater.BEST_COMPRESSION);
            }
        };
        IOUtils.copyLarge(is, gzos);
        gzos.finish();
        return baos.toByteArray();
    } catch (Exception e) {
        throw new GZIPCompressorException(e);
    } finally {
        closeQuietly(gzos);
    }
}

From source file:org.cruxframework.crux.core.server.rest.spi.HttpUtil.java

private static byte[] getResponseBytes(HttpRequest request, HttpResponse response, String responseContent)
        throws UnsupportedEncodingException, IOException {
    boolean gzipResponse = shouldGzipResponseContent(request, responseContent);
    byte[] responseBytes = (responseContent != null ? responseContent.getBytes("UTF-8") : new byte[0]);
    if (gzipResponse) {
        ByteArrayOutputStream output = null;
        GZIPOutputStream gzipOutputStream = null;
        try {/*from  w  w w  .  ja  v  a2s  .c o  m*/
            output = new ByteArrayOutputStream(responseBytes.length);
            gzipOutputStream = new GZIPOutputStream(output);
            gzipOutputStream.write(responseBytes);
            gzipOutputStream.finish();
            gzipOutputStream.flush();
            response.getOutputHeaders().putSingle(HttpHeaderNames.CONTENT_ENCODING, "gzip");
            responseBytes = output.toByteArray();
        } catch (IOException e) {
            throw new InternalServerErrorException("Unable to compress response",
                    "Error processing requested service", e);
        } finally {
            if (null != gzipOutputStream) {
                gzipOutputStream.close();
            }
            if (null != output) {
                output.close();
            }
        }
    }
    return responseBytes;
}

From source file:org.mitre.opensextant.util.FileUtility.java

/**
 *
 * @param text/*  w w w  .j  ava2 s.c  o m*/
 * @param fname
 * @return
 * @throws IOException
 */
public static boolean writeGzipFile(String text, String fname) throws IOException {
    if (fname == null || text == null) {
        return false;
    }

    FileOutputStream outstream = new FileOutputStream(fname);
    GZIPOutputStream gzout = new GZIPOutputStream(new BufferedOutputStream(outstream), default_buffer);

    gzout.write(text.getBytes(default_encoding));

    gzout.flush();
    gzout.finish();

    gzout.close();
    outstream.close();
    return true;

}

From source file:updater.builder.SoftwarePatchBuilder.java

public static void catalog(CommandLine line, Options options) throws ParseException, Exception {
    if (!line.hasOption("key")) {
        throw new Exception("Please specify the key file to use using --key");
    }//from ww  w .j a v  a  2  s  . c om
    if (!line.hasOption("output")) {
        throw new Exception("Please specify the path to output the XML file using --output");
    }

    String[] catalogArgs = line.getOptionValues("catalog");
    String keyArg = line.getOptionValue("key");
    String outputArg = line.getOptionValue("output");

    if (catalogArgs.length != 2) {
        throw new ParseException("Wrong arguments for 'catalog', expecting 2 arguments");
    }
    if (!catalogArgs[0].equals("e") && !catalogArgs[0].equals("d")) {
        throw new ParseException("Catalog mode should be either 'e' or 'd' but not " + catalogArgs[0]);
    }

    RSAKey rsaKey = RSAKey.read(Util.readFile(new File(keyArg)));

    System.out.println("Mode: " + (catalogArgs[0].equals("e") ? "encrypt" : "decrypt"));
    System.out.println("Catalog file: " + catalogArgs[1]);
    System.out.println("Key file: " + keyArg);
    System.out.println("Output file: " + outputArg);
    System.out.println();

    File in = new File(catalogArgs[1]);
    File out = new File(outputArg);
    BigInteger mod = new BigInteger(rsaKey.getModulus());

    if (catalogArgs[0].equals("e")) {
        BigInteger privateExp = new BigInteger(rsaKey.getPrivateExponent());

        RSAPrivateKey privateKey = CommonUtil.getPrivateKey(mod, privateExp);

        // compress
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        GZIPOutputStream gout = new GZIPOutputStream(bout);
        gout.write(Util.readFile(in));
        gout.finish();
        byte[] compressedData = bout.toByteArray();

        // encrypt
        int blockSize = mod.bitLength() / 8;
        byte[] encrypted = Util.rsaEncrypt(privateKey, blockSize, blockSize - 11, compressedData);

        // write to file
        Util.writeFile(out, encrypted);
    } else {
        BigInteger publicExp = new BigInteger(rsaKey.getPublicExponent());
        RSAPublicKey publicKey = CommonUtil.getPublicKey(mod, publicExp);

        // decrypt
        int blockSize = mod.bitLength() / 8;
        byte[] decrypted = Util.rsaDecrypt(publicKey, blockSize, Util.readFile(in));

        // decompress
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ByteArrayInputStream bin = new ByteArrayInputStream(decrypted);
        GZIPInputStream gin = new GZIPInputStream(bin);

        int byteRead;
        byte[] b = new byte[1024];
        while ((byteRead = gin.read(b)) != -1) {
            bout.write(b, 0, byteRead);
        }
        byte[] decompressedData = bout.toByteArray();

        // write to file
        Util.writeFile(out, decompressedData);
    }

    System.out.println("Manipulation succeed.");
}

From source file:com.hbs.common.josn.JSONUtil.java

public static void writeJSONToResponse(HttpServletResponse response, String encoding, boolean wrapWithComments,
        String serializedJSON, boolean smd, boolean gzip, String contentType) throws IOException {
    String json = serializedJSON == null ? "" : serializedJSON;
    if (wrapWithComments) {
        StringBuilder sb = new StringBuilder("/* ");
        sb.append(json);//from ww w  .j a v a 2  s.co m
        sb.append(" */");
        json = sb.toString();
    }
    if (log.isDebugEnabled()) {
        log.debug("[JSON]" + json);
    }

    if (contentType == null) {
        contentType = "application/json";
    }
    response.setContentType((smd ? "application/json-rpc;charset=" : contentType + ";charset=") + encoding);
    if (gzip) {
        response.addHeader("Content-Encoding", "gzip");
        GZIPOutputStream out = null;
        InputStream in = null;
        try {
            out = new GZIPOutputStream(response.getOutputStream());
            in = new ByteArrayInputStream(json.getBytes());
            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(encoding).length);
        PrintWriter out = response.getWriter();
        out.print(json);
    }
}

From source file:org.apache.drill.exec.vector.complex.writer.TestJsonReader.java

License:asdf

public static void gzipIt(File sourceFile) throws IOException {

    // modified from: http://www.mkyong.com/java/how-to-compress-a-file-in-gzip-format/
    byte[] buffer = new byte[1024];
    GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(sourceFile.getPath() + ".gz"));

    FileInputStream in = new FileInputStream(sourceFile);

    int len;/*from w  ww .  j  av a  2 s  .co  m*/
    while ((len = in.read(buffer)) > 0) {
        gzos.write(buffer, 0, len);
    }
    in.close();
    gzos.finish();
    gzos.close();
}

From source file:org.apache.myfaces.shared.util.StateUtils.java

public static final byte[] compress(byte[] bytes) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {/*w ww. jav a 2s  . c o  m*/
        GZIPOutputStream gzip = new GZIPOutputStream(baos);
        gzip.write(bytes, 0, bytes.length);
        gzip.finish();
        byte[] fewerBytes = baos.toByteArray();
        gzip.close();
        baos.close();
        gzip = null;
        baos = null;
        return fewerBytes;
    } catch (IOException e) {
        throw new FacesException(e);
    }
}

From source file:com.googlecode.jsonplugin.JSONUtil.java

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

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

    if (TextUtils.stringSet(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 . c o 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
    if (serializationParams.isSmd())
        response.setContentType("application/json-rpc;charset=" + serializationParams.getEncoding());
    else
        response.setContentType(
                serializationParams.getContentType() + ";charset=" + serializationParams.getEncoding());

    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());
            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:com.krawler.common.util.ByteUtil.java

/**
 * compress the supplied data using GZIPOutputStream and return the
 * compressed data./*from  ww  w . ja  va  2s. c o  m*/
 * 
 * @param data
 *            data to compress
 * @return compressesd data
 */
public static byte[] compress(byte[] data) throws IOException {
    ByteArrayOutputStream baos = null;
    GZIPOutputStream gos = null;
    try {
        baos = new ByteArrayOutputStream(data.length); // data.length
        // overkill
        gos = new GZIPOutputStream(baos);
        gos.write(data);
        gos.finish();
        return baos.toByteArray();
    } finally {
        if (gos != null) {
            gos.close();
        } else if (baos != null)
            baos.close();
    }
}

From source file:org.hyperic.hq.stats.AbstractStatsWriter.java

public static void gzipFile(final String filename) {
    new Thread() {
        public void run() {
            FileOutputStream gfile = null;
            GZIPOutputStream gstream = null;
            PrintStream pstream = null;
            BufferedReader reader = null;
            boolean succeed = false;
            try {
                gfile = new FileOutputStream(filename + ".gz");
                gstream = new GZIPOutputStream(gfile);
                pstream = new PrintStream(gstream);
                reader = new BufferedReader(new FileReader(filename));
                String tmp;//from w  ww .  j  a  v  a  2  s .c o  m
                while (null != (tmp = reader.readLine())) {
                    pstream.append(tmp).append("\n");
                }
                gstream.finish();
                succeed = true;
            } catch (IOException e) {
                log.warn(e.getMessage(), e);
            } finally {
                close(gfile);
                close(gstream);
                close(pstream);
                close(reader);
                if (succeed) {
                    new File(filename).delete();
                } else {
                    new File(filename + ".gz").delete();
                }
            }
        }

        private void close(Closeable s) {
            if (s != null) {
                try {
                    s.close();
                } catch (IOException e) {
                    log.warn(e.getMessage(), e);
                }
            }
        }
    }.start();
}