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: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  ww  .j a  v a  2  s .  co  m*/
            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:org.apache.sling.discovery.impl.topology.connector.TopologyConnectorClient.java

/** ping the server and pass the announcements between the two **/
void ping(final boolean force) {
    if (autoStopped) {
        // then we suppress any further pings!
        logger.debug("ping: autoStopped=true, hence suppressing any further pings.");
        return;// w  w w  .j  a  v  a2  s. c o  m
    }
    if (force) {
        backoffPeriodEnd = -1;
    } else if (backoffPeriodEnd > 0) {
        if (System.currentTimeMillis() < backoffPeriodEnd) {
            logger.debug("ping: not issueing a heartbeat due to backoff instruction from peer.");
            return;
        } else {
            logger.debug("ping: backoff period ended, issuing another ping now.");
        }
    }
    final String uri = connectorUrl.toString() + "." + clusterViewService.getSlingId() + ".json";
    if (logger.isDebugEnabled()) {
        logger.debug("ping: connectorUrl=" + connectorUrl + ", complete uri=" + uri);
    }
    HttpClient httpClient = new HttpClient();
    final PutMethod method = new PutMethod(uri);
    Announcement resultingAnnouncement = null;
    try {
        String userInfo = connectorUrl.getUserInfo();
        if (userInfo != null) {
            Credentials c = new UsernamePasswordCredentials(userInfo);
            httpClient.getState()
                    .setCredentials(new AuthScope(method.getURI().getHost(), method.getURI().getPort()), c);
        }

        Announcement topologyAnnouncement = new Announcement(clusterViewService.getSlingId());
        topologyAnnouncement.setServerInfo(serverInfo);
        final ClusterView clusterView = clusterViewService.getClusterView();
        topologyAnnouncement.setLocalCluster(clusterView);
        if (force) {
            logger.debug("ping: sending a resetBackoff");
            topologyAnnouncement.setResetBackoff(true);
        }
        announcementRegistry.addAllExcept(topologyAnnouncement, clusterView, new AnnouncementFilter() {

            public boolean accept(final String receivingSlingId, final Announcement announcement) {
                // filter out announcements that are of old cluster instances
                // which I dont really have in my cluster view at the moment
                final Iterator<InstanceDescription> it = clusterViewService.getClusterView().getInstances()
                        .iterator();
                while (it.hasNext()) {
                    final InstanceDescription instance = it.next();
                    if (instance.getSlingId().equals(receivingSlingId)) {
                        // then I have the receiving instance in my cluster view
                        // all fine then
                        return true;
                    }
                }
                // looks like I dont have the receiving instance in my cluster view
                // then I should also not propagate that announcement anywhere
                return false;
            }
        });
        final String p = requestValidator.encodeMessage(topologyAnnouncement.asJSON());

        if (logger.isDebugEnabled()) {
            logger.debug("ping: topologyAnnouncement json is: " + p);
        }
        requestValidator.trustMessage(method, p);
        if (config.isGzipConnectorRequestsEnabled()) {
            // tell the server that the content is gzipped:
            method.addRequestHeader("Content-Encoding", "gzip");
            // and gzip the body:
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
            gzipOut.write(p.getBytes("UTF-8"));
            gzipOut.close();
            final byte[] gzippedEncodedJson = baos.toByteArray();
            method.setRequestEntity(new ByteArrayRequestEntity(gzippedEncodedJson, "application/json"));
            lastRequestEncoding = "gzip";
        } else {
            // otherwise plaintext:
            method.setRequestEntity(new StringRequestEntity(p, "application/json", "UTF-8"));
            lastRequestEncoding = "plaintext";
        }
        // independent of request-gzipping, we do accept the response to be gzipped,
        // so indicate this to the server:
        method.addRequestHeader("Accept-Encoding", "gzip");
        DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(0, false);
        httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler);
        httpClient.getHttpConnectionManager().getParams()
                .setConnectionTimeout(1000 * config.getConnectionTimeout());
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(1000 * config.getSoTimeout());
        method.getParams().setSoTimeout(1000 * config.getSoTimeout());
        httpClient.executeMethod(method);
        if (logger.isDebugEnabled()) {
            logger.debug("ping: done. code=" + method.getStatusCode() + " - " + method.getStatusText());
        }
        lastStatusCode = method.getStatusCode();
        lastResponseEncoding = null;
        if (method.getStatusCode() == HttpServletResponse.SC_OK) {
            final Header contentEncoding = method.getResponseHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue() != null
                    && contentEncoding.getValue().contains("gzip")) {
                lastResponseEncoding = "gzip";
            } else {
                lastResponseEncoding = "plaintext";
            }
            String responseBody = requestValidator.decodeMessage(method); // limiting to 16MB, should be way enough
            if (logger.isDebugEnabled()) {
                logger.debug("ping: response body=" + responseBody);
            }
            if (responseBody != null && responseBody.length() > 0) {
                Announcement inheritedAnnouncement = Announcement.fromJSON(responseBody);
                final long backoffInterval = inheritedAnnouncement.getBackoffInterval();
                if (backoffInterval > 0) {
                    // then reset the backoffPeriodEnd:

                    /* minus 1 sec to avoid slipping the interval by a few millis */
                    this.backoffPeriodEnd = System.currentTimeMillis() + (1000 * backoffInterval) - 1000;
                    logger.debug("ping: servlet instructed to backoff: backoffInterval=" + backoffInterval
                            + ", resulting in period end of " + new Date(backoffPeriodEnd));
                } else {
                    logger.debug("ping: servlet did not instruct any backoff-ing at this stage");
                    this.backoffPeriodEnd = -1;
                }
                if (inheritedAnnouncement.isLoop()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(
                                "ping: connector response indicated a loop detected. not registering this announcement from "
                                        + inheritedAnnouncement.getOwnerId());
                    }
                    if (inheritedAnnouncement.getOwnerId().equals(clusterViewService.getSlingId())) {
                        // SLING-3316 : local-loop detected. Check config to see if we should stop this connector

                        if (config.isAutoStopLocalLoopEnabled()) {
                            inheritedAnnouncement = null; // results in connected -> false and representsloop -> true
                            autoStopped = true; // results in isAutoStopped -> true
                        }
                    }
                } else {
                    inheritedAnnouncement.setInherited(true);
                    if (announcementRegistry.registerAnnouncement(inheritedAnnouncement) == -1) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "ping: connector response is from an instance which I already see in my topology"
                                            + inheritedAnnouncement);
                        }
                        statusDetails = "receiving side is seeing me via another path (connector or cluster) already (loop)";
                        return;
                    }
                }
                resultingAnnouncement = inheritedAnnouncement;
                statusDetails = null;
            } else {
                statusDetails = "no response body received";
            }
        } else {
            statusDetails = "got HTTP Status-Code: " + lastStatusCode;
        }
        // SLING-2882 : reset suppressPingWarnings_ flag in success case
        suppressPingWarnings_ = false;
    } catch (URIException e) {
        logger.warn("ping: Got URIException: " + e + ", uri=" + uri);
        statusDetails = e.toString();
    } catch (IOException e) {
        // SLING-2882 : set/check the suppressPingWarnings_ flag
        if (suppressPingWarnings_) {
            if (logger.isDebugEnabled()) {
                logger.debug("ping: got IOException: " + e + ", uri=" + uri);
            }
        } else {
            suppressPingWarnings_ = true;
            logger.warn("ping: got IOException [suppressing further warns]: " + e + ", uri=" + uri);
        }
        statusDetails = e.toString();
    } catch (JSONException e) {
        logger.warn("ping: got JSONException: " + e);
        statusDetails = e.toString();
    } catch (RuntimeException re) {
        logger.warn("ping: got RuntimeException: " + re, re);
        statusDetails = re.toString();
    } finally {
        method.releaseConnection();
        lastInheritedAnnouncement = resultingAnnouncement;
        lastPingedAt = System.currentTimeMillis();
    }
}

