Example usage for org.springframework.http.converter HttpMessageConverter canWrite

List of usage examples for org.springframework.http.converter HttpMessageConverter canWrite

Introduction

In this page you can find the example usage for org.springframework.http.converter HttpMessageConverter canWrite.

Prototype

boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType);

Source Link

Document

Indicates whether the given class can be written by this converter.

Usage

From source file:com.yang.oa.commons.exception.RestExceptionHandler.java

@SuppressWarnings("unchecked")
private ModelAndView handleResponseBody(Object body, ServletWebRequest webRequest)
        throws ServletException, IOException {

    HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());

    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }/*from   ww  w .  j  a  va2 s  .  c om*/

    MediaType.sortByQualityValue(acceptedMediaTypes);

    HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());

    Class<?> bodyType = body.getClass();

    List<HttpMessageConverter<?>> converters = this.allMessageConverters;

    if (converters != null) {
        for (MediaType acceptedMediaType : acceptedMediaTypes) {
            for (HttpMessageConverter messageConverter : converters) {
                if (messageConverter.canWrite(bodyType, acceptedMediaType)) {
                    messageConverter.write(body, acceptedMediaType, outputMessage);
                    //return empty model and view to short circuit the iteration and to let
                    //Spring know that we've rendered the view ourselves:
                    return new ModelAndView();
                }
            }
        }
    }

    return null;
}

From source file:com.novation.eligibility.rest.spring.web.servlet.handler.RestExceptionHandler.java

@SuppressWarnings("unchecked")
private ModelAndView handleResponseBody(Object body, ServletWebRequest webRequest)
        throws ServletException, IOException {

    HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());

    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }/*  w  w w . j a v  a2  s.com*/

    MediaType.sortByQualityValue(acceptedMediaTypes);

    HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());

    Class<?> bodyType = body.getClass();

    List<HttpMessageConverter<?>> converters = this.allMessageConverters;

    if (converters != null) {
        for (MediaType acceptedMediaType : acceptedMediaTypes) {
            for (HttpMessageConverter messageConverter : converters) {
                if (messageConverter.canWrite(bodyType, acceptedMediaType)) {
                    messageConverter.write(body, acceptedMediaType, outputMessage);
                    //return empty model and view to short circuit the iteration and to let
                    //Spring know that we've rendered the view ourselves:
                    return new ModelAndView();
                }
            }
        }
    }

    if (logger.isWarnEnabled()) {
        logger.warn("Could not find HttpMessageConverter that supports return type [" + bodyType + "] and "
                + acceptedMediaTypes);
    }
    return null;
}

From source file:com.onedrive.api.internal.MultipartRelatedHttpMessageConverter.java

@SuppressWarnings("unchecked")
private void writePart(String name, HttpEntity<?> partEntity, OutputStream os) throws IOException {
    Object partBody = partEntity.getBody();
    Class<?> partType = partBody.getClass();
    HttpHeaders partHeaders = partEntity.getHeaders();
    MediaType partContentType = partHeaders.getContentType();
    for (HttpMessageConverter<?> messageConverter : this.partConverters) {
        if (messageConverter.canWrite(partType, partContentType)) {
            HttpOutputMessage multipartMessage = new MultipartHttpOutputMessage(os);
            StringBuilder builder = new StringBuilder("<").append(name).append('>');
            multipartMessage.getHeaders().set("Content-ID", builder.toString());
            if (!partHeaders.isEmpty()) {
                multipartMessage.getHeaders().putAll(partHeaders);
            }/*from   w ww .  ja  v  a2 s .c o m*/
            ((HttpMessageConverter<Object>) messageConverter).write(partBody, partContentType,
                    multipartMessage);
            return;
        }
    }
    throw new HttpMessageNotWritableException("Could not write request: no suitable HttpMessageConverter "
            + "found for request type [" + partType.getName() + "]");
}

From source file:com.oolong.platform.web.error.RestExceptionHandler.java

@SuppressWarnings("unchecked")
private ModelAndView handleResponseBody(Object body, ServletWebRequest webRequest)
        throws ServletException, IOException {

    HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());

    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }//from   w  ww  .  j ava 2 s.  c  o  m

    MediaType.sortByQualityValue(acceptedMediaTypes);

    HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());

    Class<?> bodyType = body.getClass();

    List<HttpMessageConverter<?>> converters = this.allMessageConverters;

    if (converters != null) {
        for (MediaType acceptedMediaType : acceptedMediaTypes) {
            for (HttpMessageConverter messageConverter : converters) {
                if (messageConverter.canWrite(bodyType, acceptedMediaType)) {
                    messageConverter.write(body, acceptedMediaType, outputMessage);
                    // return empty model and view to short circuit the
                    // iteration and to let
                    // Spring know that we've rendered the view ourselves:
                    return new ModelAndView();
                }
            }
        }
    }

    if (logger.isWarnEnabled()) {
        logger.warn("Could not find HttpMessageConverter that supports return type [" + bodyType + "] and "
                + acceptedMediaTypes);
    }
    return null;
}

