001 package hirondelle.web4jtools.logview.directories; 002 003 import javax.servlet.ServletConfig; 004 import javax.servlet.http.HttpServletRequest; 005 006 import hirondelle.web4j.model.ModelCtorException; 007 import hirondelle.web4j.request.RequestParameter; 008 import hirondelle.web4j.security.SafeText; 009 import hirondelle.web4j.util.Util; 010 import hirondelle.web4j.util.WebUtil; 011 012 /** 013 * Save and fetch the current {@link LogInfo}. 014 * 015 * <P>This implementation does not store items in a database. Rather, the following 016 * mechanism is used : 017 *<ul> 018 * <li>upon startup, store a default {@link LogInfo} in application scope, using default settings in <tt>web.xml</tt>. 019 * <li>allow the user to override the default settings, and store an 'override' {@link LogInfo} in <em>session</em> scope. 020 *</ul> 021 */ 022 public final class LogInfoDAO { 023 024 /** 025 * Read in config from web.xml. 026 * Called only upon startup. Place a default {@link LogInfo} object in application scope. 027 */ 028 public static void readConfig(ServletConfig aConfig) { 029 try { 030 LogInfo defaultDirInfo = new LogInfo( 031 get(LogInfoAction.PROJECT_NAME, aConfig), 032 get(LogInfoAction.APP_LOGGING_DIR, aConfig), 033 get(LogInfoAction.SERVER_LOGGING_DIR, aConfig), 034 get(LogInfoAction.SERVER_LOG_FILE_STARTS_WITH, aConfig) 035 ); 036 aConfig.getServletContext().setAttribute(LOG_INFO_KEY, defaultDirInfo); 037 } 038 catch (ModelCtorException ex) { 039 throw new RuntimeException(ex); 040 } 041 } 042 043 /** Full constructor */ 044 public LogInfoDAO(HttpServletRequest aRequest) { 045 fRequest = aRequest; 046 } 047 048 /** Key under which {@link LogInfo} objects are stored (in both application and session scopes.) */ 049 public static final String LOG_INFO_KEY = "logInfo"; 050 051 /** 052 * Fetch a {@link LogInfo} from either session scope (preferred) or application scope (default). 053 */ 054 public LogInfo fetch(){ 055 return (LogInfo)WebUtil.findAttribute(LOG_INFO_KEY, fRequest); 056 } 057 058 /** Save an 'override' {@link LogInfo} into session scope. */ 059 public void save(LogInfo aDirInfo){ 060 fRequest.getSession(true).setAttribute(LOG_INFO_KEY, aDirInfo); //for later lookup 061 } 062 063 // PRIVATE // 064 private HttpServletRequest fRequest; 065 066 private static SafeText get(RequestParameter aRequestParameter, ServletConfig aConfig){ 067 String value = aConfig.getInitParameter(aRequestParameter.getName()); 068 if ( ! Util.textHasContent(value) ) { 069 String message = "In web.xml, please specify a value for parameter named " + aRequestParameter; 070 throw new RuntimeException(message); 071 } 072 return new SafeText(value); 073 } 074 }