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.moss.simpledeb.core.DebWriter.java

private byte[] buildGzipTar(List<ArchivePath> paths) throws Exception {

    byte[] tarData;
    {// ww  w.  j  av a 2 s.  co m
        ByteArrayOutputStream tarOut = new ByteArrayOutputStream();
        TarArchiveOutputStream tar = new TarArchiveOutputStream(tarOut);

        Set<String> writtenPaths = new HashSet<String>();
        for (ArchivePath path : paths) {
            String name = path.entry().getName();

            if (writtenPaths.contains(name)) {
                throw new RuntimeException("Duplicate archive entry: " + name);
            }

            writtenPaths.add(name);

            tar.putArchiveEntry(path.entry());

            if (!path.entry().isDirectory()) {
                InputStream in = path.read();
                byte[] buffer = new byte[1024 * 10];
                for (int numRead = in.read(buffer); numRead != -1; numRead = in.read(buffer)) {
                    tar.write(buffer, 0, numRead);
                }
                in.close();
            }

            tar.closeArchiveEntry();
        }

        tar.close();
        tarData = tarOut.toByteArray();
    }

    byte[] gzipData;
    {
        ByteArrayOutputStream gzipOut = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(gzipOut);
        gzip.write(tarData);
        gzip.close();

        gzipData = gzipOut.toByteArray();
    }

    return gzipData;
}

From source file:org.apache.xmlrpc.CommonsXmlRpcTransport.java

public InputStream sendXmlRpc(byte[] request) throws IOException, XmlRpcClientException {
    method = new PostMethod(url.toString());
    method.setHttp11(http11);/*  w w w  .j  ava 2 s . co m*/
    method.setRequestHeader(new Header("Content-Type", "text/xml"));

    if (rgzip)
        method.setRequestHeader(new Header("Content-Encoding", "gzip"));

    if (gzip)
        method.setRequestHeader(new Header("Accept-Encoding", "gzip"));

    method.setRequestHeader(userAgentHeader);

    if (rgzip) {
        ByteArrayOutputStream lBo = new ByteArrayOutputStream();
        GZIPOutputStream lGzo = new GZIPOutputStream(lBo);
        lGzo.write(request);
        lGzo.finish();
        lGzo.close();
        byte[] lArray = lBo.toByteArray();
        method.setRequestBody(new ByteArrayInputStream(lArray));
        method.setRequestContentLength(-1);
    } else
        method.setRequestBody(new ByteArrayInputStream(request));

    URI hostURI = new URI(url.toString());
    HostConfiguration hostConfig = new HostConfiguration();
    hostConfig.setHost(hostURI);
    client.executeMethod(hostConfig, method);

    boolean lgzipo = false;

    Header lHeader = method.getResponseHeader("Content-Encoding");
    if (lHeader != null) {
        String lValue = lHeader.getValue();
        if (lValue != null)
            lgzipo = (lValue.indexOf("gzip") >= 0);
    }

    if (lgzipo)
        return (new GZIPInputStream(method.getResponseBodyAsStream()));
    else
        return method.getResponseBodyAsStream();
}

From source file:io.aino.agents.core.Sender.java

private byte[] getRequestContent() {
    if (!agentConfig.isGzipEnabled()) {
        return stringToSend.getBytes();
    }//  w  w w  .ja v a2  s  .  c o  m

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream gzipStream = new GZIPOutputStream(baos);
        gzipStream.write(stringToSend.getBytes());

        gzipStream.finish();
        baos.flush();
        byte[] returnBytes = baos.toByteArray();
        baos.close();
        gzipStream.close();

        return returnBytes;
    } catch (IOException e) {
        throw new AgentCoreException("Failed to compress Aino log message using gzip.");
    }
}

From source file:com.nextdoor.bender.ipc.http.HttpTransportTest.java

@Test(expected = TransportException.class)
public void testGzipErrorsResponse() throws TransportException, IOException {
    byte[] respPayload = "gzip resp".getBytes(StandardCharsets.UTF_8);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream os = new GZIPOutputStream(baos);
    os.write(respPayload);
    os.close();//from   w ww.j  a  v a 2 s. c o  m
    byte[] compressedResponse = baos.toByteArray();

    HttpClient client = getMockClientWithResponse(compressedResponse, ContentType.DEFAULT_BINARY,
            HttpStatus.SC_INTERNAL_SERVER_ERROR, true);
    HttpTransport transport = new HttpTransport(client, "", true, 1, 1);

    try {
        transport.sendBatch("foo".getBytes());
    } catch (Exception e) {
        assertEquals("http transport call failed because \"expected failure\" payload response \"gzip resp\"",
                e.getCause().getMessage());
        throw e;
    }
}

