Skip to content

AbstractHttpMessageConverter canWrite logic the wrong way round?? [SPR-6970] #11635

@spring-projects-issues

Description

@spring-projects-issues

David Melia opened SPR-6970 and commented

Hi,

the method protected boolean canWrite(MediaType mediaType) in org.springframework.http.converter.AbstractHttpMessageConverter is incorrect.

/**
 * Returns true if the given media type includes any of the
 * {@linkplain #setSupportedMediaTypes(List) supported media types}.
 * @param mediaType the media type
 * @return true if the supported media types include the media type, or if the media type is {@code null}
 */
protected boolean canWrite(MediaType mediaType) {
     if (mediaType == null) {
          return true;
     }
     for (MediaType supportedMediaType : getSupportedMediaTypes()) {
          if (mediaType.includes(supportedMediaType)) {
               return true;
          }
     }
     return false;
}

I think the line
if (mediaType.includes(supportedMediaType)
should be
if (supportedMediaType.includes(mediaType)

The reason I think this is:

  1. the javadoc states "@return true if the supported media types include the media type ..."
  2. I am using the MarshallingHttpMessageConverter which supports application/+xml by default. In my HTTP GET I am passing in accept="application/whatever+xml". so in the above canWrite tries to check if "application/whatever+xml" includes "application/+xml" which doesn't really make much sense (and also returns false obviously).

Check out my main test below which always returns false

public static void main(String[] args) {
     MediaType soapMediaType = new MediaType("application","soap+xml");
     MarshallingHttpMessageConverter msgConverter = new MarshallingHttpMessageConverter() {
                    @Override
          public boolean supports(Class<?> clazz) {
               return true;
                                  }			
                     };		
                                                                                                                                 System.out.println(msgConverter.canWrite(Object.class, soapMediaType)); // prints out false but I think should be true.	
}

Thanks


Affects: 3.0.1

Issue Links:

Referenced from: commits 85b8bef

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)type: bugA general bug

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions