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

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

Introduction

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

Prototype

public static ContentType parse(String str) throws ParseException, UnsupportedCharsetException 

Source Link

Usage

From source file:org.sentilo.platform.server.request.SentiloRequest.java

private void parseContentType() {
    final String contentTypeValue = extractHeader(HttpHeader.CONTENT_TYPE);
    try {//from  w ww. jav a2  s.  c o m
        contentType = (StringUtils.hasText(contentTypeValue)
                ? ContentType.parse(extractHeader(HttpHeader.CONTENT_TYPE))
                : getDefaultContentType());
    } catch (final ParseException pe) {
        contentType = getDefaultContentType();
    }
    logger.debug("Parsed Content-type: {}", contentTypeValue);
}

From source file:com.github.parisoft.resty.entity.EntityReaderImpl.java

@Override
public ContentType getContentType() {
    try {/* w w  w  . j a va  2s .c om*/
        return ContentType.parse(httpResponse.getFirstHeader(CONTENT_TYPE).getValue());
    } catch (Exception e) {
        return ContentType.getLenientOrDefault(httpResponse.getEntity());
    }
}

From source file:com.salesforce.dva.argus.service.callback.DefaultCallbackService.java

private HttpEntity body(DefaultAlertService.NotificationContext context, CallbackService.Request request) {
    if (request.body() != null) {
        StringEntity entity;//from   w ww.j a v a 2 s  .c  o m
        String body = request.body();
        if (request.template() == Template.ST4) {
            ST st = new ST(request.body(), delimiterStart, delimiterEnd);
            st.add("alert", context.getAlert());
            st.add("trigger", context.getTrigger());
            st.add("coolDownExpiration", context.getCoolDownExpiration());
            st.add("notification", context.getNotification());
            st.add("triggerFiredTime", context.getTriggerFiredTime());
            st.add("triggerEventValue", context.getTriggerEventValue());
            st.add("triggeredMetric", context.getTriggeredMetric());
            body = st.render();
        }
        if (request.header().containsKey(HttpHeaders.CONTENT_TYPE)) {
            entity = new StringEntity(body, ContentType.parse(request.header().get(HttpHeaders.CONTENT_TYPE)));
        } else {
            entity = new StringEntity(body, ContentType.TEXT_PLAIN);
        }
        return entity;
    }
    return null;
}

From source file:org.openscore.content.httpclient.build.EntityBuilder.java

public HttpEntity buildEntity() {
    AbstractHttpEntity httpEntity = null;
    if (!StringUtils.isEmpty(formParams)) {
        List<? extends NameValuePair> list;
        list = getNameValuePairs(formParams, !Boolean.parseBoolean(this.formParamsAreURLEncoded),
                HttpClientInputs.FORM_PARAMS, HttpClientInputs.FORM_PARAMS_ARE_URLENCODED);
        httpEntity = new UrlEncodedFormEntity(list, contentType.getCharset());
    } else if (!StringUtils.isEmpty(body)) {
        httpEntity = new StringEntity(body, contentType);
    } else if (!StringUtils.isEmpty(filePath)) {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new IllegalArgumentException(
                    "file set by input '" + HttpClientInputs.SOURCE_FILE + "' does not exist:" + filePath);
        }/*from   w w w .j a va  2  s .c o  m*/
        httpEntity = new FileEntity(file, contentType);
    }
    if (httpEntity != null) {
        if (!StringUtils.isEmpty(chunkedRequestEntity)) {
            httpEntity.setChunked(Boolean.parseBoolean(chunkedRequestEntity));
        }
        return httpEntity;
    }

    if (!StringUtils.isEmpty(multipartBodies) || !StringUtils.isEmpty(multipartFiles)) {
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        if (!StringUtils.isEmpty(multipartBodies)) {
            List<? extends NameValuePair> list;
            list = getNameValuePairs(multipartBodies, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded),
                    HttpClientInputs.MULTIPART_BODIES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED);
            ContentType bodiesCT = ContentType.parse(multipartBodiesContentType);
            for (NameValuePair nameValuePair : list) {
                multipartEntityBuilder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(), bodiesCT);
            }
        }

        if (!StringUtils.isEmpty(multipartFiles)) {
            List<? extends NameValuePair> list;
            list = getNameValuePairs(multipartFiles, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded),
                    HttpClientInputs.MULTIPART_FILES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED);
            ContentType filesCT = ContentType.parse(multipartFilesContentType);
            for (NameValuePair nameValuePair : list) {
                File file = new File(nameValuePair.getValue());
                multipartEntityBuilder.addBinaryBody(nameValuePair.getName(), file, filesCT, file.getName());
            }
        }
        return multipartEntityBuilder.build();
    }

    return null;
}