From source file:org.jlot.web.api.error.RestExceptionHandler.java

@SuppressWarnings({ "unchecked", "rawtypes", "resource" })
private ModelAndView handleResponseBody(Object body, ServletWebRequest webRequest)
        throws ServletException, IOException {

    HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());

    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }//from   w  w w  .  j a  va2 s .com

    MediaType.sortByQualityValue(acceptedMediaTypes);

    HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());

    Class<?> bodyType = body.getClass();

    List<HttpMessageConverter<?>> converters = this.allMessageConverters;

    if (converters != null) {
        for (MediaType acceptedMediaType : acceptedMediaTypes) {
            for (HttpMessageConverter messageConverter : converters) {
                if (messageConverter.canWrite(bodyType, acceptedMediaType)) {
                    messageConverter.write(body, acceptedMediaType, outputMessage);
                    // return empty model and view to short circuit the
                    // iteration and to let
                    // Spring know that we've rendered the view ourselves:

                    return new ModelAndView();
                }
            }
        }
    }

    if (logger.isWarnEnabled()) {
        logger.warn("Could not find HttpMessageConverter that supports return type [" + bodyType + "] and "
                + acceptedMediaTypes);
    }
    return null;
}

From source file:com.sti.rest.error.RestExceptionHandler.java

@SuppressWarnings({ "unchecked", "resource" })
private ModelAndView handleResponseBody(Object body, ServletWebRequest webRequest)
        throws ServletException, IOException {

    HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());

    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }/*  w  w w .j  a va  2 s  .  c  om*/

    MediaType.sortByQualityValue(acceptedMediaTypes);

    HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());

    Class<?> bodyType = body.getClass();

    List<HttpMessageConverter<?>> converters = this.allMessageConverters;

    if (converters != null) {
        for (MediaType acceptedMediaType : acceptedMediaTypes) {
            for (@SuppressWarnings("rawtypes")
            HttpMessageConverter messageConverter : converters) {
                if (messageConverter.canWrite(bodyType, acceptedMediaType)) {
                    messageConverter.write(body, acceptedMediaType, outputMessage);
                    //return empty model and view to short circuit the iteration and to let
                    //Spring know that we've rendered the view ourselves:
                    return new ModelAndView();
                }
            }
        }
    }

    if (logger.isWarnEnabled()) {
        logger.warn("Could not find HttpMessageConverter that supports return type [" + bodyType + "] and "
                + acceptedMediaTypes);
    }

    return null;
}

From source file:net.solarnetwork.web.test.SimpleCsvHttpMessageCoverterTest.java

@Test
public void testAPIContract() {
    HttpMessageConverter<?> hmc = new SimpleCsvHttpMessageConverter();
    List<MediaType> supportedTypes = hmc.getSupportedMediaTypes();
    Assert.assertEquals("Supports text/csv", Arrays.asList(CSV_MEDIA_TYPE), supportedTypes);
    Assert.assertTrue("Can write CSV", hmc.canWrite(Object.class, CSV_MEDIA_TYPE));
}

From source file:com.httpMessageConvert.FormHttpMessageConverter.java

@SuppressWarnings("unchecked")
private void writePart(String name, HttpEntity partEntity, OutputStream os) throws IOException {
    Object partBody = partEntity.getBody();
    Class<?> partType = partBody.getClass();
    HttpHeaders partHeaders = partEntity.getHeaders();
    MediaType partContentType = partHeaders.getContentType();
    for (HttpMessageConverter messageConverter : partConverters) {
        if (messageConverter.canWrite(partType, partContentType)) {
            HttpOutputMessage multipartOutputMessage = new MultipartHttpOutputMessage(os);
            multipartOutputMessage.getHeaders().setContentDispositionFormData(name, getFilename(partBody));
            if (!partHeaders.isEmpty()) {
                multipartOutputMessage.getHeaders().putAll(partHeaders);
            }//from  w w  w  .jav  a2  s.co m
            messageConverter.write(partBody, partContentType, multipartOutputMessage);
            return;
        }
    }
    throw new HttpMessageNotWritableException(
            "Could not write request: no suitable HttpMessageConverter found for request type ["
                    + partType.getName() + "]");
}

From source file:edu.colorado.orcid.impl.OrcidServicePublicImpl.java

