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 void write(int b) throws IOException 

Source Link

Document

Writes a byte to the compressed output stream.

Usage

From source file:com.couchbase.lite.DatabaseAttachmentTest.java

public void testGzippedAttachments() throws Exception {
    String attachmentName = "index.html";
    byte content[] = "This is a test attachment!".getBytes("UTF-8");

    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    GZIPOutputStream gzipOut = new GZIPOutputStream(byteOut);
    gzipOut.write(content);
    gzipOut.close();//from  w w  w.j  a  va  2 s  .c  o m
    byte contentGzipped[] = byteOut.toByteArray();

    Document doc = database.createDocument();
    UnsavedRevision rev = doc.createRevision();
    rev.setAttachment(attachmentName, "text/html", new ByteArrayInputStream(contentGzipped));
    rev.save();

    SavedRevision savedRev = doc.getCurrentRevision();
    Attachment attachment = savedRev.getAttachment(attachmentName);

    // As far as revision users are concerned their data is not gzipped
    InputStream in = attachment.getContent();
    assertNotNull(in);
    assertTrue(Arrays.equals(content, IOUtils.toByteArray(in)));
    in.close();

    Document gotDoc = database.getDocument(doc.getId());
    Revision gotRev = gotDoc.getCurrentRevision();
    Attachment gotAtt = gotRev.getAttachment(attachmentName);
    in = gotAtt.getContent();
    assertNotNull(in);
    assertTrue(Arrays.equals(content, IOUtils.toByteArray(in)));
    in.close();
}

From source file:com.bt.download.android.gui.httpserver.BrowseHandler.java

@Override
public void handle(HttpExchange exchange) throws IOException {
    assertUPnPActive();//from w w w  . ja va2s.co m

    GZIPOutputStream os = null;

    byte type = -1;

    try {

        List<NameValuePair> query = URLEncodedUtils.parse(exchange.getRequestURI(), "UTF-8");

        for (NameValuePair item : query) {
            if (item.getName().equals("type")) {
                type = Byte.parseByte(item.getValue());
            }
        }

        if (type == -1) {
            exchange.sendResponseHeaders(Code.HTTP_BAD_REQUEST, 0);
            return;
        }

        String response = getResponse(exchange, type);

        exchange.getResponseHeaders().set("Content-Encoding", "gzip");
        exchange.getResponseHeaders().set("Content-Type", "text/json; charset=UTF-8");
        exchange.sendResponseHeaders(Code.HTTP_OK, 0);

        os = new GZIPOutputStream(exchange.getResponseBody());

        os.write(response.getBytes("UTF-8"));
        os.finish();

    } catch (IOException e) {
        LOG.warning("Error browsing files type=" + type);
        throw e;
    } finally {
        if (os != null) {
            os.close();
        }
        exchange.close();
    }
}

From source file:com.zimbra.cs.dav.service.DavServlet.java

private void cacheCleanUp(DavContext ctxt, CacheStates cache) throws IOException {
    if (cache.ctagCacheEnabled && cache.cacheThisCtagResponse
            && ctxt.getStatus() == DavProtocol.STATUS_MULTI_STATUS) {
        assert (cache.ctagCacheKey != null && cache.acctVerSnapshot != null && !cache.ctagsSnapshot.isEmpty());
        DavResponse dresp = ctxt.getDavResponse();
        ByteArrayOutputStream baosRaw = null;
        try {//  ww  w . j a va2  s .c om
            baosRaw = new ByteArrayOutputStream();
            dresp.writeTo(baosRaw);
        } finally {
            ByteUtil.closeStream(baosRaw);
        }
        byte[] respData = baosRaw.toByteArray();
        int rawLen = respData.length;

        boolean forceGzip = true;
        // Cache gzipped response if client supports it.
        boolean responseGzipped = forceGzip || cache.gzipAccepted;
        if (responseGzipped) {
            ByteArrayOutputStream baosGzipped = new ByteArrayOutputStream();
            GZIPOutputStream gzos = null;
            try {
                gzos = new GZIPOutputStream(baosGzipped);
                gzos.write(respData);
            } finally {
                ByteUtil.closeStream(gzos);
            }
            respData = baosGzipped.toByteArray();
        }

        CtagResponseCacheValue ctagCacheVal = new CtagResponseCacheValue(respData, rawLen, responseGzipped,
                cache.acctVerSnapshot, cache.ctagsSnapshot);
        try {
            cache.ctagResponseCache.put(cache.ctagCacheKey, ctagCacheVal);
        } catch (ServiceException e) {
            ZimbraLog.dav.warn("Unable to cache ctag response", e);
            // No big deal if we can't cache the response.  Just move on.
        }
    }
}

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.
        ///*from w  w  w .  j  av  a2  s  .c  o  m*/
        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: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);
        gos.finish();/*w ww.  j  ava  2s .c  o  m*/
        gos.flush();
        gos.close();
        byte[] ret = outputStream.toByteArray();
        return ret;
    } else {
        return org;
    }

}

