SuppressRequestRejectedExceptionFilter.java

  1. /*
  2.  * Copyright 2019 Global Crop Diversity Trust
  3.  *
  4.  * Licensed under the Apache License, Version 2.0 (the "License");
  5.  * you may not use this file except in compliance with the License.
  6.  * You may obtain a copy of the License at
  7.  *
  8.  *   http://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  * Unless required by applicable law or agreed to in writing, software
  11.  * distributed under the License is distributed on an "AS IS" BASIS,
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  * See the License for the specific language governing permissions and
  14.  * limitations under the License.
  15.  */
  16. package org.genesys.server.servlet.filter;

  17. import org.slf4j.Logger;
  18. import org.slf4j.LoggerFactory;
  19. import org.springframework.security.web.firewall.RequestRejectedException;
  20. import org.springframework.web.filter.GenericFilterBean;

  21. import javax.servlet.FilterChain;
  22. import javax.servlet.ServletException;
  23. import javax.servlet.ServletRequest;
  24. import javax.servlet.ServletResponse;
  25. import javax.servlet.http.HttpServletRequest;
  26. import javax.servlet.http.HttpServletResponse;
  27. import java.io.IOException;

  28. /**
  29.  * https://stackoverflow.com/questions/51788764/how-to-intercept-a-requestrejectedexception-in-spring/52635656#52635656
  30.  */
  31. public class SuppressRequestRejectedExceptionFilter extends GenericFilterBean {
  32.     private static final Logger LOG = LoggerFactory.getLogger(SuppressRequestRejectedExceptionFilter.class);

  33.     @Override
  34.     public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
  35.         try {
  36.             chain.doFilter(req, res);
  37.         } catch (RequestRejectedException e) {
  38.             HttpServletRequest request = (HttpServletRequest) req;
  39.             HttpServletResponse response = (HttpServletResponse) res;
  40.             LOG.warn("Bad request {} {}: {}", request.getMethod(), request.getRequestURL(), e.getMessage());
  41.             response.sendError(HttpServletResponse.SC_NOT_FOUND);
  42.         }
  43.     }
  44. }