/** * Create new FilterConfigPropertyValues. * @param config the FilterConfig we'll use to take PropertyValues from * @param requiredProperties set of property names we need, where * we can't accept default values * @throws ServletException if any required properties are missing */ public FilterConfigPropertyValues(FilterConfig config, Set<String> requiredProperties) throws ServletException { Set<String> missingProps = (!CollectionUtils.isEmpty(requiredProperties) ? new HashSet<>(requiredProperties) : null); Enumeration<String> paramNames = config.getInitParameterNames(); while (paramNames.hasMoreElements()) { String property = paramNames.nextElement(); Object value = config.getInitParameter(property); addPropertyValue(new PropertyValue(property, value)); if (missingProps != null) { missingProps.remove(property); } } // Fail if we are still missing properties. if (!CollectionUtils.isEmpty(missingProps)) { throw new ServletException( "Initialization from FilterConfig for filter '" + config.getFilterName() + "' failed; the following required properties were missing: " + StringUtils.collectionToDelimitedString(missingProps, ", ")); } } }
public void init(FilterConfig c) throws ServletException { sc = c.getServletContext(); _me = this; try { Enumeration<String> keys = c.getInitParameterNames(); while (keys.hasMoreElements()) { String key = keys.nextElement(); String value = c.getInitParameter(key); if (!Strings.isBlank(value) && !"null".equals(value)) props.put(key, c.getInitParameter(key)); String path = c.getInitParameter("config-file"); if (path != null) { InputStream ins = getClass().getClassLoader().getResourceAsStream(path); if (ins == null) ins = c.getServletContext().getResourceAsStream(path); if (ins == null) { throw new ServletException("config-file=" + path + " not found"); String config = c.getInitParameter("config"); if (config != null) { init(new ByteArrayInputStream(config.getBytes())); throw new ServletException(e);
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResp = (HttpServletResponse) resp; Enumeration e = config.getInitParameterNames(); // for each configuration element... while(e.hasMoreElements()) { String headerName = (String) e.nextElement(); String headerValue = config.getInitParameter(headerName); // set the header with the given name and value httpResp.setHeader(headerName, headerValue); } chain.doFilter(req, resp); }
/** {@inheritDoc} */ @Override public void init(FilterConfig filterConfig) throws ServletException { final List<String> parameterNames = Collections.list(filterConfig.getInitParameterNames()); for (final String parameterName : parameterNames) { customResources.put(parameterName, filterConfig.getInitParameter(parameterName)); } }
public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; this.beanName = filterConfig.getInitParameter("beanName"); if (Strings.isBlank(beanName)) beanName = filterConfig.getFilterName(); }
@Test public void passThroughIfNotTrigger() throws ServletException, IOException { // Filter init & setup ServletContext context = mock(ServletContext.class); FilterConfig filterConfig = mock(FilterConfig.class); when(filterConfig.getFilterName()).thenReturn("dummy"); when(filterConfig.getServletContext()).thenReturn(context); when(filterConfig.getInitParameterNames()).thenReturn(new StringTokenIterator("foo, bar")); DummyFilter filter = new DummyFilter() { @Override protected boolean trigger(ServletRequest pRequest) { return false; } }; filter.init(filterConfig); // Request/response setup HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain chain = mock(FilterChain.class); // Execute filter.doFilter(request, response, chain); // Verifications verify(chain).doFilter(request, response); verify(response, never()).getOutputStream(); verify(response, never()).getWriter(); }
AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getInitParameter("management.operation.return")). thenReturn("true"); Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getInitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE, "management.operation.return")).elements()); getMockedServletContextWithStringSigner(config); filter.init(config); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar")); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); ).when(chain).doFilter(Mockito.<ServletRequest>anyObject(), Mockito.<ServletResponse>anyObject()); Mockito.when(response.containsHeader("WWW-Authenticate")).thenReturn(true); filter.doFilter(request, response, chain); Mockito.verify(response).sendError( HttpServletResponse.SC_UNAUTHORIZED, "Authentication required"); } finally {
@Test public void testGetRequestURL() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getInitParameter("management.operation.return")). thenReturn("true"); Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getInitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE, "management.operation.return")).elements()); ServletContext context = Mockito.mock(ServletContext.class); Mockito.when(context.getAttribute( AuthenticationFilter.SIGNATURE_PROVIDER_ATTRIBUTE)).thenReturn(null); Mockito.when(config.getServletContext()).thenReturn(context); filter.init(config); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar")); Mockito.when(request.getQueryString()).thenReturn("a=A&b=B"); Assert.assertEquals("http://foo:8080/bar?a=A&b=B", filter.getRequestURL(request)); } finally { filter.destroy(); } }
@Test public void redirectAllNotAllowed() throws Exception { when(config.getInitParameter("redirectPath")).thenReturn("/bar"); when(config.getInitParameter("forceRedirectAll")).thenReturn("Y"); when(config.getInitParameter("allowedPaths")).thenReturn("/foo"); when(req.getRequestURI()).thenReturn("/baz"); filter.init(config); filter.doFilter(req, resp, next); verify(resp).sendRedirect("/bar"); }
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; // set the provided HTTP response parameters for (Enumeration e = fc.getInitParameterNames(); e.hasMoreElements(); ) { String headerName = (String) e.nextElement(); response.addHeader(headerName, fc.getInitParameter(headerName)); } // pass the request/response on chain.doFilter(req, response); }
FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getInitParameter("management.operation.return")). thenReturn("true"); Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); Mockito.when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret"); Mockito.when(config.getInitParameterNames()).thenReturn( new Vector<String>( Arrays.asList(AuthenticationFilter.AUTH_TYPE, AuthenticationFilter.SIGNATURE_SECRET, "management.operation.return")).elements()); SignerSecretProvider secretProvider = getMockedServletContextWithStringSigner(config); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie});
@Test public void filterWithAllowedSubPath() throws Exception { when(config.getInitParameter("redirectPath")).thenReturn("/foo"); when(config.getInitParameter("allowedPaths")).thenReturn("/foo:/bar"); when(req.getRequestURI()).thenReturn("/servlet/bar/baz"); when(req.getContextPath()).thenReturn("/servlet"); filter.init(config); filter.doFilter(req, resp, next); verify(next).doFilter(req, resp); }
@Test public void filterNoContent() throws ServletException, IOException { // Filter init & setup ServletContext context = mock(ServletContext.class); FilterConfig filterConfig = mock(FilterConfig.class); when(filterConfig.getFilterName()).thenReturn("dummy"); when(filterConfig.getServletContext()).thenReturn(context); when(filterConfig.getInitParameterNames()).thenReturn(new StringTokenIterator("foo, bar")); DummyFilter filter = new DummyFilter(); filter.init(filterConfig); // Request/response setup ServletOutputStream out = mock(ServletOutputStream.class); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); when(response.getOutputStream()).thenReturn(out); FilterChain chain = mock(FilterChain.class); doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation) throws Throwable { HttpServletResponse response = (HttpServletResponse) invocation.getArguments()[1]; response.setContentType("image/x-imaginary"); return null; } }).when(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); // Execute filter.doFilter(request, response, chain); // Verifications verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); verify(response).setContentType("image/x-imaginary"); verify(out, atLeastOnce()).flush(); }
@Test public void normalFilterSendError() throws ServletException, IOException { ServletContext context = mock(ServletContext.class); FilterConfig filterConfig = mock(FilterConfig.class); when(filterConfig.getFilterName()).thenReturn("dummy"); when(filterConfig.getServletContext()).thenReturn(context); when(filterConfig.getInitParameterNames()).thenReturn(new StringTokenIterator("foo, bar")); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); when(response.getOutputStream()).thenReturn(out); FilterChain chain = mock(FilterChain.class); }).when(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); verify(response, atMost(1)).setContentLength(stream.size()); // setContentLength not implemented, avoid future bugs verify(out, atLeastOnce()).flush();
@Test public void triggerWithTriggerParams() throws ServletException { // Filter init & setup ServletContext context = mock(ServletContext.class); FilterConfig filterConfig = mock(FilterConfig.class); when(filterConfig.getFilterName()).thenReturn("dummy"); when(filterConfig.getServletContext()).thenReturn(context); when(filterConfig.getInitParameterNames()).thenReturn(new StringTokenIterator("triggerParams")); when(filterConfig.getInitParameter("triggerParams")).thenReturn("foo"); DummyFilter filter = new DummyFilter(); filter.init(filterConfig); // Request/response setup HttpServletRequest request = mock(HttpServletRequest.class); when(request.getParameter("foo")).thenReturn("doit"); // Execute/Verifications assertTrue(filter.trigger(request)); }
expect(filterConfig.getServletContext()).andReturn(createMock(ServletContext.class)); expect(request.getRequestURI()).andReturn("/"); expect(request.getContextPath()).andReturn("").anyTimes(); expect(request.getMethod()).andReturn("GET"); expect(request.getCookies()).andReturn(new Cookie[0]);
@Test public void testNotInvalidateSession() throws Exception { SessionProvider sessionProvider = new SessionProvider(httpSession, 1); when(authenticationService.getUser()).thenReturn(new UserImpl("testUser")); when(request.getSession(anyBoolean())).then((InvocationOnMock invocationOnMock) -> sessionProvider.provideSession()); final BasicAuthSecurityFilter filter = new BasicAuthSecurityFilter(); final FilterConfig config = mock(FilterConfig.class); when(config.getInitParameter(BasicAuthSecurityFilter.INVALIDATE_PARAM)).thenReturn("false"); filter.init(config); filter.authenticationService = authenticationService; filter.doFilter(request, response, chain); verify(httpSession, never()).invalidate(); }
@Test public void bailsOutWithVariousErrorCodes() throws Exception { when(config.getInitParameter("allowedPaths")).thenReturn("/foo"); when(req.getRequestURI()).thenReturn("/baz"); // if no errorCode parameter is specified then the default error code is 403 when(config.getInitParameter("errorCode")).thenReturn(null); filter.init(config); filter.doFilter(req, resp, next); // if the errorCode parameter is empty then the default error code is 403 when(config.getInitParameter("errorCode")).thenReturn(""); filter.init(config); filter.doFilter(req, resp, next); // if an invalid errorCode parameter is specified then the default error code is 403 when(config.getInitParameter("errorCode")).thenReturn("NaN"); filter.init(config); filter.doFilter(req, resp, next); verify(resp, times(3)).sendError(403, "/baz"); // if the errorCode parameter is specified then it is set in the filter when(config.getInitParameter("errorCode")).thenReturn("404"); filter.init(config); filter.doFilter(req, resp, next); verify(resp).sendError(404, "/baz"); }
@Before public void setUp() { config = mock(FilterConfig.class); when(config.getInitParameter(anyString())).thenReturn(null); session = mock(HttpSession.class); when(session.getAttribute(anyString())).thenReturn(null); req = mock(HttpServletRequest.class); when(req.getSession()).thenReturn(session); when(req.getContextPath()).thenReturn(""); resp = mock(HttpServletResponse.class); next = mock(FilterChain.class); filter = new ControlFilter(); }
ServletException { if (skipFilter((HttpServletRequest) request)) { chain.doFilter(request, response); } else { HttpServletResponse httpResponse = (HttpServletResponse) response; String servletPath = httpRequest.getServletPath(); servletPath = servletPath.replaceFirst("/initfilter", "/WEB-INF/view"); // strip out the /initfilter part File file = new File(filterConfig.getServletContext().getRealPath(servletPath)); if (httpRequest.getPathInfo() != null) { file = new File(file, httpRequest.getPathInfo()); try { imageFileInputStream = new FileInputStream(file); OpenmrsUtil.copyFile(imageFileInputStream, httpResponse.getOutputStream()); && !httpRequest.getServletPath().equals("/" + AUTO_RUN_OPENMRS)) { httpResponse.sendRedirect("/" + WebConstants.WEBAPP_NAME + "/" + WebConstants.SETUP_PAGE_URL); } else {