From source file:org.openchaos.android.fooping.service.PingService.java

private void sendMessage(final JSONObject json) {
    boolean encrypt = prefs.getBoolean("SendAES", false);
    boolean compress = prefs.getBoolean("SendGZIP", false);
    String exchangeHost = prefs.getString("ExchangeHost", null);
    int exchangePort = Integer.valueOf(prefs.getString("ExchangePort", "-1"));

    if (encrypt) {
        if (skeySpec == null) {
            try {
                skeySpec = new SecretKeySpec(MessageDigest.getInstance("SHA-256")
                        .digest(prefs.getString("ExchangeKey", null).getBytes("US-ASCII")), "AES");
            } catch (Exception e) {
                Log.e(tag, e.toString());
                e.printStackTrace();//from ww w  . ja v a 2  s .c om
            }
        }

        if (cipher == null) {
            try {
                cipher = Cipher.getInstance("AES/CFB8/NoPadding");
            } catch (Exception e) {
                Log.e(tag, e.toString());
                e.printStackTrace();
            }
        }

        if (skeySpec == null || cipher == null) {
            Log.e(tag, "Encryption requested but not available");
            throw new AssertionError();
        }
    }

    if (exchangeHost == null || exchangePort <= 0 || exchangePort >= 65536) {
        Log.e(tag, "Invalid server name or port");
        throw new AssertionError();
    }

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        CipherOutputStream cos = null;
        GZIPOutputStream zos = null;

        // TODO: send protocol header to signal compression & encryption

        if (encrypt) {
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            cos = new CipherOutputStream(baos, cipher);

            // write iv block
            baos.write(cipher.getIV());
        }

        final byte[] message = new JSONArray().put(json).toString().getBytes();

        if (compress) {
            zos = new GZIPOutputStream((encrypt) ? (cos) : (baos));
            zos.write(message);
            zos.finish();
            zos.close();
            if (encrypt) {
                cos.close();
            }
        } else if (encrypt) {
            cos.write(message);
            cos.close();
        } else {
            baos.write(message);
        }

        baos.flush();
        final byte[] output = baos.toByteArray();
        baos.close();

        // path MTU is the actual limit here, not only local MTU
        // TODO: make packet fragmentable (clear DF flag)
        if (output.length > 1500) {
            Log.w(tag, "Message probably too long: " + output.length + " bytes");
        }

        DatagramSocket socket = new DatagramSocket();
        // socket.setTrafficClass(0x04 | 0x02); // IPTOS_RELIABILITY | IPTOS_LOWCOST
        socket.send(
                new DatagramPacket(output, output.length, InetAddress.getByName(exchangeHost), exchangePort));
        socket.close();
        Log.d(tag, "message sent: " + output.length + " bytes (raw: " + message.length + " bytes)");
    } catch (Exception e) {
        Log.e(tag, e.toString());
        e.printStackTrace();
    }
}

From source file:org.dspace.EDMExport.controller.homeController.java