From source file:org.apache.hadoop.io.compress.TestCodec.java

public void testGzipCompatibility() throws IOException {
    Random r = new Random();
    long seed = r.nextLong();
    r.setSeed(seed);/*  w  ww. j a v a  2  s .  c  o  m*/
    LOG.info("seed: " + seed);

    DataOutputBuffer dflbuf = new DataOutputBuffer();
    GZIPOutputStream gzout = new GZIPOutputStream(dflbuf);
    byte[] b = new byte[r.nextInt(128 * 1024 + 1)];
    r.nextBytes(b);
    gzout.write(b);
    gzout.close();

    DataInputBuffer gzbuf = new DataInputBuffer();
    gzbuf.reset(dflbuf.getData(), dflbuf.getLength());

    Configuration conf = new Configuration();
    conf.setBoolean("hadoop.native.lib", false);
    CompressionCodec codec = ReflectionUtils.newInstance(GzipCodec.class, conf);
    Decompressor decom = codec.createDecompressor();
    assertNotNull(decom);
    assertEquals(BuiltInGzipDecompressor.class, decom.getClass());
    InputStream gzin = codec.createInputStream(gzbuf, decom);

    dflbuf.reset();
    IOUtils.copyBytes(gzin, dflbuf, 4096);
    final byte[] dflchk = Arrays.copyOf(dflbuf.getData(), dflbuf.getLength());
    assertTrue(java.util.Arrays.equals(b, dflchk));
}

