package org.openslx.dozmod.thrift.cache; import java.util.Collections; import java.util.List; import org.apache.log4j.Logger; import org.openslx.bwlp.thrift.iface.Organization; import org.openslx.bwlp.thrift.iface.UserInfo; import org.openslx.dozmod.thrift.Sorters; import org.openslx.thrifthelper.ThriftManager; import org.openslx.util.GenericDataCache; import org.openslx.util.GenericDataCache.CacheMode; public class OrganizationCache { private static final Logger LOGGER = Logger.getLogger(OrganizationCache.class); /** * How long should the list be cached? */ private static final int CACHE_TIME_MS = 20 * 60 * 1000; private static final GenericDataCache> cache = new GenericDataCache>( CACHE_TIME_MS) { @Override protected List update() throws Exception { List orgs = null; try { orgs = ThriftManager.getMasterClient().getOrganizations(); } catch (Exception e) { LOGGER.warn( "Failed to get organization list from master server, trying satellite for backup..", e); } if (orgs == null) { try { orgs = ThriftManager.getSatClient().getAllOrganizations(); } catch (Exception e) { LOGGER.error("Failed to get organization list from satellite server. ", e); // both failed, can this ever happen? TODO if it does, what do we do? } } if (orgs != null) Collections.sort(orgs, Sorters.organization); return orgs; } }; private OrganizationCache() { // No instancing } /** * Get all known organizations * * @return list of organizations */ public static List getAll() { return cache.get(); } /** * Find the organization the given user belongs to * * @param user * @return matching organization, or null if not found */ public static Organization find(UserInfo user) { return find(user.organizationId); } /** * Find the organization with the given id * * @param organization id * @return matching organization, or null if not found */ public static Organization find(String organizationId) { // First, try in "always cached" mode List list = cache.get(CacheMode.PREFER_CACHED); Organization org = find(organizationId, list); if (org != null) return org; // Try again with a potential refresh List newList = cache.get(CacheMode.DEFAULT); if (list == newList) // Returned list from cache as it was still recent enough return null; return find(organizationId, newList); } private static Organization find(String organizationId, List list) { if (list != null) { for (Organization org : list) { if (org.organizationId.equals(organizationId)) return org; } } return null; } }