Example usage for org.apache.http.entity ContentType toString

List of usage examples for org.apache.http.entity ContentType toString

Introduction

In this page you can find the example usage for org.apache.http.entity ContentType toString.

Prototype

public String toString() 

Source Link

Usage

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

private HttpRequestMessage createRequestMessage(Request request, boolean ignorePayload)
        throws IOException, MessagingException {
    HttpRequestMessage requestMessage = new HttpRequestMessage();
    requestMessage.setMethod(request.getMethod());
    requestMessage.setHeaders(HttpMessageConverter.convertFieldEnumerationToMap(request));
    requestMessage.setParameters(extractParameters(request));

    ContentType contentType;
    try {//from   ww  w . j  a  va2s  .co m
        contentType = ContentType.parse(request.getContentType());
    } catch (RuntimeException e) {
        contentType = ContentType.TEXT_PLAIN;
    }
    requestMessage.setContentType(contentType);

    requestMessage.setRemoteAddress(StringUtils.trimToEmpty(request.getRemoteAddr()));
    requestMessage.setQueryString(StringUtils.trimToEmpty(request.getQueryString()));
    requestMessage.setRequestUrl(StringUtils.trimToEmpty(getRequestURL(request)));
    requestMessage.setContextPath(StringUtils.trimToEmpty(new URL(requestMessage.getRequestUrl()).getPath()));

    if (!ignorePayload) {
        InputStream requestInputStream = request.getInputStream();
        // If a security handler already consumed the entity, get it from the request attribute instead
        try {
            byte[] entity = (byte[]) request.getAttribute(EntityProvider.ATTRIBUTE_NAME);
            if (entity != null) {
                requestInputStream = new ByteArrayInputStream(entity);
            }
        } catch (Exception e) {
        }

        // If the request is GZIP encoded, uncompress the content
        List<String> contentEncodingList = requestMessage.getCaseInsensitiveHeaders()
                .get(HTTP.CONTENT_ENCODING);
        if (CollectionUtils.isNotEmpty(contentEncodingList)) {
            for (String contentEncoding : contentEncodingList) {
                if (contentEncoding != null && (contentEncoding.equalsIgnoreCase("gzip")
                        || contentEncoding.equalsIgnoreCase("x-gzip"))) {
                    requestInputStream = new GZIPInputStream(requestInputStream);
                    break;
                }
            }
        }

        /*
         * First parse out the body of the HTTP request. Depending on the connector settings,
         * this could end up being a string encoded with the request charset, a byte array
         * representing the raw request payload, or a MimeMultipart object.
         */

        // Only parse multipart if XML Body is selected and Parse Multipart is enabled
        if (connectorProperties.isXmlBody() && connectorProperties.isParseMultipart()
                && ServletFileUpload.isMultipartContent(request)) {
            requestMessage.setContent(
                    new MimeMultipart(new ByteArrayDataSource(requestInputStream, contentType.toString())));
        } else if (isBinaryContentType(contentType)) {
            requestMessage.setContent(IOUtils.toByteArray(requestInputStream));
        } else {
            requestMessage.setContent(IOUtils.toString(requestInputStream,
                    HttpMessageConverter.getDefaultHttpCharset(request.getCharacterEncoding())));
        }
    }

    return requestMessage;
}

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 ww  w.  ja v  a  2  s. c o  m*/
    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:org.eclipse.californium.proxy.HttpTranslator.java

/**
 * Gets the http request starting from a CoAP request. The method creates
 * the HTTP request through its request line. The request line is built with
 * the uri coming from the string representing the CoAP method and the uri
 * obtained from the proxy-uri option. If a payload is provided, the HTTP
 * request encloses an HTTP entity and consequently the content-type is set.
 * Finally, the CoAP options are mapped to the HTTP headers.
 * /* w w w . j ava 2 s. c o m*/
 * @param coapRequest
 *            the coap request
 * 
 * 
 * 
 * @return the http request * @throws TranslationException the translation
 *         exception * @throws URISyntaxException the uRI syntax exception
 */
public static HttpRequest getHttpRequest(Request coapRequest) throws TranslationException {
    if (coapRequest == null) {
        throw new IllegalArgumentException("coapRequest == null");
    }

    HttpRequest httpRequest = null;

    String coapMethod = null;
    switch (coapRequest.getCode()) {
    case GET:
        coapMethod = "GET";
        break;
    case POST:
        coapMethod = "POST";
        break;
    case PUT:
        coapMethod = "PUT";
        break;
    case DELETE:
        coapMethod = "DELETE";
        break;
    }

    // get the proxy-uri
    URI proxyUri;
    try {
        /*
         * The new draft (14) only allows one proxy-uri option. Thus, this
         * code segment has changed.
         */
        String proxyUriString = URLDecoder.decode(coapRequest.getOptions().getProxyUri(), "UTF-8");
        proxyUri = new URI(proxyUriString);
    } catch (UnsupportedEncodingException e) {
        LOGGER.warning("UTF-8 do not support this encoding: " + e);
        throw new TranslationException("UTF-8 do not support this encoding", e);
    } catch (URISyntaxException e) {
        LOGGER.warning("Cannot translate the server uri" + e);
        throw new InvalidFieldException("Cannot get the proxy-uri from the coap message", e);
    }

    // create the requestLine
    RequestLine requestLine = new BasicRequestLine(coapMethod, proxyUri.toString(), HttpVersion.HTTP_1_1);

    // get the http entity
    HttpEntity httpEntity = getHttpEntity(coapRequest);

    // create the http request
    if (httpEntity == null) {
        httpRequest = new BasicHttpRequest(requestLine);
    } else {
        httpRequest = new BasicHttpEntityEnclosingRequest(requestLine);
        ((HttpEntityEnclosingRequest) httpRequest).setEntity(httpEntity);

        // get the content-type from the entity and set the header
        ContentType contentType = ContentType.get(httpEntity);
        httpRequest.setHeader("content-type", contentType.toString());
    }

    // set the headers
    Header[] headers = getHttpHeaders(coapRequest.getOptions().asSortedList(), "");
    for (Header header : headers) {
        httpRequest.addHeader(header);
    }

    return httpRequest;
}

