Skip to content

Fix unexpected merging of media types #3026

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,11 @@ public void calculateConsumesProduces(Method method) {
RequestMapping reqMappingClass = AnnotatedElementUtils.findMergedAnnotation(method.getDeclaringClass(), RequestMapping.class);

if (reqMappingMethod != null && reqMappingClass != null) {
fillMethods(ArrayUtils.addAll(reqMappingMethod.produces(), reqMappingClass.produces()), ArrayUtils.addAll(reqMappingMethod.consumes(), reqMappingClass.consumes()), reqMappingMethod.headers());
fillMethods(
calculateMethodMediaTypes(reqMappingMethod.produces(), reqMappingClass.produces()),
calculateMethodMediaTypes(reqMappingMethod.consumes(), reqMappingClass.consumes()),
reqMappingMethod.headers()
);
}
else if (reqMappingMethod != null) {
fillMethods(reqMappingMethod.produces(), reqMappingMethod.consumes(), reqMappingMethod.headers());
Expand Down Expand Up @@ -313,6 +317,21 @@ else if (ArrayUtils.isEmpty(methodConsumes)) {
setHeaders(headers);
}

/**
* If there is any method type(s) present, then these will override the class type(s).
* See <a href="https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-requestmapping.html#mvc-ann-requestmapping-consumes">...</a> for details
*
* @param methodTypes the method types
* @param classTypes the class types
* @return the string [ ] containing the types that can be used for the method
*/
private String[] calculateMethodMediaTypes(@Nullable String[] methodTypes, String[] classTypes) {
if (ArrayUtils.isNotEmpty(methodTypes)) {
return methodTypes;
}
return classTypes;
}

/**
* Merge string arrays into one array with unique values
*
Expand Down Expand Up @@ -478,7 +497,7 @@ public void setWithResponseBodySchemaDoc(boolean withResponseBodySchemaDoc) {
public void calculateHeadersForClass(Class<?> declaringClass) {
RequestMapping reqMappingClass = AnnotatedElementUtils.findMergedAnnotation(declaringClass, RequestMapping.class);
if (reqMappingClass != null) {
fillMethods(reqMappingClass.produces(), reqMappingClass.consumes(), reqMappingClass.headers());
setHeaders(reqMappingClass.headers());
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fillMethods triggered a media type recalculation that made the types become incorrectly assigned as the class media types. Given the name of the method, I removed the call to fillMethods and instead simply invoked setHeaders which is invoked lastly in the fillMethods method.

}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ public Optional<RequestBody> buildRequestBodyFromDoc(
}

if (requestBody.required()) {
requestBodyObject.setRequired(requestBody.required());
requestBodyObject.setRequired(true);
isEmpty = false;
}
if (requestBody.extensions().length > 0) {
Expand All @@ -128,7 +128,7 @@ public Optional<RequestBody> buildRequestBodyFromDoc(
if (isEmpty)
return Optional.empty();

buildResquestBodyContent(requestBody, requestBodyOp, methodAttributes, components, jsonViewAnnotation, classConsumes, methodConsumes, requestBodyObject);
buildRequestBodyContent(requestBody, requestBodyOp, methodAttributes, components, jsonViewAnnotation, classConsumes, methodConsumes, requestBodyObject);

return Optional.of(requestBodyObject);
}
Expand All @@ -145,7 +145,10 @@ public Optional<RequestBody> buildRequestBodyFromDoc(
* @param methodConsumes the method consumes
* @param requestBodyObject the request body object
*/
private void buildResquestBodyContent(io.swagger.v3.oas.annotations.parameters.RequestBody requestBody, RequestBody requestBodyOp, MethodAttributes methodAttributes, Components components, JsonView jsonViewAnnotation, String[] classConsumes, String[] methodConsumes, RequestBody requestBodyObject) {
private void buildRequestBodyContent(io.swagger.v3.oas.annotations.parameters.RequestBody requestBody,
RequestBody requestBodyOp, MethodAttributes methodAttributes,
Components components, JsonView jsonViewAnnotation, String[] classConsumes,
String[] methodConsumes, RequestBody requestBodyObject) {
Optional<Content> optionalContent = SpringDocAnnotationsUtils
.getContent(requestBody.content(), getConsumes(classConsumes),
getConsumes(methodConsumes), null, components, jsonViewAnnotation, parameterBuilder.isOpenapi31());
Expand Down
Original file line number Diff line number Diff line change
@@ -1,70 +1,228 @@
package org.springdoc.core.model;

import java.lang.reflect.Method;
import java.util.Locale;

import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.springdoc.core.models.MethodAttributes;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.reflect.Method;
import java.util.Locale;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.mockito.BDDMockito.given;

public class MethodAttributesTest {

@Test
public void testMergeArrays() throws Exception {
MethodAttributes methodAttributes = new MethodAttributes("application/json", "application/xml", Locale.ENGLISH);

String[] array1 = { "application/json", "application/xml" };
String[] array2 = { "application/xml", "application/yaml" };

String[] expected = { "application/json", "application/xml", "application/yaml" };

Method mergeArraysMethod = MethodAttributes.class.getDeclaredMethod("mergeArrays", String[].class, String[].class);
mergeArraysMethod.setAccessible(true);
String[] result = (String[]) mergeArraysMethod.invoke(methodAttributes, (Object) array1, (Object) array2);

assertArrayEquals(expected, result);
}

@Test
public void testMergeArraysWithNullArray1() throws Exception {
MethodAttributes methodAttributes = new MethodAttributes("application/json", "application/xml", Locale.ENGLISH);

String[] array1 = null;
String[] array2 = { "application/xml", "application/yaml" };

String[] expected = { "application/xml", "application/yaml" };

Method mergeArraysMethod = MethodAttributes.class.getDeclaredMethod("mergeArrays", String[].class, String[].class);
mergeArraysMethod.setAccessible(true);
String[] result = (String[]) mergeArraysMethod.invoke(methodAttributes, (Object) array1, (Object) array2);

assertArrayEquals(expected, result);
}

@Test
public void testDefaultProducesMediaType() {
MethodAttributes methodAttributes = new MethodAttributes("application/json", "application/xml", Locale.ENGLISH);

Method method = this.getClass().getDeclaredMethods()[0];
methodAttributes.calculateConsumesProduces(method);
private static final String APPLICATION_JSON = "application/json";
private static final String APPLICATION_XML = "application/xml";
private static final String APPLICATION_YAML = "application/yaml";

String[] expectedProduces = { "application/xml" };
String[] resultProduces = methodAttributes.getMethodProduces();
@Test
void testMergeArrays() throws Exception {
MethodAttributes methodAttributes = new MethodAttributes(APPLICATION_JSON, APPLICATION_XML, Locale.ENGLISH);

assertArrayEquals(expectedProduces, resultProduces);
}
String[] array1 = {APPLICATION_JSON, APPLICATION_XML};
String[] array2 = {APPLICATION_XML, APPLICATION_YAML};

@Test
public void testDefaultConsumesMediaType() {
MethodAttributes methodAttributes = new MethodAttributes("application/json", "application/xml", Locale.ENGLISH);
String[] expected = {APPLICATION_JSON, APPLICATION_XML, APPLICATION_YAML};

Method method = this.getClass().getDeclaredMethods()[0];
methodAttributes.calculateConsumesProduces(method);
Method mergeArraysMethod = MethodAttributes.class.getDeclaredMethod("mergeArrays", String[].class, String[].class);
mergeArraysMethod.setAccessible(true);
String[] result = (String[]) mergeArraysMethod.invoke(methodAttributes, (Object) array1, (Object) array2);

assertArrayEquals(expected, result);
}

@Test
void testMergeArraysWithNullArray1() throws Exception {
MethodAttributes methodAttributes = new MethodAttributes(APPLICATION_JSON, APPLICATION_XML, Locale.ENGLISH);

String[] expectedConsumes = { "application/json" };
String[] resultConsumes = methodAttributes.getMethodConsumes();
String[] array1 = null;
String[] array2 = {APPLICATION_XML, APPLICATION_YAML};

String[] expected = {APPLICATION_XML, APPLICATION_YAML};

assertArrayEquals(expectedConsumes, resultConsumes);
}
Method mergeArraysMethod = MethodAttributes.class.getDeclaredMethod("mergeArrays", String[].class, String[].class);
mergeArraysMethod.setAccessible(true);
String[] result = (String[]) mergeArraysMethod.invoke(methodAttributes, (Object) array1, (Object) array2);

assertArrayEquals(expected, result);
}

@Test
void testDefaultProducesMediaType() {
MethodAttributes methodAttributes = new MethodAttributes(APPLICATION_JSON, APPLICATION_XML, Locale.ENGLISH);

Method method = this.getClass().getDeclaredMethods()[0];
methodAttributes.calculateConsumesProduces(method);

String[] expectedProduces = {APPLICATION_XML};
String[] resultProduces = methodAttributes.getMethodProduces();

assertArrayEquals(expectedProduces, resultProduces);
}

@Test
void testDefaultConsumesMediaType() {
MethodAttributes methodAttributes = new MethodAttributes(APPLICATION_JSON, APPLICATION_XML, Locale.ENGLISH);

Method method = this.getClass().getDeclaredMethods()[0];
methodAttributes.calculateConsumesProduces(method);

String[] expectedConsumes = {APPLICATION_JSON};
String[] resultConsumes = methodAttributes.getMethodConsumes();

assertArrayEquals(expectedConsumes, resultConsumes);
}

@Test
void methodConsumesOverridesClassConsumes() {
MethodAttributes methodAttributes = new MethodAttributes(APPLICATION_JSON, APPLICATION_XML, Locale.ENGLISH);
RequestMapping requestMapping = givenAnnotationHasMediaTypeAnnotations(
new String[]{APPLICATION_JSON, APPLICATION_XML},
new String[]{APPLICATION_JSON, APPLICATION_XML}
);
Method method = this.getClass().getDeclaredMethods()[0];
try (MockedStatic<AnnotatedElementUtils> annotatedElementUtils = Mockito.mockStatic(AnnotatedElementUtils.class)) {
annotatedElementUtils.when(() -> AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class))
.thenReturn(requestMapping);

methodAttributes.setClassConsumes(new String[]{APPLICATION_YAML});
methodAttributes.calculateConsumesProduces(method);

String[] expectedConsumes = {APPLICATION_JSON, APPLICATION_XML};
String[] resultConsumes = methodAttributes.getMethodConsumes();

assertArrayEquals(expectedConsumes, resultConsumes);
}
}

@Test
void methodProducesOverridesClassProduces() {
MethodAttributes methodAttributes = new MethodAttributes(APPLICATION_JSON, APPLICATION_XML, Locale.ENGLISH);
RequestMapping requestMapping = givenAnnotationHasMediaTypeAnnotations(
new String[]{APPLICATION_JSON, APPLICATION_XML},
new String[]{APPLICATION_JSON, APPLICATION_XML}
);
Method method = this.getClass().getDeclaredMethods()[0];
try (MockedStatic<AnnotatedElementUtils> annotatedElementUtils = Mockito.mockStatic(AnnotatedElementUtils.class)) {
annotatedElementUtils.when(() -> AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class))
.thenReturn(requestMapping);

methodAttributes.setClassProduces(new String[]{APPLICATION_YAML});
methodAttributes.calculateConsumesProduces(method);

String[] expectedProduces = {APPLICATION_JSON, APPLICATION_XML};
String[] resultProduces = methodAttributes.getMethodProduces();

assertArrayEquals(expectedProduces, resultProduces);
}
}

@Test
void methodConsumesIsSetToClassConsumesIfNoMethodConsumesIsDefined() {
MethodAttributes methodAttributes = new MethodAttributes(APPLICATION_JSON, APPLICATION_XML, Locale.ENGLISH);
RequestMapping requestMapping = givenAnnotationHasMediaTypeAnnotations(
new String[]{APPLICATION_JSON, APPLICATION_XML},
new String[]{}
);
Method method = this.getClass().getDeclaredMethods()[0];
try (MockedStatic<AnnotatedElementUtils> annotatedElementUtils = Mockito.mockStatic(AnnotatedElementUtils.class)) {
annotatedElementUtils.when(() -> AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class))
.thenReturn(requestMapping);

String[] classConsumes = new String[]{APPLICATION_YAML};
methodAttributes.setClassConsumes(classConsumes);
methodAttributes.calculateConsumesProduces(method);

String[] resultConsumes = methodAttributes.getMethodConsumes();

assertArrayEquals(classConsumes, resultConsumes);
}
}

@Test
void methodProducesIsSetToClassProducesIfNoMethodProducesIsDefined() {
MethodAttributes methodAttributes = new MethodAttributes(APPLICATION_JSON, APPLICATION_XML, Locale.ENGLISH);
RequestMapping requestMapping = givenAnnotationHasMediaTypeAnnotations(
new String[]{},
new String[]{APPLICATION_JSON, APPLICATION_XML}
);
Method method = this.getClass().getDeclaredMethods()[0];
try (MockedStatic<AnnotatedElementUtils> annotatedElementUtils = Mockito.mockStatic(AnnotatedElementUtils.class)) {
annotatedElementUtils.when(() -> AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class))
.thenReturn(requestMapping);

String[] classProduces = new String[]{APPLICATION_YAML};
methodAttributes.setClassProduces(classProduces);
methodAttributes.calculateConsumesProduces(method);

String[] resultProduces = methodAttributes.getMethodProduces();

assertArrayEquals(classProduces, resultProduces);
}
}

@Test
void methodConsumesIsSetToClassConsumesIfNoMethodConsumesIsDefinedAndClassConsumesNotSet() {
MethodAttributes methodAttributes = new MethodAttributes(APPLICATION_JSON, APPLICATION_XML, Locale.ENGLISH);
String[] classConsumes = new String[]{APPLICATION_YAML};
RequestMapping requestMapping = givenAnnotationHasMediaTypeAnnotations(
new String[]{APPLICATION_JSON, APPLICATION_XML},
new String[]{}
);
RequestMapping classMapping = givenAnnotationHasMediaTypeAnnotations(
new String[]{},
classConsumes
);
Method method = this.getClass().getDeclaredMethods()[0];
try (MockedStatic<AnnotatedElementUtils> annotatedElementUtils = Mockito.mockStatic(AnnotatedElementUtils.class)) {
annotatedElementUtils.when(() -> AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class))
.thenReturn(requestMapping);
annotatedElementUtils.when(() -> AnnotatedElementUtils.findMergedAnnotation(method.getDeclaringClass(), RequestMapping.class))
.thenReturn(classMapping);

methodAttributes.calculateConsumesProduces(method);

String[] resultConsumes = methodAttributes.getMethodConsumes();

assertArrayEquals(classConsumes, resultConsumes);
}
}

