Example usage for org.apache.http.client.entity GzipCompressingEntity GzipCompressingEntity

List of usage examples for org.apache.http.client.entity GzipCompressingEntity GzipCompressingEntity

Introduction

In this page you can find the example usage for org.apache.http.client.entity GzipCompressingEntity GzipCompressingEntity.

Prototype

public GzipCompressingEntity(final HttpEntity entity) 

Source Link

Usage

From source file:com.github.tomakehurst.wiremock.GzipAcceptanceTest.java

@Test
public void acceptsGzippedRequest() {
    wireMockServer.stubFor(any(urlEqualTo("/gzip-request")).withRequestBody(equalTo("request body"))
            .willReturn(aResponse().withBody("response body")));

    HttpEntity compressedBody = new GzipCompressingEntity(
            new StringEntity("request body", ContentType.TEXT_PLAIN));
    WireMockResponse response = testClient.post("/gzip-request", compressedBody);

    assertThat(response.content(), is("response body"));
}

From source file:com.android.tools.idea.diagnostics.crash.GoogleCrash.java

@NotNull
@Override//w w w.  j  av a 2 s.  c o  m
public CompletableFuture<String> submit(@NotNull final HttpEntity requestEntity) {
    CompletableFuture<String> future = new CompletableFuture<>();

    try {
        ourExecutor.submit(() -> {
            try {
                HttpClient client = HttpClients.createDefault();

                HttpEntity entity = requestEntity;
                if (!UNIT_TEST_MODE) {
                    // The test server used in testing doesn't handle gzip compression (netty requires jcraft jzlib for gzip decompression)
                    entity = new GzipCompressingEntity(requestEntity);
                }

                HttpPost post = new HttpPost(myCrashUrl);
                post.setEntity(entity);

                HttpResponse response = client.execute(post);
                StatusLine statusLine = response.getStatusLine();
                if (statusLine.getStatusCode() >= 300) {
                    future.completeExceptionally(new HttpResponseException(statusLine.getStatusCode(),
                            statusLine.getReasonPhrase()));
                    return;
                }

                entity = response.getEntity();
                if (entity == null) {
                    future.completeExceptionally(new NullPointerException("Empty response entity"));
                    return;
                }

                String reportId = EntityUtils.toString(entity);
                if (DEBUG_BUILD) {
                    //noinspection UseOfSystemOutOrSystemErr
                    System.out.println("Report submitted: http://go/crash-staging/" + reportId);
                }
                future.complete(reportId);
            } catch (IOException e) {
                future.completeExceptionally(e);
            }
        });
    } catch (RejectedExecutionException ignore) {
        // handled by the rejected execution handler associated with ourExecutor
    }

    return future;
}

From source file:com.flipkart.poseidon.handlers.http.impl.HttpConnectionPool.java

/**
 * Method for executing HTTP PUT request
 *///  w w  w .  j  a v a  2  s  .com
public HttpResponse doPUT(String uri, byte[] data, Map<String, String> requestHeaders) throws Exception {
    HttpPut request = new HttpPut(constructUrl(uri));
    if (data != null) {
        if (this.requestGzipEnabled) {
            request.addHeader(CONTENT_ENCODING, COMPRESSION_TYPE);
            request.setEntity(new GzipCompressingEntity(new ByteArrayEntity(data)));
        } else {
            request.setEntity(new ByteArrayEntity(data));
        }
    }
    setRequestHeaders(request, requestHeaders);
    return execute(request);
}

From source file:com.flipkart.poseidon.handlers.http.impl.HttpConnectionPool.java

/**
 * Method for executing HTTP POST request
 *//*from  w w  w .j  a  va2s . c o m*/
public HttpResponse doPOST(String uri, byte[] data, Map<String, String> requestHeaders) throws Exception {
    HttpPost request = new HttpPost(constructUrl(uri));
    if (data != null) {
        if (this.requestGzipEnabled) {
            request.addHeader(CONTENT_ENCODING, COMPRESSION_TYPE);
            request.setEntity(new GzipCompressingEntity(new ByteArrayEntity(data)));
        } else {
            request.setEntity(new ByteArrayEntity(data));
        }
    }
    setRequestHeaders(request, requestHeaders);
    return execute(request);
}

From source file:com.github.tomakehurst.wiremock.RecordingDslAcceptanceTest.java

@Test
public void recordsIntoPlainTextWhenRequestIsGZipped() {
    proxyingService.startRecording(targetBaseUrl);
    targetService.stubFor(post("/gzipped").willReturn(ok("Zippy")));

    HttpEntity compressedBody = new GzipCompressingEntity(new StringEntity("expected body", TEXT_PLAIN));
    client.post("/gzipped", compressedBody);

    StubMapping mapping = proxyingService.stopRecording().getStubMappings().get(0);
    assertThat(mapping.getRequest().getBodyPatterns().get(0).getExpected(), is("expected body"));
}

From source file:com.flipkart.poseidon.handlers.http.impl.HttpConnectionPool.java

/**
 * Method for executing HTTP POST request with form params
 *///from   w  ww.  j a  v  a 2 s .  c  o m