From source file:io.cloudslang.content.httpclient.build.EntityBuilder.java

public HttpEntity buildEntity() {
    AbstractHttpEntity httpEntity = null;
    if (!StringUtils.isEmpty(formParams)) {
        List<? extends NameValuePair> list;
        list = getNameValuePairs(formParams, !Boolean.parseBoolean(this.formParamsAreURLEncoded),
                HttpClientInputs.FORM_PARAMS, HttpClientInputs.FORM_PARAMS_ARE_URLENCODED);
        Charset charset = contentType != null ? contentType.getCharset() : null;
        httpEntity = new UrlEncodedFormEntity(list, charset);
    } else if (!StringUtils.isEmpty(body)) {
        httpEntity = new StringEntity(body, contentType);
    } else if (!StringUtils.isEmpty(filePath)) {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new IllegalArgumentException(
                    "file set by input '" + HttpClientInputs.SOURCE_FILE + "' does not exist:" + filePath);
        }/*  w ww .ja  v  a  2s. com*/
        httpEntity = new FileEntity(file, contentType);
    }
    if (httpEntity != null) {
        if (!StringUtils.isEmpty(chunkedRequestEntity)) {
            httpEntity.setChunked(Boolean.parseBoolean(chunkedRequestEntity));
        }
        return httpEntity;
    }

    if (!StringUtils.isEmpty(multipartBodies) || !StringUtils.isEmpty(multipartFiles)) {
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        if (!StringUtils.isEmpty(multipartBodies)) {
            List<? extends NameValuePair> list;
            list = getNameValuePairs(multipartBodies, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded),
                    HttpClientInputs.MULTIPART_BODIES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED);
            ContentType bodiesCT = ContentType.parse(multipartBodiesContentType);
            for (NameValuePair nameValuePair : list) {
                multipartEntityBuilder.addTextBody(nameValuePair.getName(), nameValuePair.getValue(), bodiesCT);
            }
        }

        if (!StringUtils.isEmpty(multipartFiles)) {
            List<? extends NameValuePair> list;
            list = getNameValuePairs(multipartFiles, !Boolean.parseBoolean(this.multipartValuesAreURLEncoded),
                    HttpClientInputs.MULTIPART_FILES, HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED);
            ContentType filesCT = ContentType.parse(multipartFilesContentType);
            for (NameValuePair nameValuePair : list) {
                File file = new File(nameValuePair.getValue());
                multipartEntityBuilder.addBinaryBody(nameValuePair.getName(), file, filesCT, file.getName());
            }
        }
        return multipartEntityBuilder.build();
    }

    return null;
}

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

private static void processContent(DonkeyElement contentElement, Object content, ContentType contentType,
        boolean parseMultipart, BinaryContentTypeResolver resolver)
        throws DonkeyElementException, MessagingException, IOException {
    if (resolver == null) {
        resolver = defaultResolver;/*  w  w  w  . ja  v  a 2  s  .  c om*/
    }

    if (parseMultipart && content instanceof MimeMultipart) {
        contentElement.setAttribute("multipart", "yes");
        MimeMultipart multipart = (MimeMultipart) content;

        String boundary = contentType.getParameter("boundary");
        if (StringUtils.isNotBlank(boundary)) {
            contentElement.setAttribute("boundary", boundary);
        }

        if (StringUtils.isNotEmpty(multipart.getPreamble())) {
            contentElement.addChildElement("Preamble", multipart.getPreamble());
        }

        for (int partIndex = 0; partIndex < multipart.getCount(); partIndex++) {
            BodyPart part = multipart.getBodyPart(partIndex);
            DonkeyElement partElement = contentElement.addChildElement("Part");
            DonkeyElement headersElement = partElement.addChildElement("Headers");
            ContentType partContentType = contentType;

            for (Enumeration<javax.mail.Header> en = part.getAllHeaders(); en.hasMoreElements();) {
                javax.mail.Header header = en.nextElement();
                headersElement.addChildElement(header.getName(), header.getValue());

                if (header.getName().equalsIgnoreCase("Content-Type")) {
                    try {
                        partContentType = ContentType.parse(header.getValue());
                    } catch (RuntimeException e) {
                    }
                }
            }

            processContent(partElement.addChildElement("Content"), part.getContent(), partContentType, true,
                    resolver);
        }
    } else {
        contentElement.setAttribute("multipart", "no");
        String charset = getDefaultHttpCharset(
                contentType.getCharset() != null ? contentType.getCharset().name() : null);

        // Call the resolver to determine if the content should be Base64 encoded
        if (resolver.isBinaryContentType(contentType)) {
            contentElement.setAttribute("encoding", "Base64");
            byte[] contentByteArray = null;

            if (content instanceof StreamSource) {
                StreamSource streamSource = (StreamSource) content;
                if (streamSource.getInputStream() != null) {
                    contentByteArray = IOUtils.toByteArray(streamSource.getInputStream());
                } else if (streamSource.getReader() != null) {
                    contentByteArray = IOUtils.toString(streamSource.getReader()).getBytes(charset);
                }
            } else if (content instanceof InputStream) {
                contentByteArray = IOUtils.toByteArray((InputStream) content);
            } else if (content instanceof byte[]) {
                contentByteArray = (byte[]) content;
            }

            if (contentByteArray == null) {
                contentByteArray = (content != null ? content.toString() : "").getBytes(charset);
            }

            contentElement.setTextContent(new String(Base64Util.encodeBase64(contentByteArray), "US-ASCII"));
        } else {
            String contentText = null;

            if (content instanceof StreamSource) {
                StreamSource streamSource = (StreamSource) content;
                if (streamSource.getInputStream() != null) {
                    contentText = IOUtils.toString(streamSource.getInputStream(), charset);
                } else if (streamSource.getReader() != null) {
                    contentText = IOUtils.toString(streamSource.getReader());
                }
            } else if (content instanceof InputStream) {
                contentText = IOUtils.toString((InputStream) content, charset);
            } else if (content instanceof byte[]) {
                contentText = new String((byte[]) content, charset);
            }

            if (contentText == null) {
                contentText = content != null ? content.toString() : "";
            }

            contentElement.setTextContent(contentText);
        }
    }
}

