Skip to content

Allow excluding individual methods from OpenApi output #1429

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

Merged
merged 1 commit into from
Jan 8, 2022
Merged
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 @@ -650,10 +650,27 @@ protected void getRouterFunctionPaths(String beanName, AbstractRouterFunctionVis
* @return the boolean
*/
protected boolean isFilterCondition(HandlerMethod handlerMethod, String operationPath, String[] produces, String[] consumes, String[] headers) {
return isPackageToScan(handlerMethod.getBeanType().getPackage())
return isSuitableTargetMethod(handlerMethod)
&& isPackageToScan(handlerMethod.getBeanType().getPackage())
&& isFilterCondition(operationPath, produces, consumes, headers);
}

/**
* Is target method suitable for inclusion in current documentation/
*
* @param handlerMethod the method to check
* @return whether the method should be included in the current OpenAPI definition
*/
protected boolean isSuitableTargetMethod(HandlerMethod handlerMethod) {
return springDocConfigProperties.getGroupConfigs().stream()
.filter(groupConfig -> this.groupName.equals(groupConfig.getGroup()))
.findAny()
.map(GroupConfig::getMethodFilters)
.map(Collection::stream)
.map(stream -> stream.allMatch(m -> m.includeMethodInOpenApi(handlerMethod.getMethod())))
.orElse(true);
}

/**
* Is condition to match boolean.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ public class GroupedOpenApi {
*/
private final List<String> consumesToMatch;

/**
* The method filters to use.
*/
private final List<MethodFilter> methodFilters;

/**
* Instantiates a new Grouped open api.
*
Expand All @@ -104,6 +109,7 @@ private GroupedOpenApi(Builder builder) {
this.pathsToExclude = builder.pathsToExclude;
this.openApiCustomisers = Objects.requireNonNull(builder.openApiCustomisers);
this.operationCustomizers = Objects.requireNonNull(builder.operationCustomizers);
this.methodFilters = Objects.requireNonNull(builder.methodFilters);
if (CollectionUtils.isEmpty(this.pathsToMatch)
&& CollectionUtils.isEmpty(this.packagesToScan)
&& CollectionUtils.isEmpty(this.producesToMatch)
Expand All @@ -112,7 +118,8 @@ private GroupedOpenApi(Builder builder) {
&& CollectionUtils.isEmpty(this.pathsToExclude)
&& CollectionUtils.isEmpty(this.packagesToExclude)
&& CollectionUtils.isEmpty(openApiCustomisers)
&& CollectionUtils.isEmpty(operationCustomizers))
&& CollectionUtils.isEmpty(operationCustomizers)
&& CollectionUtils.isEmpty(methodFilters))
throw new IllegalStateException("Packages to scan or paths to filter or openApiCustomisers/operationCustomizers can not be all null for the group:" + this.group);
}

Expand Down Expand Up @@ -215,6 +222,15 @@ public List<OperationCustomizer> getOperationCustomizers() {
return operationCustomizers;
}

/**
* Gets method filters.
*
* @return the method filters
*/
public List<MethodFilter> getMethodFilters() {
return methodFilters;
}

/**
* The type Builder.
* @author bnasslahsen
Expand All @@ -230,6 +246,11 @@ public static class Builder {
*/
private final List<OperationCustomizer> operationCustomizers = new ArrayList<>();

/**
* The methods filters to apply.
*/
private final List<MethodFilter> methodFilters = new ArrayList<>();

/**
* The Group.
*/
Expand Down Expand Up @@ -387,6 +408,17 @@ public Builder addOperationCustomizer(OperationCustomizer operationCustomizer) {
return this;
}

/**
* Add method filter.
*
* @param methodFilter an additional filter to apply to the matched methods
* @return the builder
*/
public Builder addMethodFilter(MethodFilter methodFilter) {
this.methodFilters.add(methodFilter);
return this;
}

/**
* Build grouped open api.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
*
* *
* * * Copyright 2019-2020 the original author or authors.
* * *
* * * Licensed under the Apache License, Version 2.0 (the "License");
* * * you may not use this file except in compliance with the License.
* * * You may obtain a copy of the License at
* * *
* * * https://www.apache.org/licenses/LICENSE-2.0
* * *
* * * Unless required by applicable law or agreed to in writing, software
* * * distributed under the License is distributed on an "AS IS" BASIS,
* * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * * See the License for the specific language governing permissions and
* * * limitations under the License.
* *
*
*/

package org.springdoc.core;

import java.lang.reflect.Method;

/**
* A filter to allow conditionally including any detected methods in an OpenApi definition.
* @author michael.clarke
*/
@FunctionalInterface
public interface MethodFilter {

/**
* Whether the given method should be included in the generated OpenApi definitions. Only methods from classes
* detected by the relevant loader will be passed to this filter; it cannot be used to load methods that are not
* annotated with `RequestMethod` or similar mechanisms. Methods that are rejected by this filter will not be
* processed any further, although methods accepted by this filter may still be rejected by other checks, such as
* package inclusion checks so may still be excluded from the final OpenApi definition.
*
* @param method the method to perform checks against
* @return whether this method should be used for further processing
*/
boolean includeMethodInOpenApi(Method method);
}
Original file line number Diff line number Diff line change
Expand Up @@ -1081,6 +1081,11 @@ public static class GroupConfig {
*/
private List<String> consumesToMatch;

/**
* The method filters to use.
*/
private List<MethodFilter> methodFilters;

/**
* Instantiates a new Group config.
*/
Expand All @@ -1098,10 +1103,32 @@ public GroupConfig() {
* @param producesToMatch the produces to match
* @param consumesToMatch the consumes to match
* @param headersToMatch the headers to match
* @deprecated Use {@link #GroupConfig(String, List, List, List, List, List, List, List, List)}
*/
@Deprecated
public GroupConfig(String group, List<String> pathsToMatch, List<String> packagesToScan,
List<String> packagesToExclude, List<String> pathsToExclude,
List<String> producesToMatch,List<String> consumesToMatch,List<String> headersToMatch) {
List<String> producesToMatch, List<String> consumesToMatch, List<String> headersToMatch) {
this(group, pathsToMatch, packagesToScan, packagesToExclude, pathsToExclude, producesToMatch, consumesToMatch, headersToMatch, new ArrayList<>());
}

/**
* Instantiates a new Group config.
*
* @param group the group
* @param pathsToMatch the paths to match
* @param packagesToScan the packages to scan
* @param packagesToExclude the packages to exclude
* @param pathsToExclude the paths to exclude
* @param producesToMatch the produces to match
* @param consumesToMatch the consumes to match
* @param headersToMatch the headers to match
* @param methodFilters the method filters to use
*/
public GroupConfig(String group, List<String> pathsToMatch, List<String> packagesToScan,
List<String> packagesToExclude, List<String> pathsToExclude,
List<String> producesToMatch, List<String> consumesToMatch, List<String> headersToMatch,
List<MethodFilter> methodFilters) {
this.pathsToMatch = pathsToMatch;
this.pathsToExclude = pathsToExclude;
this.packagesToExclude = packagesToExclude;
Expand All @@ -1110,6 +1137,7 @@ public GroupConfig(String group, List<String> pathsToMatch, List<String> package
this.producesToMatch = producesToMatch;
this.consumesToMatch = consumesToMatch;
this.headersToMatch = headersToMatch;
this.methodFilters = methodFilters;
}

/**
Expand Down Expand Up @@ -1255,5 +1283,23 @@ public List<String> getProducesToMatch() {
public void setProducesToMatch(List<String> producesToMatch) {
this.producesToMatch = producesToMatch;
}

/**
* Gets the method filters to use.
*
* @return the method filters to use
*/
public List<MethodFilter> getMethodFilters() {
return methodFilters;
}

/**
* Sets the method filters to use.
*
* @param methodFilters the method filters to use
*/
public void setMethodFilters(List<MethodFilter> methodFilters) {
this.methodFilters = methodFilters;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public void afterPropertiesSet() {
this.groupedOpenApiResources = groupedOpenApis.stream()
.collect(Collectors.toMap(GroupedOpenApi::getGroup, item ->
{
GroupConfig groupConfig = new GroupConfig(item.getGroup(), item.getPathsToMatch(), item.getPackagesToScan(), item.getPackagesToExclude(), item.getPathsToExclude(), item.getProducesToMatch(), item.getConsumesToMatch(),item.getHeadersToMatch());
GroupConfig groupConfig = new GroupConfig(item.getGroup(), item.getPathsToMatch(), item.getPackagesToScan(), item.getPackagesToExclude(), item.getPathsToExclude(), item.getProducesToMatch(), item.getConsumesToMatch(),item.getHeadersToMatch(), item.getMethodFilters());
springDocConfigProperties.addGroupConfig(groupConfig);
return buildWebFluxOpenApiResource(item);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public void afterPropertiesSet() {
this.groupedOpenApiResources = groupedOpenApis.stream()
.collect(Collectors.toMap(GroupedOpenApi::getGroup, item ->
{
GroupConfig groupConfig = new GroupConfig(item.getGroup(), item.getPathsToMatch(), item.getPackagesToScan(), item.getPackagesToExclude(), item.getPathsToExclude(), item.getProducesToMatch(), item.getConsumesToMatch(), item.getHeadersToMatch());
GroupConfig groupConfig = new GroupConfig(item.getGroup(), item.getPathsToMatch(), item.getPackagesToScan(), item.getPackagesToExclude(), item.getPathsToExclude(), item.getProducesToMatch(), item.getConsumesToMatch(), item.getHeadersToMatch(), item.getMethodFilters());
springDocConfigProperties.addGroupConfig(groupConfig);
return buildWebMvcOpenApiResource(item);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package test.org.springdoc.api.app177;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

import org.springdoc.core.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AnnotatedController {

@Group1
@GetMapping("/annotated")
public String annotatedGet() {
return "annotated";
}

@Group1
@PostMapping("/annotated")
public String annotatedPost() {
return "annotated";
}

@Group2
@PutMapping("/annotated")
public String annotatedPut() {
return "annotated";
}

@Bean
public GroupedOpenApi group1OpenApi() {
return GroupedOpenApi.builder()
.group("annotatedGroup1")
.addMethodFilter(method -> method.isAnnotationPresent(Group1.class))
.build();
}

@Bean
public GroupedOpenApi group2OpenApi() {
return GroupedOpenApi.builder()
.group("annotatedGroup2")
.addMethodFilter(method -> method.isAnnotationPresent(Group2.class))
.build();
}

@Bean
public GroupedOpenApi group3OpenApi() {
return GroupedOpenApi.builder()
.group("annotatedCombinedGroup")
.addMethodFilter(method -> method.isAnnotationPresent(Group1.class) || method.isAnnotationPresent(Group2.class))
.build();
}

@Retention(RetentionPolicy.RUNTIME)
@interface Group1 {

}

@Retention(RetentionPolicy.RUNTIME)
@interface Group2 {

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
*
* *
* * *
* * * * Copyright 2019-2020 the original author or authors.
* * * *
* * * * Licensed under the Apache License, Version 2.0 (the "License");
* * * * you may not use this file except in compliance with the License.
* * * * You may obtain a copy of the License at
* * * *
* * * * https://www.apache.org/licenses/LICENSE-2.0
* * * *
* * * * Unless required by applicable law or agreed to in writing, software
* * * * distributed under the License is distributed on an "AS IS" BASIS,
* * * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * * * See the License for the specific language governing permissions and
* * * * limitations under the License.
* * *
* *
*
*
*/

package test.org.springdoc.api.app177;

import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.jupiter.api.Test;
import org.springdoc.core.Constants;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import test.org.springdoc.api.AbstractSpringDocTest;

class SpringDocApp177Test extends AbstractSpringDocTest {

@SpringBootApplication
static class SpringDocTestApp {}

@Test
void testFilterOnlyPicksUpMatchedMethods() throws Exception {
mockMvc.perform(get(Constants.DEFAULT_API_DOCS_URL + "/annotatedGroup1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.openapi", is("3.0.1")))
.andExpect(content().json(getContent("results/app177-1.json"), true));
}

@Test
void testFilterOnlyPicksUpMatchedMethodsWithDifferentFilter() throws Exception {
mockMvc.perform(get(Constants.DEFAULT_API_DOCS_URL + "/annotatedGroup2"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.openapi", is("3.0.1")))
.andExpect(content().json(getContent("results/app177-2.json"), true));
}

@Test
void testFilterOnlyPicksUpCombinedMatchedMethods() throws Exception {
mockMvc.perform(get(Constants.DEFAULT_API_DOCS_URL + "/annotatedCombinedGroup"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.openapi", is("3.0.1")))
.andExpect(content().json(getContent("results/app177.json"), true));
}

}
Loading