From source file:com.rackspacecloud.blueflood.inputs.handlers.HttpHandlerIntegrationTest.java

@Test
public void testCompressedRequests() throws Exception {

    URIBuilder builder = getMetricsURIBuilder().setPath("/v2.0/acTEST/ingest");

    HttpPost post = new HttpPost(builder.build());
    String content = generateJSONMetricsData();
    ByteArrayOutputStream baos = new ByteArrayOutputStream(content.length());
    GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
    gzipOut.write(content.getBytes());
    gzipOut.close();/* ww w.  jav a 2  s .  c  o  m*/
    ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray());
    //Setting the content encoding to gzip
    entity.setContentEncoding("gzip");
    baos.close();
    post.setEntity(entity);
    HttpResponse response = client.execute(post);

    try {
        assertEquals(200, response.getStatusLine().getStatusCode());
    } finally {
        EntityUtils.consume(response.getEntity()); // Releases connection apparently
    }
}

From source file:org.apache.sling.discovery.base.connectors.ping.TopologyConnectorClient.java

/** ping the server and pass the announcements between the two **/
void ping(final boolean force) {
    if (autoStopped) {
        // then we suppress any further pings!
        logger.debug("ping: autoStopped=true, hence suppressing any further pings.");
        return;//  w w w .  j av a2s .  com
    }
    if (force) {
        backoffPeriodEnd = -1;
    } else if (backoffPeriodEnd > 0) {
        if (System.currentTimeMillis() < backoffPeriodEnd) {
            logger.debug("ping: not issueing a heartbeat due to backoff instruction from peer.");
            return;
        } else {
            logger.debug("ping: backoff period ended, issuing another ping now.");
        }
    }
    final String uri = connectorUrl.toString() + "." + clusterViewService.getSlingId() + ".json";
    if (logger.isDebugEnabled()) {
        logger.debug("ping: connectorUrl=" + connectorUrl + ", complete uri=" + uri);
    }
    final HttpClientContext clientContext = HttpClientContext.create();
    final CloseableHttpClient httpClient = createHttpClient();
    final HttpPut putRequest = new HttpPut(uri);

    // setting the connection timeout (idle connection, configured in seconds)
    putRequest.setConfig(
            RequestConfig.custom().setConnectTimeout(1000 * config.getSocketConnectTimeout()).build());

    Announcement resultingAnnouncement = null;
    try {
        String userInfo = connectorUrl.getUserInfo();
        if (userInfo != null) {
            Credentials c = new UsernamePasswordCredentials(userInfo);
            clientContext.getCredentialsProvider().setCredentials(
                    new AuthScope(putRequest.getURI().getHost(), putRequest.getURI().getPort()), c);
        }

        Announcement topologyAnnouncement = new Announcement(clusterViewService.getSlingId());
        topologyAnnouncement.setServerInfo(serverInfo);
        final ClusterView clusterView;
        try {
            clusterView = clusterViewService.getLocalClusterView();
        } catch (UndefinedClusterViewException e) {
            // SLING-5030 : then we cannot ping
            logger.warn("ping: no clusterView available at the moment, cannot ping others now: " + e);
            return;
        }
        topologyAnnouncement.setLocalCluster(clusterView);
        if (force) {
            logger.debug("ping: sending a resetBackoff");
            topologyAnnouncement.setResetBackoff(true);
        }
        announcementRegistry.addAllExcept(topologyAnnouncement, clusterView, new AnnouncementFilter() {

            public boolean accept(final String receivingSlingId, final Announcement announcement) {
                // filter out announcements that are of old cluster instances
                // which I dont really have in my cluster view at the moment
                final Iterator<InstanceDescription> it = clusterView.getInstances().iterator();
                while (it.hasNext()) {
                    final InstanceDescription instance = it.next();
                    if (instance.getSlingId().equals(receivingSlingId)) {
                        // then I have the receiving instance in my cluster view
                        // all fine then
                        return true;
                    }
                }
                // looks like I dont have the receiving instance in my cluster view
                // then I should also not propagate that announcement anywhere
                return false;
            }
        });
        final String p = requestValidator.encodeMessage(topologyAnnouncement.asJSON());

        if (logger.isDebugEnabled()) {
            logger.debug("ping: topologyAnnouncement json is: " + p);
        }
        requestValidator.trustMessage(putRequest, p);
        if (config.isGzipConnectorRequestsEnabled()) {
            // tell the server that the content is gzipped:
            putRequest.addHeader("Content-Encoding", "gzip");
            // and gzip the body:
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
            gzipOut.write(p.getBytes("UTF-8"));
            gzipOut.close();
            final byte[] gzippedEncodedJson = baos.toByteArray();
            putRequest.setEntity(new ByteArrayEntity(gzippedEncodedJson, ContentType.APPLICATION_JSON));
            lastRequestEncoding = "gzip";
        } else {
            // otherwise plaintext:
            final StringEntity plaintext = new StringEntity(p, "UTF-8");
            plaintext.setContentType(ContentType.APPLICATION_JSON.getMimeType());
            putRequest.setEntity(plaintext);
            lastRequestEncoding = "plaintext";
        }
        // independent of request-gzipping, we do accept the response to be gzipped,
        // so indicate this to the server:
        putRequest.addHeader("Accept-Encoding", "gzip");
        final CloseableHttpResponse response = httpClient.execute(putRequest, clientContext);
        if (logger.isDebugEnabled()) {
            logger.debug("ping: done. code=" + response.getStatusLine().getStatusCode() + " - "
                    + response.getStatusLine().getReasonPhrase());
        }
        lastStatusCode = response.getStatusLine().getStatusCode();
        lastResponseEncoding = null;
        if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) {
            final Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue() != null
                    && contentEncoding.getValue().contains("gzip")) {
                lastResponseEncoding = "gzip";
            } else {
                lastResponseEncoding = "plaintext";
            }
            final String responseBody = requestValidator.decodeMessage(putRequest.getURI().getPath(), response); // limiting to 16MB, should be way enough
            if (logger.isDebugEnabled()) {
                logger.debug("ping: response body=" + responseBody);
            }
            if (responseBody != null && responseBody.length() > 0) {
                Announcement inheritedAnnouncement = Announcement.fromJSON(responseBody);
                final long backoffInterval = inheritedAnnouncement.getBackoffInterval();
                if (backoffInterval > 0) {
                    // then reset the backoffPeriodEnd:

                    /* minus 1 sec to avoid slipping the interval by a few millis */
                    this.backoffPeriodEnd = System.currentTimeMillis() + (1000 * backoffInterval) - 1000;
                    logger.debug("ping: servlet instructed to backoff: backoffInterval=" + backoffInterval
                            + ", resulting in period end of " + new Date(backoffPeriodEnd));
                } else {
                    logger.debug("ping: servlet did not instruct any backoff-ing at this stage");
                    this.backoffPeriodEnd = -1;
                }
                if (inheritedAnnouncement.isLoop()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(
                                "ping: connector response indicated a loop detected. not registering this announcement from "
                                        + inheritedAnnouncement.getOwnerId());
                    }
                    if (inheritedAnnouncement.getOwnerId().equals(clusterViewService.getSlingId())) {
                        // SLING-3316 : local-loop detected. Check config to see if we should stop this connector

                        if (config.isAutoStopLocalLoopEnabled()) {
                            inheritedAnnouncement = null; // results in connected -> false and representsloop -> true
                            autoStopped = true; // results in isAutoStopped -> true
                        }
                    }
                } else {
                    inheritedAnnouncement.setInherited(true);
                    if (announcementRegistry.registerAnnouncement(inheritedAnnouncement) == -1) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "ping: connector response is from an instance which I already see in my topology"
                                            + inheritedAnnouncement);
                        }
                        statusDetails = "receiving side is seeing me via another path (connector or cluster) already (loop)";
                        return;
                    }
                }
                resultingAnnouncement = inheritedAnnouncement;
                statusDetails = null;
            } else {
                statusDetails = "no response body received";
            }
        } else {
            statusDetails = "got HTTP Status-Code: " + lastStatusCode;
        }
        // SLING-2882 : reset suppressPingWarnings_ flag in success case
        suppressPingWarnings_ = false;
    } catch (IOException e) {
        // SLING-2882 : set/check the suppressPingWarnings_ flag
        if (suppressPingWarnings_) {
            if (logger.isDebugEnabled()) {
                logger.debug("ping: got IOException: " + e + ", uri=" + uri);
            }
        } else {
            suppressPingWarnings_ = true;
            logger.warn("ping: got IOException [suppressing further warns]: " + e + ", uri=" + uri);
        }
        statusDetails = e.toString();
    } catch (JSONException e) {
        logger.warn("ping: got JSONException: " + e);
        statusDetails = e.toString();
    } catch (RuntimeException re) {
        logger.warn("ping: got RuntimeException: " + re, re);
        statusDetails = re.toString();
    } finally {
        putRequest.releaseConnection();
        lastInheritedAnnouncement = resultingAnnouncement;
        lastPingedAt = System.currentTimeMillis();
        try {
            httpClient.close();
        } catch (IOException e) {
            logger.error("disconnect: could not close httpClient: " + e, e);
        }
    }
}

