Example usage for java.util.zip GZIPOutputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Writes remaining compressed data to the output stream and closes the underlying stream.

Usage

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 ww w  . ja va2s  . 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
    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:org.apache.oozie.compression.GzipCompressionCodec.java

public byte[] compressBytes(byte[] header, byte[] data) throws IOException {
    ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(2000);
    byteOutput.write(header);/*from   www.j av  a 2  s.c om*/
    GZIPOutputStream gzipOut = new GZIPOutputStream(byteOutput);
    gzipOut.write(data);
    gzipOut.close();
    return byteOutput.toByteArray();
}

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);
    }//  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(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.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  ww w .  ja 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.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 {//ww w  .j ava 2 s.c om
            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.slc.sli.api.security.oauth.TokenGeneratorTest.java

/**
 * Not enabled, but would be a quick and dirty way of verifying some amount
 * of entropy in our pseudo-randomness by checking out well it compresses
 *//*from ww w .java  2  s  .c  o  m*/
public void testEntropy() throws Exception {
    String string = TokenGenerator.generateToken(1000);
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    GZIPOutputStream out = new GZIPOutputStream(bytes);
    out.write(string.getBytes());
    out.close();
    assertTrue("Entropy was too low..." + bytes.toByteArray().length, bytes.toByteArray().length > 700);
}

From source file:org.exist.xquery.modules.compression.GZipFunction.java

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    // is there some data to GZip?
    if (args[0].isEmpty())
        return Sequence.EMPTY_SEQUENCE;

    BinaryValue bin = (BinaryValue) args[0].itemAt(0);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // gzip the data
    try {/*w w  w .  j a  v  a  2 s . co  m*/
        GZIPOutputStream gzos = new GZIPOutputStream(baos);
        bin.streamTo(gzos);
        gzos.close();

        return BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(),
                new ByteArrayInputStream(baos.toByteArray()));
    } catch (IOException ioe) {
        throw new XPathException(this, ioe.getMessage());
    }
}

From source file:org.pentaho.di.cluster.HttpUtilTest.java

/**
 * https://www.securecoding.cert.org/confluence/display/java/IDS12-J.+Perform+lossless+conversion+
 * of+String+data+between+differing+character+encodings
 *
 * @param in//from  w w w.  j a  va  2 s.c o  m
 *          string to encode
 * @return
 * @throws IOException
 */
private String canonicalBase64Encode(String in) throws IOException {
    Charset charset = Charset.forName(DEFAULT_ENCODING);
    CharsetEncoder encoder = charset.newEncoder();
    encoder.reset();
    ByteBuffer baosbf = encoder.encode(CharBuffer.wrap(in));
    byte[] bytes = new byte[baosbf.limit()];
    baosbf.get(bytes);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzos = new GZIPOutputStream(baos);
    gzos.write(bytes);
    gzos.close();
    String encoded = new String(Base64.encodeBase64(baos.toByteArray()));

    return encoded;
}

From source file:com.orange.clara.cloud.servicedbdumper.filer.compression.GzipCompressing.java

@Async
public Future<Boolean> gziptIt(InputStream inputStream, OutputStream outputStream) throws IOException {
    logger.debug("Start compressing...");
    GZIPOutputStream gout = new GZIPOutputStream(outputStream);
    ByteStreams.copy(inputStream, gout);
    gout.flush();//from   w  w w.  j a v  a  2  s .  co  m
    gout.close();
    outputStream.flush();
    outputStream.close();
    inputStream.close();
    logger.debug("Finish compressing");
    return new AsyncResult<Boolean>(true);
}

From source file:org.apache.oozie.compression.GzipCompressionCodec.java

public byte[] compressString(byte[] header, String data) throws IOException {
    ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(1000);
    byteOutput.write(header);//from   ww w.j  ava 2  s . c om
    GZIPOutputStream gzipOut = new GZIPOutputStream(byteOutput);
    gzipOut.write(data.getBytes(CodecFactory.UTF_8_ENCODING));
    gzipOut.close();
    return byteOutput.toByteArray();
}