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:de.iteratec.iteraplan.presentation.ajax.DojoUtils.java

public static void write(Object data, HttpServletResponse response) throws IOException {
    HttpMessageConverter<Object> converter = getConverter();
    if (!converter.canWrite(data.getClass(), MediaType.APPLICATION_JSON)) {
        throw new IllegalArgumentException("The object cannot be serialized to JSON");
    }/*  w ww  . j a v  a 2 s. c  o  m*/

    converter.write(data, MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response));
}

From source file:gumga.framework.presentation.exceptionhandler.ErrorMessageHandlerExceptionResolver.java

/**
 * Copied from//from w w  w  .  java 2  s. c  om
 * {@link org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver}
 */
@SuppressWarnings("unchecked")
private ModelAndView handleResponseBody(Object returnValue, 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);
    }
    MediaType.sortByQualityValue(acceptedMediaTypes);
    try (ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(webRequest.getResponse())) {
        Class<?> returnValueType = returnValue.getClass();
        if (this.messageConverters != null) {
            for (MediaType acceptedMediaType : acceptedMediaTypes) {
                for (HttpMessageConverter messageConverter : this.messageConverters) {
                    if (messageConverter.canWrite(returnValueType, acceptedMediaType)) {
                        messageConverter.write(returnValue, acceptedMediaType, outputMessage);
                        return new ModelAndView();
                    }
                }
            }
        }
        if (logger.isWarnEnabled()) {
            logger.warn("Could not find HttpMessageConverter that supports return type [" + returnValueType
                    + "] and " + acceptedMediaTypes);
        }
    }

    return null;
}

From source file:com.iflytek.edu.cloud.frame.spring.RequestResponseBodyMethodProcessorExt.java

@Override
protected <T> void writeWithMessageConverters(T returnValue, MethodParameter returnType,
        ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage)
        throws IOException, HttpMediaTypeNotAcceptableException {
    Class<?> returnValueClass = returnValue.getClass();
    HttpServletRequest servletRequest = inputMessage.getServletRequest();
    String format = servletRequest.getParameter(Constants.SYS_PARAM_KEY_FORMAT);

    MediaType contentType = MEDIA_TYPE_XML;

    if (Constants.DATA_FORMAT_JSON.equals(format))
        contentType = MEDIA_TYPE_JSON;//www .  ja  v  a  2 s.  c  o  m
    ;

    if (ClassUtils.isPrimitiveOrWrapper(returnValueClass)) {
        if (Constants.DATA_FORMAT_JSON.equals(format)) {
            String result = "{\"return\":\"" + returnValue + "\"}";
            write(result, contentType, outputMessage);
        } else {
            String result = "<return>" + returnValue + "</return>";
            write(result, contentType, outputMessage);
        }

    } else {

        for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
            if (messageConverter.canWrite(returnValueClass, contentType)) {
                ((HttpMessageConverter<T>) messageConverter).write(returnValue, contentType, outputMessage);
                if (logger.isDebugEnabled()) {
                    logger.debug("Written [" + returnValue + "] as \"" + contentType + "\" using ["
                            + messageConverter + "]");
                }
                return;
            }
        }
    }
}

From source file:org.craftercms.commons.rest.HttpMessageConvertingResponseWriter.java

/**
 * Returns the media types that can be produced:
 * <ul>//from  ww w  . jav  a2s.  c o  m
 *    <li>Media types of configured converters that can write the specific return value, or</li>
 *    <li>{@link org.springframework.http.MediaType#ALL}</li>
 * </ul>
 */
protected List<MediaType> getProducibleMediaTypes(Class<?> returnValueClass) {
    if (!allSupportedMediaTypes.isEmpty()) {
        List<MediaType> result = new ArrayList<>();
        for (HttpMessageConverter<?> converter : messageConverters) {
            if (converter.canWrite(returnValueClass, null)) {
                result.addAll(converter.getSupportedMediaTypes());
            }
        }

        return result;
    } else {
        return Collections.singletonList(MediaType.ALL);
    }
}

From source file:org.cloudfoundry.identity.uaa.error.ExceptionReportHttpMessageConverter.java