From source file:org.opensextant.util.TextUtils.java

/**
 *
 * @param buf/*from  w w  w.  jav a2  s  .c o  m*/
 *            text
 * @param charset
 *            character set encoding for text
 * @return byte array for the compressed result
 * @throws IOException
 *             on error with compression or text encoding
 */
public static byte[] compress(String buf, String charset) throws IOException {

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gz = new GZIPOutputStream(out);
    gz.write(buf.getBytes(charset));
    gz.close();

    return out.toByteArray();
}

From source file:org.apache.sling.discovery.etcd.EtcdServiceTest.java

@Test
public void testGetGzipped() throws Exception {
    HttpServlet servlet = new HttpServlet() {
        @Override/*from  w  w  w . j  ava  2s  . c o m*/
        protected void service(HttpServletRequest req, HttpServletResponse res)
                throws ServletException, IOException {
            String acceptEncoding = req.getHeader("Accept-Encoding");
            if (acceptEncoding != null && acceptEncoding.equalsIgnoreCase("gzip")) {
                res.setHeader("Content-Encoding", "gzip");
                res.setStatus(200);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                GZIPOutputStream gzip = new GZIPOutputStream(out);
                String data = IOUtils.toString(getClass().getResourceAsStream("/get-properties.json"), "UTF-8");
                gzip.write(data.getBytes("UTF-8"));
                gzip.close();
                res.getOutputStream().write(out.toByteArray());
            } else {
                throw new IllegalArgumentException("accept-encoding not found or not gzip");
            }
        }
    };
    server = startServer(servlet, "/v2/keys/discovery/properties/sling-id");
    EtcdService etcdService = buildEtcdService(serverPort(server));
    Map<String, String> properties = etcdService.getProperties("sling-id");
    Assert.assertNotNull(properties);
    Assert.assertEquals(1, properties.size());
}

