/** * Settings bean */ package nl.thimojansenit.bean; import java.io.Serializable; import java.util.Date; import java.util.HashMap; import java.util.Map; import nl.thimojansenit.DummyMap; /** * @author Thimo Jansen <thimo@jansenit.nl> */ public class Settings implements Serializable { private static final long serialVersionUID = 1L; private Map<String, Cache> _cache = new HashMap<String, Cache>(); /** * Retrieve cached value of setting. If not yet cached or value is too old (> 60 minutes), get fresh value * * @param name * of setting to retrieve * @return value of setting */ public String getValue(String name) { Date now = new Date(); if (!_cache.containsKey(name) || (now.getTime() - _cache.get(name).getDatetime().getTime()) > 1000 * 60 * 60) { _cache.put(name, new Cache(getFromMap(name))); } return _cache.get(name).getValue(); } /** * Get SettingsMap object through which EL can fetch the value for a setting * * @return SettingsMap */ public SettingsMap getValue() { return new SettingsMap(this); } /** * Static method to retrieve settings, replace this code with your own logic */ static private String getFromMap(String name) { Map<String, String> settings = new HashMap<String, String>(); settings.put("hostname", "www.thimojansenit.nl"); settings.put("db_names", "names.nsf"); return settings.get(name); } /** * InnerClass used to provide settings to EL. This class uses the parent bean to fetch values for settings */ @SuppressWarnings("unchecked") private class SettingsMap extends DummyMap implements Map { // Reference to parent Settings bean private Settings _settings; public SettingsMap(Settings settings) { _settings = settings; } public Object get(Object obj) { return _settings.getValue((String) obj); } } /** * InnerClass used to store cached values, includes date/time stamp */ private class Cache { private Date _datetime; private String _value; public Cache(String value) { _datetime = new Date(); _value = value; } public Date getDatetime() { return _datetime; } public String getValue() { return _value; } } } /* * Support class DummyMap */ package nl.thimojansenit; import java.util.Collection; import java.util.Map; import java.util.Set; // abstract class used by java server faces to pass parameter to a method as map key @SuppressWarnings("unchecked") public abstract class DummyMap implements Map { public Collection values() { return null; } public Object put(Object key, Object value) { return null; } public Set keySet() { return null; } public boolean isEmpty() { return false; } public int size() { return 0; } public void putAll(Map t) { } public void clear() { } public boolean containsValue(Object value) { return false; } public Object remove(Object key) { return null; } public boolean containsKey(Object key) { return false; } public Set entrySet() { return null; } // subclasses should override this method call their method with obj as the parameter public abstract Object get(Object obj); }