Anonymous type can be replaced with lambda

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

View File

@ -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<Long> 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<Long> 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));

View File

@ -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<ObjectIdentity> findChildren(ObjectIdentity parentIdentity) {
Object[] args = { parentIdentity.getIdentifier().toString(), parentIdentity.getType() };
List<ObjectIdentity> objects = jdbcOperations.query(findChildrenSql, args,
new RowMapper<ObjectIdentity>() {
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) {

View File

@ -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);
}

View File

@ -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(),

View File

@ -99,9 +99,7 @@ public final class WebSecurity extends
private SecurityExpressionHandler<FilterInvocation> expressionHandler = defaultWebSecurityExpressionHandler;
private Runnable postBuildAction = new Runnable() {
public void run() {
}
private Runnable postBuildAction = () -> {
};
/**

View File

@ -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);
});
}

View File

@ -178,19 +178,9 @@ public class AnnotationParameterNameDiscoverer implements ParameterNameDiscovere
return null;
}
private static final ParameterNameFactory<Constructor<?>> CONSTRUCTOR_METHODPARAM_FACTORY = new ParameterNameFactory<Constructor<?>>() {
private static final ParameterNameFactory<Constructor<?>> CONSTRUCTOR_METHODPARAM_FACTORY = constructor -> constructor.getParameterAnnotations();
public Annotation[][] findParameterAnnotations(Constructor<?> constructor) {
return constructor.getParameterAnnotations();
}
};
private static final ParameterNameFactory<Method> METHOD_METHODPARAM_FACTORY = new ParameterNameFactory<Method>() {
public Annotation[][] findParameterAnnotations(Method method) {
return method.getParameterAnnotations();
}
};
private static final ParameterNameFactory<Method> METHOD_METHODPARAM_FACTORY = method -> method.getParameterAnnotations();
/**
* Strategy interface for looking up the parameter names.

View File

@ -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<UserDetails> loadUsersByUsername(String username) {
return getJdbcTemplate().query(this.usersByUsernameQuery,
new String[] { username }, new RowMapper<UserDetails>() {
@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<GrantedAuthority> loadUserAuthorities(String username) {
return getJdbcTemplate().query(this.authoritiesByUsernameQuery,
new String[] { username }, new RowMapper<GrantedAuthority>() {
@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<GrantedAuthority> loadGroupAuthorities(String username) {
return getJdbcTemplate().query(this.groupAuthoritiesByUsernameQuery,
new String[] { username }, new RowMapper<GrantedAuthority>() {
@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);
});
}

View File

@ -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<GrantedAuthority>() {
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());
});
}

View File

@ -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<GrantedAuthority> getReachableGrantedAuthorities(
Collection<? extends GrantedAuthority> authorities) {
return AuthorityUtils.createAuthorityList("ROLE_C");
}
});
root.setRoleHierarchy(authorities -> AuthorityUtils.createAuthorityList("ROLE_C"));
assertThat(root.hasRole("C")).isTrue();
assertThat(root.hasAuthority("ROLE_C")).isTrue();

View File

@ -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;

View File

@ -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",

View File

@ -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;
}

View File

@ -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<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
assertThat(SecurityContextHolder.getContext()).isEqualTo(securityContext);
return null;
}
doAnswer((Answer<Object>) invocation -> {
assertThat(SecurityContextHolder.getContext()).isEqualTo(securityContext);
return null;
}).when(delegate).run();
executor = Executors.newFixedThreadPool(1);

View File

@ -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();

View File

@ -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<SecurityContext> getSecurityContexts() {
return Collections.emptyList();
}
@Override
public String getId() {
return session1.getId();
}
});
public List<SecurityContext> getSecurityContexts() {
return Collections.emptyList();
}
});
@Override
public String getId() {
return session1.getId();
}
}));
// Try second session again
login2 = login()

View File

@ -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");
}

View File

@ -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<Map<String, List<String>>> set = new HashSet<>();
ContextMapper roleMapper = new ContextMapper() {
public Object mapFromContext(Object ctx) {
DirContextAdapter adapter = (DirContextAdapter) ctx;
Map<String, List<String>> 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<String, List<String>> 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));
}
/**

View File

@ -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<GrantedAuthority> getUserAuthorities(final DistinguishedName dn,
final String username) {
SearchExecutor se = new SearchExecutor() {
public NamingEnumeration<SearchResult> 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<? extends GrantedAuthority> 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;
});
}

View File

@ -36,12 +36,10 @@ import java.util.Map;
* @author Rob Winch
*/
public final class SimpDestinationMessageMatcher implements MessageMatcher<Object> {
public static final MessageMatcher<Object> NULL_DESTINATION_MATCHER = new MessageMatcher<Object>() {
public boolean matches(Message<? extends Object> message) {
String destination = SimpMessageHeaderAccessor.getDestination(message
.getHeaders());
return destination == null;
}
public static final MessageMatcher<Object> NULL_DESTINATION_MATCHER = message -> {
String destination = SimpMessageHeaderAccessor.getDestination(message
.getHeaders());
return destination == null;
};
private final PathMatcher matcher;

View File

@ -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(

View File

@ -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();
}

View File

@ -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<Contact> findAll() {
return getJdbcTemplate().query(
"select id, contact_name, email from contacts order by id",
new RowMapper<Contact>() {
public Contact mapRow(ResultSet rs, int rowNum) throws SQLException {
return mapContact(rs);
}
});
(rs, rowNum) -> mapContact(rs));
}
public List<String> findAllPrincipals() {
@ -92,11 +77,7 @@ public class ContactDaoSpring extends JdbcDaoSupport implements ContactDao {
public Contact getById(Long id) {
List<Contact> list = getJdbcTemplate().query(
"select id, contact_name, email from contacts where id = ? order by id",
new RowMapper<Contact>() {
public Contact mapRow(ResultSet rs, int rowNum) throws SQLException {
return mapContact(rs);
}
}, id);
(rs, rowNum) -> mapContact(rs), id);
if (list.size() == 0) {
return null;

View File

@ -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<Object>() {
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<Object>() {
public Object doInTransaction(TransactionStatus arg0) {
mutableAclService.updateAcl(acl);
tt.execute(arg0 -> {
mutableAclService.updateAcl(acl);
return null;
}
return null;
});
}
}

View File

@ -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<Directory>() {
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<Directory> directories = getJdbcTemplate().query(
SELECT_FROM_DIRECTORY_NULL, new RowMapper<Directory>() {
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<AbstractElement> directories = getJdbcTemplate().query(
SELECT_FROM_DIRECTORY, new Object[] { directory.getId() },
new RowMapper<AbstractElement>() {
public Directory mapRow(ResultSet rs, int rowNumber)
throws SQLException {
return getDirectoryWithImmediateParentPopulated(rs
.getLong("id"));
}
});
(rs, rowNumber) -> getDirectoryWithImmediateParentPopulated(rs
.getLong("id")));
List<File> files = getJdbcTemplate().query(SELECT_FROM_FILE,
new Object[] { directory.getId() }, new RowMapper<File>() {
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);

View File

@ -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<String>() {
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) {

View File

@ -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";
}
}
}

View File

@ -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<FilterInvocation> 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()

View File

@ -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;
}
}
}

View File

@ -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

View File

@ -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();
});
}

View File

@ -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<PersistentRememberMeToken>() {
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()) {

View File

@ -91,11 +91,9 @@ public class JaasApiIntegrationFilter extends GenericFilterBean {
chain.doFilter(request, response);
return;
}
final PrivilegedExceptionAction<Object> continueChain = new PrivilegedExceptionAction<Object>() {
public Object run() throws IOException, ServletException {
chain.doFilter(request, response);
return null;
}
final PrivilegedExceptionAction<Object> 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;
}
}
}

View File

@ -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

View File

@ -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));
};
}

View File

@ -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.<br>
* For hierarchically unrelated classes their fully qualified name will be compared.
*/
private static final Comparator<Class<? extends Throwable>> CLASS_HIERARCHY_COMPARATOR = new Comparator<Class<? extends Throwable>>() {
public int compare(Class<? extends Throwable> class1,
Class<? extends Throwable> 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<? extends Throwable>> 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());
}
};
/**

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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