From source file:de.derschimi.proxyservlet.TestServlet.java

/** Copy response body data (the entity) from the proxy to the servlet client. */
protected void copyResponseEntity(HttpResponse proxyResponse, HttpServletResponse servletResponse)
        throws IOException {
    HttpEntity entity = proxyResponse.getEntity();
    if (entity != null) {

        OutputStream servletOutputStream = servletResponse.getOutputStream();
        if (entity.getContentEncoding() != null) {
            servletResponse.setCharacterEncoding("UTF-8");

            String charset = entity.getContentType().getValue();

            String charst = charset.substring(charset.lastIndexOf("=") + 1);
            if (entity.getContentEncoding().getValue().equals("gzip")) {
                InputStream in = entity.getContent();

                InputStream zin = new GZIPInputStream(in);
                StringWriter writer = new StringWriter();

                IOUtils.copy(zin, writer, "UTF-8");
                String theString = writer.toString();

                // System.out.println(theString);
                theString = theString.replaceAll("href=\"/", "href=\"/" + path + "/");
                theString = theString.replaceAll("src=\"/", "src=\"/" + path + "/");

                // css
                String par = "(";
                String pattern = "url" + par + "\"/static/";
                // replace all uses regex
                while (theString.contains(pattern)) {
                    theString = theString.replace(pattern, "url" + par + "\"/" + path + "/static/");
                }/*from  w w  w. j  a  v  a  2 s .  c  o m*/
                // css...
                String pattern2 = "url" + par + "/static/";
                while (theString.contains(pattern2)) {
                    theString = theString.replace(pattern2, "url" + par + "/" + path + "/static/");
                }
                //  window.location = '/artikel/a-774487.html';
                theString = replace(theString, "window.location = '/artikel/",
                        "windows.location = '/" + path + "/artikel/");
                //a.href = "/video/video
                theString = replace(theString, "a.href = \"/video/video",
                        "a.href = \"/" + path + "/video/video");
                // ("src", "/video/video
                theString = replace(theString, "(\"src\", \"/video/video",
                        "(\"src\", \"" + path + "/video/video");

                // flash :)
                String pattern3 = "data=\"/static/";
                while (theString.contains(pattern3)) {
                    theString = theString.replace(pattern3, "data=" + "/" + path + "/static/");
                }

                ByteArrayOutputStream out = new ByteArrayOutputStream();

                GZIPOutputStream gzip = new GZIPOutputStream(out);
                gzip.write(theString.getBytes());
                gzip.close();

                servletOutputStream.write(out.toByteArray());
            } else {
                System.err.println("not a gzip request:");
            }
        } else {
            entity.writeTo(servletOutputStream);
        }
    }
}

