List of usage examples for java.util.zip GZIPOutputStream finish
public void finish() throws IOException
From source file:cn.keke.travelmix.publictransport.JsonProxyRouter.java
public void handle(HttpExchange xchg) throws IOException { try {//from w ww.j av a 2s .c o m StringBuffer response = new StringBuffer(4096); String query = xchg.getRequestURI().getRawQuery(); String callbackMethod = HttpClientHelper.parseQueryMap(query).get("callback"); response.append(callbackMethod).append("("); LOG.info(query); if (StringUtils.isNotEmpty(query)) { RoutingJob job = createRoutingJob(query); if (job != null) { RoutingTask task = null; Header[] headers = convertRequestHeaders(xchg.getRequestHeaders()); List<Future<String>> futures = new ArrayList<Future<String>>(Provider.values().length); while ((task = job.pop()) != null) { task.setHeaders(headers); task.setResponse(response); futures.add(ExecutorUtils.THREAD_POOL.submit(task)); } for (Future<String> future : futures) { if (job.isHandled()) { System.out.println("Finished: " + job); break; } else { future.get(); } } } } response.append(");"); xchg.getResponseHeaders().set("Content-Encoding", "gzip"); xchg.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0); GZIPOutputStream os = new GZIPOutputStream(xchg.getResponseBody()); LOG.info(response.toString()); os.write(response.toString().getBytes()); os.finish(); xchg.close(); } catch (Exception e) { LOG.warn("Json Routing Request failed", e); } }
From source file:com.edgenius.wiki.service.impl.SitemapServiceImpl.java
private void zipToFile(File sizemapZipFile, byte[] bytes) throws FileNotFoundException, IOException { FileOutputStream gzos = new FileOutputStream(sizemapZipFile); GZIPOutputStream gzipstream = new GZIPOutputStream(gzos); gzipstream.write(bytes);// w w w. ja v a2 s. co m gzipstream.finish(); IOUtils.closeQuietly(gzos); }
From source file:com.iisigroup.cap.utils.CapSerialization.java
/** * compress byte array data with GZIP./*from w w w .java 2 s .co m*/ * * @param input * the input data * @return the compressed data * @throws java.io.IOException */ public byte[] compress(byte[] input) throws java.io.IOException { byte[] result = null; java.io.ByteArrayOutputStream baout = null; GZIPOutputStream gzipout = null; try { baout = new java.io.ByteArrayOutputStream(); gzipout = new GZIPOutputStream(baout); gzipout.write(input); gzipout.finish(); result = baout.toByteArray(); return result; } finally { IOUtils.closeQuietly(baout); IOUtils.closeQuietly(gzipout); } }
From source file:org.mule.util.compression.GZipCompression.java
/** * Used for compressing a byte array into a new byte array using GZIP * //from w w w. j a va 2 s . co m * @param bytes An array of bytes to compress * @return a compressed byte array * @throws java.io.IOException if it fails to write to a GZIPOutputStream * @see java.util.zip.GZIPOutputStream */ public byte[] compressByteArray(byte[] bytes) throws IOException { // TODO add strict behaviour as option if (bytes == null || isCompressed(bytes)) { // nothing to compress if (logger.isDebugEnabled()) { logger.debug("Data already compressed; doing nothing"); } return bytes; } if (logger.isDebugEnabled()) { logger.debug("Compressing message of size: " + bytes.length); } ByteArrayOutputStream baos = null; GZIPOutputStream gzos = null; try { baos = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE); gzos = new GZIPOutputStream(baos); gzos.write(bytes, 0, bytes.length); gzos.finish(); gzos.close(); byte[] compressedByteArray = baos.toByteArray(); baos.close(); if (logger.isDebugEnabled()) { logger.debug("Compressed message to size: " + compressedByteArray.length); } return compressedByteArray; } catch (IOException ioex) { throw ioex; } finally { IOUtils.closeQuietly(gzos); IOUtils.closeQuietly(baos); } }
From source file:com.google.ie.web.view.GsonView.java
@Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { String jsonResult = getJsonString(filterModel(model)); // Write the result to response response.setContentType(contentType); response.setStatus(statusCode);//from ww w . ja v a 2 s . c o m response.setCharacterEncoding(characterEncoding); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Expires", "0"); response.setHeader("Pragma", "No-cache"); if (isGzipInRequest(request)) { response.addHeader("Content-Encoding", "gzip"); GZIPOutputStream out = null; try { out = new GZIPOutputStream(response.getOutputStream()); out.write(jsonResult.getBytes(characterEncoding)); } finally { if (out != null) { out.finish(); out.close(); } } } else { response.getWriter().print(jsonResult); } }
From source file:org.apache.mahout.text.SequenceFilesFromMailArchivesTest.java
/** * Create the input and output directories needed for testing * the SequenceFilesFromMailArchives application. *///from w w w .ja va2 s . com @Override @Before public void setUp() throws Exception { super.setUp(); inputDir = getTestTempDir("mail-archives-in"); // write test mail messages to a gzipped file in a nested directory File subDir = new File(inputDir, "subdir"); subDir.mkdir(); File gzFile = new File(subDir, "mail-messages.gz"); GZIPOutputStream gzOut = null; try { gzOut = new GZIPOutputStream(new FileOutputStream(gzFile)); gzOut.write(testMailMessages.getBytes("UTF-8")); gzOut.finish(); } finally { Closeables.close(gzOut, false); } File subDir2 = new File(subDir, "subsubdir"); subDir2.mkdir(); File gzFile2 = new File(subDir2, "mail-messages-2.gz"); try { gzOut = new GZIPOutputStream(new FileOutputStream(gzFile2)); gzOut.write(testMailMessages.getBytes("UTF-8")); gzOut.finish(); } finally { Closeables.close(gzOut, false); } }
From source file:halive.shootinoutside.common.core.game.map.GameMap.java
public byte[] serializeMapToCompressedByteArray() throws IOException { //Compress data ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzipOut = new GZIPOutputStream(out); gzipOut.write(serializeMapToJSONString().getBytes()); gzipOut.flush();/* w w w . j a v a2 s. co m*/ gzipOut.finish(); return out.toByteArray(); }
From source file:org.appcelerator.transport.AjaxServiceTransportServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ////w w w .ja v a2s . c o m // make sure we check the integrity of the request before we continue // if (!validate(req, resp)) { LOG.warn("security validation failed for request=" + req + " from " + req.getRemoteAddr()); return; } String type = req.getContentType(); int idx = type.indexOf(';'); if (idx > 0) { type = type.substring(0, idx); } try { // decode the incoming request ArrayList<Message> requests = new ArrayList<Message>(1); ArrayList<Message> responses = new ArrayList<Message>(1); ServiceMarshaller.getMarshaller(type).decode(req.getInputStream(), requests); if (requests.isEmpty()) { // no incoming messages, just return accepted header resp.setHeader("Content-Length", "0"); resp.setContentType("text/plain;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_ACCEPTED); return; } HttpSession session = req.getSession(); InetAddress address = InetAddress.getByName(req.getRemoteAddr()); //String instanceid = req.getParameter("instanceid"); for (Message request : requests) { request.setUser(req.getUserPrincipal()); request.setSession(session); request.setAddress(address); request.setServletRequest(req); //FIXME => refactor this out if (request.getType().equals(MessageType.APPCELERATOR_STATUS_REPORT)) { IMessageDataObject data = (IMessageDataObject) request.getData(); data.put("remoteaddr", req.getRemoteAddr()); data.put("remotehost", req.getRemoteHost()); data.put("remoteuser", req.getRemoteUser()); } ServiceRegistry.dispatch(request, responses); } if (responses.isEmpty()) { // no response messages, just return accepted header resp.setHeader("Content-Length", "0"); resp.setContentType("text/plain;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_ACCEPTED); return; } // setup the response resp.setStatus(HttpServletResponse.SC_OK); resp.setHeader("Connection", "Keep-Alive"); resp.setHeader("Pragma", "no-cache"); resp.setHeader("Cache-control", "no-cache, no-store, private, must-revalidate"); resp.setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); // encode the responses ServletOutputStream output = resp.getOutputStream(); ByteArrayOutputStream bout = new ByteArrayOutputStream(1000); String responseType = ServiceMarshaller.getMarshaller(type).encode(responses, req.getSession().getId(), bout); byte buf[] = bout.toByteArray(); ByteArrayInputStream bin = new ByteArrayInputStream(buf); resp.setContentType(responseType); // do gzip encoding if browser supports it and if length > 1000 bytes String ae = req.getHeader("accept-encoding"); if (ae != null && ae.indexOf("gzip") != -1 && buf.length > 1000) { resp.setHeader("Content-Encoding", "gzip"); //a Vary: Accept-Encoding HTTP response header to alert proxies that a cached response should be sent only to //clients that send the appropriate Accept-Encoding request header. This prevents compressed content from being sent //to a client that will not understand it. resp.addHeader("Vary", "Accept-Encoding"); GZIPOutputStream gzip = new GZIPOutputStream(output, buf.length); Util.copy(bin, gzip); gzip.flush(); gzip.finish(); } else { resp.setContentLength(buf.length); Util.copy(bin, output); } output.flush(); } catch (Throwable e) { LOG.error("Error handling incoming POST request", e); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:com.generalbioinformatics.rdf.AbstractTripleStore.java
public RecordStream sparqlSelect(String query) throws StreamException { try {//ww w. j a v a2 s . c om RecordStream rs; long start = System.currentTimeMillis(); if (cacheDir == null) { rs = _sparqlSelectDirect(query); long delta = System.currentTimeMillis() - start; fireQueryPerformed(query, delta); } else { if (!cacheDir.exists()) { if (!cacheDir.mkdirs()) throw new IOException("Could not create cache directory"); } int hashCode = query.hashCode() + 3 * this.hashCode(); String hashCodeString = String.format("%08x", hashCode); File cacheSubdir = new File(cacheDir, hashCodeString.substring(0, 2)); File out = new File(cacheSubdir, hashCodeString + ".txt.gz"); if (out.exists()) { // merely "touch" the file, so we know the cached file was used recently. org.apache.commons.io.FileUtils.touch(out); } else { // make subdir if it doesn't exist. if (!cacheSubdir.exists()) { if (!cacheSubdir.mkdir()) throw new IOException("Couldn't create directory " + cacheSubdir); } File tmp = File.createTempFile(hashCodeString + "-", ".tmp", cacheSubdir); try { OutputStream os = new FileOutputStream(tmp); GZIPOutputStream gos = new GZIPOutputStream(os); RecordStream rsx = _sparqlSelectDirect(query); long delta = System.currentTimeMillis() - start; Utils.queryResultsToFile(this, delta, rsx, query, gos); gos.finish(); os.close(); fireQueryPerformed(query, delta); } catch (RuntimeException e) { tmp.delete(); throw (e); } catch (StreamException e) { tmp.delete(); throw (e); } tmp.renameTo(out); } InputStream is = HFileUtils.openZipStream(out); rs = TsvRecordStream.open(is).filterComments().get(); } return rs; } catch (IOException ex) { throw new StreamException(ex); } }
From source file:org.geoserver.wcs.responses.AscCoverageResponseDelegate.java
public void encode(GridCoverage2D sourceCoverage, String outputFormat, Map<String, String> econdingParameters, OutputStream output) throws ServiceException, IOException { if (sourceCoverage == null) { throw new IllegalStateException(new StringBuffer("It seems prepare() has not been called") .append(" or has not succeed").toString()); }/*from w w w .j a va2s. c om*/ GZIPOutputStream gzipOut = null; if (isOutputCompressed(outputFormat)) { gzipOut = new GZIPOutputStream(output); output = gzipOut; } ArcGridWriter writer = null; try { writer = new ArcGridWriter(output); writer.write(sourceCoverage, null); if (gzipOut != null) { gzipOut.finish(); gzipOut.flush(); } } finally { try { if (writer != null) writer.dispose(); } catch (Throwable e) { // eating exception } if (gzipOut != null) IOUtils.closeQuietly(gzipOut); sourceCoverage.dispose(true); } }