public HttpResponse doPOST(String uri, List<NameValuePair> formParams, Map<String, String> requestHeaders)
        throws Exception {
    HttpPost request = new HttpPost(constructUrl(uri));
    if (this.requestGzipEnabled) {
        request.addHeader(CONTENT_ENCODING, COMPRESSION_TYPE);
        request.setEntity(new GzipCompressingEntity(new UrlEncodedFormEntity(formParams)));
    } else {
        request.setEntity(new UrlEncodedFormEntity(formParams));
    }
    setRequestHeaders(request, requestHeaders);
    return execute(request);
}

From source file:com.hp.octane.integrations.services.rest.OctaneRestClientImpl.java

/**
 * This method should be the ONLY mean that creates Http Request objects
 *
 * @param octaneRequest Request data as it is maintained in Octane related flavor
 * @return pre-configured HttpUriRequest
 *//*from  ww  w . j av  a2 s.co m*/
private HttpUriRequest createHttpRequest(OctaneRequest octaneRequest) {
    HttpUriRequest request;
    RequestBuilder requestBuilder;

    //  create base request by METHOD
    if (octaneRequest.getMethod().equals(HttpMethod.GET)) {
        requestBuilder = RequestBuilder.get(octaneRequest.getUrl());
    } else if (octaneRequest.getMethod().equals(HttpMethod.DELETE)) {
        requestBuilder = RequestBuilder.delete(octaneRequest.getUrl());
    } else if (octaneRequest.getMethod().equals(HttpMethod.POST)) {
        requestBuilder = RequestBuilder.post(octaneRequest.getUrl());
        requestBuilder
                .addHeader(new BasicHeader(RestService.CONTENT_ENCODING_HEADER, RestService.GZIP_ENCODING));
        requestBuilder.setEntity(new GzipCompressingEntity(
                new InputStreamEntity(octaneRequest.getBody(), ContentType.APPLICATION_JSON)));
    } else if (octaneRequest.getMethod().equals(HttpMethod.PUT)) {
        requestBuilder = RequestBuilder.put(octaneRequest.getUrl());
        requestBuilder
                .addHeader(new BasicHeader(RestService.CONTENT_ENCODING_HEADER, RestService.GZIP_ENCODING));
        requestBuilder.setEntity(new GzipCompressingEntity(
                new InputStreamEntity(octaneRequest.getBody(), ContentType.APPLICATION_JSON)));
    } else {
        throw new RuntimeException("HTTP method " + octaneRequest.getMethod() + " not supported");
    }

    //  set custom headers
    if (octaneRequest.getHeaders() != null) {
        for (Map.Entry<String, String> e : octaneRequest.getHeaders().entrySet()) {
            requestBuilder.setHeader(e.getKey(), e.getValue());
        }
    }

    //  set system headers
    requestBuilder.setHeader(CLIENT_TYPE_HEADER, CLIENT_TYPE_VALUE);

    request = requestBuilder.build();
    return request;
}

From source file:com.flipkart.poseidon.handlers.http.impl.HttpConnectionPool.java

/**
 *
 * @param request//from ww  w .  jav  a 2  s  .c om
 * @param data
 */
private void setRequestBody(HttpEntityEnclosingRequestBase request, byte[] data) {
    if (data != null) {
        if (this.requestGzipEnabled) {
            request.addHeader(CONTENT_ENCODING, COMPRESSION_TYPE);
            request.setEntity(new GzipCompressingEntity(new ByteArrayEntity(data)));
        } else {
            request.setEntity(new ByteArrayEntity(data));
        }
    }
}

From source file:io.hops.hopsworks.api.kibana.KibanaProxyServlet.java

/**
 * Copy response body data (the entity) from the proxy to the servlet client.
 *
 * @param proxyResponse//from  w  ww. j av  a2 s  .c o  m
 * @param servletResponse
 * @param kibanaFilter
 * @param email
 */