/**
 * Controller para la url /viewXml.htm con mtodo GET y sin parmetros.
 * Se recogen los datos del formulario con la configuracin de elementos EDM para mostrar el xml de los tems seleccionados.
 * Si hay errores se redirige a la lista de tems seleccionados, si no se muestra el xml con los datos en EDM.
 * Si el xml a mostrar excede los 2MB y no se comprime con el servlet se comprime el contenido y se enva tambin.
 * //  w ww.java 2  s. c  o m
 * @param edmExportBOFormEDMData objeto que recoge los datos pasados del formulario {@link EDMExportBOFormEDMData}
 * @param result objeto con el que se une la peticin y se valida {@link BindingResult}
 * @param model objeto de Spring Model con la peticin {@link Model}
 * @param request objeto de la peticin http para recoger los datos del objeto flash (como la sesin pero dura una peticin)
 * @return cadena con la vista a renderizar y mostrar
 */
@RequestMapping(value = "/viewXml.htm", method = RequestMethod.GET)
public String getViewXML(@ModelAttribute(value = "FormEDMData") EDMExportBOFormEDMData edmExportBOFormEDMData,
        BindingResult result, Model model, HttpServletRequest request) {
    logger.debug("homeController.getViewXML");
    Map<String, ?> map = RequestContextUtils.getInputFlashMap(request);
    if (map == null) {
        logger.debug("No FlashMap");
        return "redirect:selectedItems.htm";
    }
    if (result.hasErrors()) {
        logErrorValid(result);
        return "redirect:selectedItems.htm";
    } else {
        edmExportServiceXML.setEdmExportServiceListItems(edmExportServiceListItems);
        String edmXML = edmExportServiceXML.showEDMXML(edmExportBOFormEDMData, servletContext.getRealPath(""));
        logger.debug(edmXML);
        String edmXMLEncoded = "";
        String encoding = request.getHeader("Content-Encoding");
        //while (edmXML.length() <= 1500000) edmXML += edmXML;
        if (edmXML.length() > 1500000 && (encoding == null || (encoding != null && encoding.isEmpty()))) {
            ByteArrayOutputStream output = null;
            GZIPOutputStream gzOut = null;
            try {
                output = new ByteArrayOutputStream();
                gzOut = new GZIPOutputStream(output);
                gzOut.write(edmXML.getBytes("UTF-8"));
                gzOut.finish();
                byte[] encoded = Base64.encodeBase64(output.toByteArray());
                edmXMLEncoded = new String(encoded, "UTF-8");
            } catch (IOException e) {
                logger.debug("IOException", e);
            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (gzOut != null)
                        gzOut.close();
                } catch (IOException e) {
                    logger.debug("IOException", e);
                }

            }
        }
        logger.debug(edmXMLEncoded);
        model.addAttribute("formatXML", edmExportBOFormEDMData.getXmlFormat());
        model.addAttribute("edmXML", edmXML);
        model.addAttribute("edmXMLEncoded", edmXMLEncoded);
        model.addAttribute("listElementsFilled", edmExportServiceXML.getListElementsFilled());
        return returnView("viewXml", model);
    }
}

From source file:org.mskcc.cbio.portal.servlet.NetworkServlet.java

