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.mirth.connect.connectors.http.HttpDispatcher.java

private HttpRequestBase buildHttpRequest(URI hostURI, HttpDispatcherProperties httpDispatcherProperties,
        ConnectorMessage connectorMessage, File tempFile, ContentType contentType, Charset charset)
        throws Exception {
    String method = httpDispatcherProperties.getMethod();
    boolean isMultipart = httpDispatcherProperties.isMultipart();
    Map<String, List<String>> headers = httpDispatcherProperties.getHeaders();
    Map<String, List<String>> parameters = httpDispatcherProperties.getParameters();

    Object content = null;/*from   www  .  j  a  v  a2  s  .  c om*/
    if (httpDispatcherProperties.isDataTypeBinary()) {
        content = getAttachmentHandlerProvider().reAttachMessage(httpDispatcherProperties.getContent(),
                connectorMessage, null, true);
    } else {
        content = getAttachmentHandlerProvider().reAttachMessage(httpDispatcherProperties.getContent(),
                connectorMessage);

        // If text mode is used and a specific charset isn't already defined, use the one from the connector properties
        if (contentType.getCharset() == null) {
            contentType = HttpMessageConverter.setCharset(contentType, charset);
        }
    }

    // populate the query parameters
    List<NameValuePair> queryParameters = new ArrayList<NameValuePair>(parameters.size());

    for (Entry<String, List<String>> parameterEntry : parameters.entrySet()) {
        for (String value : parameterEntry.getValue()) {
            logger.debug("setting query parameter: [" + parameterEntry.getKey() + ", " + value + "]");
            queryParameters.add(new BasicNameValuePair(parameterEntry.getKey(), value));
        }
    }

    HttpRequestBase httpMethod = null;
    HttpEntity httpEntity = null;
    URIBuilder uriBuilder = new URIBuilder(hostURI);

    // create the method
    if ("GET".equalsIgnoreCase(method)) {
        setQueryString(uriBuilder, queryParameters);
        httpMethod = new HttpGet(uriBuilder.build());
    } else if ("POST".equalsIgnoreCase(method)) {
        if (isMultipart) {
            logger.debug("setting multipart file content");
            setQueryString(uriBuilder, queryParameters);
            httpMethod = new HttpPost(uriBuilder.build());

            if (content instanceof String) {
                FileUtils.writeStringToFile(tempFile, (String) content, contentType.getCharset(), false);
            } else {
                FileUtils.writeByteArrayToFile(tempFile, (byte[]) content, false);
            }

            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.addPart(tempFile.getName(),
                    new FileBody(tempFile, contentType, tempFile.getName()));
            httpEntity = multipartEntityBuilder.build();
        } else if (StringUtils.startsWithIgnoreCase(contentType.getMimeType(),
                ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
            httpMethod = new HttpPost(uriBuilder.build());
            httpEntity = new UrlEncodedFormEntity(queryParameters, contentType.getCharset());
        } else {
            setQueryString(uriBuilder, queryParameters);
            httpMethod = new HttpPost(uriBuilder.build());

            if (content instanceof String) {
                httpEntity = new StringEntity((String) content, contentType);
            } else {
                httpEntity = new ByteArrayEntity((byte[]) content);
            }
        }
    } else if ("PUT".equalsIgnoreCase(method)) {
        if (StringUtils.startsWithIgnoreCase(contentType.getMimeType(),
                ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
            httpMethod = new HttpPut(uriBuilder.build());
            httpEntity = new UrlEncodedFormEntity(queryParameters, contentType.getCharset());
        } else {
            setQueryString(uriBuilder, queryParameters);
            httpMethod = new HttpPut(uriBuilder.build());

            if (content instanceof String) {
                httpEntity = new StringEntity((String) content, contentType);
            } else {
                httpEntity = new ByteArrayEntity((byte[]) content);
            }
        }
    } else if ("DELETE".equalsIgnoreCase(method)) {
        setQueryString(uriBuilder, queryParameters);
        httpMethod = new HttpDelete(uriBuilder.build());
    }

    if (httpMethod instanceof HttpEntityEnclosingRequestBase) {
        // Compress the request entity if necessary
        List<String> contentEncodingList = (List<String>) new CaseInsensitiveMap(headers)
                .get(HTTP.CONTENT_ENCODING);
        if (CollectionUtils.isNotEmpty(contentEncodingList)) {
            for (String contentEncoding : contentEncodingList) {
                if (contentEncoding != null && (contentEncoding.toLowerCase().equals("gzip")
                        || contentEncoding.toLowerCase().equals("x-gzip"))) {
                    httpEntity = new GzipCompressingEntity(httpEntity);
                    break;
                }
            }
        }

        ((HttpEntityEnclosingRequestBase) httpMethod).setEntity(httpEntity);
    }

    // set the headers
    for (Entry<String, List<String>> headerEntry : headers.entrySet()) {
        for (String value : headerEntry.getValue()) {
            logger.debug("setting method header: [" + headerEntry.getKey() + ", " + value + "]");
            httpMethod.addHeader(headerEntry.getKey(), value);
        }
    }

    // Only set the Content-Type for entity-enclosing methods, but not if multipart is used
    if (("POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method)) && !isMultipart) {
        httpMethod.setHeader(HTTP.CONTENT_TYPE, contentType.toString());
    }

    return httpMethod;
}

From source file:com.hp.mqm.client.MqmRestClientImpl.java

@Override
public boolean putEvents(String eventsJSON) {
    HttpPut request;//from ww  w  .java  2 s.  c om
    HttpResponse response = null;
    boolean result = true;
    try {
        request = new HttpPut(createSharedSpaceInternalApiUri(URI_PUT_EVENTS));
        request.setEntity(
                new GzipCompressingEntity(new StringEntity(eventsJSON, ContentType.APPLICATION_JSON)));
        response = execute(request);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_TEMPORARY_REDIRECT) {
            // ad-hoc handling as requested by Jenkins Insight team
            HttpClientUtils.closeQuietly(response);
            login();
            response = execute(request);
        }
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            logger.severe(
                    "put request failed while sending events: " + response.getStatusLine().getStatusCode());
            result = false;
        }
    } catch (Exception e) {
        logger.severe("put request failed while sending events: " + e.getClass().getName());
        result = false;
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
    return result;
}

From source file:com.hp.mqm.client.MqmRestClientImpl.java

@Override
public boolean postCoverageReports(String selfIdentity, String ciJobId, String ciBuildId,
        InputStream inputStream, Long contentLength, String reportType) {
    HttpPut request;//from  w  w w . j  a  v  a2s  . c o  m
    HttpResponse response = null;
    boolean result = true;

    try {
        request = new HttpPut(createSharedSpaceInternalApiUri(URI_POST_COVERAGE_REPORTS, selfIdentity, ciJobId,
                ciBuildId, reportType));
        request.setEntity(new GzipCompressingEntity(new InputStreamEntity(inputStream)));
        response = execute(request);
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE
                || statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            result = false;
            logger.severe("post request failed while sending coverage reports: " + statusCode);
        } else if (statusCode != HttpStatus.SC_OK) {
            logger.severe("coverage reports post failed" + statusCode);
            throw createRequestException("coverage reports post failed", response);
        }
        logger.info(IOUtils.toString(response.getEntity().getContent(), "UTF-8"));
    } catch (IOException e) {
        throw new RequestErrorException("Cannot post coverage reports to MQM.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
    return result;
}

From source file:com.hp.mqm.client.MqmRestClientImpl.java

@Override
public int putAbridgedResult(String selfIdentity, String taskId, String contentJSON) {
    HttpPut request;/*from  www  . ja v a2  s  .c  o  m*/
    HttpResponse response = null;
    try {
        request = new HttpPut(createSharedSpaceInternalApiUri(URI_PUT_ABRIDGED_RESULT, selfIdentity, taskId));
        request.setEntity(
                new GzipCompressingEntity(new StringEntity(contentJSON, ContentType.APPLICATION_JSON)));

        response = execute(request);
        return response.getStatusLine().getStatusCode();
    } catch (Exception e) {
        logger.severe("failed to submit abridged task's result: " + e.getMessage());
        throw new RuntimeException(e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:org.eclipse.epp.internal.logging.aeri.ui.v2.AeriServer.java

public ServerResponse upload(ErrorReport report, IProgressMonitor monitor) throws IOException {
    String body = Reports.toJson(report, false);
    StringEntity stringEntity = new StringEntity(body, ContentType.APPLICATION_OCTET_STREAM.withCharset(UTF_8));
    // length of zipped conent is unknown, using the progress of the string-stream instead.
    // download progress percentage will be accurate, download progress size will be too large by the compression factor
    HttpEntity entity = new GzipCompressingEntity(
            Responses.decorateForProgressMonitoring(stringEntity, monitor));

    String submitUrl = configuration.getSubmitUrl();
    URI target = newURI(submitUrl);
    // @formatter:off
    Request request = Request.Post(target).viaProxy(getProxyHost(target).orNull()).body(entity)
            .connectTimeout(configuration.getConnectTimeoutMs()).staleConnectionCheck(true)
            .socketTimeout(configuration.getSocketTimeoutMs());
    // @formatter:on
    String response = proxyAuthentication(executor, target).execute(request).returnContent().asString();
    ServerResponse05 response05 = Json.deserialize(response, ServerResponse05.class);

    // TODO complete dto
    ServerResponse result = new ServerResponse();
    result.setReportTitle(abbreviate(report.getStatus().getMessage(), 80));
    result.setIncidentId(response05.getBugId().orNull());
    result.setIncidentUrl(response05.getBugUrl().orNull());
    result.setResolution(tryParse(response05));
    result.setCommitterMessage(response05.getInformation().orNull());
    return result;
}