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.github.parisoft.resty.request.Request.java

/**
 * Sets the <code><a href=http://tools.ietf.org/html/rfc2616#section-14.1>Accept</a></code> header values.<br>
 * <br>/*from w w  w .j a v  a2s  .  c o  m*/
 * <i>Note:</i> this is equivalent to {@code header("Accept", String...)}
 *
 * @param contentTypes The {@link ContentType}(s) expected as response, or <code>null</code> to remove the Accept header
 * @return this request
 */
public Request accept(ContentType... contentTypes) {
    if (isEmpty(contentTypes)) {
        return header(ACCEPT, NULL_VALUE);
    }

    for (ContentType contentType : contentTypes) {
        header(ACCEPT, contentType.toString());
    }

    return this;
}

From source file:at.deder.ybr.test.cukes.HttpServerSimulator.java

public void addResource(String path, String resource, int respCode, String respText, ContentType contentType,
        byte[] content) {
    if (path.endsWith("/")) {
        path = path.substring(0, path.length() - 1);
    }//  ww w. ja va2  s .c  o  m

    Map<String, VirtualResource> resMap;
    if (resourceMap.containsKey(path)) {
        resMap = resourceMap.get(path);
    } else {
        resMap = new HashMap<>();
    }

    VirtualResource vr = new VirtualResource(contentType.toString(), content);
    vr.httpStatus = respCode;
    vr.httpStatusText = respText;
    resMap.put(resource, vr);

    if (!resourceMap.containsKey(path)) {
        resourceMap.put(path, resMap);
    }
}

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

@Override
protected Response sendXmlRequest(URL url, RequestMethod method, String xml)
        throws IOException, OAuthException {
    if (httpClient == null)
        throw new IOException("No HTTP client was specified!");

    if (method == null)
        method = RequestMethod.GET;/*from   w w w  .ja va2s  .co  m*/
    xml = (RequestMethod.POST.equals(method) || RequestMethod.PUT.equals(method)) ? StringUtils.trimToNull(xml)
            : null;

    HttpUriRequest request = null;
    if (RequestMethod.GET.equals(method)) {
        request = new HttpGet(url.toString());
    } else if (RequestMethod.POST.equals(method)) {
        request = new HttpPost(url.toString());
    } else if (RequestMethod.PUT.equals(method)) {
        request = new HttpPut(url.toString());
    } else if (RequestMethod.DELETE.equals(method)) {
        request = new HttpDelete(url.toString());
    } else {
        throw new IOException("Unsupported request method '" + method + "'!");
    }

    if (xml != null && request instanceof HttpEntityEnclosingRequest) {
        ContentType xmlType = ContentType.create("application/xml", getEncoding());

        request.setHeader("Content-Type", xmlType.toString());
        request.setHeader("Content-Language", "en-US");

        StringEntity xmlEntity = new StringEntity(xml, xmlType);
        ((HttpEntityEnclosingRequest) request).setEntity(xmlEntity);
    }
    request.setHeader("Accept", "application/xml");

    // sign request
    getAuthConsumer().sign(request);

    // send request
    HttpResponse response = httpClient.execute(request);

    // create response
    return createResponse(response);
}

From source file:com.github.parisoft.resty.request.Request.java

/**
 * Sets the <a href=http://tools.ietf.org/html/rfc2616#section-14.17>Content-Type</a> header value.<br>
 * <br>/*ww  w  .ja v  a2 s .  c  o m*/
 * <i>Note:</i> this is equivalent to {@code header("Content-Type", String)}
 *
 * @param contentType The {@link ContentType} of the request entity, or <code>null</code> to remove the Content-Type header
 * @return this request
 */
public Request type(ContentType contentType) {
    if (contentType == null) {
        return header(CONTENT_TYPE, NULL_VALUE);
    }

    return header(CONTENT_TYPE, contentType.toString());
}

From source file:biz.mosil.webtools.MosilWeb.java

