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:com.navercorp.pinpoint.web.filter.Base64.java

public static String encodeBytes(byte[] source, int off, int len, int options) {
    if ((options & 2) == 2) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream gzos = null;

        String var33;
        try {//ww  w . j  a  v a 2  s  . co m
            gzos = new GZIPOutputStream(new Base64.Base64OutputStream(baos, 1 | options));
            gzos.write(source, off, len);
            gzos.close();
            gzos = null;
            String var32 = new String(baos.toByteArray(), "UTF-8");
            return var32;
        } catch (UnsupportedEncodingException var27) {
            var33 = new String(baos.toByteArray());
        } catch (IOException var28) {
            LOG.error("error encoding byte array", var28);
            var33 = null;
            return var33;
        } finally {
            if (gzos != null) {
                try {
                    gzos.close();
                } catch (Exception var25) {
                    LOG.error("error closing GZIPOutputStream", var25);
                }
            }

            try {
                baos.close();
            } catch (Exception var24) {
                LOG.error("error closing ByteArrayOutputStream", var24);
            }

        }

        return var33;
    } else {
        boolean breakLines = (options & 8) == 0;
        int len43 = len * 4 / 3;
        byte[] outBuff = new byte[len43 + (len % 3 > 0 ? 4 : 0) + (breakLines ? len43 / 76 : 0)];
        int d = 0;
        int e = 0;
        int len2 = len - 2;

        for (int lineLength = 0; d < len2; e += 4) {
            encode3to4(source, d + off, 3, outBuff, e, options);
            lineLength += 4;
            if (breakLines && lineLength == 76) {
                outBuff[e + 4] = 10;
                ++e;
                lineLength = 0;
            }

            d += 3;
        }

        if (d < len) {
            encode3to4(source, d + off, len - d, outBuff, e, options);
            e += 4;
        }

        try {
            return new String(outBuff, 0, e, "UTF-8");
        } catch (UnsupportedEncodingException var26) {
            return new String(outBuff, 0, e);
        }
    }
}

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);/* ww  w  .j  av a 2  s  . c om*/
        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: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 a2  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.zotoh.core.io.StreamUte.java

/**
 * @param bits/*ww  w  . j a va 2  s. c  om*/
 * @return
 * @throws IOException
 */
public static byte[] gzip(byte[] bits) throws IOException {

    ByteOStream baos = new ByteOStream();
    GZIPOutputStream g = new GZIPOutputStream(baos);

    if (bits != null && bits.length > 0) {
        g.write(bits, 0, bits.length);
        g.close();
    }

    return baos.asBytes();
}

From source file:packjacket.StaticUtils.java

/**
 * GZips the main log file/* w w  w.  j  a  v a  2  s  . c o  m*/
 * @return the gzipped file
 * @throws IOException if any I/O error occurs
 */
public static File gzipLog() throws IOException {
    //Write out buffer of log file
    RunnerClass.nfh.flush();
    //Initialize log and gzip-log files
    File log = new File(RunnerClass.homedir + "pj.log");
    GZIPOutputStream out = new GZIPOutputStream(
            new FileOutputStream(new File(log.getCanonicalPath() + ".pjl")));
    FileInputStream in = new FileInputStream(log);

    //How many bytes to copy with each incrmental copy of file.
    int bufferSize = 4 * 1024;

    //Buffer into which data is read from source file
    byte[] buffer = new byte[bufferSize];
    //How many bytes read so far
    int bytesRead;
    //Runs until no bytes left to read from source
    while ((bytesRead = in.read(buffer)) >= 0)
        out.write(buffer, 0, bytesRead);
    //Close streams
    out.close();
    in.close();

    return new File(log.getCanonicalPath() + ".pjl");
}

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  w  w . j  a v a 2  s .  c  o  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 {/*from   w  w  w .j av 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.wattzap.model.social.SelfLoopsAPI.java

public static int uploadActivity(String email, String passWord, String fileName, String note)
        throws IOException {
    JSONObject jsonObj = null;// ww w  . j a  v  a2 s .  c  o m

    FileInputStream in = null;
    GZIPOutputStream out = null;
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("enctype", "multipart/mixed");

        in = new FileInputStream(fileName);
        // Create stream to compress data and write it to the to file.
        ByteArrayOutputStream obj = new ByteArrayOutputStream();
        out = new GZIPOutputStream(obj);

        // Copy bytes from one stream to the other
        byte[] buffer = new byte[4096];
        int bytes_read;
        while ((bytes_read = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytes_read);
        }
        out.close();
        in.close();

        ByteArrayBody bin = new ByteArrayBody(obj.toByteArray(), ContentType.create("application/x-gzip"),
                fileName);
        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("email", new StringBody(email, ContentType.TEXT_PLAIN))
                .addPart("pw", new StringBody(passWord, ContentType.TEXT_PLAIN)).addPart("tcxfile", bin)
                .addPart("note", new StringBody(note, ContentType.TEXT_PLAIN)).build();

        httpPost.setEntity(reqEntity);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            int code = response.getStatusLine().getStatusCode();
            switch (code) {
            case 200:

                HttpEntity respEntity = response.getEntity();

                if (respEntity != null) {
                    // EntityUtils to get the response content
                    String content = EntityUtils.toString(respEntity);
                    //System.out.println(content);
                    JSONParser jsonParser = new JSONParser();
                    jsonObj = (JSONObject) jsonParser.parse(content);
                }

                break;
            case 403:
                throw new RuntimeException(
                        "Authentification failure " + email + " " + response.getStatusLine());
            default:
                throw new RuntimeException("Error " + code + " " + response.getStatusLine());
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
        }

        int activityId = ((Long) jsonObj.get("activity_id")).intValue();

        // parse error code
        int error = ((Long) jsonObj.get("error_code")).intValue();
        if (activityId == -1) {
            String message = (String) jsonObj.get("message");
            switch (error) {
            case 102:
                throw new RuntimeException("Empty TCX file " + fileName);
            case 103:
                throw new RuntimeException("Invalide TCX Format " + fileName);
            case 104:
                throw new RuntimeException("TCX Already Present " + fileName);
            case 105:
                throw new RuntimeException("Invalid XML " + fileName);
            case 106:
                throw new RuntimeException("invalid compression algorithm");
            case 107:
                throw new RuntimeException("Invalid file mime types");
            default:
                throw new RuntimeException(message + " " + error);
            }
        }

        return activityId;
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
        httpClient.close();
    }
}

From source file:com.wxxr.nirvana.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  va2  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());

    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:com.struts2ext.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);
    }//ww  w. ja v a  2s  .  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
    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(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);
    }
}