From source file:cn.keke.travelmix.publictransport.JsonProxyRouter.java

public void handle(HttpExchange xchg) throws IOException {
    try {//www . ja  va2 s .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.ocp.picasa.GDataClient.java

private ByteArrayEntity getCompressedEntity(byte[] data) throws IOException {
    ByteArrayEntity entity;// ww  w  . j  av a 2s.  c om
    if (data.length >= MIN_GZIP_SIZE) {
        ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(data.length / 2);
        GZIPOutputStream gzipOutput = new GZIPOutputStream(byteOutput);
        gzipOutput.write(data);
        gzipOutput.close();
        entity = new ByteArrayEntity(byteOutput.toByteArray());
    } else {
        entity = new ByteArrayEntity(data);
    }
    return entity;
}

From source file:org.csploit.android.core.System.java

public static String saveSession(String sessionName) throws IOException {
    StringBuilder builder = new StringBuilder();
    String filename = mStoragePath + '/' + sessionName + ".dss", session;

    builder.append(SESSION_MAGIC + "\n");

    // skip the network target
    synchronized (mTargets) {
        builder.append(mTargets.size() - 1).append("\n");
        for (Target target : mTargets) {
            if (target.getType() != Target.Type.NETWORK)
                target.serialize(builder);
        }/*from   www  . ja v a2s  .c om*/
    }

    session = builder.toString();

    FileOutputStream ostream = new FileOutputStream(filename);
    GZIPOutputStream gzip = new GZIPOutputStream(ostream);

    gzip.write(session.getBytes());

    gzip.close();

    mSessionName = sessionName;

    return filename;
}

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);/* www. java2  s .co 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:com.parse.ParseHttpClientTest.java

private void doSingleParseHttpClientExecuteWithGzipResponse(int responseCode, String responseStatus,
        final String responseContent, ParseHttpClient client) throws Exception {
    MockWebServer server = new MockWebServer();

    // Make mock response
    Buffer buffer = new Buffer();
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    GZIPOutputStream gzipOut = new GZIPOutputStream(byteOut);
    gzipOut.write(responseContent.getBytes());
    gzipOut.close();/*from w w w . j a va 2s.  c o m*/
    buffer.write(byteOut.toByteArray());
    MockResponse mockResponse = new MockResponse().setStatus("HTTP/1.1 " + responseCode + " " + responseStatus)
            .setBody(buffer).setHeader("Content-Encoding", "gzip");

    // Start mock server
    server.enqueue(mockResponse);
    server.start();

    // We do not need to add Accept-Encoding header manually, httpClient library should do that.
    String requestUrl = server.getUrl("/").toString();
    ParseHttpRequest parseRequest = new ParseHttpRequest.Builder().setUrl(requestUrl)
            .setMethod(ParseHttpRequest.Method.GET).build();

    // Execute request
    ParseHttpResponse parseResponse = client.execute(parseRequest);

    RecordedRequest recordedRequest = server.takeRequest();

    // Verify request method
    assertEquals(ParseHttpRequest.Method.GET.toString(), recordedRequest.getMethod());

    // Verify request headers
    Headers recordedHeaders = recordedRequest.getHeaders();

    assertEquals("gzip", recordedHeaders.get("Accept-Encoding"));

    // Verify response body
    byte[] content = ParseIOUtils.toByteArray(parseResponse.getContent());
    assertArrayEquals(responseContent.getBytes(), content);

    // Shutdown mock server
    server.shutdown();
}

From source file:com.thoughtworks.go.server.websocket.ConsoleLogSender.java

byte[] maybeGzipIfLargeEnough(byte[] input) {
    if (input.length < 512) {
        return input;
    }//from  w  w w.jav a2  s .com
    // To avoid having to re-allocate the internal byte array, allocate an initial buffer assuming a safe 10:1 compression ratio
    final ByteArrayOutputStream gzipBytes = new ByteArrayOutputStream(input.length / 10);
    try {
        final GZIPOutputStream gzipOutputStream = new GZIPOutputStream(gzipBytes, 1024 * 8);
        gzipOutputStream.write(input);
        gzipOutputStream.close();
    } catch (IOException e) {
        LOGGER.error("Could not gzip {}", input);
    }
    return gzipBytes.toByteArray();
}