/**
 * HTTP//from ww  w. ja va  2 s  .com
 * @param _isSSL        ? HTTPS
 * @param _type         {@link biz.mosil.webtools.MosilWebConf.ContentType}
 * @param _postData      POST ???
 * @param _queryString     GET ??(Query String)
 * */
private MosilWeb webInvoke(boolean _isSSL, ContentType _type, final String _postData,
        final String _queryString) {
    chkHostName();
    try {
        String targetUrl = ((_isSSL) ? "https://" : "http://") + mHostName;
        if (!_queryString.equals("")) {
            targetUrl += "?" + _queryString;
        }

        HttpPost httpPost = new HttpPost(targetUrl);
        httpPost.setHeader("Accept", MosilWebConf.HEADER_ACCEPT);
        httpPost.setHeader("Content-Type", _type.toString());
        StringEntity entity = null;
        try {
            entity = new StringEntity(_postData, "UTF-8");
        } catch (UnsupportedEncodingException _ex) {
            throw new RuntimeException("" + _ex.toString());
        }
        httpPost.setEntity(entity);

        mHttpResponse = (_isSSL)
                ? MosilSSLSocketFactory.getHttpClient(mHttpParams).execute(httpPost, mHttpContext)
                : new DefaultHttpClient(mHttpParams).execute(httpPost, mHttpContext);
        if (mHttpResponse != null) {
            mResponse = EntityUtils.toString(mHttpResponse.getEntity());
        }
    } catch (ClientProtocolException _ex) {
        Log.e(TAG, "Client Protocol Exception: " + _ex.toString());
    } catch (IOException _ex) {
        Log.e(TAG, "IO Exception: " + _ex.toString());
    }

    return this;
}

From source file:org.ambraproject.wombat.service.FreemarkerMailServiceImpl.java

private BodyPart createBodyPart(ContentType contentType, Template htmlTemplate, Model context)
        throws IOException, MessagingException {
    BodyPart htmlPage = new MimeBodyPart();
    String encoding = getConfiguration().getDefaultEncoding();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(0x100);
    Writer writer = new BufferedWriter(new OutputStreamWriter(outputStream, encoding));

    htmlTemplate.setOutputEncoding(encoding);
    htmlTemplate.setEncoding(encoding);/*from  ww  w.  ja va2s  . c o m*/

    try {
        htmlTemplate.process(context, writer);
    } catch (TemplateException e) {
        throw new MailPreparationException("Can't generate " + contentType.getMimeType() + " subscription mail",
                e);
    }

    htmlPage.setDataHandler(createBodyPartDataHandler(outputStream.toByteArray(),
            contentType.toString() + "; charset=" + getConfiguration().getDefaultEncoding()));

    return htmlPage;
}

From source file:org.apache.hadoop.gateway.dispatch.DefaultDispatch.java

private String getInboundResponseContentType(final HttpEntity entity) {
    String fullContentType = null;
    if (entity != null) {
        ContentType entityContentType = ContentType.get(entity);
        if (entityContentType != null) {
            if (entityContentType.getCharset() == null) {
                final String entityMimeType = entityContentType.getMimeType();
                final String defaultCharset = MimeTypes.getDefaultCharsetForMimeType(entityMimeType);
                if (defaultCharset != null) {
                    LOG.usingDefaultCharsetForEntity(entityMimeType, defaultCharset);
                    entityContentType = entityContentType.withCharset(defaultCharset);
                }//from   www  .  ja v  a2 s . com
            } else {
                LOG.usingExplicitCharsetForEntity(entityContentType.getMimeType(),
                        entityContentType.getCharset());
            }
            fullContentType = entityContentType.toString();
        }
    }
    if (fullContentType == null) {
        LOG.unknownResponseEntityContentType();
    } else {
        LOG.inboundResponseEntityContentType(fullContentType);
    }
    return fullContentType;
}

From source file:org.apache.camel.component.olingo2.api.impl.Olingo2AppImpl.java

/**
 * public for unit test, not to be used otherwise
 *//*from ww  w  .j  a  v a2  s  .co m*/