public void processGetNetworkRequest(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    try {/*from   www .j a  va  2  s . com*/
        StringBuilder messages = new StringBuilder();

        XDebug xdebug = new XDebug(req);

        String xd = req.getParameter("xdebug");
        boolean logXDebug = xd != null && xd.equals("1");

        //  Get User Defined Gene List
        String geneListStr = req.getParameter(QueryBuilder.GENE_LIST);
        Set<String> queryGenes = new HashSet<String>(Arrays.asList(geneListStr.toUpperCase().split("[, ]+")));
        int nMiRNA = filterNodes(queryGenes);
        if (nMiRNA > 0) {
            messages.append("MicroRNAs were excluded from the network query. ");
        }

        //String geneticProfileIdSetStr = xssUtil.getCleanInput (req, QueryBuilder.GENETIC_PROFILE_IDS);

        String netSrc = req.getParameter("netsrc");
        String strNetSize = req.getParameter("netsize");
        NetworkIO.NetworkSize netSize;
        try {
            netSize = NetworkIO.NetworkSize.valueOf(strNetSize.toUpperCase());
        } catch (Exception e) {
            netSize = NetworkIO.NetworkSize.LARGE;
        }

        String dsSrc = req.getParameter("source");
        List<String> dataSources = dsSrc == null ? null : Arrays.asList(dsSrc.split("[, ]+"));

        Network network;
        xdebug.startTimer();
        if ("cpath2".equalsIgnoreCase(netSrc)) {
            network = NetworkIO.readNetworkFromCPath2(queryGenes, true);
            if (logXDebug) {
                xdebug.logMsg("GetPathwayCommonsNetwork", "<a href=\"" + NetworkIO.getCPath2URL(queryGenes)
                        + "\" target=\"_blank\">cPath2 URL</a>");
            }
        } else {
            network = NetworkIO.readNetworkFromCGDS(queryGenes, netSize, dataSources, true);
        }

        //network = NetworkIO.readNetworkFromCPath2(queryGenes, true);

        xdebug.stopTimer();
        xdebug.logMsg(this,
                "Successfully retrieved networks from " + netSrc + ": took " + xdebug.getTimeElapsed() + "ms");

        // get cancer study id
        // if cancer study id is null, return the current network
        String cancerStudyId = req.getParameter(QueryBuilder.CANCER_STUDY_ID);
        CancerStudy cancerStudy = DaoCancerStudy.getCancerStudyByStableId(cancerStudyId);

        if (network.countNodes() != 0 && cancerStudyId != null) {

            // add attribute is_query to indicate if a node is in query genes
            // and get the list of genes in network
            xdebug.logMsg(this, "Retrieving data from CGDS...");

            // Get sample ids
            Set<String> targetSampleIds = getSampleIds(req, cancerStudyId);
            List<Integer> internalSampleIds = InternalIdUtil.getInternalNonNormalSampleIds(
                    cancerStudy.getInternalId(), new ArrayList<String>(targetSampleIds));

            //  Get User Selected Genetic Profiles
            Set<GeneticProfile> geneticProfileSet = getGeneticProfileSet(req, cancerStudyId);

            // getzScoreThreshold
            double zScoreThreshold = Double.parseDouble(req.getParameter(QueryBuilder.Z_SCORE_THRESHOLD));

            xdebug.startTimer();

            Map<String, Map<String, Integer>> mapQueryGeneAlterationCaseNumber = getMapQueryGeneAlterationCaseNumber(
                    req);

            DaoGeneOptimized daoGeneOptimized = DaoGeneOptimized.getInstance();

            Set<Node> queryNodes = new HashSet<Node>();
            for (Node node : network.getNodes()) {
                if (node.getType().equals(NodeType.DRUG))
                    continue;

                String ngnc = NetworkUtils.getSymbol(node);
                if (ngnc == null) {
                    continue;
                }

                if (mapQueryGeneAlterationCaseNumber != null) {
                    if (queryGenes.contains(ngnc)) {
                        queryNodes.add(node);
                        continue;
                    }
                }

                CanonicalGene canonicalGene = daoGeneOptimized.getGene(ngnc);
                if (canonicalGene == null) {
                    continue;
                }

                long entrezGeneId = canonicalGene.getEntrezGeneId();

                // add attributes
                addCGDSDataAsNodeAttribute(node, entrezGeneId, geneticProfileSet, internalSampleIds,
                        zScoreThreshold);
            }

            xdebug.stopTimer();
            xdebug.logMsg(this, "Retrived data from CGDS. Took " + xdebug.getTimeElapsed() + "ms");

            if (mapQueryGeneAlterationCaseNumber != null) {
                addAttributesForQueryGenes(queryNodes, internalSampleIds.size(),
                        mapQueryGeneAlterationCaseNumber);
            }

            String nLinker = req.getParameter("linkers");
            if (nLinker != null && nLinker.matches("[0-9]+")) {
                int nBefore = network.countNodes();
                int querySize = queryGenes.size();
                String strDiffusion = req.getParameter("diffusion");
                double diffusion;
                try {
                    diffusion = Double.parseDouble(strDiffusion);
                } catch (Exception ex) {
                    diffusion = 0;
                }

                xdebug.startTimer();
                pruneNetworkByAlteration(network, diffusion, Integer.parseInt(nLinker), querySize);
                int nAfter = network.countNodes(true);
                if (nBefore != nAfter) {
                    messages.append("The network below contains ");
                    messages.append(nAfter);
                    messages.append(" nodes, including your ");
                    messages.append(querySize);
                    messages.append(" query gene");
                    if (querySize > 1) {
                        messages.append("s");
                    }
                    messages.append(" and the ");
                    messages.append(nAfter - querySize);
                    messages.append(" most frequently altered neighbor genes ");
                    messages.append(" (out of a total of ");
                    messages.append(nBefore - querySize);
                    messages.append(").\n");
                }
                xdebug.stopTimer();
                xdebug.logMsg(this, "Prune network. Took " + xdebug.getTimeElapsed() + "ms");
            }

            String encodedQueryAlteration = encodeQueryAlteration(mapQueryGeneAlterationCaseNumber);

            if (logXDebug) {
                xdebug.logMsg(this,
                        "<a href=\"" + getNetworkServletUrl(req, false, false, false, encodedQueryAlteration)
                                + "\" target=\"_blank\">NetworkServlet URL</a>");
            }

            messages.append("Download the complete network in ");
            messages.append("<a href=\"");
            messages.append(getNetworkServletUrl(req, true, true, false, encodedQueryAlteration));
            messages.append("\" target=\"_blank\">GraphML</a> ");
            messages.append("or <a href=\"");
            messages.append(getNetworkServletUrl(req, true, true, true, encodedQueryAlteration));
            messages.append("\" target=\"_blank\">SIF</a>");
            messages.append(
                    " for import into <a href=\"http://cytoscape.org\" target=\"_blank\">Cytoscape</a>");
            messages.append(" (<a href=\"http://chianti.ucsd.edu/cyto_web/plugins/displayplugininfo.php?");
            messages.append("name=GraphMLReader\" target=\"_blank\">GraphMLReader plugin</a>");
            messages.append(" is required for importing GraphML).");
        }

        String format = req.getParameter("format");
        boolean sif = format != null && format.equalsIgnoreCase("sif");

        String download = req.getParameter("download");
        if (download != null && download.equalsIgnoreCase("on")) {
            res.setContentType("application/octet-stream");
            res.addHeader("content-disposition",
                    "attachment; filename=cbioportal." + (sif ? "sif" : "graphml"));
            messages.append("In order to open this file in Cytoscape, please install GraphMLReader plugin.");
        } else {
            res.setContentType("text/" + (sif ? "plain" : "xml"));
        }

        String gzip = req.getParameter("gzip");
        boolean isGzip = gzip != null && gzip.equalsIgnoreCase("on");
        if (isGzip) {
            res.setHeader("Content-Encoding", "gzip");
        }

        NetworkIO.NodeLabelHandler nodeLabelHandler = new NetworkIO.NodeLabelHandler() {
            // using HGNC gene symbol as label if available
            public String getLabel(Node node) {
                if (node.getType().equals(NodeType.DRUG))
                    return (String) node.getAttribute("NAME");

                String symbol = NetworkUtils.getSymbol(node);
                if (symbol != null) {
                    return symbol;
                }

                Object strNames = node.getAttributes().get("PARTICIPANT_NAME");
                if (strNames != null) {
                    String[] names = strNames.toString().split(";", 2);
                    if (names.length > 0) {
                        return names[0];
                    }
                }

                return node.getId();
            }
        };

        String graph;
        if (sif) {
            graph = NetworkIO.writeNetwork2Sif(network, nodeLabelHandler);
        } else {
            graph = NetworkIO.writeNetwork2GraphML(network, nodeLabelHandler);
        }

        if (logXDebug) {
            writeXDebug(xdebug, res);
        }

        String msgoff = req.getParameter("msgoff");
        if ((msgoff == null || !msgoff.equals("t")) && messages.length() > 0) {
            writeMsg(messages.toString(), res);
        }

        if (isGzip) {
            GZIPOutputStream out = new GZIPOutputStream(res.getOutputStream());
            out.write(graph.getBytes());
            out.close();
        } else {
            PrintWriter writer = res.getWriter();
            writer.write(graph);
            writer.close();
        }
    } catch (Exception e) {
        //throw new ServletException (e);
        writeMsg("Error loading network. Please report this to " + GlobalProperties.getEmailContact() + "!\n"
                + e.toString(), res);
        res.getWriter().write("<graphml></graphml>");
    }
}

