Anonymous type can be replaced with lambda

This commit is contained in:
Lars Grefer
2019-08-06 23:40:48 +02:00
committed by Josh Cummings
parent 05f42a4995
commit fb39d9c255
53 changed files with 347 additions and 722 deletions

View File

@@ -21,7 +21,6 @@ import static org.mockito.Mockito.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
@@ -55,15 +54,13 @@ public class FilterChainProxyTests {
public void setup() throws Exception {
matcher = mock(RequestMatcher.class);
filter = mock(Filter.class);
doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock inv) throws Throwable {
Object[] args = inv.getArguments();
FilterChain fc = (FilterChain) args[2];
HttpServletRequestWrapper extraWrapper = new HttpServletRequestWrapper(
(HttpServletRequest) args[0]);
fc.doFilter(extraWrapper, (HttpServletResponse) args[1]);
return null;
}
doAnswer((Answer<Object>) inv -> {
Object[] args = inv.getArguments();
FilterChain fc = (FilterChain) args[2];
HttpServletRequestWrapper extraWrapper = new HttpServletRequestWrapper(
(HttpServletRequest) args[0]);
fc.doFilter(extraWrapper, (HttpServletResponse) args[1]);
return null;
}).when(filter).doFilter(any(),
any(), any());
fcp = new FilterChainProxy(new DefaultSecurityFilterChain(matcher,
@@ -187,12 +184,10 @@ public class FilterChainProxyTests {
@Test
public void doFilterClearsSecurityContextHolder() throws Exception {
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock inv) throws Throwable {
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken("username", "password"));
return null;
}
doAnswer((Answer<Object>) inv -> {
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken("username", "password"));
return null;
}).when(filter).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(FilterChain.class));
@@ -204,12 +199,10 @@ public class FilterChainProxyTests {
@Test
public void doFilterClearsSecurityContextHolderWithException() throws Exception {
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock inv) throws Throwable {
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken("username", "password"));
throw new ServletException("oops");
}
doAnswer((Answer<Object>) inv -> {
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken("username", "password"));
throw new ServletException("oops");
}).when(filter).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(FilterChain.class));
@@ -228,23 +221,19 @@ public class FilterChainProxyTests {
public void doFilterClearsSecurityContextHolderOnceOnForwards() throws Exception {
final FilterChain innerChain = mock(FilterChain.class);
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock inv) throws Throwable {
TestingAuthenticationToken expected = new TestingAuthenticationToken(
"username", "password");
SecurityContextHolder.getContext().setAuthentication(expected);
doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock inv) throws Throwable {
innerChain.doFilter(request, response);
return null;
}
}).when(filter).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(FilterChain.class));
fcp.doFilter(request, response, innerChain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(expected);
doAnswer((Answer<Object>) inv -> {
TestingAuthenticationToken expected = new TestingAuthenticationToken(
"username", "password");
SecurityContextHolder.getContext().setAuthentication(expected);
doAnswer((Answer<Object>) inv1 -> {
innerChain.doFilter(request, response);
return null;
}
}).when(filter).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(FilterChain.class));
fcp.doFilter(request, response, innerChain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(expected);
return null;
}).when(filter).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(FilterChain.class));

View File

@@ -44,7 +44,6 @@ import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.RememberMeAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
@@ -324,11 +323,5 @@ public class ExceptionTranslationFilterTests {
verifyZeroInteractions(mockEntryPoint);
}
private AuthenticationEntryPoint mockEntryPoint = new AuthenticationEntryPoint() {
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException,
ServletException {
response.sendRedirect(request.getContextPath() + "/login.jsp");
}
};
private AuthenticationEntryPoint mockEntryPoint = (request, response, authException) -> response.sendRedirect(request.getContextPath() + "/login.jsp");
}

View File

