1 16 package org.outerj.daisy.authentication; 17 18 import org.outerj.daisy.authentication.AuthenticationScheme; 19 import org.outerj.daisy.authentication.AuthenticationException; 20 import org.outerj.daisy.repository.Credentials; 21 import org.outerj.daisy.repository.user.User; 22 import org.outerj.daisy.repository.user.UserManager; 23 import org.apache.commons.collections.map.LRUMap; 24 25 import java.util.Collections ; 26 import java.util.Map ; 27 28 31 public class CachingAuthenticationScheme implements AuthenticationScheme { 32 private AuthenticationScheme delegate; 33 private long maxCacheDuration; 34 private Map cache; 35 36 42 public CachingAuthenticationScheme(AuthenticationScheme delegate, long maxCacheDuration, int maxCacheSize) { 43 this.delegate = delegate; 44 this.maxCacheDuration = maxCacheDuration; 45 this.cache = Collections.synchronizedMap(new LRUMap(maxCacheSize)); 46 } 47 48 public String getName() { 49 return delegate.getName(); 50 } 51 52 public String getDescription() { 53 return delegate.getDescription(); 54 } 55 56 public void clearCaches() { 57 cache.clear(); 58 } 59 60 public boolean check(Credentials credentials) throws AuthenticationException { 61 String password = getFromCache(credentials.getLogin()); 62 63 if (password != null && password.equals(credentials.getPassword())) 64 return true; 65 66 boolean valid = delegate.check(credentials); 67 if (valid) { 68 putInCache(credentials); 69 return true; 70 } 71 72 return false; 73 } 74 75 public User createUser(Credentials crendentials, UserManager userManager) throws AuthenticationException { 76 return delegate.createUser(crendentials, userManager); 77 } 78 79 private String getFromCache(String login) { 80 CacheEntry cacheEntry = (CacheEntry)cache.get(login); 81 if (cacheEntry != null) { 82 if ((System.currentTimeMillis() - cacheEntry.created) > maxCacheDuration) { 83 cache.remove(login); 84 return null; 85 } 86 return cacheEntry.password; 87 } 88 return null; 89 } 90 91 private void putInCache(Credentials credentials) { 92 cache.put(credentials.getLogin(), new CacheEntry(credentials.getPassword())); 93 } 94 95 private static class CacheEntry { 96 long created = System.currentTimeMillis(); 97 String password; 98 99 CacheEntry(String password) { 100 this.password = password; 101 } 102 } 103 } 104 | Popular Tags |