List of usage examples for java.util.zip GZIPOutputStream flush
public void flush() throws IOException
From source file:org.n52.ses.common.environment.SESMiniServlet.java
private void printResponse(HttpServletRequest request, HttpServletResponse response, String string) throws IOException { int contentLength = string.getBytes("UTF-8").length; if (firstResponsePrint.getAndSet(false)) { ConfigurationRegistry conf = ConfigurationRegistry.getInstance(); if (conf == null) { firstResponsePrint.getAndSet(true); } else {/*from w w w.ja v a 2 s. c om*/ minimumContentLengthForGzip = Integer .parseInt(conf.getPropertyForKey(ConfigurationRegistry.MINIMUM_GZIP_SIZE)); } } // compressed response if (contentLength > minimumContentLengthForGzip && clientSupportsGzip(request)) { response.addHeader("Content-Encoding", "gzip"); GZIPOutputStream gzip = new GZIPOutputStream(response.getOutputStream(), contentLength); String type = response.getContentType(); if (!type.contains("charset")) { response.setContentType(type + "; charset=utf-8"); } gzip.write(string.getBytes(Charset.forName("UTF-8"))); gzip.flush(); gzip.finish(); } // uncompressed response else { response.setContentLength(contentLength); response.setCharacterEncoding("UTF-8"); PrintWriter writer = response.getWriter(); writer.write(string); writer.flush(); } }
From source file:com.chenshu.compress.CompressOldTest.java
@Benchmark public int jdkGzip2Compress() { ByteArrayInputStream bin = null; ByteArrayOutputStream bout = null; GZIPOutputStream gzout = null; try {// ww w. j av a 2s.c o m bin = new ByteArrayInputStream(data); bout = new ByteArrayOutputStream(data.length); gzout = new GZIPOutputStream(bout) { { def.setLevel(level); } }; int count; byte ret[] = new byte[1024]; while ((count = bin.read(ret, 0, 1024)) != -1) { gzout.write(ret, 0, count); } gzout.finish(); gzout.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (gzout != null) { try { gzout.close(); } catch (IOException e) { e.printStackTrace(); } } if (bout != null) { try { bout.close(); } catch (IOException e) { e.printStackTrace(); } } } byte[] bs = bout.toByteArray(); return bs.length; }
From source file:org.intermine.api.lucene.KeywordSearch.java
private static void writeObjectToDB(ObjectStore os, String key, Object object) throws IOException, SQLException { LOG.debug("Saving stream to database..."); Database db = ((ObjectStoreInterMineImpl) os).getDatabase(); LargeObjectOutputStream streamOut = null; GZIPOutputStream gzipStream = null; ObjectOutputStream objectStream = null; try {/*from w w w .j a v a 2 s. c om*/ streamOut = MetadataManager.storeLargeBinary(db, key); gzipStream = new GZIPOutputStream(new BufferedOutputStream(streamOut)); objectStream = new ObjectOutputStream(gzipStream); LOG.debug("GZipping and serializing object..."); objectStream.writeObject(object); } finally { if (objectStream != null) { objectStream.flush(); objectStream.close(); } if (gzipStream != null) { gzipStream.finish(); gzipStream.flush(); gzipStream.close(); } if (streamOut != null) { streamOut.close(); } } }
From source file:com.weibo.api.motan.protocol.rpc.CompressRpcCodec.java
public byte[] compress(byte[] org, boolean useGzip, int minGzSize) throws IOException { if (useGzip && org.length > minGzSize) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); GZIPOutputStream gos = new GZIPOutputStream(outputStream); gos.write(org);//from www.j av a 2 s .co m gos.finish(); gos.flush(); gos.close(); byte[] ret = outputStream.toByteArray(); return ret; } else { return org; } }
From source file:org.gwtspringhibernate.reference.rlogman.spring.GwtServiceExporter.java
private void writeResponse(HttpServletRequest request, HttpServletResponse response, String responsePayload) throws IOException { byte[] reply = responsePayload.getBytes(CHARSET_UTF8); String contentType = CONTENT_TYPE_TEXT_PLAIN_UTF8; if (acceptsGzipEncoding(request) && shouldCompressResponse(request, response, responsePayload)) { // Compress the reply and adjust headers. ///* ww w .j av a2 s .c om*/ ByteArrayOutputStream output = null; GZIPOutputStream gzipOutputStream = null; Throwable caught = null; try { output = new ByteArrayOutputStream(reply.length); gzipOutputStream = new GZIPOutputStream(output); gzipOutputStream.write(reply); gzipOutputStream.finish(); gzipOutputStream.flush(); response.setHeader(CONTENT_ENCODING, CONTENT_ENCODING_GZIP); reply = output.toByteArray(); } catch (UnsupportedEncodingException e) { caught = e; } catch (IOException e) { caught = e; } finally { if (null != gzipOutputStream) { gzipOutputStream.close(); } if (null != output) { output.close(); } } if (caught != null) { /** * Our logger will not be servlet context's log (we don't have * direct access to it at this point) * @author rlogman@gmail.com */ logger.error("Unable to compress response", caught); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } // Send the reply. // response.setContentLength(reply.length); response.setContentType(contentType); response.setStatus(HttpServletResponse.SC_OK); response.getOutputStream().write(reply); }
From source file:org.intermine.web.search.ClassAttributes.java
private static void writeObjectToDB(ObjectStore os, String key, Object object) throws IOException, SQLException { LOG.info("Saving stream to database..."); Database db = ((ObjectStoreInterMineImpl) os).getDatabase(); LargeObjectOutputStream streamOut = MetadataManager.storeLargeBinary(db, key); GZIPOutputStream gzipStream = new GZIPOutputStream(new BufferedOutputStream(streamOut)); ObjectOutputStream objectStream = new ObjectOutputStream(gzipStream); LOG.info("GZipping and serializing object..."); objectStream.writeObject(object);/* w w w. j av a 2s. co m*/ objectStream.flush(); gzipStream.finish(); gzipStream.flush(); streamOut.close(); }
From source file:de.zib.scalaris.TransactionSingleOpTest.java
/** * Tests how long it takes to read a large string with different compression * schemes./*from ww w .ja v a2 s . c o m*/ * * @param compressed * how to compress * @param key * the key to append to the {@link #testTime} * * @throws ConnectionException * @throws UnknownException * @throws AbortException * @throws NotFoundException * @throws IOException */ protected void testReadLargeString(final int compression, final String key) throws ConnectionException, UnknownException, AbortException, NotFoundException, IOException { final StringBuilder sb = new StringBuilder(testData.length * 8 * 100); for (int i = 0; i < 100; ++i) { for (final String data : testData) { sb.append(data); } } final String expected = sb.toString(); final TransactionSingleOp conn = new TransactionSingleOp(); conn.setCompressed(true); switch (compression) { case 1: conn.setCompressed(false); case 2: conn.write(testTime + key, expected); break; case 3: conn.setCompressed(false); case 4: final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final GZIPOutputStream gos = new GZIPOutputStream(bos); gos.write(expected.getBytes("UTF-8")); gos.flush(); gos.close(); conn.write(testTime + key, new Base64(0).encodeToString(bos.toByteArray())); break; default: return; } try { for (int i = 0; i < 500; ++i) { String actual = conn.read(testTime + key).stringValue(); if (compression >= 3) { final byte[] packed = new Base64(0).decode(actual); final ByteArrayOutputStream unpacked = new ByteArrayOutputStream(); final ByteArrayInputStream bis = new ByteArrayInputStream(packed); final GZIPInputStream gis = new GZIPInputStream(bis); final byte[] bbuf = new byte[256]; int read = 0; while ((read = gis.read(bbuf)) >= 0) { unpacked.write(bbuf, 0, read); } gis.close(); actual = new String(unpacked.toString("UTF-8")); } assertEquals(expected, actual); } } finally { conn.closeConnection(); } }
From source file:com.funambol.transport.http.server.Sync4jServlet.java
/** * Sets the content of HTTP response.//from w w w .j av a 2 s . com * * Compresses the response if the Accept-Encoding is gzip or deflate. * Sets the Content-Encoding according to the encoding used. * Sets the Content-Length with the length of the compressed response. * Sets the Uncompressed-Content-Length with the length of the uncompressed * response. * The response will be compressed only if the length of the uncompressed * response is greater than the give sizeThreashold. * * @param httpResponse the HttpServletResponse * @param requestAcceptEncoding the <code>Accept-Encoding</code> specified * in the request * @param sizeThreshold if the response is smaller of this value, it * should not be compressed * @param resp the SyncResponse object contains the response message * @param requestTime the time in which the request is arrived to servlet * @param sessionId the session identifier * @throws java.io.IOException if an error occurs * */ private void setResponseContent(HttpServletResponse httpResponse, String requestAcceptEncoding, String sizeThreshold, SyncResponse resp, long requestTime, String sessionId) throws IOException { byte[] responseContent = null; OutputStream out = null; try { out = httpResponse.getOutputStream(); responseContent = resp.getMessage(); int uncompressedContentLength = responseContent.length; if (supportedEncoding != null && !"".equals(supportedEncoding) && enableCompression) { if (log.isTraceEnabled()) { log.trace("Setting Accept-Encoding to " + supportedEncoding); } httpResponse.setHeader(HEADER_ACCEPT_ENCODING, supportedEncoding); } String encodingToUse = null; if (requestAcceptEncoding != null) { if (requestAcceptEncoding.indexOf(COMPRESSION_TYPE_GZIP) != -1 && requestAcceptEncoding.indexOf(COMPRESSION_TYPE_DEFLATE) != -1) { encodingToUse = preferredEncoding; } else if (requestAcceptEncoding.indexOf(COMPRESSION_TYPE_DEFLATE) != -1) { encodingToUse = COMPRESSION_TYPE_DEFLATE; } else if (requestAcceptEncoding.indexOf(COMPRESSION_TYPE_GZIP) != -1) { encodingToUse = COMPRESSION_TYPE_GZIP; } } int threshold = 0; try { if (sizeThreshold != null && sizeThreshold.length() != 0) { threshold = Integer.parseInt(sizeThreshold); } } catch (NumberFormatException ex) { // // Ignoring the specified value // if (log.isTraceEnabled()) { log.trace("The size threshold specified by the client (" + sizeThreshold + ") is not valid."); } } // // If the encodingToUse is null or the // uncompressed response length is less than // sizeThreshold, the response will not be compressed. // if (encodingToUse == null || uncompressedContentLength < threshold) { if (log.isTraceEnabled()) { if (enableCompression) { if (requestAcceptEncoding == null) { log.trace( "The client doesn't support any encoding. " + "The response is not compressed"); } else if (encodingToUse == null) { log.trace("The specified Accept-Encoding (" + requestAcceptEncoding + ") is not recognized. The response is not compressed"); } else if (uncompressedContentLength < threshold) { log.trace("The response is not compressed because smaller than " + threshold); } } } if (log.isTraceEnabled()) { log.trace("Setting Content-Length to: " + uncompressedContentLength); } httpResponse.setContentLength(uncompressedContentLength); out.write(responseContent); out.flush(); return; } if (encodingToUse != null) { if (log.isTraceEnabled()) { log.trace("Compressing the response using: " + encodingToUse); log.trace("Setting Uncompressed-Content-Length to: " + uncompressedContentLength); } httpResponse.setHeader(HEADER_UNCOMPRESSED_CONTENT_LENGTH, String.valueOf(uncompressedContentLength)); if (encodingToUse.equals(COMPRESSION_TYPE_GZIP)) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); GZIPOutputStream outTmp = new GZIPOutputStream(bos); outTmp.write(responseContent, 0, uncompressedContentLength); outTmp.flush(); outTmp.close(); // // Get the compressed data // responseContent = bos.toByteArray(); int compressedLength = responseContent.length; if (log.isTraceEnabled()) { log.trace("Setting Content-Length to: " + compressedLength); log.trace("Setting Content-Encoding to: " + COMPRESSION_TYPE_GZIP); } httpResponse.setContentLength(compressedLength); httpResponse.setHeader(HEADER_CONTENT_ENCODING, COMPRESSION_TYPE_GZIP); out.write(responseContent); out.flush(); } else if (encodingToUse.equals(COMPRESSION_TYPE_DEFLATE)) { // // Create the compressor with specificated level of compression // Deflater compressor = new Deflater(); compressor.setLevel(compressionLevel); compressor.setInput(responseContent); compressor.finish(); // // Create an expandable byte array to hold the compressed data. // You cannot use an array that's the same size as the orginal because // there is no guarantee that the compressed data will be smaller than // the uncompressed data. // ByteArrayOutputStream bos = new ByteArrayOutputStream(uncompressedContentLength); // // Compress the response // byte[] buf = new byte[SIZE_INPUT_BUFFER]; while (!compressor.finished()) { int count = compressor.deflate(buf); bos.write(buf, 0, count); } // // Get the compressed data // responseContent = bos.toByteArray(); int compressedLength = responseContent.length; if (log.isTraceEnabled()) { log.trace("Setting Content-Length to: " + compressedLength); log.trace("Setting Content-Encoding to: " + COMPRESSION_TYPE_DEFLATE); } httpResponse.setContentLength(compressedLength); httpResponse.setHeader(HEADER_CONTENT_ENCODING, COMPRESSION_TYPE_DEFLATE); out.write(responseContent); out.flush(); } } } finally { if (out != null) { out.close(); } if (logMessages) { logResponse(responseContent, requestTime, sessionId); } } }
From source file:org.ramadda.util.Utils.java
/** * _more_/*from ww w. j a va 2s. c o m*/ * * @param s _more_ * * @return _more_ * * @throws Exception _more_ */ public static String compress(String s) throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); GZIPOutputStream gos = new GZIPOutputStream(bos); IOUtil.write(gos, s); gos.flush(); IOUtil.close(gos); bos.flush(); IOUtil.close(bos); byte[] bytes = bos.toByteArray(); return encodeBase64(bytes); }
From source file:au.org.ala.biocache.web.WMSController.java
/** * Get occurrences by query as gzipped csv. * * @param requestParams/* w w w . j av a2 s. c o m*/ * @param response * @throws Exception */ @RequestMapping(value = { "/webportal/occurrences.gz", "/mapping/occurrences.gz" }, method = RequestMethod.GET) public void occurrenceGz(SpatialSearchRequestParams requestParams, HttpServletResponse response) throws Exception { response.setContentType("text/plain"); response.setCharacterEncoding("gzip"); ServletOutputStream outStream = response.getOutputStream(); java.util.zip.GZIPOutputStream gzip = new java.util.zip.GZIPOutputStream(outStream); writeOccurrencesCsvToStream(requestParams, gzip); gzip.flush(); gzip.close(); }