SEC-2114: Provide Spring Cache Abstraction based cache implementations
As of Spring 3.1 spring has its own cache abstraction. This commit adds cache imlpementations based on that abstraction.
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
package org.springframework.security.core.userdetails.cache;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.security.core.userdetails.UserCache;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Caches {@link UserDetails} intances in a Spring defined {@link Cache}.
|
||||
*
|
||||
* @author Marten Deinum
|
||||
* @since 3.2
|
||||
*/
|
||||
public class SpringCacheBasedUserCache implements UserCache, InitializingBean {
|
||||
|
||||
|
||||
//~ Static fields/initializers =====================================================================================
|
||||
|
||||
private static final Log logger = LogFactory.getLog(SpringCacheBasedUserCache.class);
|
||||
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
private Cache cache;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
Assert.notNull(cache, "cache mandatory");
|
||||
}
|
||||
|
||||
public Cache getCache() {
|
||||
return cache;
|
||||
}
|
||||
|
||||
public UserDetails getUserFromCache(String username) {
|
||||
Cache.ValueWrapper element = username != null ? cache.get(username) : null;
|
||||
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Cache hit: " + (element != null) + "; username: " + username);
|
||||
}
|
||||
|
||||
if (element == null) {
|
||||
return null;
|
||||
} else {
|
||||
return (UserDetails) element.get();
|
||||
}
|
||||
}
|
||||
|
||||
public void putUserInCache(UserDetails user) {
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Cache put: " + user.getUsername());
|
||||
}
|
||||
cache.put(user.getUsername(), user);
|
||||
}
|
||||
|
||||
public void removeUserFromCache(UserDetails user) {
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("Cache remove: " + user.getUsername());
|
||||
}
|
||||
|
||||
this.removeUserFromCache(user.getUsername());
|
||||
}
|
||||
|
||||
public void removeUserFromCache(String username) {
|
||||
cache.evict(username);
|
||||
}
|
||||
|
||||
public void setCache(Cache cache) {
|
||||
this.cache = cache;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user