From fb39d9c255196031a9622cfd197d1fb05fd96bb2 Mon Sep 17 00:00:00 2001 From: Lars Grefer Date: Tue, 6 Aug 2019 23:40:48 +0200 Subject: [PATCH] Anonymous type can be replaced with lambda --- .../acls/jdbc/BasicLookupStrategy.java | 40 +++---- .../security/acls/jdbc/JdbcAclService.java | 16 +-- .../aspect/AnnotationSecurityAspect.aj | 6 +- .../cas/web/CasAuthenticationFilterTests.java | 12 +- .../annotation/web/builders/WebSecurity.java | 4 +- .../WebSecurityConfigurerAdapter.java | 10 +- .../AnnotationParameterNameDiscoverer.java | 14 +-- .../core/userdetails/jdbc/JdbcDaoImpl.java | 40 ++----- .../provisioning/JdbcUserDetailsManager.java | 112 +++++++----------- .../SecurityExpressionRootTests.java | 10 +- .../HierarchicalRolesTestHelper.java | 6 +- .../jaas/JaasAuthenticationProviderTests.java | 6 +- .../authentication/jaas/TestLoginModule.java | 14 +-- ...elegatingSecurityContextRunnableTests.java | 9 +- .../UserDetailsByNameServiceWrapperTests.java | 14 +-- .../ConcurrentSessionManagementTests.java | 26 ++-- .../SpringSecurityLdapTemplateITests.java | 7 +- .../ldap/SpringSecurityLdapTemplate.java | 62 +++++----- .../userdetails/LdapUserDetailsManager.java | 72 +++++------ .../SimpDestinationMessageMatcher.java | 10 +- .../openid/OpenID4JavaConsumerTests.java | 6 +- .../OpenIDAuthenticationFilterTests.java | 8 +- .../java/sample/contact/ContactDaoSpring.java | 41 ++----- .../sample/contact/DataSourcePopulator.java | 18 +-- .../main/java/sample/dms/DocumentDaoImpl.java | 72 +++++------ .../dms/secured/SecureDocumentDaoImpl.java | 10 +- .../servletapi/mvc/ServletApiController.java | 28 ++--- .../taglibs/authz/AbstractAuthorizeTag.java | 9 +- ...ckMvcRequestPostProcessorsDigestTests.java | 14 +-- .../security/web/FilterInvocation.java | 9 +- .../access/ExceptionTranslationFilter.java | 11 +- .../rememberme/JdbcTokenRepositoryImpl.java | 12 +- .../web/jaasapi/JaasApiIntegrationFilter.java | 10 +- .../matcher/ServerWebExchangeMatchers.java | 1 + .../web/session/ConcurrentSessionFilter.java | 15 +-- .../security/web/util/ThrowableAnalyzer.java | 37 ++---- .../security/web/FilterChainProxyTests.java | 65 +++++----- .../ExceptionTranslationFilterTests.java | 9 +- ...namePasswordAuthenticationFilterTests.java | 8 +- ...PreAuthenticatedProcessingFilterTests.java | 8 +- ...henticatedAuthenticationProviderTests.java | 16 +-- ...tedAuthoritiesUserDetailsServiceTests.java | 6 +- ...estAttributeAuthenticationFilterTests.java | 10 +- ...equestHeaderAuthenticationFilterTests.java | 8 +- ...PreAuthenticatedProcessingFilterTests.java | 8 +- ...PreAuthenticatedProcessingFilterTests.java | 8 +- .../switchuser/SwitchUserFilterTests.java | 12 +- .../www/DigestAuthenticationFilterTests.java | 11 +- ...SecurityContextPersistenceFilterTests.java | 12 +- .../web/header/HeaderWriterFilterTests.java | 29 ++--- .../JaasApiIntegrationFilterTests.java | 42 +++---- .../HttpSessionRequestCacheTests.java | 8 +- ...yContextHolderAwareRequestFilterTests.java | 18 +-- 53 files changed, 347 insertions(+), 722 deletions(-) diff --git a/acl/src/main/java/org/springframework/security/acls/jdbc/BasicLookupStrategy.java b/acl/src/main/java/org/springframework/security/acls/jdbc/BasicLookupStrategy.java index faee44d5f0..153ba2492e 100644 --- a/acl/src/main/java/org/springframework/security/acls/jdbc/BasicLookupStrategy.java +++ b/acl/src/main/java/org/springframework/security/acls/jdbc/BasicLookupStrategy.java @@ -17,7 +17,6 @@ package org.springframework.security.acls.jdbc; import java.io.Serializable; import java.lang.reflect.Field; -import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; @@ -33,7 +32,6 @@ import javax.sql.DataSource; import org.springframework.core.convert.ConversionException; import org.springframework.core.convert.ConversionService; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.security.acls.domain.AccessControlEntryImpl; import org.springframework.security.acls.domain.AclAuthorizationStrategy; @@ -248,14 +246,12 @@ public class BasicLookupStrategy implements LookupStrategy { String sql = computeRepeatingSql(lookupPrimaryKeysWhereClause, findNow.size()); Set parentsToLookup = jdbcTemplate.query(sql, - new PreparedStatementSetter() { - public void setValues(PreparedStatement ps) throws SQLException { - int i = 0; + ps -> { + int i = 0; - for (Long toFind : findNow) { - i++; - ps.setLong(i, toFind); - } + for (Long toFind : findNow) { + i++; + ps.setLong(i, toFind); } }, new ProcessResultSet(acls, sids)); @@ -383,22 +379,20 @@ public class BasicLookupStrategy implements LookupStrategy { objectIdentities.size()); Set parentsToLookup = jdbcTemplate.query(sql, - new PreparedStatementSetter() { - public void setValues(PreparedStatement ps) throws SQLException { - int i = 0; - for (ObjectIdentity oid : objectIdentities) { - // Determine prepared statement values for this iteration - String type = oid.getType(); + ps -> { + int i = 0; + for (ObjectIdentity oid : objectIdentities) { + // Determine prepared statement values for this iteration + String type = oid.getType(); - // No need to check for nulls, as guaranteed non-null by - // ObjectIdentity.getIdentifier() interface contract - String identifier = oid.getIdentifier().toString(); + // No need to check for nulls, as guaranteed non-null by + // ObjectIdentity.getIdentifier() interface contract + String identifier = oid.getIdentifier().toString(); - // Inject values - ps.setString((2 * i) + 1, identifier); - ps.setString((2 * i) + 2, type); - i++; - } + // Inject values + ps.setString((2 * i) + 1, identifier); + ps.setString((2 * i) + 2, type); + i++; } }, new ProcessResultSet(acls, sids)); diff --git a/acl/src/main/java/org/springframework/security/acls/jdbc/JdbcAclService.java b/acl/src/main/java/org/springframework/security/acls/jdbc/JdbcAclService.java index 380bb69306..d39be243ca 100644 --- a/acl/src/main/java/org/springframework/security/acls/jdbc/JdbcAclService.java +++ b/acl/src/main/java/org/springframework/security/acls/jdbc/JdbcAclService.java @@ -16,8 +16,6 @@ package org.springframework.security.acls.jdbc; import java.io.Serializable; -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.Arrays; import java.util.List; import java.util.Map; @@ -29,7 +27,6 @@ import org.apache.commons.logging.LogFactory; import org.springframework.core.convert.ConversionService; import org.springframework.jdbc.core.JdbcOperations; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.core.RowMapper; import org.springframework.security.acls.domain.ObjectIdentityImpl; import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.AclService; @@ -95,14 +92,11 @@ public class JdbcAclService implements AclService { public List findChildren(ObjectIdentity parentIdentity) { Object[] args = { parentIdentity.getIdentifier().toString(), parentIdentity.getType() }; List objects = jdbcOperations.query(findChildrenSql, args, - new RowMapper() { - public ObjectIdentity mapRow(ResultSet rs, int rowNum) - throws SQLException { - String javaType = rs.getString("class"); - Serializable identifier = (Serializable) rs.getObject("obj_id"); - identifier = aclClassIdUtils.identifierFrom(identifier, rs); - return new ObjectIdentityImpl(javaType, identifier); - } + (rs, rowNum) -> { + String javaType = rs.getString("class"); + Serializable identifier = (Serializable) rs.getObject("obj_id"); + identifier = aclClassIdUtils.identifierFrom(identifier, rs); + return new ObjectIdentityImpl(javaType, identifier); }); if (objects.size() == 0) { diff --git a/aspects/src/main/java/org/springframework/security/access/intercept/aspectj/aspect/AnnotationSecurityAspect.aj b/aspects/src/main/java/org/springframework/security/access/intercept/aspectj/aspect/AnnotationSecurityAspect.aj index bb3ffd1474..3459f96f55 100644 --- a/aspects/src/main/java/org/springframework/security/access/intercept/aspectj/aspect/AnnotationSecurityAspect.aj +++ b/aspects/src/main/java/org/springframework/security/access/intercept/aspectj/aspect/AnnotationSecurityAspect.aj @@ -72,11 +72,7 @@ public aspect AnnotationSecurityAspect implements InitializingBean { return proceed(); } - AspectJCallback callback = new AspectJCallback() { - public Object proceedWithObject() { - return proceed(); - } - }; + AspectJCallback callback = () -> proceed(); return this.securityInterceptor.invoke(thisJoinPoint, callback); } diff --git a/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationFilterTests.java b/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationFilterTests.java index f4ce95bac4..700e24240f 100644 --- a/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationFilterTests.java +++ b/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationFilterTests.java @@ -67,11 +67,7 @@ public class CasAuthenticationFilterTests { request.addParameter("ticket", "ST-0-ER94xMJmn6pha35CQRoZ"); CasAuthenticationFilter filter = new CasAuthenticationFilter(); - filter.setAuthenticationManager(new AuthenticationManager() { - public Authentication authenticate(Authentication a) { - return a; - } - }); + filter.setAuthenticationManager(a -> a); assertThat(filter.requiresAuthentication(request, new MockHttpServletResponse())).isTrue(); @@ -83,10 +79,8 @@ public class CasAuthenticationFilterTests { @Test(expected = AuthenticationException.class) public void testNullServiceTicketHandledGracefully() throws Exception { CasAuthenticationFilter filter = new CasAuthenticationFilter(); - filter.setAuthenticationManager(new AuthenticationManager() { - public Authentication authenticate(Authentication a) { - throw new BadCredentialsException("Rejected"); - } + filter.setAuthenticationManager(a -> { + throw new BadCredentialsException("Rejected"); }); filter.attemptAuthentication(new MockHttpServletRequest(), diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/builders/WebSecurity.java b/config/src/main/java/org/springframework/security/config/annotation/web/builders/WebSecurity.java index 391e9f2d24..a09ecc9c3d 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/builders/WebSecurity.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/builders/WebSecurity.java @@ -99,9 +99,7 @@ public final class WebSecurity extends private SecurityExpressionHandler expressionHandler = defaultWebSecurityExpressionHandler; - private Runnable postBuildAction = new Runnable() { - public void run() { - } + private Runnable postBuildAction = () -> { }; /** diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurerAdapter.java b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurerAdapter.java index dd014bbd03..ecabda57c8 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurerAdapter.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurerAdapter.java @@ -320,12 +320,10 @@ public abstract class WebSecurityConfigurerAdapter implements public void init(final WebSecurity web) throws Exception { final HttpSecurity http = getHttp(); - web.addSecurityFilterChainBuilder(http).postBuildAction(new Runnable() { - public void run() { - FilterSecurityInterceptor securityInterceptor = http - .getSharedObject(FilterSecurityInterceptor.class); - web.securityInterceptor(securityInterceptor); - } + web.addSecurityFilterChainBuilder(http).postBuildAction(() -> { + FilterSecurityInterceptor securityInterceptor = http + .getSharedObject(FilterSecurityInterceptor.class); + web.securityInterceptor(securityInterceptor); }); } diff --git a/core/src/main/java/org/springframework/security/core/parameters/AnnotationParameterNameDiscoverer.java b/core/src/main/java/org/springframework/security/core/parameters/AnnotationParameterNameDiscoverer.java index c7b388698f..daac6e6d95 100644 --- a/core/src/main/java/org/springframework/security/core/parameters/AnnotationParameterNameDiscoverer.java +++ b/core/src/main/java/org/springframework/security/core/parameters/AnnotationParameterNameDiscoverer.java @@ -178,19 +178,9 @@ public class AnnotationParameterNameDiscoverer implements ParameterNameDiscovere return null; } - private static final ParameterNameFactory> CONSTRUCTOR_METHODPARAM_FACTORY = new ParameterNameFactory>() { + private static final ParameterNameFactory> CONSTRUCTOR_METHODPARAM_FACTORY = constructor -> constructor.getParameterAnnotations(); - public Annotation[][] findParameterAnnotations(Constructor constructor) { - return constructor.getParameterAnnotations(); - } - }; - - private static final ParameterNameFactory METHOD_METHODPARAM_FACTORY = new ParameterNameFactory() { - - public Annotation[][] findParameterAnnotations(Method method) { - return method.getParameterAnnotations(); - } - }; + private static final ParameterNameFactory METHOD_METHODPARAM_FACTORY = method -> method.getParameterAnnotations(); /** * Strategy interface for looking up the parameter names. diff --git a/core/src/main/java/org/springframework/security/core/userdetails/jdbc/JdbcDaoImpl.java b/core/src/main/java/org/springframework/security/core/userdetails/jdbc/JdbcDaoImpl.java index 160f60ba30..ab271a6799 100644 --- a/core/src/main/java/org/springframework/security/core/userdetails/jdbc/JdbcDaoImpl.java +++ b/core/src/main/java/org/springframework/security/core/userdetails/jdbc/JdbcDaoImpl.java @@ -16,8 +16,6 @@ package org.springframework.security.core.userdetails.jdbc; -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -27,7 +25,6 @@ import org.springframework.context.ApplicationContextException; import org.springframework.context.MessageSource; import org.springframework.context.MessageSourceAware; import org.springframework.context.support.MessageSourceAccessor; -import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.SpringSecurityMessageSource; @@ -225,17 +222,12 @@ public class JdbcDaoImpl extends JdbcDaoSupport */ protected List loadUsersByUsername(String username) { return getJdbcTemplate().query(this.usersByUsernameQuery, - new String[] { username }, new RowMapper() { - @Override - public UserDetails mapRow(ResultSet rs, int rowNum) - throws SQLException { - String username = rs.getString(1); - String password = rs.getString(2); - boolean enabled = rs.getBoolean(3); - return new User(username, password, enabled, true, true, true, - AuthorityUtils.NO_AUTHORITIES); - } - + new String[] { username }, (rs, rowNum) -> { + String username1 = rs.getString(1); + String password = rs.getString(2); + boolean enabled = rs.getBoolean(3); + return new User(username1, password, enabled, true, true, true, + AuthorityUtils.NO_AUTHORITIES); }); } @@ -246,14 +238,10 @@ public class JdbcDaoImpl extends JdbcDaoSupport */ protected List loadUserAuthorities(String username) { return getJdbcTemplate().query(this.authoritiesByUsernameQuery, - new String[] { username }, new RowMapper() { - @Override - public GrantedAuthority mapRow(ResultSet rs, int rowNum) - throws SQLException { - String roleName = JdbcDaoImpl.this.rolePrefix + rs.getString(2); + new String[] { username }, (rs, rowNum) -> { + String roleName = JdbcDaoImpl.this.rolePrefix + rs.getString(2); - return new SimpleGrantedAuthority(roleName); - } + return new SimpleGrantedAuthority(roleName); }); } @@ -265,14 +253,10 @@ public class JdbcDaoImpl extends JdbcDaoSupport */ protected List loadGroupAuthorities(String username) { return getJdbcTemplate().query(this.groupAuthoritiesByUsernameQuery, - new String[] { username }, new RowMapper() { - @Override - public GrantedAuthority mapRow(ResultSet rs, int rowNum) - throws SQLException { - String roleName = getRolePrefix() + rs.getString(3); + new String[] { username }, (rs, rowNum) -> { + String roleName = getRolePrefix() + rs.getString(3); - return new SimpleGrantedAuthority(roleName); - } + return new SimpleGrantedAuthority(roleName); }); } diff --git a/core/src/main/java/org/springframework/security/provisioning/JdbcUserDetailsManager.java b/core/src/main/java/org/springframework/security/provisioning/JdbcUserDetailsManager.java index ca1652324d..5d298568c0 100644 --- a/core/src/main/java/org/springframework/security/provisioning/JdbcUserDetailsManager.java +++ b/core/src/main/java/org/springframework/security/provisioning/JdbcUserDetailsManager.java @@ -32,16 +32,12 @@ import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl; import org.springframework.context.ApplicationContextException; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.PreparedStatementSetter; -import org.springframework.jdbc.core.RowMapper; import org.springframework.util.Assert; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.sql.DataSource; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.Collection; import java.util.List; @@ -176,20 +172,17 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa public void createUser(final UserDetails user) { validateUserDetails(user); - getJdbcTemplate().update(createUserSql, new PreparedStatementSetter() { - @Override - public void setValues(PreparedStatement ps) throws SQLException { - ps.setString(1, user.getUsername()); - ps.setString(2, user.getPassword()); - ps.setBoolean(3, user.isEnabled()); + getJdbcTemplate().update(createUserSql, ps -> { + ps.setString(1, user.getUsername()); + ps.setString(2, user.getPassword()); + ps.setBoolean(3, user.isEnabled()); - int paramCount = ps.getParameterMetaData().getParameterCount(); - if (paramCount > 3) { - //NOTE: acc_locked, acc_expired and creds_expired are also to be inserted - ps.setBoolean(4, !user.isAccountNonLocked()); - ps.setBoolean(5, !user.isAccountNonExpired()); - ps.setBoolean(6, !user.isCredentialsNonExpired()); - } + int paramCount = ps.getParameterMetaData().getParameterCount(); + if (paramCount > 3) { + //NOTE: acc_locked, acc_expired and creds_expired are also to be inserted + ps.setBoolean(4, !user.isAccountNonLocked()); + ps.setBoolean(5, !user.isAccountNonExpired()); + ps.setBoolean(6, !user.isCredentialsNonExpired()); } }); @@ -201,25 +194,22 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa public void updateUser(final UserDetails user) { validateUserDetails(user); - getJdbcTemplate().update(updateUserSql, new PreparedStatementSetter() { - @Override - public void setValues(PreparedStatement ps) throws SQLException { - ps.setString(1, user.getPassword()); - ps.setBoolean(2, user.isEnabled()); + getJdbcTemplate().update(updateUserSql, ps -> { + ps.setString(1, user.getPassword()); + ps.setBoolean(2, user.isEnabled()); - int paramCount = ps.getParameterMetaData().getParameterCount(); - if (paramCount == 3) { - ps.setString(3, user.getUsername()); - } else { - //NOTE: acc_locked, acc_expired and creds_expired are also updated - ps.setBoolean(3, !user.isAccountNonLocked()); - ps.setBoolean(4, !user.isAccountNonExpired()); - ps.setBoolean(5, !user.isCredentialsNonExpired()); - - ps.setString(6, user.getUsername()); - } + int paramCount = ps.getParameterMetaData().getParameterCount(); + if (paramCount == 3) { + ps.setString(3, user.getUsername()); + } else { + //NOTE: acc_locked, acc_expired and creds_expired are also updated + ps.setBoolean(3, !user.isAccountNonLocked()); + ps.setBoolean(4, !user.isAccountNonExpired()); + ps.setBoolean(5, !user.isCredentialsNonExpired()); + ps.setString(6, user.getUsername()); } + }); if (getEnableAuthorities()) { @@ -337,11 +327,9 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa for (GrantedAuthority a : authorities) { final String authority = a.getAuthority(); getJdbcTemplate().update(insertGroupAuthoritySql, - new PreparedStatementSetter() { - public void setValues(PreparedStatement ps) throws SQLException { - ps.setInt(1, groupId); - ps.setString(2, authority); - } + ps -> { + ps.setInt(1, groupId); + ps.setString(2, authority); }); } } @@ -351,11 +339,7 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa Assert.hasText(groupName, "groupName should have text"); final int id = findGroupId(groupName); - PreparedStatementSetter groupIdPSS = new PreparedStatementSetter() { - public void setValues(PreparedStatement ps) throws SQLException { - ps.setInt(1, id); - } - }; + PreparedStatementSetter groupIdPSS = ps -> ps.setInt(1, id); getJdbcTemplate().update(deleteGroupMembersSql, groupIdPSS); getJdbcTemplate().update(deleteGroupAuthoritiesSql, groupIdPSS); getJdbcTemplate().update(deleteGroupSql, groupIdPSS); @@ -375,11 +359,9 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa Assert.hasText(groupName, "groupName should have text"); final int id = findGroupId(groupName); - getJdbcTemplate().update(insertGroupMemberSql, new PreparedStatementSetter() { - public void setValues(PreparedStatement ps) throws SQLException { - ps.setInt(1, id); - ps.setString(2, username); - } + getJdbcTemplate().update(insertGroupMemberSql, ps -> { + ps.setInt(1, id); + ps.setString(2, username); }); userCache.removeUserFromCache(username); @@ -392,11 +374,9 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa final int id = findGroupId(groupName); - getJdbcTemplate().update(deleteGroupMemberSql, new PreparedStatementSetter() { - public void setValues(PreparedStatement ps) throws SQLException { - ps.setInt(1, id); - ps.setString(2, username); - } + getJdbcTemplate().update(deleteGroupMemberSql, ps -> { + ps.setInt(1, id); + ps.setString(2, username); }); userCache.removeUserFromCache(username); @@ -407,13 +387,10 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa Assert.hasText(groupName, "groupName should have text"); return getJdbcTemplate().query(groupAuthoritiesSql, new String[] { groupName }, - new RowMapper() { - public GrantedAuthority mapRow(ResultSet rs, int rowNum) - throws SQLException { - String roleName = getRolePrefix() + rs.getString(3); + (rs, rowNum) -> { + String roleName = getRolePrefix() + rs.getString(3); - return new SimpleGrantedAuthority(roleName); - } + return new SimpleGrantedAuthority(roleName); }); } @@ -425,12 +402,9 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa final int id = findGroupId(groupName); - getJdbcTemplate().update(deleteGroupAuthoritySql, new PreparedStatementSetter() { - - public void setValues(PreparedStatement ps) throws SQLException { - ps.setInt(1, id); - ps.setString(2, authority.getAuthority()); - } + getJdbcTemplate().update(deleteGroupAuthoritySql, ps -> { + ps.setInt(1, id); + ps.setString(2, authority.getAuthority()); }); } @@ -440,11 +414,9 @@ public class JdbcUserDetailsManager extends JdbcDaoImpl implements UserDetailsMa Assert.notNull(authority, "authority cannot be null"); final int id = findGroupId(groupName); - getJdbcTemplate().update(insertGroupAuthoritySql, new PreparedStatementSetter() { - public void setValues(PreparedStatement ps) throws SQLException { - ps.setInt(1, id); - ps.setString(2, authority.getAuthority()); - } + getJdbcTemplate().update(insertGroupAuthoritySql, ps -> { + ps.setInt(1, id); + ps.setString(2, authority.getAuthority()); }); } diff --git a/core/src/test/java/org/springframework/security/access/expression/SecurityExpressionRootTests.java b/core/src/test/java/org/springframework/security/access/expression/SecurityExpressionRootTests.java index 9825131b48..32d3de6089 100644 --- a/core/src/test/java/org/springframework/security/access/expression/SecurityExpressionRootTests.java +++ b/core/src/test/java/org/springframework/security/access/expression/SecurityExpressionRootTests.java @@ -19,15 +19,12 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.assertj.core.api.Assertions.*; -import java.util.Collection; import org.junit.Before; import org.junit.Test; -import org.springframework.security.access.hierarchicalroles.RoleHierarchy; import org.springframework.security.authentication.AuthenticationTrustResolver; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; -import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; /** @@ -66,12 +63,7 @@ public class SecurityExpressionRootTests { @Test public void roleHierarchySupportIsCorrectlyUsedInEvaluatingRoles() throws Exception { - root.setRoleHierarchy(new RoleHierarchy() { - public Collection getReachableGrantedAuthorities( - Collection authorities) { - return AuthorityUtils.createAuthorityList("ROLE_C"); - } - }); + root.setRoleHierarchy(authorities -> AuthorityUtils.createAuthorityList("ROLE_C")); assertThat(root.hasRole("C")).isTrue(); assertThat(root.hasAuthority("ROLE_C")).isTrue(); diff --git a/core/src/test/java/org/springframework/security/access/hierarchicalroles/HierarchicalRolesTestHelper.java b/core/src/test/java/org/springframework/security/access/hierarchicalroles/HierarchicalRolesTestHelper.java index 0308d90b56..901abbdf9d 100755 --- a/core/src/test/java/org/springframework/security/access/hierarchicalroles/HierarchicalRolesTestHelper.java +++ b/core/src/test/java/org/springframework/security/access/hierarchicalroles/HierarchicalRolesTestHelper.java @@ -75,11 +75,7 @@ public abstract class HierarchicalRolesTestHelper { for (final String role : roles) { // Use non SimpleGrantedAuthority (SEC-863) - authorities.add(new GrantedAuthority() { - public String getAuthority() { - return role; - } - }); + authorities.add((GrantedAuthority) () -> role); } return authorities; diff --git a/core/src/test/java/org/springframework/security/authentication/jaas/JaasAuthenticationProviderTests.java b/core/src/test/java/org/springframework/security/authentication/jaas/JaasAuthenticationProviderTests.java index 4421175f54..eb44e0b057 100644 --- a/core/src/test/java/org/springframework/security/authentication/jaas/JaasAuthenticationProviderTests.java +++ b/core/src/test/java/org/springframework/security/authentication/jaas/JaasAuthenticationProviderTests.java @@ -234,11 +234,7 @@ public class JaasAuthenticationProviderTests { @Test public void testLoginExceptionResolver() { assertThat(jaasProvider.getLoginExceptionResolver()).isNotNull(); - jaasProvider.setLoginExceptionResolver(new LoginExceptionResolver() { - public AuthenticationException resolveException(LoginException e) { - return new LockedException("This is just a test!"); - } - }); + jaasProvider.setLoginExceptionResolver(e -> new LockedException("This is just a test!")); try { jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user", diff --git a/core/src/test/java/org/springframework/security/authentication/jaas/TestLoginModule.java b/core/src/test/java/org/springframework/security/authentication/jaas/TestLoginModule.java index 82490b20cf..e9d1cf5504 100644 --- a/core/src/test/java/org/springframework/security/authentication/jaas/TestLoginModule.java +++ b/core/src/test/java/org/springframework/security/authentication/jaas/TestLoginModule.java @@ -16,8 +16,6 @@ package org.springframework.security.authentication.jaas; -import java.security.Principal; - import java.util.Map; import javax.security.auth.Subject; @@ -77,17 +75,9 @@ public class TestLoginModule implements LoginModule { throw new LoginException("Bad Password"); } - subject.getPrincipals().add(new Principal() { - public String getName() { - return "TEST_PRINCIPAL"; - } - }); + subject.getPrincipals().add(() -> "TEST_PRINCIPAL"); - subject.getPrincipals().add(new Principal() { - public String getName() { - return "NULL_PRINCIPAL"; - } - }); + subject.getPrincipals().add(() -> "NULL_PRINCIPAL"); return true; } diff --git a/core/src/test/java/org/springframework/security/concurrent/DelegatingSecurityContextRunnableTests.java b/core/src/test/java/org/springframework/security/concurrent/DelegatingSecurityContextRunnableTests.java index 8ec29dead6..6858041035 100644 --- a/core/src/test/java/org/springframework/security/concurrent/DelegatingSecurityContextRunnableTests.java +++ b/core/src/test/java/org/springframework/security/concurrent/DelegatingSecurityContextRunnableTests.java @@ -28,7 +28,6 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.invocation.InvocationOnMock; import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import org.springframework.core.task.SyncTaskExecutor; @@ -59,11 +58,9 @@ public class DelegatingSecurityContextRunnableTests { @Before public void setUp() throws Exception { originalSecurityContext = SecurityContextHolder.createEmptyContext(); - doAnswer(new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - assertThat(SecurityContextHolder.getContext()).isEqualTo(securityContext); - return null; - } + doAnswer((Answer) invocation -> { + assertThat(SecurityContextHolder.getContext()).isEqualTo(securityContext); + return null; }).when(delegate).run(); executor = Executors.newFixedThreadPool(1); diff --git a/core/src/test/java/org/springframework/security/core/userdetails/UserDetailsByNameServiceWrapperTests.java b/core/src/test/java/org/springframework/security/core/userdetails/UserDetailsByNameServiceWrapperTests.java index 96d2c1fe44..6da8ad2af0 100644 --- a/core/src/test/java/org/springframework/security/core/userdetails/UserDetailsByNameServiceWrapperTests.java +++ b/core/src/test/java/org/springframework/security/core/userdetails/UserDetailsByNameServiceWrapperTests.java @@ -48,14 +48,12 @@ public class UserDetailsByNameServiceWrapperTests { UserDetailsByNameServiceWrapper svc = new UserDetailsByNameServiceWrapper(); final User user = new User("dummy", "dummy", true, true, true, true, AuthorityUtils.NO_AUTHORITIES); - svc.setUserDetailsService(new UserDetailsService() { - public UserDetails loadUserByUsername(String name) { - if (user != null && user.getUsername().equals(name)) { - return user; - } - else { - return null; - } + svc.setUserDetailsService(name -> { + if (user != null && user.getUsername().equals(name)) { + return user; + } + else { + return null; } }); svc.afterPropertiesSet(); diff --git a/itest/web/src/integration-test/java/org/springframework/security/integration/ConcurrentSessionManagementTests.java b/itest/web/src/integration-test/java/org/springframework/security/integration/ConcurrentSessionManagementTests.java index aa7f2093a6..335f957ef3 100644 --- a/itest/web/src/integration-test/java/org/springframework/security/integration/ConcurrentSessionManagementTests.java +++ b/itest/web/src/integration-test/java/org/springframework/security/integration/ConcurrentSessionManagementTests.java @@ -33,8 +33,6 @@ import org.springframework.mock.web.MockHttpSession; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.session.SessionDestroyedEvent; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.ResultHandler; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; /** @@ -70,23 +68,17 @@ public class ConcurrentSessionManagementTests extends AbstractWebServerIntegrati // Now logout to kill first session mockMvc.perform(post("/logout").with(csrf())) .andExpect(status().is3xxRedirection()) - .andDo(new ResultHandler() { - @SuppressWarnings("serial") + .andDo(result -> context.publishEvent(new SessionDestroyedEvent(session1) { @Override - public void handle(MvcResult result) throws Exception { - context.publishEvent(new SessionDestroyedEvent(session1) { - @Override - public List getSecurityContexts() { - return Collections.emptyList(); - } - - @Override - public String getId() { - return session1.getId(); - } - }); + public List getSecurityContexts() { + return Collections.emptyList(); } - }); + + @Override + public String getId() { + return session1.getId(); + } + })); // Try second session again login2 = login() diff --git a/ldap/src/integration-test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateITests.java b/ldap/src/integration-test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateITests.java index d52e0c3b72..e994a47f43 100644 --- a/ldap/src/integration-test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateITests.java +++ b/ldap/src/integration-test/java/org/springframework/security/ldap/SpringSecurityLdapTemplateITests.java @@ -85,11 +85,8 @@ public class SpringSecurityLdapTemplateITests extends AbstractLdapIntegrationTes @Test public void namingExceptionIsTranslatedCorrectly() { try { - template.executeReadOnly(new ContextExecutor() { - public Object executeWithContext(DirContext dirContext) - throws NamingException { - throw new NamingException(); - } + template.executeReadOnly((ContextExecutor) dirContext -> { + throw new NamingException(); }); fail("Expected UncategorizedLdapException on NamingException"); } diff --git a/ldap/src/main/java/org/springframework/security/ldap/SpringSecurityLdapTemplate.java b/ldap/src/main/java/org/springframework/security/ldap/SpringSecurityLdapTemplate.java index 230bfe9263..fe0d9c0002 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/SpringSecurityLdapTemplate.java +++ b/ldap/src/main/java/org/springframework/security/ldap/SpringSecurityLdapTemplate.java @@ -134,15 +134,13 @@ public class SpringSecurityLdapTemplate extends LdapTemplate { public DirContextOperations retrieveEntry(final String dn, final String[] attributesToRetrieve) { - return (DirContextOperations) executeReadOnly(new ContextExecutor() { - public Object executeWithContext(DirContext ctx) throws NamingException { - Attributes attrs = ctx.getAttributes(dn, attributesToRetrieve); + return (DirContextOperations) executeReadOnly((ContextExecutor) ctx -> { + Attributes attrs = ctx.getAttributes(dn, attributesToRetrieve); - // Object object = ctx.lookup(LdapUtils.getRelativeName(dn, ctx)); + // Object object = ctx.lookup(LdapUtils.getRelativeName(dn, ctx)); - return new DirContextAdapter(attrs, new DistinguishedName(dn), - new DistinguishedName(ctx.getNameInNamespace())); - } + return new DirContextAdapter(attrs, new DistinguishedName(dn), + new DistinguishedName(ctx.getNameInNamespace())); }); } @@ -205,32 +203,30 @@ public class SpringSecurityLdapTemplate extends LdapTemplate { final HashSet>> set = new HashSet<>(); - ContextMapper roleMapper = new ContextMapper() { - public Object mapFromContext(Object ctx) { - DirContextAdapter adapter = (DirContextAdapter) ctx; - Map> record = new HashMap<>(); - if (attributeNames == null || attributeNames.length == 0) { - try { - for (NamingEnumeration ae = adapter.getAttributes().getAll(); ae - .hasMore();) { - Attribute attr = (Attribute) ae.next(); - extractStringAttributeValues(adapter, record, attr.getID()); - } - } - catch (NamingException x) { - org.springframework.ldap.support.LdapUtils - .convertLdapException(x); + ContextMapper roleMapper = ctx -> { + DirContextAdapter adapter = (DirContextAdapter) ctx; + Map> record = new HashMap<>(); + if (attributeNames == null || attributeNames.length == 0) { + try { + for (NamingEnumeration ae = adapter.getAttributes().getAll(); ae + .hasMore();) { + Attribute attr = (Attribute) ae.next(); + extractStringAttributeValues(adapter, record, attr.getID()); } } - else { - for (String attributeName : attributeNames) { - extractStringAttributeValues(adapter, record, attributeName); - } + catch (NamingException x) { + org.springframework.ldap.support.LdapUtils + .convertLdapException(x); } - record.put(DN_KEY, Arrays.asList(getAdapterDN(adapter))); - set.add(record); - return null; } + else { + for (String attributeName : attributeNames) { + extractStringAttributeValues(adapter, record, attributeName); + } + } + record.put(DN_KEY, Arrays.asList(getAdapterDN(adapter))); + set.add(record); + return null; }; SearchControls ctls = new SearchControls(); @@ -313,12 +309,8 @@ public class SpringSecurityLdapTemplate extends LdapTemplate { public DirContextOperations searchForSingleEntry(final String base, final String filter, final Object[] params) { - return (DirContextOperations) executeReadOnly(new ContextExecutor() { - public Object executeWithContext(DirContext ctx) throws NamingException { - return searchForSingleEntryInternal(ctx, searchControls, base, filter, - params); - } - }); + return (DirContextOperations) executeReadOnly((ContextExecutor) ctx -> searchForSingleEntryInternal(ctx, searchControls, base, filter, + params)); } /** diff --git a/ldap/src/main/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManager.java b/ldap/src/main/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManager.java index 582d095d4b..626a06ac19 100644 --- a/ldap/src/main/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManager.java +++ b/ldap/src/main/java/org/springframework/security/ldap/userdetails/LdapUserDetailsManager.java @@ -25,14 +25,12 @@ import java.util.ListIterator; import javax.naming.Context; import javax.naming.NameNotFoundException; import javax.naming.NamingEnumeration; -import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.BasicAttribute; import javax.naming.directory.DirContext; import javax.naming.directory.ModificationItem; import javax.naming.directory.SearchControls; -import javax.naming.directory.SearchResult; import javax.naming.ldap.ExtendedRequest; import javax.naming.ldap.ExtendedResponse; import javax.naming.ldap.LdapContext; @@ -112,18 +110,15 @@ public class LdapUserDetailsManager implements UserDetailsManager { private final LdapTemplate template; /** Default context mapper used to create a set of roles from a list of attributes */ - private AttributesMapper roleMapper = new AttributesMapper() { + private AttributesMapper roleMapper = attributes -> { + Attribute roleAttr = attributes.get(groupRoleAttributeName); - public Object mapFromAttributes(Attributes attributes) throws NamingException { - Attribute roleAttr = attributes.get(groupRoleAttributeName); + NamingEnumeration ne = roleAttr.getAll(); + // assert ne.hasMore(); + Object group = ne.next(); + String role = group.toString(); - NamingEnumeration ne = roleAttr.getAll(); - // assert ne.hasMore(); - Object group = ne.next(); - String role = group.toString(); - - return new SimpleGrantedAuthority(rolePrefix + role.toUpperCase()); - } + return new SimpleGrantedAuthority(rolePrefix + role.toUpperCase()); }; private String[] attributesToRetrieve; @@ -147,16 +142,14 @@ public class LdapUserDetailsManager implements UserDetailsManager { private DirContextAdapter loadUserAsContext(final DistinguishedName dn, final String username) { - return (DirContextAdapter) template.executeReadOnly(new ContextExecutor() { - public Object executeWithContext(DirContext ctx) throws NamingException { - try { - Attributes attrs = ctx.getAttributes(dn, attributesToRetrieve); - return new DirContextAdapter(attrs, LdapUtils.getFullDn(dn, ctx)); - } - catch (NameNotFoundException notFound) { - throw new UsernameNotFoundException( - "User " + username + " not found", notFound); - } + return (DirContextAdapter) template.executeReadOnly((ContextExecutor) ctx -> { + try { + Attributes attrs = ctx.getAttributes(dn, attributesToRetrieve); + return new DirContextAdapter(attrs, LdapUtils.getFullDn(dn, ctx)); + } + catch (NameNotFoundException notFound) { + throw new UsernameNotFoundException( + "User " + username + " not found", notFound); } }); } @@ -217,16 +210,13 @@ public class LdapUserDetailsManager implements UserDetailsManager { @SuppressWarnings("unchecked") List getUserAuthorities(final DistinguishedName dn, final String username) { - SearchExecutor se = new SearchExecutor() { - public NamingEnumeration executeSearch(DirContext ctx) - throws NamingException { - DistinguishedName fullDn = LdapUtils.getFullDn(dn, ctx); - SearchControls ctrls = new SearchControls(); - ctrls.setReturningAttributes(new String[] { groupRoleAttributeName }); + SearchExecutor se = ctx -> { + DistinguishedName fullDn = LdapUtils.getFullDn(dn, ctx); + SearchControls ctrls = new SearchControls(); + ctrls.setReturningAttributes(new String[] { groupRoleAttributeName }); - return ctx.search(groupSearchBase, groupSearchFilter, new String[] { - fullDn.toUrl(), username }, ctrls); - } + return ctx.search(groupSearchBase, groupSearchFilter, new String[] { + fullDn.toUrl(), username }, ctrls); }; AttributesMapperCallbackHandler roleCollector = new AttributesMapperCallbackHandler( @@ -339,19 +329,17 @@ public class LdapUserDetailsManager implements UserDetailsManager { private void modifyAuthorities(final DistinguishedName userDn, final Collection authorities, final int modType) { - template.executeReadWrite(new ContextExecutor() { - public Object executeWithContext(DirContext ctx) throws NamingException { - for (GrantedAuthority authority : authorities) { - String group = convertAuthorityToGroup(authority); - DistinguishedName fullDn = LdapUtils.getFullDn(userDn, ctx); - ModificationItem addGroup = new ModificationItem(modType, - new BasicAttribute(groupMemberAttributeName, fullDn.toUrl())); + template.executeReadWrite((ContextExecutor) ctx -> { + for (GrantedAuthority authority : authorities) { + String group = convertAuthorityToGroup(authority); + DistinguishedName fullDn = LdapUtils.getFullDn(userDn, ctx); + ModificationItem addGroup = new ModificationItem(modType, + new BasicAttribute(groupMemberAttributeName, fullDn.toUrl())); - ctx.modifyAttributes(buildGroupDn(group), - new ModificationItem[] { addGroup }); - } - return null; + ctx.modifyAttributes(buildGroupDn(group), + new ModificationItem[] { addGroup }); } + return null; }); } diff --git a/messaging/src/main/java/org/springframework/security/messaging/util/matcher/SimpDestinationMessageMatcher.java b/messaging/src/main/java/org/springframework/security/messaging/util/matcher/SimpDestinationMessageMatcher.java index 7fdd21ae88..625902a404 100644 --- a/messaging/src/main/java/org/springframework/security/messaging/util/matcher/SimpDestinationMessageMatcher.java +++ b/messaging/src/main/java/org/springframework/security/messaging/util/matcher/SimpDestinationMessageMatcher.java @@ -36,12 +36,10 @@ import java.util.Map; * @author Rob Winch */ public final class SimpDestinationMessageMatcher implements MessageMatcher { - public static final MessageMatcher NULL_DESTINATION_MATCHER = new MessageMatcher() { - public boolean matches(Message message) { - String destination = SimpMessageHeaderAccessor.getDestination(message - .getHeaders()); - return destination == null; - } + public static final MessageMatcher NULL_DESTINATION_MATCHER = message -> { + String destination = SimpMessageHeaderAccessor.getDestination(message + .getHeaders()); + return destination == null; }; private final PathMatcher matcher; diff --git a/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java b/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java index ec45411e57..e87ce2fd2f 100644 --- a/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java +++ b/openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java @@ -176,11 +176,7 @@ public class OpenID4JavaConsumerTests { new NullAxFetchListFactory()); VerificationResult vr = mock(VerificationResult.class); DiscoveryInformation di = mock(DiscoveryInformation.class); - Identifier id = new Identifier() { - public String getIdentifier() { - return "id"; - } - }; + Identifier id = (Identifier) () -> "id"; Message msg = mock(Message.class); when( diff --git a/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationFilterTests.java b/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationFilterTests.java index 1622c3ff59..415beae628 100644 --- a/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationFilterTests.java +++ b/openid/src/test/java/org/springframework/security/openid/OpenIDAuthenticationFilterTests.java @@ -29,8 +29,6 @@ import org.junit.Before; import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; public class OpenIDAuthenticationFilterTests { @@ -50,11 +48,7 @@ public class OpenIDAuthenticationFilterTests { SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler(); filter.setAuthenticationSuccessHandler(new SavedRequestAwareAuthenticationSuccessHandler()); successHandler.setDefaultTargetUrl(DEFAULT_TARGET_URL); - filter.setAuthenticationManager(new AuthenticationManager() { - public Authentication authenticate(Authentication a) { - return a; - } - }); + filter.setAuthenticationManager(a -> a); filter.afterPropertiesSet(); } diff --git a/samples/xml/contacts/src/main/java/sample/contact/ContactDaoSpring.java b/samples/xml/contacts/src/main/java/sample/contact/ContactDaoSpring.java index 1fbf647eed..36619dd260 100644 --- a/samples/xml/contacts/src/main/java/sample/contact/ContactDaoSpring.java +++ b/samples/xml/contacts/src/main/java/sample/contact/ContactDaoSpring.java @@ -16,13 +16,10 @@ package sample.contact; -import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; -import org.springframework.jdbc.core.PreparedStatementSetter; -import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.support.JdbcDaoSupport; /** @@ -38,44 +35,32 @@ public class ContactDaoSpring extends JdbcDaoSupport implements ContactDao { public void create(final Contact contact) { getJdbcTemplate().update("insert into contacts values (?, ?, ?)", - new PreparedStatementSetter() { - public void setValues(PreparedStatement ps) throws SQLException { - ps.setLong(1, contact.getId()); - ps.setString(2, contact.getName()); - ps.setString(3, contact.getEmail()); - } + ps -> { + ps.setLong(1, contact.getId()); + ps.setString(2, contact.getName()); + ps.setString(3, contact.getEmail()); }); } public void delete(final Long contactId) { getJdbcTemplate().update("delete from contacts where id = ?", - new PreparedStatementSetter() { - public void setValues(PreparedStatement ps) throws SQLException { - ps.setLong(1, contactId); - } - }); + ps -> ps.setLong(1, contactId)); } public void update(final Contact contact) { getJdbcTemplate().update( "update contacts set contact_name = ?, address = ? where id = ?", - new PreparedStatementSetter() { - public void setValues(PreparedStatement ps) throws SQLException { - ps.setString(1, contact.getName()); - ps.setString(2, contact.getEmail()); - ps.setLong(3, contact.getId()); - } + ps -> { + ps.setString(1, contact.getName()); + ps.setString(2, contact.getEmail()); + ps.setLong(3, contact.getId()); }); } public List findAll() { return getJdbcTemplate().query( "select id, contact_name, email from contacts order by id", - new RowMapper() { - public Contact mapRow(ResultSet rs, int rowNum) throws SQLException { - return mapContact(rs); - } - }); + (rs, rowNum) -> mapContact(rs)); } public List findAllPrincipals() { @@ -92,11 +77,7 @@ public class ContactDaoSpring extends JdbcDaoSupport implements ContactDao { public Contact getById(Long id) { List list = getJdbcTemplate().query( "select id, contact_name, email from contacts where id = ? order by id", - new RowMapper() { - public Contact mapRow(ResultSet rs, int rowNum) throws SQLException { - return mapContact(rs); - } - }, id); + (rs, rowNum) -> mapContact(rs), id); if (list.size() == 0) { return null; diff --git a/samples/xml/contacts/src/main/java/sample/contact/DataSourcePopulator.java b/samples/xml/contacts/src/main/java/sample/contact/DataSourcePopulator.java index 8d856133fe..290b694d17 100644 --- a/samples/xml/contacts/src/main/java/sample/contact/DataSourcePopulator.java +++ b/samples/xml/contacts/src/main/java/sample/contact/DataSourcePopulator.java @@ -34,8 +34,6 @@ import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import org.springframework.util.Assert; @@ -166,12 +164,10 @@ public class DataSourcePopulator implements InitializingBean { for (int i = 1; i < createEntities; i++) { final ObjectIdentity objectIdentity = new ObjectIdentityImpl(Contact.class, (long) i); - tt.execute(new TransactionCallback() { - public Object doInTransaction(TransactionStatus arg0) { - mutableAclService.createAcl(objectIdentity); + tt.execute(arg0 -> { + mutableAclService.createAcl(objectIdentity); - return null; - } + return null; }); } @@ -273,12 +269,10 @@ public class DataSourcePopulator implements InitializingBean { } private void updateAclInTransaction(final MutableAcl acl) { - tt.execute(new TransactionCallback() { - public Object doInTransaction(TransactionStatus arg0) { - mutableAclService.updateAcl(acl); + tt.execute(arg0 -> { + mutableAclService.updateAcl(acl); - return null; - } + return null; }); } } diff --git a/samples/xml/dms/src/main/java/sample/dms/DocumentDaoImpl.java b/samples/xml/dms/src/main/java/sample/dms/DocumentDaoImpl.java index c3f7dd4b86..fc1c73afc0 100755 --- a/samples/xml/dms/src/main/java/sample/dms/DocumentDaoImpl.java +++ b/samples/xml/dms/src/main/java/sample/dms/DocumentDaoImpl.java @@ -15,11 +15,8 @@ */ package sample.dms; -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.List; -import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.security.util.FieldUtils; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -80,23 +77,20 @@ public class DocumentDaoImpl extends JdbcDaoSupport implements DocumentDao { /** Executes recursive SQL as needed to build a full Directory hierarchy of objects */ private Directory getDirectoryWithImmediateParentPopulated(final Long id) { return getJdbcTemplate().queryForObject(SELECT_FROM_DIRECTORY_SINGLE, - new Object[] { id }, new RowMapper() { - public Directory mapRow(ResultSet rs, int rowNumber) - throws SQLException { - Long parentDirectoryId = rs - .getLong("parent_directory_id"); - Directory parentDirectory = Directory.ROOT_DIRECTORY; - if (parentDirectoryId != null - && !parentDirectoryId.equals(-1L)) { - // Need to go and lookup the parent, so do that first - parentDirectory = getDirectoryWithImmediateParentPopulated(parentDirectoryId); - } - Directory directory = new Directory(rs - .getString("directory_name"), parentDirectory); - FieldUtils.setProtectedFieldValue("id", directory, - rs.getLong("id")); - return directory; + new Object[] { id }, (rs, rowNumber) -> { + Long parentDirectoryId = rs + .getLong("parent_directory_id"); + Directory parentDirectory = Directory.ROOT_DIRECTORY; + if (parentDirectoryId != null + && !parentDirectoryId.equals(-1L)) { + // Need to go and lookup the parent, so do that first + parentDirectory = getDirectoryWithImmediateParentPopulated(parentDirectoryId); } + Directory directory = new Directory(rs + .getString("directory_name"), parentDirectory); + FieldUtils.setProtectedFieldValue("id", directory, + rs.getLong("id")); + return directory; }); } @@ -105,38 +99,26 @@ public class DocumentDaoImpl extends JdbcDaoSupport implements DocumentDao { "Directory required (the ID can be null to refer to root)"); if (directory.getId() == null) { List directories = getJdbcTemplate().query( - SELECT_FROM_DIRECTORY_NULL, new RowMapper() { - public Directory mapRow(ResultSet rs, int rowNumber) - throws SQLException { - return getDirectoryWithImmediateParentPopulated(rs - .getLong("id")); - } - }); + SELECT_FROM_DIRECTORY_NULL, (rs, rowNumber) -> getDirectoryWithImmediateParentPopulated(rs + .getLong("id"))); return directories.toArray(new AbstractElement[] {}); } List directories = getJdbcTemplate().query( SELECT_FROM_DIRECTORY, new Object[] { directory.getId() }, - new RowMapper() { - public Directory mapRow(ResultSet rs, int rowNumber) - throws SQLException { - return getDirectoryWithImmediateParentPopulated(rs - .getLong("id")); - } - }); + (rs, rowNumber) -> getDirectoryWithImmediateParentPopulated(rs + .getLong("id"))); List files = getJdbcTemplate().query(SELECT_FROM_FILE, - new Object[] { directory.getId() }, new RowMapper() { - public File mapRow(ResultSet rs, int rowNumber) throws SQLException { - Long parentDirectoryId = rs - .getLong("parent_directory_id"); - Directory parentDirectory = null; - if (parentDirectoryId != null) { - parentDirectory = getDirectoryWithImmediateParentPopulated(parentDirectoryId); - } - File file = new File(rs.getString("file_name"), parentDirectory); - FieldUtils.setProtectedFieldValue("id", file, - rs.getLong("id")); - return file; + new Object[] { directory.getId() }, (rs, rowNumber) -> { + Long parentDirectoryId = rs + .getLong("parent_directory_id"); + Directory parentDirectory = null; + if (parentDirectoryId != null) { + parentDirectory = getDirectoryWithImmediateParentPopulated(parentDirectoryId); } + File file = new File(rs.getString("file_name"), parentDirectory); + FieldUtils.setProtectedFieldValue("id", file, + rs.getLong("id")); + return file; }); // Add the File elements after the Directory elements directories.addAll(files); diff --git a/samples/xml/dms/src/main/java/sample/dms/secured/SecureDocumentDaoImpl.java b/samples/xml/dms/src/main/java/sample/dms/secured/SecureDocumentDaoImpl.java index bc349e86bc..2fad553bb6 100755 --- a/samples/xml/dms/src/main/java/sample/dms/secured/SecureDocumentDaoImpl.java +++ b/samples/xml/dms/src/main/java/sample/dms/secured/SecureDocumentDaoImpl.java @@ -15,10 +15,6 @@ */ package sample.dms.secured; -import java.sql.ResultSet; -import java.sql.SQLException; - -import org.springframework.jdbc.core.RowMapper; import org.springframework.security.acls.domain.BasePermission; import org.springframework.security.acls.domain.ObjectIdentityImpl; import org.springframework.security.acls.domain.PrincipalSid; @@ -49,11 +45,7 @@ public class SecureDocumentDaoImpl extends DocumentDaoImpl implements SecureDocu public String[] getUsers() { return getJdbcTemplate().query(SELECT_FROM_USERS, - new RowMapper() { - public String mapRow(ResultSet rs, int rowNumber) throws SQLException { - return rs.getString("USERNAME"); - } - }).toArray(new String[] {}); + (rs, rowNumber) -> rs.getString("USERNAME")).toArray(new String[] {}); } public void create(AbstractElement element) { diff --git a/samples/xml/servletapi/src/main/java/org/springframework/security/samples/servletapi/mvc/ServletApiController.java b/samples/xml/servletapi/src/main/java/org/springframework/security/samples/servletapi/mvc/ServletApiController.java index 7d61982c8b..bebd9f52e0 100644 --- a/samples/xml/servletapi/src/main/java/org/springframework/security/samples/servletapi/mvc/ServletApiController.java +++ b/samples/xml/servletapi/src/main/java/org/springframework/security/samples/servletapi/mvc/ServletApiController.java @@ -147,20 +147,18 @@ public class ServletApiController { @RequestMapping("/async") public void asynch(HttpServletRequest request, HttpServletResponse response) { final AsyncContext async = request.startAsync(); - async.start(new Runnable() { - public void run() { - Authentication authentication = SecurityContextHolder.getContext() - .getAuthentication(); - try { - final HttpServletResponse asyncResponse = (HttpServletResponse) async - .getResponse(); - asyncResponse.setStatus(HttpServletResponse.SC_OK); - asyncResponse.getWriter().write(String.valueOf(authentication)); - async.complete(); - } - catch (Exception e) { - throw new RuntimeException(e); - } + async.start(() -> { + Authentication authentication = SecurityContextHolder.getContext() + .getAuthentication(); + try { + final HttpServletResponse asyncResponse = (HttpServletResponse) async + .getResponse(); + asyncResponse.setStatus(HttpServletResponse.SC_OK); + asyncResponse.getWriter().write(String.valueOf(authentication)); + async.complete(); + } + catch (Exception e) { + throw new RuntimeException(e); } }); } @@ -211,4 +209,4 @@ public class ServletApiController { public String login(@ModelAttribute LoginForm loginForm) { return "login"; } -} \ No newline at end of file +} diff --git a/taglibs/src/main/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTag.java b/taglibs/src/main/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTag.java index abf0fb0c10..1da2aa966c 100644 --- a/taglibs/src/main/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTag.java +++ b/taglibs/src/main/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTag.java @@ -18,9 +18,7 @@ package org.springframework.security.taglibs.authz; import java.io.IOException; import java.util.Map; -import javax.servlet.FilterChain; import javax.servlet.ServletContext; -import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; @@ -146,11 +144,8 @@ public abstract class AbstractAuthorizeTag { protected EvaluationContext createExpressionEvaluationContext( SecurityExpressionHandler handler) { FilterInvocation f = new FilterInvocation(getRequest(), getResponse(), - new FilterChain() { - public void doFilter(ServletRequest request, ServletResponse response) - throws IOException, ServletException { - throw new UnsupportedOperationException(); - } + (request, response) -> { + throw new UnsupportedOperationException(); }); return handler.createEvaluationContext(SecurityContextHolder.getContext() diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsDigestTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsDigestTests.java index 18b6fe86a4..852f939fde 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsDigestTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsDigestTests.java @@ -25,9 +25,6 @@ import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; 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.web.authentication.www.DigestAuthenticationEntryPoint; import org.springframework.security.web.authentication.www.DigestAuthenticationFilter; @@ -59,13 +56,8 @@ public class SecurityMockMvcRequestPostProcessorsDigestTests { entryPoint.setKey("key"); entryPoint.setRealmName("Spring Security"); filter = new DigestAuthenticationFilter(); - filter.setUserDetailsService(new UserDetailsService() { - public UserDetails loadUserByUsername(String username) - throws UsernameNotFoundException { - return new User(username, password, AuthorityUtils - .createAuthorityList("ROLE_USER")); - } - }); + filter.setUserDetailsService(username -> new User(username, password, AuthorityUtils + .createAuthorityList("ROLE_USER"))); filter.setAuthenticationEntryPoint(entryPoint); filter.afterPropertiesSet(); } @@ -133,4 +125,4 @@ public class SecurityMockMvcRequestPostProcessorsDigestTests { }); return username; } -} \ No newline at end of file +} diff --git a/web/src/main/java/org/springframework/security/web/FilterInvocation.java b/web/src/main/java/org/springframework/security/web/FilterInvocation.java index e85ce6fe39..46c9e0486f 100644 --- a/web/src/main/java/org/springframework/security/web/FilterInvocation.java +++ b/web/src/main/java/org/springframework/security/web/FilterInvocation.java @@ -16,13 +16,11 @@ package org.springframework.security.web; -import java.io.IOException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import javax.servlet.FilterChain; -import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; @@ -48,11 +46,8 @@ import org.springframework.security.web.util.UrlUtils; public class FilterInvocation { // ~ Static fields // ================================================================================================== - static final FilterChain DUMMY_CHAIN = new FilterChain() { - public void doFilter(ServletRequest req, ServletResponse res) - throws IOException, ServletException { - throw new UnsupportedOperationException("Dummy filter chain"); - } + static final FilterChain DUMMY_CHAIN = (req, res) -> { + throw new UnsupportedOperationException("Dummy filter chain"); }; // ~ Instance fields diff --git a/web/src/main/java/org/springframework/security/web/access/ExceptionTranslationFilter.java b/web/src/main/java/org/springframework/security/web/access/ExceptionTranslationFilter.java index c2b21d3f5b..3e3345250c 100644 --- a/web/src/main/java/org/springframework/security/web/access/ExceptionTranslationFilter.java +++ b/web/src/main/java/org/springframework/security/web/access/ExceptionTranslationFilter.java @@ -27,7 +27,6 @@ import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.savedrequest.HttpSessionRequestCache; import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.security.web.util.ThrowableAnalyzer; -import org.springframework.security.web.util.ThrowableCauseExtractor; import org.springframework.util.Assert; import org.springframework.web.filter.GenericFilterBean; @@ -241,12 +240,10 @@ public class ExceptionTranslationFilter extends GenericFilterBean { protected void initExtractorMap() { super.initExtractorMap(); - registerExtractor(ServletException.class, new ThrowableCauseExtractor() { - public Throwable extractCause(Throwable throwable) { - ThrowableAnalyzer.verifyThrowableHierarchy(throwable, - ServletException.class); - return ((ServletException) throwable).getRootCause(); - } + registerExtractor(ServletException.class, throwable -> { + ThrowableAnalyzer.verifyThrowableHierarchy(throwable, + ServletException.class); + return ((ServletException) throwable).getRootCause(); }); } diff --git a/web/src/main/java/org/springframework/security/web/authentication/rememberme/JdbcTokenRepositoryImpl.java b/web/src/main/java/org/springframework/security/web/authentication/rememberme/JdbcTokenRepositoryImpl.java index 392c051e1d..bca39cabe0 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/rememberme/JdbcTokenRepositoryImpl.java +++ b/web/src/main/java/org/springframework/security/web/authentication/rememberme/JdbcTokenRepositoryImpl.java @@ -18,11 +18,8 @@ package org.springframework.security.web.authentication.rememberme; import org.springframework.dao.DataAccessException; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.dao.IncorrectResultSizeDataAccessException; -import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.support.JdbcDaoSupport; -import java.sql.ResultSet; -import java.sql.SQLException; import java.util.*; /** @@ -85,13 +82,8 @@ public class JdbcTokenRepositoryImpl extends JdbcDaoSupport implements public PersistentRememberMeToken getTokenForSeries(String seriesId) { try { return getJdbcTemplate().queryForObject(tokensBySeriesSql, - new RowMapper() { - public PersistentRememberMeToken mapRow(ResultSet rs, int rowNum) - throws SQLException { - return new PersistentRememberMeToken(rs.getString(1), rs - .getString(2), rs.getString(3), rs.getTimestamp(4)); - } - }, seriesId); + (rs, rowNum) -> new PersistentRememberMeToken(rs.getString(1), rs + .getString(2), rs.getString(3), rs.getTimestamp(4)), seriesId); } catch (EmptyResultDataAccessException zeroResults) { if (logger.isDebugEnabled()) { diff --git a/web/src/main/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilter.java b/web/src/main/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilter.java index c6f894a111..b3c799b75d 100644 --- a/web/src/main/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilter.java +++ b/web/src/main/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilter.java @@ -91,11 +91,9 @@ public class JaasApiIntegrationFilter extends GenericFilterBean { chain.doFilter(request, response); return; } - final PrivilegedExceptionAction continueChain = new PrivilegedExceptionAction() { - public Object run() throws IOException, ServletException { - chain.doFilter(request, response); - return null; - } + final PrivilegedExceptionAction continueChain = () -> { + chain.doFilter(request, response); + return null; }; if (logger.isDebugEnabled()) { @@ -160,4 +158,4 @@ public class JaasApiIntegrationFilter extends GenericFilterBean { public final void setCreateEmptySubject(boolean createEmptySubject) { this.createEmptySubject = createEmptySubject; } -} \ No newline at end of file +} diff --git a/web/src/main/java/org/springframework/security/web/server/util/matcher/ServerWebExchangeMatchers.java b/web/src/main/java/org/springframework/security/web/server/util/matcher/ServerWebExchangeMatchers.java index 1d490d5a6b..7b0ec7da59 100644 --- a/web/src/main/java/org/springframework/security/web/server/util/matcher/ServerWebExchangeMatchers.java +++ b/web/src/main/java/org/springframework/security/web/server/util/matcher/ServerWebExchangeMatchers.java @@ -65,6 +65,7 @@ public abstract class ServerWebExchangeMatchers { * Matches any exchange * @return the matcher to use */ + @SuppressWarnings("Convert2Lambda") public static ServerWebExchangeMatcher anyExchange() { // we don't use a lambda to ensure a unique equals and hashcode // which otherwise can cause problems with adding multiple entries to an ordered LinkedHashMap diff --git a/web/src/main/java/org/springframework/security/web/session/ConcurrentSessionFilter.java b/web/src/main/java/org/springframework/security/web/session/ConcurrentSessionFilter.java index 3c552a9b79..6228203c41 100644 --- a/web/src/main/java/org/springframework/security/web/session/ConcurrentSessionFilter.java +++ b/web/src/main/java/org/springframework/security/web/session/ConcurrentSessionFilter.java @@ -96,17 +96,12 @@ public class ConcurrentSessionFilter extends GenericFilterBean { () -> expiredUrl + " isn't a valid redirect URL"); this.expiredUrl = expiredUrl; this.sessionRegistry = sessionRegistry; - this.sessionInformationExpiredStrategy = new SessionInformationExpiredStrategy() { - - @Override - public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException { - HttpServletRequest request = event.getRequest(); - HttpServletResponse response = event.getResponse(); - SessionInformation info = event.getSessionInformation(); - - redirectStrategy.sendRedirect(request, response, determineExpiredUrl(request, info)); - } + this.sessionInformationExpiredStrategy = event -> { + HttpServletRequest request = event.getRequest(); + HttpServletResponse response = event.getResponse(); + SessionInformation info = event.getSessionInformation(); + redirectStrategy.sendRedirect(request, response, determineExpiredUrl(request, info)); }; } diff --git a/web/src/main/java/org/springframework/security/web/util/ThrowableAnalyzer.java b/web/src/main/java/org/springframework/security/web/util/ThrowableAnalyzer.java index 4e7425e2bb..e1cf919724 100755 --- a/web/src/main/java/org/springframework/security/web/util/ThrowableAnalyzer.java +++ b/web/src/main/java/org/springframework/security/web/util/ThrowableAnalyzer.java @@ -40,22 +40,16 @@ public class ThrowableAnalyzer { * * @see Throwable#getCause() */ - public static final ThrowableCauseExtractor DEFAULT_EXTRACTOR = new ThrowableCauseExtractor() { - public Throwable extractCause(Throwable throwable) { - return throwable.getCause(); - } - }; + public static final ThrowableCauseExtractor DEFAULT_EXTRACTOR = throwable -> throwable.getCause(); /** * Default extractor for {@link InvocationTargetException} instances. * * @see InvocationTargetException#getTargetException() */ - public static final ThrowableCauseExtractor INVOCATIONTARGET_EXTRACTOR = new ThrowableCauseExtractor() { - public Throwable extractCause(Throwable throwable) { - verifyThrowableHierarchy(throwable, InvocationTargetException.class); - return ((InvocationTargetException) throwable).getTargetException(); - } + public static final ThrowableCauseExtractor INVOCATIONTARGET_EXTRACTOR = throwable -> { + verifyThrowableHierarchy(throwable, InvocationTargetException.class); + return ((InvocationTargetException) throwable).getTargetException(); }; /** @@ -64,21 +58,16 @@ public class ThrowableAnalyzer { * greater by this comparator.
* For hierarchically unrelated classes their fully qualified name will be compared. */ - private static final Comparator> CLASS_HIERARCHY_COMPARATOR = new Comparator>() { - - public int compare(Class class1, - Class class2) { - if (class1.isAssignableFrom(class2)) { - return 1; - } - else if (class2.isAssignableFrom(class1)) { - return -1; - } - else { - return class1.getName().compareTo(class2.getName()); - } + private static final Comparator> CLASS_HIERARCHY_COMPARATOR = (class1, class2) -> { + if (class1.isAssignableFrom(class2)) { + return 1; + } + else if (class2.isAssignableFrom(class1)) { + return -1; + } + else { + return class1.getName().compareTo(class2.getName()); } - }; /** diff --git a/web/src/test/java/org/springframework/security/web/FilterChainProxyTests.java b/web/src/test/java/org/springframework/security/web/FilterChainProxyTests.java index 862deb84f7..9451b4b811 100644 --- a/web/src/test/java/org/springframework/security/web/FilterChainProxyTests.java +++ b/web/src/test/java/org/springframework/security/web/FilterChainProxyTests.java @@ -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() { - 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) 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() { - public Object answer(InvocationOnMock inv) throws Throwable { - SecurityContextHolder.getContext().setAuthentication( - new TestingAuthenticationToken("username", "password")); - return null; - } + doAnswer((Answer) 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() { - public Object answer(InvocationOnMock inv) throws Throwable { - SecurityContextHolder.getContext().setAuthentication( - new TestingAuthenticationToken("username", "password")); - throw new ServletException("oops"); - } + doAnswer((Answer) 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() { - public Object answer(InvocationOnMock inv) throws Throwable { - TestingAuthenticationToken expected = new TestingAuthenticationToken( - "username", "password"); - SecurityContextHolder.getContext().setAuthentication(expected); - doAnswer(new Answer() { - 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) inv -> { + TestingAuthenticationToken expected = new TestingAuthenticationToken( + "username", "password"); + SecurityContextHolder.getContext().setAuthentication(expected); + doAnswer((Answer) 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)); diff --git a/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java b/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java index 6349c4468e..bf9c9cbe1a 100644 --- a/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/access/ExceptionTranslationFilterTests.java @@ -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"); } diff --git a/web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java index 24b713bee0..c673ce8ca6 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilterTests.java @@ -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() { - public Authentication answer(InvocationOnMock invocation) - throws Throwable { - return (Authentication) invocation.getArguments()[0]; - } - }); + (Answer) invocation -> (Authentication) invocation.getArguments()[0]); return am; } diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java index bea1ca6098..ceb01891bf 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/AbstractPreAuthenticatedProcessingFilterTests.java @@ -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() { - public Authentication answer(InvocationOnMock invocation) - throws Throwable { - return (Authentication) invocation.getArguments()[0]; - } - }); + (Answer) invocation -> (Authentication) invocation.getArguments()[0]); } filter.setAuthenticationManager(am); diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationProviderTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationProviderTests.java index 17a17aa13d..959b5ad4e6 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationProviderTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedAuthenticationProviderTests.java @@ -126,17 +126,13 @@ public class PreAuthenticatedAuthenticationProviderTests { private AuthenticationUserDetailsService getPreAuthenticatedUserDetailsService( final UserDetails aUserDetails) { - return new AuthenticationUserDetailsService() { - - 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"); }; } diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests.java index a963a483fc..dc8b248884 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests.java @@ -67,11 +67,7 @@ public class PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests { PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService(); PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken( userName, "dummy"); - token.setDetails(new GrantedAuthoritiesContainer() { - public Collection getGrantedAuthorities() { - return gas; - } - }); + token.setDetails((GrantedAuthoritiesContainer) () -> gas); UserDetails ud = svc.loadUserDetails(token); assertThat(ud.isAccountNonExpired()).isTrue(); assertThat(ud.isAccountNonLocked()).isTrue(); diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/RequestAttributeAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/RequestAttributeAuthenticationFilterTests.java index 7233019329..b6d04b5540 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/RequestAttributeAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/RequestAttributeAuthenticationFilterTests.java @@ -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() { - public Authentication answer(InvocationOnMock invocation) - throws Throwable { - return (Authentication) invocation.getArguments()[0]; - } - }); + .thenAnswer((Answer) invocation -> (Authentication) invocation.getArguments()[0]); return am; } diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/header/RequestHeaderAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/header/RequestHeaderAuthenticationFilterTests.java index 8a6207f472..e4de657aa8 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/header/RequestHeaderAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/header/RequestHeaderAuthenticationFilterTests.java @@ -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() { - public Authentication answer(InvocationOnMock invocation) - throws Throwable { - return (Authentication) invocation.getArguments()[0]; - } - }); + (Answer) invocation -> (Authentication) invocation.getArguments()[0]); return am; } diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilterTests.java index f9a7a2259f..607d151d03 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/j2ee/J2eePreAuthenticatedProcessingFilterTests.java @@ -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; } diff --git a/web/src/test/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilterTests.java index db6dc212b3..395d45c0b4 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/preauth/websphere/WebSpherePreAuthenticatedProcessingFilterTests.java @@ -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() { - public Authentication answer(InvocationOnMock invocation) - throws Throwable { - return (Authentication) invocation.getArguments()[0]; - } - }); + (Answer) invocation -> (Authentication) invocation.getArguments()[0]); filter.setAuthenticationManager(am); WebSpherePreAuthenticatedWebAuthenticationDetailsSource ads = new WebSpherePreAuthenticatedWebAuthenticationDetailsSource( diff --git a/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilterTests.java index 0cf3acd5c3..05f8060931 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/switchuser/SwitchUserFilterTests.java @@ -439,14 +439,10 @@ public class SwitchUserFilterTests { SwitchUserFilter filter = new SwitchUserFilter(); filter.setUserDetailsService(new MockUserDetailsService()); - filter.setSwitchUserAuthorityChanger(new SwitchUserAuthorityChanger() { - public Collection modifyGrantedAuthorities( - UserDetails targetUser, Authentication currentAuthentication, - Collection authoritiesToBeGranted) { - List auths = new ArrayList<>(); - auths.add(new SimpleGrantedAuthority("ROLE_NEW")); - return auths; - } + filter.setSwitchUserAuthorityChanger((targetUser, currentAuthentication, authoritiesToBeGranted) -> { + List auths = new ArrayList<>(); + auths.add(new SimpleGrantedAuthority("ROLE_NEW")); + return auths; }); Authentication result = filter.attemptSwitchUser(request); diff --git a/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilterTests.java index 3ac9c115c3..e1d27eaf77 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/www/DigestAuthenticationFilterTests.java @@ -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); diff --git a/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java b/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java index d83f1986a0..917dc1c3ae 100644 --- a/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/context/SecurityContextPersistenceFilterTests.java @@ -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); diff --git a/web/src/test/java/org/springframework/security/web/header/HeaderWriterFilterTests.java b/web/src/test/java/org/springframework/security/web/header/HeaderWriterFilterTests.java index 4846726118..77a2255a27 100644 --- a/web/src/test/java/org/springframework/security/web/header/HeaderWriterFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/header/HeaderWriterFilterTests.java @@ -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); } diff --git a/web/src/test/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilterTests.java b/web/src/test/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilterTests.java index c4b673f5e1..d6ff8fe75c 100644 --- a/web/src/test/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/jaasapi/JaasApiIntegrationFilterTests.java @@ -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); } } }; diff --git a/web/src/test/java/org/springframework/security/web/savedrequest/HttpSessionRequestCacheTests.java b/web/src/test/java/org/springframework/security/web/savedrequest/HttpSessionRequestCacheTests.java index 69ddf916de..e967dc02be 100644 --- a/web/src/test/java/org/springframework/security/web/savedrequest/HttpSessionRequestCacheTests.java +++ b/web/src/test/java/org/springframework/security/web/savedrequest/HttpSessionRequestCacheTests.java @@ -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"); diff --git a/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java b/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java index 8419656786..c731ae8c96 100644 --- a/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java @@ -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);