public void execute(HttpUriRequest httpUriRequest, ContentType contentType,
        FutureCallback<HttpResponse> callback) {

    // add accept header when its not a form or multipart
    final String contentTypeString = contentType.toString();
    if (!ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType.getMimeType())
            && !contentType.getMimeType().startsWith(MULTIPART_MIME_TYPE)) {
        // otherwise accept what is being sent
        httpUriRequest.addHeader(HttpHeaders.ACCEPT, contentTypeString);
    }
    // is something being sent?
    if (httpUriRequest instanceof HttpEntityEnclosingRequestBase
            && httpUriRequest.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) {
        httpUriRequest.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeString);
    }

    // set user specified custom headers
    if (httpHeaders != null && !httpHeaders.isEmpty()) {
        for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
            httpUriRequest.setHeader(entry.getKey(), entry.getValue());
        }
    }

    // add client protocol version if not specified
    if (!httpUriRequest.containsHeader(ODataHttpHeaders.DATASERVICEVERSION)) {
        httpUriRequest.addHeader(ODataHttpHeaders.DATASERVICEVERSION, ODataServiceVersion.V20);
    }
    if (!httpUriRequest.containsHeader(MAX_DATA_SERVICE_VERSION)) {
        httpUriRequest.addHeader(MAX_DATA_SERVICE_VERSION, ODataServiceVersion.V30);
    }

    // execute request
    client.execute(httpUriRequest, callback);
}

From source file:uk.ac.susx.tag.method51.webapp.handler.CodingInstanceHandler.java

/**
 * Re-issue the request to an instance./* ww  w .  j  av a 2 s. c om*/
 *
 * @param target
 * @param baseRequest
 * @param request
 * @param response
 * @throws IOException
 */