@Test
void methodProducesIsSetToClassProducesIfNoMethodProducesIsDefinedAndClassProducesNotSet() {
MethodAttributes methodAttributes = new MethodAttributes(APPLICATION_JSON, APPLICATION_XML, Locale.ENGLISH);
String[] classProduces = new String[]{APPLICATION_YAML};
RequestMapping requestMapping = givenAnnotationHasMediaTypeAnnotations(
new String[]{},
new String[]{APPLICATION_JSON, APPLICATION_XML}
);
RequestMapping classMapping = givenAnnotationHasMediaTypeAnnotations(
classProduces,
new String[]{}
);
Method method = this.getClass().getDeclaredMethods()[0];
try (MockedStatic<AnnotatedElementUtils> annotatedElementUtils = Mockito.mockStatic(AnnotatedElementUtils.class)) {
annotatedElementUtils.when(() -> AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class))
.thenReturn(requestMapping);
annotatedElementUtils.when(() -> AnnotatedElementUtils.findMergedAnnotation(method.getDeclaringClass(), RequestMapping.class))
.thenReturn(classMapping);

methodAttributes.calculateConsumesProduces(method);

String[] resultProduces = methodAttributes.getMethodProduces();

assertArrayEquals(classProduces, resultProduces);
}
}

private RequestMapping givenAnnotationHasMediaTypeAnnotations(String[] produces, String[] consumes) {
RequestMapping requestMapping = Mockito.mock(RequestMapping.class);
given(requestMapping.produces()).willReturn(produces);
given(requestMapping.consumes()).willReturn(consumes);
return requestMapping;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,27 @@
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/api", produces = { "application/xml" }, consumes = { "application/json" })
@RequestMapping(value = "/api", produces = {"application/xml"}, consumes = {"application/json"})
public class HelloController {

@RequestMapping(value = "/testpost", method = RequestMethod.POST, produces = { "application/json" },
consumes = { "application/json;charset=UTF-8", "application/json; charset=UTF-8" })
public ResponseEntity<TestObject> testpost(@RequestBody TestObject dto) {
return ResponseEntity.ok(dto);
}
@RequestMapping(value = "/testpost", method = RequestMethod.POST, produces = {"application/json"},
consumes = {"application/json;charset=UTF-8", "application/json; charset=UTF-8"})
public ResponseEntity<TestObject> postWithProducesAndConsumes(@RequestBody TestObject dto) {
return ResponseEntity.ok(dto);
}

@RequestMapping(value = "/testpost2", method = RequestMethod.POST, consumes = {"application/json;charset=UTF-8"})
public ResponseEntity<TestObject> postWithConsumes(@RequestBody TestObject dto) {
return ResponseEntity.ok(dto);
}

@RequestMapping(value = "/testpost3", method = RequestMethod.POST, produces = {"application/json"})
public ResponseEntity<TestObject> postWithProduces(@RequestBody TestObject dto) {
return ResponseEntity.ok(dto);
}

@RequestMapping(value = "/testpost4", method = RequestMethod.POST)
public ResponseEntity<TestObject> post(@RequestBody TestObject dto) {
return ResponseEntity.ok(dto);
}
}
Loading