@Override
protected void writeInternal(ExceptionReport report, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {
    Exception e = report.getException();
    Map<String, String> map = new HashMap<String, String>();
    map.put("error", UaaStringUtils.getErrorName(e));
    map.put("message", e.getMessage());
    if (report.isTrace()) {
        StringWriter trace = new StringWriter();
        e.printStackTrace(new PrintWriter(trace));
        map.put("trace", trace.toString());
    }/*  w w w.  jav a2  s.  c o  m*/
    for (HttpMessageConverter<?> converter : messageConverters) {
        for (MediaType mediaType : converter.getSupportedMediaTypes()) {
            if (converter.canWrite(Map.class, mediaType)) {
                @SuppressWarnings({ "rawtypes", "unchecked" })
                HttpMessageConverter<Map> messageConverter = (HttpMessageConverter<Map>) converter;
                messageConverter.write(map, mediaType, outputMessage);
                return;
            }
        }
    }
}

From source file:org.ayfaar.app.spring.handler.RestExceptionHandler.java

@SuppressWarnings("unchecked")
protected 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  ww.j av  a2 s . co  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.craftercms.commons.rest.HttpMessageConvertingResponseWriter.java

public <T> void writeWithMessageConverters(T returnValue, HttpServletRequest request,
        HttpServletResponse response) throws IOException, HttpMediaTypeNotAcceptableException {
    Class<?> returnValueClass = returnValue.getClass();
    List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(request);
    List<MediaType> producibleMediaTypes = getProducibleMediaTypes(returnValueClass);

    Set<MediaType> compatibleMediaTypes = new LinkedHashSet<MediaType>();
    for (MediaType r : requestedMediaTypes) {
        for (MediaType p : producibleMediaTypes) {
            if (r.isCompatibleWith(p)) {
                compatibleMediaTypes.add(getMostSpecificMediaType(r, p));
            }/*from   w  ww .  jav  a 2s .c o m*/
        }
    }
    if (compatibleMediaTypes.isEmpty()) {
        throw new HttpMediaTypeNotAcceptableException(producibleMediaTypes);
    }

    List<MediaType> mediaTypes = new ArrayList<MediaType>(compatibleMediaTypes);
    MediaType.sortBySpecificityAndQuality(mediaTypes);

    MediaType selectedMediaType = null;
    for (MediaType mediaType : mediaTypes) {
        if (mediaType.isConcrete()) {
            selectedMediaType = mediaType;
            break;
        } else if (mediaType.equals(MediaType.ALL) || mediaType.equals(MEDIA_TYPE_APPLICATION)) {
            selectedMediaType = MediaType.APPLICATION_OCTET_STREAM;
            break;
        }
    }

    if (selectedMediaType != null) {
        selectedMediaType = selectedMediaType.removeQualityValue();
        for (HttpMessageConverter<?> messageConverter : messageConverters) {
            if (messageConverter.canWrite(returnValueClass, selectedMediaType)) {
                ((HttpMessageConverter<T>) messageConverter).write(returnValue, selectedMediaType,
                        new ServletServerHttpResponse(response));

                logger.debug(LOG_KEY_WRITTEN_WITH_MESSAGE_CONVERTER, returnValue, selectedMediaType,
                        messageConverter);

                return;
            }
        }
    }

    throw new HttpMediaTypeNotAcceptableException(allSupportedMediaTypes);
}

From source file:com.epam.ta.reportportal.commons.exception.rest.RestExceptionHandler.java

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

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

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

    MediaType.sortByQualityValue(acceptedMediaTypes);

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

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

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

    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.cloudfoundry.identity.uaa.error.ConvertingExceptionView.java

@SuppressWarnings("unchecked")
private void writeWithMessageConverters(Object returnValue, HttpInputMessage inputMessage,
        HttpOutputMessage outputMessage) throws IOException, HttpMediaTypeNotAcceptableException {
    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }//from  w w  w .ja  v  a2 s  .  c  o m
    MediaType.sortByQualityValue(acceptedMediaTypes);
    Class<?> returnValueType = returnValue.getClass();
    List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>();
    if (messageConverters != null) {
        for (MediaType acceptedMediaType : acceptedMediaTypes) {
            for (@SuppressWarnings("rawtypes")
            HttpMessageConverter messageConverter : messageConverters) {
                if (messageConverter.canWrite(returnValueType, acceptedMediaType)) {
                    messageConverter.write(returnValue, acceptedMediaType, outputMessage);
                    if (logger.isDebugEnabled()) {
                        MediaType contentType = outputMessage.getHeaders().getContentType();
                        if (contentType == null) {
                            contentType = acceptedMediaType;
                        }
                        logger.debug("Written [" + returnValue + "] as \"" + contentType + "\" using ["
                                + messageConverter + "]");
                    }
                    // this.responseArgumentUsed = true;
                    return;
                }
            }
        }
        for (@SuppressWarnings("rawtypes")
        HttpMessageConverter messageConverter : messageConverters) {
            allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes());
        }
    }
    throw new HttpMediaTypeNotAcceptableException(allSupportedMediaTypes);
}

From source file:it.unitn.disi.smatch.web.server.api.handlers.ExceptionDetailsExceptionResolver.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  w w  .  ja  va  2s  .  co 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;
}