public String createOrcid(String email, String givenNames, String familyName)
        throws OrcidException, OrcidEmailExistsException, OrcidHttpException {

    String newOrcid = null;/*from   w  ww  .ja v a2s .  c o  m*/

    log.debug("Creating ORCID...");
    log.debug("email: " + email);
    log.debug("givenNames: " + givenNames);
    log.debug("familyName: " + familyName);

    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", "application/xml");
    headers.set("Content-Type", "application/vdn.orcid+xml");
    headers.set("Authorization", "Bearer " + orcidCreateToken);

    OrcidMessage message = new OrcidMessage();
    message.setEmail(email);
    message.setGivenNames(givenNames);
    message.setFamilyName(familyName);
    message.setMessageVersion(orcidMessageVersion);
    //TODO Affiliation should be set based on organization once faculty from more than one organization are processed
    message.setAffiliationType(OrcidMessage.AFFILIATION_TYPE_EMPLOYMENT);
    message.setAffiliationOrganizationName(OrcidMessage.CU_BOULDER);
    message.setAffiliationOrganizationAddressCity(OrcidMessage.BOULDER);
    message.setAffiliationOrganizationAddressRegion(OrcidMessage.CO);
    message.setAffiliationOrganizationAddressCountry(OrcidMessage.US);
    message.setAffiliationOrganizationDisambiguatedId(OrcidMessage.DISAMBIGUATED_ID_CU_BOULDER);
    message.setAffiliationOrganizationDisambiguationSource(OrcidMessage.DISAMBIGUATION_SOURCE_RINGOLD);

    HttpEntity entity = new HttpEntity(message, headers);

    log.debug("Configured RestTemplate Message Converters...");
    List<HttpMessageConverter<?>> converters = orcidRestTemplate.getMessageConverters();
    for (HttpMessageConverter<?> converter : converters) {
        log.debug("converter: " + converter);
        log.debug("supported media types: " + converter.getSupportedMediaTypes());
        log.debug("converter.canWrite(String.class, MediaType.APPLICATION_XML): "
                + converter.canWrite(String.class, MediaType.APPLICATION_XML));
        log.debug("converter.canWrite(Message.class, MediaType.APPLICATION_XML): "
                + converter.canWrite(OrcidMessage.class, MediaType.APPLICATION_XML));
    }

    log.debug("Request headers: " + headers);

    HttpStatus responseStatusCode = null;
    String responseBody = null;

    try {
        if (useTestHttpProxy.equalsIgnoreCase("TRUE")) {
            log.info("Using HTTP ***TEST*** proxy...");
            System.setProperty("http.proxyHost", testHttpProxyHost);
            System.setProperty("http.proxyPort", testHttpProxyPort);
            log.info("http.proxyHost: " + System.getProperty("http.proxyHost"));
            log.info("http.proxyPort: " + System.getProperty("http.proxyPort"));
        }
        ResponseEntity<String> responseEntity = orcidRestTemplate.postForEntity(orcidCreateURL, entity,
                String.class);
        responseStatusCode = responseEntity.getStatusCode();
        responseBody = responseEntity.getBody();
        HttpHeaders responseHeaders = responseEntity.getHeaders();
        URI locationURI = responseHeaders.getLocation();
        String uriString = locationURI.toString();
        newOrcid = extractOrcid(uriString);
        log.debug("HTTP response status code: " + responseStatusCode);
        log.debug("HTTP response headers:     " + responseHeaders);
        log.debug("HTTP response body:        " + responseBody);
        log.debug("HTTP response location:    " + locationURI);
        log.debug("New ORCID:                 " + newOrcid);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
            log.debug(e.getStatusCode());
            log.debug(e.getResponseBodyAsString());
            log.debug(e.getMessage());
            throw new OrcidEmailExistsException(e);
        }
        OrcidHttpException ohe = new OrcidHttpException(e);
        ohe.setStatusCode(e.getStatusCode());
        throw ohe;
    }

    return newOrcid;
}

From source file:com.revolsys.ui.web.rest.interceptor.WebAnnotationMethodHandlerAdapter.java

private View handleResponseBody(final Object returnValue, final ServletWebRequest webRequest)
        throws ServletException, IOException {

    final HttpServletRequest request = webRequest.getRequest();
    String jsonp = request.getParameter("jsonp");
    if (jsonp == null) {
        jsonp = request.getParameter("callback");
    }/*  w  ww  .j  av  a 2 s.  c  o m*/
    request.setAttribute(IoConstants.JSONP_PROPERTY, jsonp);
    List<MediaType> acceptedMediaTypes = MediaTypeUtil.getAcceptedMediaTypes(request,
            WebAnnotationMethodHandlerAdapter.this.mediaTypes,
            WebAnnotationMethodHandlerAdapter.this.mediaTypeOrder,
            WebAnnotationMethodHandlerAdapter.this.urlPathHelper,
            WebAnnotationMethodHandlerAdapter.this.parameterName,
            WebAnnotationMethodHandlerAdapter.this.defaultMediaType);
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }
    final Class<?> returnValueType = returnValue.getClass();
    final Set<MediaType> allSupportedMediaTypes = new LinkedHashSet<>();
    if (WebAnnotationMethodHandlerAdapter.this.messageConverters != null) {
        for (final MediaType acceptedMediaType : acceptedMediaTypes) {
            for (final HttpMessageConverter<?> messageConverter : WebAnnotationMethodHandlerAdapter.this.messageConverters) {
                allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes());
                if (messageConverter.canWrite(returnValueType, acceptedMediaType)) {
                    final MediaType mediaType = getMediaType(messageConverter.getSupportedMediaTypes(),
                            acceptedMediaType);
                    return new HttpMessageConverterView(messageConverter, mediaType, returnValue);
                }
            }
        }
    }
    throw new HttpMediaTypeNotAcceptableException(new ArrayList<>(allSupportedMediaTypes));
}