How to exclude OPTIONS, HEAD and PATCH options from spring -data-rest entityController

I use spring -data-rest-webmvc: jar: 2.5.3.RELEASE to write a REST API and display resources in springfox-data-rest-2.6.0. The markup displays all the methods in RestEntityController. I excluded some methods at the repository level using @RestResource(exported = false). But swagger loads all the other HTTP methods like OPTIONS, HEAD and PATCH, which I cannot exclude from RepositoryRestResource.

How to make my swagger a pure resource, including only my CRUD and search methods? You must support this either when using the spring -data-rest configuration, or using the springfox configuration.

+4
source share
4 answers

After you delve into the springfox documentation and discard some dead end ideas, I come up with two solutions that can solve your problem. Apply and mix them according to your needs.

Tip # 1 - Filter Using RequestHandlerSelectors

Tell springfox which endpoint method you would like to show in swagger-ui. Therefore, you can configure RequestHandlerSelectorto scan the entire application, a specific package, or classes and methods that you annotated with the annotation.

//Example for the method scan based on springfox @ApiOperation annotation

@Bean
public Docket api() {    
    return new Docket(DocumentationType.SWAGGER_2)          
      .select()                                       
      .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).paths(PathSelectors.any())
      .build();
}



// Within your dao or repository class
public interface QueuedMessageDao extends CrudRepository<QueuedMessage, Integer> {
    @ApiOperation(value = "This method finds all messages that are queued with the recipient email address")
    List<QueuedMessage> findByRecipientEmail(String email); 
}

spring -data-rest swagger. () HTTP- swagger-ui, GET, HEAD OPTIONS /<entity>/search. , , .

# 2 - PathSelectors

/<entity>/search swagger, , , , . , GET.

//Example for the method scan based on springfox @ApiOperation annotation

@Bean
public Docket api() {    
    return new Docket(DocumentationType.SWAGGER_2)          
      .select()                                       
      .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).paths(PathSelectors.regex("^(?!(/.*(/search)$)).*$"))
      .build();
}

// Within your dao or repository class
public interface QueuedMessageDao extends CrudRepository<QueuedMessage, Integer> {

    @ApiOperation(value = "this generates a business search endpoint")
    List<QueuedMessage> findById(int id);

    @ApiOperation(value = "This method finds all messages that are queued with the recipient email address")
    List<QueuedMessage> findByRecipientEmail(String email); 
}

, - swagger. , !

+5

:

public class MyInterceptor extends HandlerInterceptorAdapter{    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //let disable OPTIONS and HEAD
            if (request.getMethod().equalsIgnoreCase("OPTIONS") || request.getMethod().equalsIgnoreCase("HEAD")) {            
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "Unauthorized Request");
                return false;
            } else {
                return true;
            }
        }
    }

@Configuration
@EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter {
     @Override
        public void addInterceptors(InterceptorRegistry registry){
            registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
        }
} 
+1

, , CRUD- Swagger. Springfox Predicate CRUD, .

@Bean
public Docket api() { 
    return new Docket(DocumentationType.SWAGGER_2)  
        .select()                                  
            .apis(customRequestHandlers())
            .build();
}

private Predicate<RequestHandler> customRequestHandlers() {     
    return new Predicate<RequestHandler>() {
        @Override
        public boolean apply(RequestHandler input) {
            Set<RequestMethod> methods = input.supportedMethods();
            return methods.contains(RequestMethod.GET)  
                || methods.contains(RequestMethod.POST)
                || methods.contains(RequestMethod.PUT)
                || methods.contains(RequestMethod.DELETE);
        }
    };
}
0
source

Eliminating certain HttpMethods using Springfox 2 is pretty simple with its ApiSelectorBuilder, which accepts Guavas Predicates.

This snippet excludes all methods from api-docs and swagger-ui.html, which are OPTIONS, HEAD or PATCH.

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(Predicates.not(requestHandler -> {
                // exclude all methods being OPTIONS, HEAD or PATCH
                final Set<RequestMethod> methods = requestHandler.getRequestMapping().getMethodsCondition().getMethods();
                return !Collections.disjoint(methods, Arrays.asList(RequestMethod.OPTIONS, RequestMethod.HEAD, RequestMethod.PATCH));
            }))
            .build();
}

This can be easily expanded to further eliminate the common error controller.

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(Predicates
                    .and(
                            // exclude /errors
                            Predicates.not(requestHandler -> requestHandler.getRequestMapping().getPatternsCondition().getPatterns().contains("/error")),
                            // exclude all methods being OPTIONS, HEAD or PATCH
                            Predicates.not(requestHandler -> !Collections.disjoint(requestHandler.getRequestMapping().getMethodsCondition().getMethods(),
                                    Arrays.asList(RequestMethod.OPTIONS, RequestMethod.HEAD, RequestMethod.PATCH)))
                    )
            )
            .build();
}
0
source

Source: https://habr.com/ru/post/1657064/


All Articles