From source file:org.eclipse.californium.proxy.HttpTranslator.java

/**
 * Sets the parameters of the incoming http response from a CoAP response.
 * The status code is mapped through the properties file and is set through
 * the StatusLine. The options are translated to the corresponding headers
 * and the max-age (in the header cache-control) is set to the default value
 * (60 seconds) if not already present. If the request method was not HEAD
 * and the coap response has a payload, the entity and the content-type are
 * set in the http response.//www. j  a  v a2s  . co m
 * 
 * @param coapResponse
 *            the coap response
 * @param httpResponse
 * 
 * 
 * 
 * @param httpRequest
 *            HttpRequest
 * @throws TranslationException
 *             the translation exception
 */
public static void getHttpResponse(HttpRequest httpRequest, Response coapResponse, HttpResponse httpResponse)
        throws TranslationException {
    if (httpRequest == null) {
        throw new IllegalArgumentException("httpRequest == null");
    }
    if (coapResponse == null) {
        throw new IllegalArgumentException("coapResponse == null");
    }
    if (httpResponse == null) {
        throw new IllegalArgumentException("httpResponse == null");
    }

    // get/set the response code
    ResponseCode coapCode = coapResponse.getCode();
    String httpCodeString = HTTP_TRANSLATION_PROPERTIES.getProperty(KEY_COAP_CODE + coapCode.value);

    if (httpCodeString == null || httpCodeString.isEmpty()) {
        LOGGER.warning("httpCodeString == null");
        throw new TranslationException("httpCodeString == null");
    }

    int httpCode = 0;
    try {
        httpCode = Integer.parseInt(httpCodeString.trim());
    } catch (NumberFormatException e) {
        LOGGER.warning("Cannot convert the coap code in http status code" + e);
        throw new TranslationException("Cannot convert the coap code in http status code", e);
    }

    // create the http response and set the status line
    String reason = EnglishReasonPhraseCatalog.INSTANCE.getReason(httpCode, Locale.ENGLISH);
    StatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, httpCode, reason);
    httpResponse.setStatusLine(statusLine);

    String uriString = httpRequest.getRequestLine().getUri();
    int index_query = uriString.indexOf("//");
    String query = uriString.substring(index_query + 2);
    int index_host = query.indexOf("/");
    String host = query.substring(0, index_host);

    // set the headers
    Header[] headers = getHttpHeaders(coapResponse.getOptions().asSortedList(), host);
    httpResponse.setHeaders(headers);

    // set max-age if not already set
    if (!httpResponse.containsHeader("cache-control")) {
        httpResponse.setHeader("cache-control",
                "max-age=" + Long.toString(OptionNumberRegistry.Defaults.MAX_AGE));
    }

    // get the http entity if the request was not HEAD
    if (!httpRequest.getRequestLine().getMethod().equalsIgnoreCase("head")) {
        if ((httpRequest.getRequestLine().getMethod().equalsIgnoreCase("put")) && (coapCode.value == 131)) {
            String linkPut = getLinkPut(coapResponse);
            Header link = new BasicHeader("Link", linkPut);
            httpResponse.addHeader(link);
        }
        // if the content-type is not set in the coap response and if the
        // response contains an error, then the content-type should set to
        // text-plain
        if (coapResponse.getOptions().getContentFormat() == MediaTypeRegistry.UNDEFINED
                && (ResponseCode.isClientError(coapCode) || ResponseCode.isServerError(coapCode))) {
            LOGGER.info("Set contenttype to TEXT_PLAIN");
            coapResponse.getOptions().setContentFormat(MediaTypeRegistry.TEXT_PLAIN);
        }

        HttpEntity httpEntity = getHttpEntity(coapResponse);
        if (httpEntity != null) {
            httpResponse.setEntity(httpEntity);

            // get the content-type from the entity and set the header
            ContentType contentType = ContentType.get(httpEntity);
            httpResponse.setHeader("content-type", contentType.toString());
        }
    }
}

From source file:org.gradle.api.internal.externalresource.transport.http.RepeatableInputStreamEntity.java

public RepeatableInputStreamEntity(Factory<InputStream> source, Long contentLength, ContentType contentType) {
    super();/*from  w ww . j a v  a 2  s  .com*/
    this.source = source;
    this.contentLength = contentLength;
    if (contentType != null) {
        setContentType(contentType.toString());
    }
}

From source file:org.gradle.internal.resource.transport.http.RepeatableInputStreamEntity.java

public RepeatableInputStreamEntity(LocalResource source, ContentType contentType) {
    super();//from w  ww . j a  v  a  2  s  . com
    this.source = source;
    if (contentType != null) {
        setContentType(contentType.toString());
    }
}