protected void copyResponseEntity(HttpResponse proxyResponse, HttpServletResponse servletResponse,
        KibanaFilter kibanaFilter, String email) throws IOException {
    if (kibanaFilter == null) {
        super.copyResponseEntity(proxyResponse, servletResponse);
    } else {
        switch (kibanaFilter) {

        case LEGACY_SCROLL_START:
        case KIBANA_DEFAULT_INDEX:
            return;
        case KIBANA_SAVED_OBJECTS_API:
        case ELASTICSEARCH_SEARCH:
            HttpEntity entity = proxyResponse.getEntity();
            if (entity != null) {
                GzipDecompressingEntity gzipEntity = new GzipDecompressingEntity(entity);
                String resp = EntityUtils.toString(gzipEntity);
                BasicHttpEntity basic = new BasicHttpEntity();
                //Remove all projects other than the current one and check
                //if user is authorizer to access it
                JSONObject indices = new JSONObject(resp);
                LOG.log(Level.FINE, "indices:{0}", indices.toString());
                JSONArray hits = null;

                String projectName = currentProjects.get(email);
                List<String> projects = new ArrayList();
                //If we don't have the current project, filter out based on all user's projects
                if (Strings.isNullOrEmpty(projectName)) {
                    List<String> projectNames = projectController.findProjectNamesByUser(email, true);
                    if (projectNames != null && !projectNames.isEmpty()) {
                        projects.addAll(projectNames);
                    }
                } else {
                    projects.add(projectName);
                }
                if (kibanaFilter == KibanaFilter.ELASTICSEARCH_SEARCH
                        && HopsUtils.jsonKeyExists(indices, "buckets")) {
                    hits = indices.getJSONObject("aggregations").getJSONObject("indices")
                            .getJSONArray("buckets");
                } else if (kibanaFilter == KibanaFilter.KIBANA_SAVED_OBJECTS_API
                        && indices.has("saved_objects")) {
                    hits = indices.getJSONArray("saved_objects");
                }
                if (hits != null) {
                    LOG.log(Level.FINE, "hits:{0}", hits);
                    for (int i = hits.length() - 1; i >= 0; i--) {
                        String objectId = null;
                        switch (kibanaFilter) {
                        case ELASTICSEARCH_SEARCH:
                            objectId = hits.getJSONObject(i).getString("key");
                            break;
                        case KIBANA_SAVED_OBJECTS_API:
                            objectId = elasticController.getIndexFromKibana(hits.getJSONObject(i));
                            break;
                        default:
                            break;
                        }
                        if (!Strings.isNullOrEmpty(objectId)
                                && (!isAuthorizedKibanaObject(objectId, email, projects))) {
                            hits.remove(i);
                            LOG.log(Level.FINE, "removed objectId:{0}", objectId);
                        }
                    }
                }

                InputStream in = IOUtils.toInputStream(indices.toString());

                OutputStream servletOutputStream = servletResponse.getOutputStream();
                basic.setContent(in);
                GzipCompressingEntity compress = new GzipCompressingEntity(basic);
                compress.writeTo(servletOutputStream);

            }
            break;
        default:
            super.copyResponseEntity(proxyResponse, servletResponse);
            break;
        }

    }
}

From source file:org.dcache.srm.client.HttpClientSender.java

/**
 * Creates a HttpRequest encoding a particular SOAP call.
 *
 * Called once per SOAP call./*  w  w  w . ja  va2  s  .c  om*/
 */
protected HttpUriRequest createHttpRequest(MessageContext msgContext, URI url) throws AxisFault {
    boolean posting = true;
    // If we're SOAP 1.2, allow the web method to be set from the
    // MessageContext.
    if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
        String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
        if (webMethod != null) {
            posting = webMethod.equals(HTTPConstants.HEADER_POST);
        }
    }

    HttpRequestBase request = posting ? new HttpPost(url) : new HttpGet(url);

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : "";
    if (action == null) {
        action = "";
    }

    Message msg = msgContext.getRequestMessage();
    request.addHeader(HTTPConstants.HEADER_CONTENT_TYPE, msg.getContentType(msgContext.getSOAPConstants()));
    request.addHeader(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\"");

    String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
    if (httpVersion != null && httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) {
        request.setProtocolVersion(HttpVersion.HTTP_1_0);
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers.
    MimeHeaders mimeHeaders = msg.getMimeHeaders();
    if (mimeHeaders != null) {
        Iterator i = mimeHeaders.getAllHeaders();
        while (i.hasNext()) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            // HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set.
            // Let's not duplicate them.
            String name = mimeHeader.getName();
            if (!name.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    && !name.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
                request.addHeader(name, mimeHeader.getValue());
            }
        }
    }

    boolean isChunked = false;
    boolean isExpectContinueEnabled = false;
    Map<?, ?> userHeaderTable = (Map) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);
    if (userHeaderTable != null) {
        for (Map.Entry<?, ?> me : userHeaderTable.entrySet()) {
            Object keyObj = me.getKey();
            if (keyObj != null) {
                String key = keyObj.toString().trim();
                String value = me.getValue().toString().trim();
                if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)) {
                    isExpectContinueEnabled = value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue);
                } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                    isChunked = JavaUtils.isTrue(value);
                } else {
                    request.addHeader(key, value);
                }
            }
        }
    }

    RequestConfig.Builder config = RequestConfig.custom();
    // optionally set a timeout for the request
    if (msgContext.getTimeout() != 0) {
        /* ISSUE: these are not the same, but MessageContext has only one definition of timeout */
        config.setSocketTimeout(msgContext.getTimeout()).setConnectTimeout(msgContext.getTimeout());
    } else if (clientProperties.getConnectionPoolTimeout() != 0) {
        config.setConnectTimeout(clientProperties.getConnectionPoolTimeout());
    }
    config.setContentCompressionEnabled(msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP));
    config.setExpectContinueEnabled(isExpectContinueEnabled);
    request.setConfig(config.build());

    if (request instanceof HttpPost) {
        HttpEntity requestEntity = new MessageEntity(request, msgContext.getRequestMessage(), isChunked);
        if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
            requestEntity = new GzipCompressingEntity(requestEntity);
        }
        ((HttpPost) request).setEntity(requestEntity);
    }

    return request;
}