PagedRequestServletFilter implements Filter { @Override public void doFilter(final ServletRequest req, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; if (HttpMethod.GET.name().equals(request.getMethod())) { if (request.getParameterMap().containsKey(LIMIT_KEY)) { Integer limit = Integer.valueOf(request.getParameter(LIMIT_KEY)); if (limit > maxPaginationCount) { String message = MessageFormat.format("Limit out of range: {0}, maximum limit:{1}", limit, maxPaginationCount); RuntimeException outOfRangeException = new LimitOutOfRangeException(limit, message); LOGGER.error(message, outOfRangeException); throw outOfRangeException; } } } chain.doFilter(request, response); }  @Override void doFilter(final ServletRequest req, final ServletResponse response, final FilterChain chain); @Override void destroy(); @Override void init(final FilterConfig config); void setMaxPaginationCount(final Integer maxPaginationCount);  }
@Test public void testDoFilter() throws Exception { Map<String, String[]> parameterMap = new HashMap<String, String[]>(); String[] limits = { "100" }; parameterMap.put("limit", limits); when(req.getMethod()).thenReturn("GET"); when(req.getParameter("limit")).thenReturn(limits[0]); when(req.getParameterMap()).thenReturn(parameterMap); unit.doFilter(req, response, chain); verify(chain).doFilter(req, response); }
@Test public void testDoFilterWithEmptyParametersMap() throws Exception { Map<String, String[]> parameterMap = Collections.emptyMap(); when(req.getMethod()).thenReturn("GET"); when(req.getParameterMap()).thenReturn(parameterMap); unit.doFilter(req, response, chain); verify(req, times(0)).getParameter("limit"); verify(chain).doFilter(req, response); }
@Test public void testDoFilterWithPostMethod() throws Exception { Map<String, String[]> parameterMap = new HashMap<String, String[]>(); String[] limits = { "100" }; parameterMap.put("limit", limits); when(req.getMethod()).thenReturn("POST"); when(req.getParameter("limit")).thenReturn(limits[0]); when(req.getParameterMap()).thenReturn(parameterMap); unit.doFilter(req, response, chain); verify(req, times(0)).getParameter("limit"); verify(req, times(0)).getParameterMap(); verify(chain).doFilter(req, response); }
@Test(expected = LimitOutOfRangeException.class) public void testDoFilterWithOutOfLimitValue() throws Exception { Map<String, String[]> parameterMap = new HashMap<String, String[]>(); String[] limits = { "900" }; parameterMap.put("limit", limits); when(req.getMethod()).thenReturn("GET"); when(req.getParameter("limit")).thenReturn(limits[0]); when(req.getParameterMap()).thenReturn(parameterMap); unit.doFilter(req, response, chain); }