UserNameOverrideFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { final HttpServletRequest httpServletRequest = (HttpServletRequest) request; Matcher userNameMatcher = getUserNameMatcher(httpServletRequest.getRequestURI()); if (userNameMatcher.find()) { String userNameFromUri = URLDecoder.decode(userNameMatcher.group("username"), "UTF-8"); final String userName = AuthorizationHelper.resolveLoginAliasToUserName(userNameFromUri); if (!userNameFromUri.equals(userName)) { final String requestUriOverride = String.format("%s%s%s", userNameMatcher.group("pre"), userName, userNameMatcher.group("post")); request = new HttpServletRequestWrapper(httpServletRequest) { @Override public String getRequestURI() { return requestUriOverride; } }; } } } chain.doFilter(request, response); }  @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); @Override void destroy();  }
@Test public void testDoFilterNoUserNameInUri() throws Exception { expect(userRelatedRequest.getRequestURI()).andReturn("/test/test1").anyTimes(); filterChain.doFilter(same(userRelatedRequest), same(response)); expectLastCall(); replayAll(); filter.doFilter(userRelatedRequest, response, filterChain); verifyAll(); }
@Test public void testDoFilterWithUserNameInUri() throws Exception { expect(userRelatedRequest.getRequestURI()).andReturn("/test/users/testUserName/test1").anyTimes(); filterChain.doFilter(same(userRelatedRequest), same(response)); expectLastCall(); replayAll(); filter.doFilter(userRelatedRequest, response, filterChain); verifyAll(); }
@Test public void testDoFilterWithLoginAliasInUri() throws Exception { expect(userRelatedRequest.getRequestURI()).andReturn(String.format("/test/users/%s/test1", URLEncoder.encode("testLoginAlias@testdomain.com", "UTF-8"))).anyTimes(); Capture<ServletRequest> requestCapture = Capture.newInstance(); filterChain.doFilter(capture(requestCapture), same(response)); expectLastCall(); PowerMock.mockStatic(AuthorizationHelper.class); expect(AuthorizationHelper.resolveLoginAliasToUserName(eq("testLoginAlias@testdomain.com"))).andReturn("testuser1"); PowerMock.replay(AuthorizationHelper.class); replayAll(); filter.doFilter(userRelatedRequest, response, filterChain); HttpServletRequest updatedRequest = (HttpServletRequest)requestCapture.getValue(); assertEquals("testLoginAlias@testdomain.com login alias in the request Uri should be resolved to testuser1 user name !", "/test/users/testuser1/test1", updatedRequest.getRequestURI()); PowerMock.verify(AuthorizationHelper.class); verifyAll(); }