From source file:at.ofai.gate.virtualcorpus.JDBCCorpus.java

protected InputStream getGZIPCompressedInputStream(String theString, String theEncoding) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gos = new GZIPOutputStream(baos);
    gos.write(theString.getBytes(theEncoding));
    gos.close();//from w  w w  .j  a  v a 2 s.  c o  m
    ByteArrayInputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
    return inputStream;
}

From source file:org.ofbiz.webapp.event.RestEventHandler.java

private void createAndSendRESTResponse(Map<String, Object> serviceResults, String serviceName,
        HttpServletResponse response) throws EventHandlerException {
    try {//from  www.j a v a 2 s . co m
        // setup the response
        Debug.logVerbose("[EventHandler] : Setting up response message", module);

        JsonConfig config = new JsonConfig();
        config.registerJsonValueProcessor(java.util.Date.class, new JsDateJsonValueProcessor());
        config.registerJsonValueProcessor(java.sql.Date.class, new JsDateJsonValueProcessor());
        config.registerJsonValueProcessor(java.sql.Timestamp.class, new JsDateJsonValueProcessor());
        config.registerJsonValueProcessor(java.sql.Time.class, new JsDateJsonValueProcessor());
        JSONObject restResults = JSONObject.fromObject(serviceResults, config);

        //               Debug.logInfo("restResults ==================" + restResults, module);

        // log the response message
        if (Debug.verboseOn()) {
            try {
                Debug.logInfo("Response Message:\n" + restResults + "\n", module);
            } catch (Throwable t) {
            }
        }

        //Writer out = response.getWriter();
        //out.write(restResults.toString());
        //restResult.write(out);
        //out.flush();
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        GZIPOutputStream gout = new GZIPOutputStream(bout); //buffer
        gout.write(restResults.toString().getBytes());
        gout.close();
        //??
        byte g[] = bout.toByteArray();
        response.setHeader("Content-Encoding", "gzip");
        response.setHeader("Content-Length", g.length + "");
        response.getOutputStream().write(g);
        //restResult.write(response.getOutputStream());
        //response.getOutputStream().flush();
    } catch (Exception e) {
        Debug.logError(e, module);
        throw new EventHandlerException(e.getMessage(), e);
    }
}