From source file:com.mirth.connect.connectors.http.HttpReceiver.java

private void sendResponse(Request baseRequest, HttpServletResponse servletResponse,
        DispatchResult dispatchResult) throws Exception {
    ContentType contentType = ContentType
            .parse(replaceValues(connectorProperties.getResponseContentType(), dispatchResult));
    if (!connectorProperties.isResponseDataTypeBinary() && contentType.getCharset() == null) {
        /*//  ww  w  .  j  a  va  2  s.  com
         * If text mode is used and a specific charset isn't already defined, use the one from
         * the connector properties. We can't use ContentType.withCharset here because it
         * doesn't preserve other parameters, like boundary definitions
         */
        contentType = ContentType.parse(contentType.toString() + "; charset="
                + CharsetUtils.getEncoding(connectorProperties.getCharset()));
    }
    servletResponse.setContentType(contentType.toString());

    // set the response headers
    for (Entry<String, List<String>> entry : connectorProperties.getResponseHeaders().entrySet()) {
        for (String headerValue : entry.getValue()) {
            servletResponse.addHeader(entry.getKey(), replaceValues(headerValue, dispatchResult));
        }
    }

    // set the status code
    int statusCode = NumberUtils
            .toInt(replaceValues(connectorProperties.getResponseStatusCode(), dispatchResult), -1);

    /*
     * set the response body and status code (if we choose a response from the drop-down)
     */
    if (dispatchResult != null && dispatchResult.getSelectedResponse() != null) {
        dispatchResult.setAttemptedResponse(true);

        Response selectedResponse = dispatchResult.getSelectedResponse();
        Status newMessageStatus = selectedResponse.getStatus();

        /*
         * If the status code is custom, use the entered/replaced string If is is not a
         * variable, use the status of the destination's response (success = 200, failure = 500)
         * Otherwise, return 200
         */
        if (statusCode != -1) {
            servletResponse.setStatus(statusCode);
        } else if (newMessageStatus != null && newMessageStatus.equals(Status.ERROR)) {
            servletResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        } else {
            servletResponse.setStatus(HttpStatus.SC_OK);
        }

        String message = selectedResponse.getMessage();

        if (message != null) {
            OutputStream responseOutputStream = servletResponse.getOutputStream();
            byte[] responseBytes;
            if (connectorProperties.isResponseDataTypeBinary()) {
                responseBytes = Base64Util.decodeBase64(message.getBytes("US-ASCII"));
            } else {
                responseBytes = message.getBytes(CharsetUtils.getEncoding(connectorProperties.getCharset()));
            }

            // If the client accepts GZIP compression, compress the content
            boolean gzipResponse = false;
            for (Enumeration<String> en = baseRequest.getHeaders("Accept-Encoding"); en.hasMoreElements();) {
                String acceptEncoding = en.nextElement();

                if (acceptEncoding != null && acceptEncoding.contains("gzip")) {
                    gzipResponse = true;
                    break;
                }
            }

            if (gzipResponse) {
                servletResponse.setHeader(HTTP.CONTENT_ENCODING, "gzip");
                GZIPOutputStream gzipOutputStream = new GZIPOutputStream(responseOutputStream);
                gzipOutputStream.write(responseBytes);
                gzipOutputStream.finish();
            } else {
                responseOutputStream.write(responseBytes);
            }

            // TODO include full HTTP payload in sentResponse
        }
    } else {
        /*
         * If the status code is custom, use the entered/replaced string Otherwise, return 200
         */
        if (statusCode != -1) {
            servletResponse.setStatus(statusCode);
        } else {
            servletResponse.setStatus(HttpStatus.SC_OK);
        }
    }
}

From source file:de.zib.scalaris.TransactionSingleOpTest.java

/**
 * Tests how long it takes to read a large string with different compression
 * schemes./*from w ww .  j  a  va2s. c  om*/
 *
 * @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();
    }
}