package org.openslx.dozmod.thrift.cache; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.apache.thrift.TException; import org.openslx.bwlp.thrift.iface.UserInfo; import org.openslx.dozmod.thrift.Session; import org.openslx.thrifthelper.ThriftManager; import org.openslx.util.GenericDataCache; import org.openslx.util.GenericDataCache.CacheMode; public class UserCache { private static final Logger LOGGER = Logger.getLogger(UserCache.class); /** * How long should the list be cached? */ private static final int CACHE_TIME_MS = 5 * 60 * 1000; private static final GenericDataCache> cache = new GenericDataCache>( CACHE_TIME_MS) { @Override protected List update() throws Exception { List result = null; int pageSize = Session.getSatelliteConfig().pageSize; for (int i = 0;; ++i) { List page = ThriftManager.getSatClient() .getUserList(Session.getSatelliteToken(), i); if (result == null) { result = page; } else { result.addAll(page); } if (page.size() < pageSize) break; } if (result != null) { result = Collections.unmodifiableList(result); } return result; } }; // map for caching users found on the masterserver private static final Map cachedUserFromMaster = new HashMap(); private UserCache() { // No instancing } /** * Get all known users * * @return list of users */ public static List getAll() { return cache.get(); } /** * Find the user with the given id * * @param user id * @return matching user, or null if not found */ public static UserInfo find(String userId) { // First, try in "always cached" mode List list = cache.get(CacheMode.PREFER_CACHED); UserInfo user = find(userId, list); if (user != null) return user; // still no user, look in local cache for master user // TODO check validity of the map? if (cachedUserFromMaster.containsKey(userId)) return cachedUserFromMaster.get(userId); // Try again with a potential refresh List newList = cache.get(CacheMode.DEFAULT); if (list != newList) { // Skip second searh if lists are identical user = find(userId, newList); } if (user == null) { // not in cached map either, query master try { user = ThriftManager.getMasterClient().getUser(Session.getMasterToken(), userId); } catch (TException e) { LOGGER.error("User with ID '" + userId + "' not found on the masterserver.", e); return null; } // remember it if (user != null) cachedUserFromMaster.put(userId, user); } return user; } private static UserInfo find(String userId, List list) { if (list != null) { for (UserInfo user : list) { if (user.userId.equals(userId)) return user; } } return null; } }