@@ -22,7 +22,6 @@ import static org.assertj.core.api.Assertions.*;
import javax.servlet.ServletException;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
@@ -161,12 +160,7 @@ public class UsernamePasswordAuthenticationFilterTests {
private AuthenticationManager createAuthenticationManager() {
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenAnswer(
new Answer<Authentication>() {
public Authentication answer(InvocationOnMock invocation)
throws Throwable {
return (Authentication) invocation.getArguments()[0];
}
});
(Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
return am;
}

View File

@@ -30,7 +30,6 @@ import javax.servlet.http.HttpServletRequest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
@@ -396,12 +395,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
}
else {
when(am.authenticate(any(Authentication.class))).thenAnswer(
new Answer<Authentication>() {
public Authentication answer(InvocationOnMock invocation)
throws Throwable {
return (Authentication) invocation.getArguments()[0];
}
});
(Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
}
filter.setAuthenticationManager(am);

View File

@@ -126,17 +126,13 @@ public class PreAuthenticatedAuthenticationProviderTests {
private AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> getPreAuthenticatedUserDetailsService(
final UserDetails aUserDetails) {
return new AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken>() {
public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token)
throws UsernameNotFoundException {
if (aUserDetails != null
&& aUserDetails.getUsername().equals(token.getName())) {
return aUserDetails;
}
throw new UsernameNotFoundException("notfound");
return token -> {
if (aUserDetails != null
&& aUserDetails.getUsername().equals(token.getName())) {
return aUserDetails;
}
throw new UsernameNotFoundException("notfound");
};
}

View File

@@ -67,11 +67,7 @@ public class PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests {
PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
userName, "dummy");
token.setDetails(new GrantedAuthoritiesContainer() {
public Collection<? extends GrantedAuthority> getGrantedAuthorities() {
return gas;
}
});
token.setDetails((GrantedAuthoritiesContainer) () -> gas);
UserDetails ud = svc.loadUserDetails(token);
assertThat(ud.isAccountNonExpired()).isTrue();
assertThat(ud.isAccountNonLocked()).isTrue();

View File

@@ -21,7 +21,6 @@ import static org.mockito.Mockito.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
@@ -29,8 +28,6 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedCredentialsNotFoundException;
import org.springframework.security.web.authentication.preauth.RequestAttributeAuthenticationFilter;
/**
*
@@ -159,12 +156,7 @@ public class RequestAttributeAuthenticationFilterTests {
private AuthenticationManager createAuthenticationManager() {
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class)))
.thenAnswer(new Answer<Authentication>() {
public Authentication answer(InvocationOnMock invocation)
throws Throwable {
return (Authentication) invocation.getArguments()[0];
}
});
.thenAnswer((Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
return am;
}

View File

@@ -21,7 +21,6 @@ import static org.mockito.Mockito.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
@@ -152,12 +151,7 @@ public class RequestHeaderAuthenticationFilterTests {
private AuthenticationManager createAuthenticationManager() {
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenAnswer(
new Answer<Authentication>() {
public Authentication answer(InvocationOnMock invocation)
throws Throwable {
return (Authentication) invocation.getArguments()[0];
}
});
(Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
return am;
}

View File

@@ -17,7 +17,6 @@ package org.springframework.security.web.authentication.preauth.j2ee;
import static org.assertj.core.api.Assertions.assertThat;
import java.security.Principal;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
@@ -60,12 +59,7 @@ public class J2eePreAuthenticatedProcessingFilterTests {
}
};
req.setRemoteUser(aUserName);
req.setUserPrincipal(new Principal() {
public String getName() {
return aUserName;
}
});
req.setUserPrincipal(() -> aUserName);
return req;
}

View File

@@ -21,7 +21,6 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.*;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
@@ -56,12 +55,7 @@ public class WebSpherePreAuthenticatedProcessingFilterTests {
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenAnswer(
new Answer<Authentication>() {
public Authentication answer(InvocationOnMock invocation)
throws Throwable {
return (Authentication) invocation.getArguments()[0];
}
});
(Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
filter.setAuthenticationManager(am);
WebSpherePreAuthenticatedWebAuthenticationDetailsSource ads = new WebSpherePreAuthenticatedWebAuthenticationDetailsSource(

View File

@@ -439,14 +439,10 @@ public class SwitchUserFilterTests {
SwitchUserFilter filter = new SwitchUserFilter();
filter.setUserDetailsService(new MockUserDetailsService());
filter.setSwitchUserAuthorityChanger(new SwitchUserAuthorityChanger() {
public Collection<GrantedAuthority> modifyGrantedAuthorities(
UserDetails targetUser, Authentication currentAuthentication,
Collection<? extends GrantedAuthority> authoritiesToBeGranted) {
List<GrantedAuthority> auths = new ArrayList<>();
auths.add(new SimpleGrantedAuthority("ROLE_NEW"));
return auths;
}
filter.setSwitchUserAuthorityChanger((targetUser, currentAuthentication, authoritiesToBeGranted) -> {
List<GrantedAuthority> auths = new ArrayList<>();
auths.add(new SimpleGrantedAuthority("ROLE_NEW"));
return auths;
});
Authentication result = filter.attemptSwitchUser(request);

View File

@@ -38,7 +38,6 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.userdetails.cache.NullUserCache;
import org.springframework.util.StringUtils;
@@ -131,14 +130,8 @@ public class DigestAuthenticationFilterTests {
SecurityContextHolder.clearContext();
// Create User Details Service
UserDetailsService uds = new UserDetailsService() {
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
return new User("rod,ok", "koala",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
}
};
UserDetailsService uds = username -> new User("rod,ok", "koala",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
ep.setRealmName(REALM);

View File

@@ -20,7 +20,6 @@ import static org.mockito.Mockito.*;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
@@ -91,13 +90,10 @@ public class SecurityContextPersistenceFilterTests {
when(repo.loadContext(any(HttpRequestResponseHolder.class))).thenReturn(scBefore);
final FilterChain chain = new FilterChain() {
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
assertThat(SecurityContextHolder.getContext().getAuthentication()).isEqualTo(beforeAuth);
// Change the context here
SecurityContextHolder.setContext(scExpectedAfter);
}
final FilterChain chain = (request1, response1) -> {
assertThat(SecurityContextHolder.getContext().getAuthentication()).isEqualTo(beforeAuth);
// Change the context here
SecurityContextHolder.setContext(scExpectedAfter);
};
filter.doFilter(request, response, chain);

View File

@@ -15,16 +15,11 @@
*/
package org.springframework.security.web.header;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -100,17 +95,13 @@ public class HeaderWriterFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, new FilterChain() {
@Override
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
verifyZeroInteractions(HeaderWriterFilterTests.this.writer1);
filter.doFilter(request, response, (request1, response1) -> {
verifyZeroInteractions(HeaderWriterFilterTests.this.writer1);
response.flushBuffer();
response1.flushBuffer();
verify(HeaderWriterFilterTests.this.writer1).writeHeaders(
any(HttpServletRequest.class), any(HttpServletResponse.class));
}
verify(HeaderWriterFilterTests.this.writer1).writeHeaders(
any(HttpServletRequest.class), any(HttpServletResponse.class));
});
verifyNoMoreInteractions(this.writer1);
@@ -146,14 +137,8 @@ public class HeaderWriterFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, new FilterChain() {
@Override
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
verify(HeaderWriterFilterTests.this.writer1).writeHeaders(
any(HttpServletRequest.class), any(HttpServletResponse.class));
}
});
filter.doFilter(request, response, (request1, response1) -> verify(HeaderWriterFilterTests.this.writer1).writeHeaders(
any(HttpServletRequest.class), any(HttpServletResponse.class)));
verifyNoMoreInteractions(this.writer1);
}

View File

@@ -20,7 +20,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.security.AccessController;
import java.security.Principal;
import java.util.HashMap;
import javax.security.auth.Subject;
@@ -84,33 +83,24 @@ public class JaasApiIntegrationFilterTests {
this.response = new MockHttpServletResponse();
authenticatedSubject = new Subject();
authenticatedSubject.getPrincipals().add(new Principal() {
public String getName() {
return "principal";
}
});
authenticatedSubject.getPrincipals().add(() -> "principal");
authenticatedSubject.getPrivateCredentials().add("password");
authenticatedSubject.getPublicCredentials().add("username");
callbackHandler = new CallbackHandler() {
public void handle(Callback[] callbacks)
throws IOException, UnsupportedCallbackException {
for (Callback callback : callbacks) {
if (callback instanceof NameCallback) {
((NameCallback) callback).setName("user");
}
else if (callback instanceof PasswordCallback) {
((PasswordCallback) callback).setPassword(
"password".toCharArray());
}
else if (callback instanceof TextInputCallback) {
// ignore
}
else {
throw new UnsupportedCallbackException(callback,
"Unrecognized Callback " + callback);
}
callbackHandler = callbacks -> {
for (Callback callback : callbacks) {
if (callback instanceof NameCallback) {
((NameCallback) callback).setName("user");
}
else if (callback instanceof PasswordCallback) {
((PasswordCallback) callback).setPassword(
"password".toCharArray());
}
else if (callback instanceof TextInputCallback) {
// ignore
}
else {
throw new UnsupportedCallbackException(callback,
"Unrecognized Callback " + callback);
}
}
};

View File

@@ -30,7 +30,6 @@ import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.web.PortResolverImpl;
import org.springframework.security.web.util.matcher.RequestMatcher;
/**
*
@@ -62,12 +61,7 @@ public class HttpSessionRequestCacheTests {
@Test
public void requestMatcherDefinesCorrectSubsetOfCachedRequests() throws Exception {
HttpSessionRequestCache cache = new HttpSessionRequestCache();
cache.setRequestMatcher(new RequestMatcher() {
public boolean matches(HttpServletRequest request) {
return request.getMethod().equals("GET");
}
});
cache.setRequestMatcher(request -> request.getMethod().equals("GET"));
MockHttpServletRequest request = new MockHttpServletRequest("POST",
"/destination");

View File

@@ -317,11 +317,7 @@ public class SecurityContextHolderAwareRequestFilterTests {
SecurityContextHolder.setContext(context);
AsyncContext asyncContext = mock(AsyncContext.class);
when(this.request.getAsyncContext()).thenReturn(asyncContext);
Runnable runnable = new Runnable() {
@Override
public void run() {
}
Runnable runnable = () -> {
};
wrappedRequest().getAsyncContext().start(runnable);
@@ -346,11 +342,7 @@ public class SecurityContextHolderAwareRequestFilterTests {
SecurityContextHolder.setContext(context);
AsyncContext asyncContext = mock(AsyncContext.class);
when(this.request.startAsync()).thenReturn(asyncContext);
Runnable runnable = new Runnable() {
@Override
public void run() {
}
Runnable runnable = () -> {
};
wrappedRequest().startAsync().start(runnable);
@@ -376,11 +368,7 @@ public class SecurityContextHolderAwareRequestFilterTests {
AsyncContext asyncContext = mock(AsyncContext.class);
when(this.request.startAsync(this.request, this.response))
.thenReturn(asyncContext);
Runnable runnable = new Runnable() {
@Override
public void run() {
}
Runnable runnable = () -> {
};
wrappedRequest().startAsync(this.request, this.response).start(runnable);