private void coding(final String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    new DoSomethingWithTheSpecifiedJobID(request, response) {

        public void something(String jid) throws IOException {

            Integer port = project.m51(jid).getPort();

            //int port = ((Number)j.getMeta("port")).intValue();

            HttpClient httpclient = new DefaultHttpClient();

            String method = request.getMethod();

            String target = "/coding" + request.getParameter("_target");

            URIBuilder builder = new URIBuilder();

            Set<String> ignore = new HashSet<>();
            ignore.add("id");
            ignore.add("_target");

            builder.setHost("localhost").setScheme("http").setPort(port).setPath(target);

            try {

                HttpUriRequest uriRequest;

                if ("GET".equals(method)) {
                    for (Map.Entry<String, String[]> e : request.getParameterMap().entrySet()) {
                        String key = e.getKey();
                        if (!ignore.contains(key)) {
                            builder.setParameter(e.getKey(), e.getValue()[0]);
                        }
                    }
                    URI uri = builder.build();
                    uriRequest = new HttpGet(uri);
                } else {
                    URI uri = builder.build();
                    List<NameValuePair> params = new ArrayList<>();
                    for (Map.Entry<String, String[]> e : request.getParameterMap().entrySet()) {
                        String key = e.getKey();
                        if (!ignore.contains(key)) {
                            params.add(new BasicNameValuePair(key, e.getValue()[0]));
                        }
                    }
                    uriRequest = new HttpPost(uri);
                    ((HttpPost) uriRequest).setEntity(new UrlEncodedFormEntity(params));
                }

                LOG.info("re-issuing request: {}", uriRequest.toString());

                HttpResponse r = httpclient.execute(uriRequest);

                StatusLine statusLine = r.getStatusLine();
                HttpEntity entity = r.getEntity();
                if (statusLine.getStatusCode() >= 400) {
                    try {
                        ContentType contentType = ContentType.get(entity);
                        String responseBody = EntityUtils.toString(entity, contentType.getCharset());
                        throw new RequestException(statusLine.getReasonPhrase() + responseBody,
                                statusLine.getStatusCode());
                    } catch (IOException | ParseException | NullPointerException e) {
                        EntityUtils.consume(entity);
                        throw new RequestException(statusLine.getReasonPhrase(), statusLine.getStatusCode());
                    }
                }

                response.setStatus(statusLine.getStatusCode());

                ContentType contentType = ContentType.get(entity);
                if (contentType == null) {
                    error("null content type!", response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                } else {
                    String responseBody = EntityUtils.toString(entity, contentType.getCharset());

                    response.setContentType(contentType.toString());
                    response.setCharacterEncoding(contentType.getCharset().toString());
                    response.getWriter().print(responseBody);
                }

            } catch (URISyntaxException e) {
                error(e.getMessage(), response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        }
    };
}

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

private void sendResponse(Request baseRequest, HttpServletResponse servletResponse,
        DispatchResult dispatchResult) throws Exception {
    ContentType contentType = ContentType
            .parse(replaceValues(connectorProperties.getResponseContentType(), dispatchResult));
    if (!connectorProperties.isResponseDataTypeBinary() && contentType.getCharset() == null) {
        /*//  w w w.  j  av  a  2 s  . c o  m
         * If text mode is used and a specific charset isn't already defined, use the one from
         * the connector properties. We can't use ContentType.withCharset here because it
         * doesn't preserve other parameters, like boundary definitions
         */
        contentType = ContentType.parse(contentType.toString() + "; charset="
                + CharsetUtils.getEncoding(connectorProperties.getCharset()));
    }
    servletResponse.setContentType(contentType.toString());

    // set the response headers
    for (Entry<String, List<String>> entry : connectorProperties.getResponseHeaders().entrySet()) {
        for (String headerValue : entry.getValue()) {
            servletResponse.addHeader(entry.getKey(), replaceValues(headerValue, dispatchResult));
        }
    }

    // set the status code
    int statusCode = NumberUtils
            .toInt(replaceValues(connectorProperties.getResponseStatusCode(), dispatchResult), -1);

    /*
     * set the response body and status code (if we choose a response from the drop-down)
     */
    if (dispatchResult != null && dispatchResult.getSelectedResponse() != null) {
        dispatchResult.setAttemptedResponse(true);

        Response selectedResponse = dispatchResult.getSelectedResponse();
        Status newMessageStatus = selectedResponse.getStatus();

        /*
         * If the status code is custom, use the entered/replaced string If is is not a
         * variable, use the status of the destination's response (success = 200, failure = 500)
         * Otherwise, return 200
         */
        if (statusCode != -1) {
            servletResponse.setStatus(statusCode);
        } else if (newMessageStatus != null && newMessageStatus.equals(Status.ERROR)) {
            servletResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        } else {
            servletResponse.setStatus(HttpStatus.SC_OK);
        }

        String message = selectedResponse.getMessage();

        if (message != null) {
            OutputStream responseOutputStream = servletResponse.getOutputStream();
            byte[] responseBytes;
            if (connectorProperties.isResponseDataTypeBinary()) {
                responseBytes = Base64Util.decodeBase64(message.getBytes("US-ASCII"));
            } else {
                responseBytes = message.getBytes(CharsetUtils.getEncoding(connectorProperties.getCharset()));
            }

            // If the client accepts GZIP compression, compress the content
            boolean gzipResponse = false;
            for (Enumeration<String> en = baseRequest.getHeaders("Accept-Encoding"); en.hasMoreElements();) {
                String acceptEncoding = en.nextElement();

                if (acceptEncoding != null && acceptEncoding.contains("gzip")) {
                    gzipResponse = true;
                    break;
                }
            }

            if (gzipResponse) {
                servletResponse.setHeader(HTTP.CONTENT_ENCODING, "gzip");
                GZIPOutputStream gzipOutputStream = new GZIPOutputStream(responseOutputStream);
                gzipOutputStream.write(responseBytes);
                gzipOutputStream.finish();
            } else {
                responseOutputStream.write(responseBytes);
            }

            // TODO include full HTTP payload in sentResponse
        }
    } else {
        /*
         * If the status code is custom, use the entered/replaced string Otherwise, return 200
         */
        if (statusCode != -1) {
            servletResponse.setStatus(statusCode);
        } else {
            servletResponse.setStatus(HttpStatus.SC_OK);
        }
    }
}