From source file:org.openestate.is24.restapi.hc42.HttpComponents42Client.java

/**
 * Retrieves a {@link Response} from a {@link HttpResponse}.
 *
 * @param response/*from   ww  w .ja  va2 s .  c  o m*/
 * {@link HttpResponse}, that was received by the client
 *
 * @return
 * {@link Response} of the request
 *
 * @throws IOException
 * if the {@link Response} can't be obtained
 */
protected Response createResponse(HttpResponse response) throws IOException {
    HttpEntity responseEntity = null;
    InputStream responseInput = null;
    try {
        StatusLine responseStatus = response.getStatusLine();
        responseEntity = response.getEntity();

        // get charset of the response
        String contentTypeHeader = (responseEntity.getContentType() != null)
                ? StringUtils.trimToNull(responseEntity.getContentType().getValue())
                : null;
        ContentType contentType = (contentTypeHeader != null) ? ContentType.parse(contentTypeHeader) : null;
        String charset = (contentType != null && contentType.getCharset() != null)
                ? contentType.getCharset().name()
                : null;
        if (charset == null)
            charset = getEncoding();

        // read response body
        responseInput = new BufferedInputStream(responseEntity.getContent());

        // possibly decompress response body from gzip
        String encoding = (responseEntity.getContentEncoding() != null)
                ? responseEntity.getContentEncoding().getValue()
                : null;
        if ("gzip".equalsIgnoreCase(encoding))
            responseInput = new GZIPInputStream(responseInput);

        // get L-IS24-RequestRefnum header of the response
        Header requestRefNum = response.getFirstHeader(RESPONSE_HEADER_REQUEST_REFNUM);

        // create response
        return new Response(responseStatus.getStatusCode(), responseStatus.getReasonPhrase(),
                (requestRefNum != null) ? requestRefNum.getValue() : null,
                IOUtils.toString(responseInput, charset));
    } finally {
        IOUtils.closeQuietly(responseInput);
        EntityUtils.consume(responseEntity);
    }
}

From source file:ca.uhn.fhir.rest.server.servlet.ServletRequestDetails.java

@Override
public Charset getCharset() {
    String ct = getHeader(Constants.HEADER_CONTENT_TYPE);

    Charset charset = null;//from  w  w w . j av a  2 s  .co m
    if (isNotBlank(ct)) {
        ContentType parsedCt = ContentType.parse(ct);
        charset = parsedCt.getCharset();
    }
    return charset;
}

From source file:org.esigate.servlet.impl.ResponseCapturingWrapper.java

@Override
public void setContentType(String type) {
    ContentType parsedContentType = ContentType.parse(type);
    this.contentType = parsedContentType.getMimeType();
    if (parsedContentType.getCharset() != null) {
        this.characterEncoding = parsedContentType.getCharset().name();
    }//from   w w  w  . j a va  2  s  .c o  m
    updateContentTypeHeader();
}