Mercurial > hg > digilib
changeset 1183:95f9e334c0d3
reshuffled configuration classes.
author | robcast |
---|---|
date | Fri, 12 Apr 2013 17:41:43 +0200 |
parents | 8bf1b3eda48c |
children | 72c68a2dc14e |
files | common/src/main/java/digilib/conf/DigilibConfiguration.java common/src/main/java/digilib/io/FileOps.java common/src/main/java/digilib/util/ParameterMap.java pdf/src/main/java/digilib/conf/PDFServletConfiguration.java pdf/src/main/java/digilib/servlet/PDFCache.java servlet/src/main/java/digilib/conf/DigilibServletConfiguration.java |
diffstat | 6 files changed, 407 insertions(+), 274 deletions(-) [+] |
line wrap: on
line diff
--- a/common/src/main/java/digilib/conf/DigilibConfiguration.java Wed Apr 10 09:33:19 2013 +0200 +++ b/common/src/main/java/digilib/conf/DigilibConfiguration.java Fri Apr 12 17:41:43 2013 +0200 @@ -49,10 +49,12 @@ */ public DigilibConfiguration() { super(20); + /* * Definition of parameters and default values. System parameters that * are not read from config file have a type 's'. */ + // digilib version newParameter("digilib.version", "2.2.0", null, 's'); // sending image files as-is allowed @@ -79,17 +81,18 @@ */ @SuppressWarnings("unchecked") public void configure() { + DigilibConfiguration config = this; // we start log4j with a default logger config TODO: is this the right place? BasicConfigurator.configure(); /* * initialise static DocuImage class instance */ try { - Class<DocuImage> docuImageClass = (Class<DocuImage>) Class.forName(getAsString("docuimage-class")); + Class<DocuImage> docuImageClass = (Class<DocuImage>) Class.forName(config.getAsString("docuimage-class")); DocuImageFactory.setDocuImageClass(docuImageClass); // DocuImage class instance - newParameter("servlet.docuimage.class", docuImageClass, null, 's'); - newParameter("servlet.docuimage.version", DocuImageFactory.getInstance().getVersion(), null, 's'); + config.newParameter("servlet.docuimage.class", docuImageClass, null, 's'); + config.newParameter("servlet.docuimage.version", DocuImageFactory.getInstance().getVersion(), null, 's'); } catch (ClassNotFoundException e) { logger.error("Error setting DocuImage class!"); }
--- a/common/src/main/java/digilib/io/FileOps.java Wed Apr 10 09:33:19 2013 +0200 +++ b/common/src/main/java/digilib/io/FileOps.java Fri Apr 12 17:41:43 2013 +0200 @@ -400,4 +400,14 @@ return m; } + /** + * clean up any broken and unfinished files from the temporary directory. + */ + public static void emptyDirectory(File dir) { + File[] temp_files = dir.listFiles(); + for (File f : temp_files) { + f.delete(); + } + } + }
--- a/common/src/main/java/digilib/util/ParameterMap.java Wed Apr 10 09:33:19 2013 +0200 +++ b/common/src/main/java/digilib/util/ParameterMap.java Fri Apr 12 17:41:43 2013 +0200 @@ -315,7 +315,8 @@ return false; } - /** Returns of the option has been set. + /** + * Returns if the option has been set. * @param opt * @return */ @@ -323,18 +324,50 @@ return options.hasOption(opt); } + /** + * Returns a map with all Parameters of a type. + * @param type + * @return + */ + public HashMap<String, Parameter> getParameters(int type) { + HashMap<String, Parameter> map = new HashMap<String, Parameter>(); + for (String k : params.keySet()) { + Parameter p = params.get(k); + if (p.getType() == type) { + map.put(k, p); + } + } + return map; + } + + /** + * Returns the parameter Map. + * @return + */ public HashMap<String, Parameter> getParams() { return params; } + /** + * Sets the parameter Map. + * @param params + */ public void setParams(HashMap<String, Parameter> params) { this.params = params; } + /** + * Returns the options Set. + * @return + */ public OptionsSet getOptions() { return options; } + /** + * Sets the options Set. + * @param options + */ public void setOptions(OptionsSet options) { this.options = options; }
--- a/pdf/src/main/java/digilib/conf/PDFServletConfiguration.java Wed Apr 10 09:33:19 2013 +0200 +++ b/pdf/src/main/java/digilib/conf/PDFServletConfiguration.java Fri Apr 12 17:41:43 2013 +0200 @@ -1,5 +1,6 @@ package digilib.conf; +import java.io.File; import java.io.OutputStream; import java.util.List; @@ -7,6 +8,7 @@ import javax.servlet.ServletContextEvent; import digilib.image.DocuImage; +import digilib.io.FileOps; import digilib.util.DigilibJobCenter; /* @@ -40,21 +42,17 @@ * Class to hold the digilib servlet configuration parameters. The parameters * can be read from the digilib-config file and be passed to other servlets or * beans. <br> - * errorImgFileName: image file to send in case of error. <br> - * denyImgFileName: image file to send if access is denied. <br> - * baseDirs: array of base directories in order of preference (prescaled - * versions first). <br> - * useAuth: use authentication information. <br> - * authConfPath: authentication configuration file. <br> - * ... <br> * * @author casties * */ public class PDFServletConfiguration extends DigilibServletConfiguration { - private DigilibJobCenter<OutputStream> pdfExecutor; - private DigilibJobCenter<DocuImage> pdfImageExecutor; + public static final String PDFSERVLET_CONFIG_KEY = "digilib.pdfservlet.configuration"; + public static final String PDFIMAGEEXECUTOR_KEY = "pdfservlet.worker.pdfimageexecutor"; + public static final String PDFEXECUTOR_KEY = "pdfservlet.worker.pdfexecutor"; + public static final String PDFWORKDIR_KEY = "pdfservlet.work.dir"; + public static final String PDFCACHEDIR_KEY = "pdfservlet.cache.dir"; public String getVersion() { return "2.2.0 pdf"; @@ -71,9 +69,13 @@ */ // Executor for PDF operations - newParameter("servlet.worker.pdfexecutor", null, null, 's'); + newParameter(PDFEXECUTOR_KEY, null, null, 's'); // Executor for PDF-image operations - newParameter("servlet.worker.pdfimageexecutor", null, null, 's'); + newParameter(PDFIMAGEEXECUTOR_KEY, null, null, 's'); + // working directory for PDF generation + newParameter(PDFWORKDIR_KEY, null, null, 's'); + // cache directory for PDF files + newParameter(PDFCACHEDIR_KEY, null, null, 's'); /* * parameters that can be read from config file have a type 'f' @@ -99,17 +101,88 @@ @Override public void configure(ServletContext context) { super.configure(context); - PDFServletConfiguration dlConfig = this; + configurePdfServlet(context); + } + + /** + * @param config + * @param context + * + */ + protected void configurePdfServlet(ServletContext context) { + PDFServletConfiguration config = this; // PDF worker threads - int pnt = dlConfig.getAsInt("pdf-worker-threads"); - int pmt = dlConfig.getAsInt("pdf-max-waiting-threads"); - pdfExecutor = new DigilibJobCenter<OutputStream>(pnt, pmt, false, "servlet.worker.pdfexecutor"); - dlConfig.setValue("servlet.worker.pdfexecutor", pdfExecutor); + int pnt = config.getAsInt("pdf-worker-threads"); + int pmt = config.getAsInt("pdf-max-waiting-threads"); + DigilibJobCenter<OutputStream> pdfExecutor = new DigilibJobCenter<OutputStream>(pnt, pmt, false, "servlet.worker.pdfexecutor"); + config.setValue(PDFEXECUTOR_KEY, pdfExecutor); // PDF image worker threads - int pint = dlConfig.getAsInt("pdf-image-worker-threads"); - int pimt = dlConfig.getAsInt("pdf-image-max-waiting-threads"); - pdfImageExecutor = new DigilibJobCenter<DocuImage>(pint, pimt, false, "servlet.worker.pdfimageexecutor"); - dlConfig.setValue("servlet.worker.pdfimageexecutor", pdfImageExecutor); + int pint = config.getAsInt("pdf-image-worker-threads"); + int pimt = config.getAsInt("pdf-image-max-waiting-threads"); + DigilibJobCenter<DocuImage> pdfImageExecutor = new DigilibJobCenter<DocuImage>(pint, pimt, false, "servlet.worker.pdfimageexecutor"); + config.setValue(PDFIMAGEEXECUTOR_KEY, pdfImageExecutor); + /* + * set up temporary directories + */ + String temp_fn = config.getAsString("pdf-temp-dir"); + File temp_directory = new File(temp_fn); + if (!temp_directory.exists()) { + // try to create + temp_directory.mkdirs(); + } else { + // rid the temporary directory of possible incomplete document files + FileOps.emptyDirectory(temp_directory); + } + config.setValue(PDFWORKDIR_KEY, temp_directory); + String cache_fn = config.getAsString("pdf-cache-dir"); + File cache_directory = new File(cache_fn); + if (!cache_directory.exists()) { + // try to create + cache_directory.mkdirs(); + } + config.setValue(PDFCACHEDIR_KEY, cache_directory); + + /* + * set as the PDF servlets main config + */ + context.setAttribute(PDFSERVLET_CONFIG_KEY, this); + } + + /** + * Initialisation on first run. + */ + public void contextInitialized(ServletContextEvent cte) { + ServletContext context = cte.getServletContext(); + context.log("***** Digital Image Library PDF Servlet Configuration (" + getVersion() + ") *****"); + + // see if there is a Configuration instance + DigilibServletConfiguration dlConfig = DigilibServletConfiguration.getCurrentConfig(context); + DigilibServletConfiguration pdfConfig = PDFServletConfiguration.getCurrentConfig(context); + if (dlConfig == null && pdfConfig == null) { + // there is no config yet - full configure + try { + readConfig(context); + configure(context); + } catch (Exception e) { + logger.error("Error reading digilib servlet configuration:", e); + } + } else if (pdfConfig == null){ + // merge the existing config + logger.debug("PDFServletConfiguration re-using config!"); + try { + // read config file + readConfig(context); + // add configured 's' Parameters from dlConfig + params.putAll(dlConfig.getParameters('s')); + // just configure PDF stuff + logger.info("***** Digital Image Library PDF Servlet Configuration (" + getVersion() + ") *****"); + configurePdfServlet(context); + } catch (Exception e) { + logger.error("Error reading digilib servlet configuration:", e); + } + } else { + logger.warn("PDFServletConfiguration already configured!"); + } } /* (non-Javadoc) @@ -118,7 +191,11 @@ @Override public void contextDestroyed(ServletContextEvent sce) { super.contextDestroyed(sce); - if (pdfExecutor != null) { + ServletContext context = sce.getServletContext(); + DigilibServletConfiguration config = PDFServletConfiguration.getCurrentConfig(context); + @SuppressWarnings("unchecked") + DigilibJobCenter<DocuImage> pdfExecutor = (DigilibJobCenter<DocuImage>) config.getValue(PDFEXECUTOR_KEY); + if (pdfExecutor != null) { // shut down pdf thread pool List<Runnable> rj = pdfExecutor.shutdownNow(); int nrj = rj.size(); @@ -126,6 +203,8 @@ logger.error("Still running threads when shutting down PDF job queue: " + nrj); } } + @SuppressWarnings("unchecked") + DigilibJobCenter<DocuImage> pdfImageExecutor = (DigilibJobCenter<DocuImage>) config.getValue(PDFIMAGEEXECUTOR_KEY); if (pdfImageExecutor != null) { // shut down pdf image thread pool List<Runnable> rj = pdfImageExecutor.shutdownNow(); @@ -136,5 +215,15 @@ } } + /** + * Returns the current DigilibConfiguration from the context. + * + * @param context + * @return + */ + public static DigilibServletConfiguration getCurrentConfig(ServletContext context) { + DigilibServletConfiguration config = (DigilibServletConfiguration) context.getAttribute(PDFServletConfiguration.PDFSERVLET_CONFIG_KEY); + return config; + } }
--- a/pdf/src/main/java/digilib/servlet/PDFCache.java Wed Apr 10 09:33:19 2013 +0200 +++ b/pdf/src/main/java/digilib/servlet/PDFCache.java Fri Apr 12 17:41:43 2013 +0200 @@ -41,18 +41,20 @@ import digilib.conf.DigilibConfiguration; import digilib.conf.PDFRequest; +import digilib.conf.PDFServletConfiguration; import digilib.image.DocuImage; import digilib.pdf.PDFFileWorker; import digilib.util.DigilibJobCenter; /** - * A class for handling user requests for pdf documents made from digilib images. + * A class for handling user requests for pdf documents made from digilib + * images. * - * If a document does not already exist, it will be enqueued for generation; if it does exist, it is sent - * to the user. + * If a document does not already exist, it will be enqueued for generation; if + * it does exist, it is sent to the user. * * @author cmielack - * + * */ @SuppressWarnings("serial") @@ -69,109 +71,84 @@ /** logger for authentication related */ protected static Logger authlog = Logger.getLogger("digilib.pdf.auth"); - private DigilibConfiguration dlConfig = null; - - public static String instanceKey = "digilib.servlet.PDFCache"; - - private DigilibJobCenter<File> pdfJobCenter = null; - - private DigilibJobCenter<DocuImage> pdfImageJobCenter = null; - - private File cache_directory = new File("cache"); - - private File temp_directory = new File("pdf_temp"); - - private static String JSP_WIP = "/pdf/wip.jsp"; - - private static String JSP_ERROR = "/pdf/error.jsp"; - - /** document status. - * DONE: document exists in cache - * WIP: document is "work in progress" - * NONEXISTENT: document does not exist in cache and is not in progress - * ERROR: an error occurred while processing the request - */ - public static enum PDFStatus {DONE, WIP, NONEXISTENT, ERROR}; + private DigilibConfiguration dlConfig = null; + + public static String instanceKey = "digilib.servlet.PDFCache"; + + private DigilibJobCenter<File> pdfJobCenter = null; + + private DigilibJobCenter<DocuImage> pdfImageJobCenter = null; + + private File cacheDir = new File("cache"); + + private File workDir = new File("pdf_temp"); + + private static String JSP_WIP = "/pdf/wip.jsp"; - - @SuppressWarnings("unchecked") + private static String JSP_ERROR = "/pdf/error.jsp"; + + /** + * document status. DONE: document exists in cache WIP: document is + * "work in progress" NONEXISTENT: document does not exist in cache and is + * not in progress ERROR: an error occurred while processing the request + */ + public static enum PDFStatus { + DONE, WIP, NONEXISTENT, ERROR + }; + + @SuppressWarnings("unchecked") public void init(ServletConfig config) throws ServletException { - super.init(config); - - System.out.println("***** Digital Image Library Image PDF-Cache Servlet (version " - + version + ") *****"); - // say hello in the log file - logger.info("***** Digital Image Library Image PDF-Cache Servlet (version " - + version + ") *****"); + super.init(config); - ServletContext context = getServletContext(); - dlConfig = (DigilibConfiguration) context.getAttribute("digilib.servlet.configuration"); - if (dlConfig == null) { - // no Configuration - throw new ServletException("No Configuration!"); - } - - String temp_fn = dlConfig.getAsString("pdf-temp-dir"); - temp_directory = new File(temp_fn); - if (!temp_directory.exists()) { - // try to create - temp_directory.mkdirs(); - } else { - // rid the temporary directory of possible incomplete document files - emptyDirectory(temp_directory); - } - if (!temp_directory.isDirectory()) { - throw new ServletException("Configuration error: problem with pdf-temp-dir="+temp_fn); - } - - String cache_fn = dlConfig.getAsString("pdf-cache-dir"); - cache_directory = new File(cache_fn); - if (!cache_directory.exists()) { - // try to create - cache_directory.mkdirs(); - } - if (!cache_directory.isDirectory()) { - throw new ServletException("Configuration error: problem with pdf-cache-dir="+cache_fn); + System.out.println("***** Digital Image Library Image PDF-Cache Servlet (version " + version + ") *****"); + // say hello in the log file + logger.info("***** Digital Image Library Image PDF-Cache Servlet (version " + version + ") *****"); + + ServletContext context = getServletContext(); + dlConfig = PDFServletConfiguration.getCurrentConfig(context); + if (dlConfig == null) { + // no Configuration + throw new ServletException("No Configuration!"); + } + workDir = dlConfig.getAsFile(PDFServletConfiguration.PDFWORKDIR_KEY); + cacheDir = dlConfig.getAsFile(PDFServletConfiguration.PDFCACHEDIR_KEY); + if (!workDir.isDirectory()) { + throw new ServletException("Configuration error: problem with pdf-temp-dir=" + workDir); } + if (!cacheDir.isDirectory()) { + throw new ServletException("Configuration error: problem with pdf-cache-dir=" + cacheDir); + } + pdfJobCenter = (DigilibJobCenter<File>) dlConfig.getValue(PDFServletConfiguration.PDFEXECUTOR_KEY); + pdfImageJobCenter = (DigilibJobCenter<DocuImage>) dlConfig.getValue(PDFServletConfiguration.PDFIMAGEEXECUTOR_KEY); + // register this instance globally + context.setAttribute(instanceKey, this); + } - pdfJobCenter = (DigilibJobCenter<File>) dlConfig.getValue("servlet.worker.pdfexecutor"); - pdfImageJobCenter = (DigilibJobCenter<DocuImage>) dlConfig.getValue("servlet.worker.pdfimageexecutor"); - - // register this instance globally - context.setAttribute(instanceKey, this); - - } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + /* + * (non-Javadoc) + * + * @see + * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest + * , javax.servlet.http.HttpServletResponse) */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException { accountlog.info("GET from " + request.getRemoteAddr()); this.processRequest(request, response); } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + /* + * (non-Javadoc) + * + * @see + * javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest + * , javax.servlet.http.HttpServletResponse) */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { accountlog.info("POST from " + request.getRemoteAddr()); this.processRequest(request, response); } - - /** - * clean up any broken and unfinished files from the temporary directory. - */ - public void emptyDirectory(File dir){ - File[] temp_files = dir.listFiles(); - for (File f: temp_files){ - f.delete(); - } - } - - - public void processRequest(HttpServletRequest request, - HttpServletResponse response) throws ServletException { + + public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException { if (dlConfig == null) { logger.error("ERROR: No Configuration!"); @@ -179,54 +156,54 @@ } String docid = ""; - try { - // evaluate request ( make a PDFJobDeclaration , get the DocumentId) - PDFRequest pdfji = new PDFRequest(request, dlConfig); - - docid = pdfji.getDocumentId(); - - // if some invalid data has been entered ... - if(!pdfji.checkValidity()) { - notifyUser(PDFStatus.ERROR, docid, request, response); - return; - } - - PDFStatus status = getStatus(docid); - - if (status == PDFStatus.NONEXISTENT) { - // not there -- start creation - try { - createNewPdfDocument(pdfji, docid); - notifyUser(status, docid, request, response); - return; - } catch (FileNotFoundException e) { - // error in pdf creation - logger.error(e.getMessage()); - notifyUser(PDFStatus.ERROR, docid, request, response); - return; - } - } else if (status == PDFStatus.DONE) { - // pdf created -- send it - try { - ServletOps.sendFile(getCacheFile(docid), "application/pdf", getDownloadFilename(pdfji), response, logger); - return; - } catch (Exception e) { - // sending didn't work - logger.error(e.getMessage()); + try { + // evaluate request ( make a PDFJobDeclaration , get the DocumentId) + PDFRequest pdfji = new PDFRequest(request, dlConfig); + + docid = pdfji.getDocumentId(); + + // if some invalid data has been entered ... + if (!pdfji.checkValidity()) { + notifyUser(PDFStatus.ERROR, docid, request, response); return; } - } else { - // should be work in progress - notifyUser(status, docid, request, response); - return; - } - } catch (Exception e) { + + PDFStatus status = getStatus(docid); + + if (status == PDFStatus.NONEXISTENT) { + // not there -- start creation + try { + createNewPdfDocument(pdfji, docid); + notifyUser(status, docid, request, response); + return; + } catch (FileNotFoundException e) { + // error in pdf creation + logger.error(e.getMessage()); + notifyUser(PDFStatus.ERROR, docid, request, response); + return; + } + } else if (status == PDFStatus.DONE) { + // pdf created -- send it + try { + ServletOps.sendFile(getCacheFile(docid), "application/pdf", getDownloadFilename(pdfji), response, logger); + return; + } catch (Exception e) { + // sending didn't work + logger.error(e.getMessage()); + return; + } + } else { + // should be work in progress + notifyUser(status, docid, request, response); + return; + } + } catch (Exception e) { // error in pdf creation logger.error(e.getMessage()); notifyUser(PDFStatus.ERROR, docid, request, response); return; - } - } + } + } /** * depending on the documents status, redirect the user to the appropriate @@ -237,8 +214,7 @@ * @param request * @param response */ - public void notifyUser(PDFStatus status, String documentid, - HttpServletRequest request, HttpServletResponse response) { + public void notifyUser(PDFStatus status, String documentid, HttpServletRequest request, HttpServletResponse response) { String jsp = null; @@ -275,80 +251,81 @@ } - - /** check the status of the document corresponding to the documentid */ - public PDFStatus getStatus(String documentid){ - // looks into the cache and temp directory in order to find out the status of the document - File cached = getCacheFile(documentid); - File wip = getTempFile(documentid); - if(cached.exists()){ - return PDFStatus.DONE; - } else if (wip.exists()){ - return PDFStatus.WIP; - } else { - return PDFStatus.NONEXISTENT; - } - } + /** check the status of the document corresponding to the documentid */ + public PDFStatus getStatus(String documentid) { + // looks into the cache and temp directory in order to find out the + // status of the document + File cached = getCacheFile(documentid); + File wip = getTempFile(documentid); + if (cached.exists()) { + return PDFStatus.DONE; + } else if (wip.exists()) { + return PDFStatus.WIP; + } else { + return PDFStatus.NONEXISTENT; + } + } + + /** + * create new thread for pdf generation. + * + * @param pdfji + * @param filename + * @return + * @throws FileNotFoundException + */ + public Future<File> createNewPdfDocument(PDFRequest pdfji, String filename) throws FileNotFoundException { + // start new worker + File tempf = this.getTempFile(filename); + File finalf = this.getCacheFile(filename); + PDFFileWorker job = new PDFFileWorker(dlConfig, tempf, finalf, pdfji, pdfImageJobCenter); + // start job + Future<File> jobTicket = pdfJobCenter.submit(job); + return jobTicket; + } - /** - * create new thread for pdf generation. - * - * @param pdfji - * @param filename - * @return - * @throws FileNotFoundException - */ - public Future<File> createNewPdfDocument(PDFRequest pdfji, String filename) throws FileNotFoundException{ - // start new worker - File tempf = this.getTempFile(filename); - File finalf = this.getCacheFile(filename); - PDFFileWorker job = new PDFFileWorker(dlConfig, tempf, finalf, pdfji, pdfImageJobCenter); - // start job - Future<File> jobTicket = pdfJobCenter.submit(job); - return jobTicket; - } - - - /** - * generate the filename the user is going to receive the pdf as - * - * @param pdfji - * @return - */ - public String getDownloadFilename(PDFRequest pdfji){ - // filename example: digilib_example_pgs1-3.pdf - String filename; - filename = "digilib_"; - filename += pdfji.getAsString("fn"); - filename += "_pgs" + pdfji.getAsString("pgs"); - filename += ".pdf"; - - return filename; - } - - public File getCacheDirectory(){ - return cache_directory; - } - - public File getTempDirectory(){ - return temp_directory; - } - - /** - * returns a File object based on filename in the temp directory. - * @param filename - * @return - */ - public File getTempFile(String filename) { - return new File(temp_directory, filename); - } + /** + * generate the filename the user is going to receive the pdf as + * + * @param pdfji + * @return + */ + public String getDownloadFilename(PDFRequest pdfji) { + // filename example: digilib_example_pgs1-3.pdf + String filename; + filename = "digilib_"; + filename += pdfji.getAsString("fn"); + filename += "_pgs" + pdfji.getAsString("pgs"); + filename += ".pdf"; + + return filename; + } - /** + public File getCacheDirectory() { + return cacheDir; + } + + public File getTempDirectory() { + return workDir; + } + + /** + * returns a File object based on filename in the temp directory. + * + * @param filename + * @return + */ + public File getTempFile(String filename) { + return new File(workDir, filename); + } + + /** * returns a File object based on filename in the cache directory. + * * @param filename * @return */ public File getCacheFile(String filename) { - return new File(cache_directory, filename); + return new File(cacheDir, filename); } }
--- a/servlet/src/main/java/digilib/conf/DigilibServletConfiguration.java Wed Apr 10 09:33:19 2013 +0200 +++ b/servlet/src/main/java/digilib/conf/DigilibServletConfiguration.java Fri Apr 12 17:41:43 2013 +0200 @@ -71,11 +71,17 @@ */ public class DigilibServletConfiguration extends DigilibConfiguration implements ServletContextListener { - /** time the webapp (i.e. this class) was loaded */ + public static final String AUTH_OP_KEY = "servlet.auth.op"; + + public static final String IMAGEEXECUTOR_KEY = "servlet.worker.imageexecutor"; + + public static final String SERVLET_CONFIG_KEY = "digilib.servlet.configuration"; + + public static final String DIR_CACHE_KEY = "servlet.dir.cache"; + + /** the time the webapp (i.e. this class) was loaded */ public final Long webappStartTime = System.currentTimeMillis(); - private DigilibJobCenter<DocuImage> imageExecutor; - public String getVersion() { return "2.2.0 srv"; } @@ -94,12 +100,12 @@ // configuration file location newParameter("servlet.config.file", null, null, 's'); // DocuDirCache instance - newParameter("servlet.dir.cache", null, null, 's'); + newParameter(DIR_CACHE_KEY, null, null, 's'); // Executor for image operations - newParameter("servlet.worker.imageexecutor", null, null, 's'); + newParameter(IMAGEEXECUTOR_KEY, null, null, 's'); // AuthOps instance - newParameter("servlet.auth.op", null, null, 's'); - // classes TODO: do we need this? + newParameter(AUTH_OP_KEY, null, null, 's'); + // classes TODO: do we need these as parameters? newParameter("servlet.filemeta.class", null, null, 's'); newParameter("servlet.dirmeta.class", null, null, 's'); newParameter("servlet.authops.class", null, null, 's'); @@ -151,7 +157,7 @@ public void readConfig(ServletContext c) throws SAXException, IOException { /* - * Get config file name. The file name is first looked for as an init + * Get config file. The file name is first looked for as an init * parameter, then in a fixed location in the webapp. */ if (c == null) { @@ -178,13 +184,13 @@ */ for (Entry<String, String> confEntry : confTable.entrySet()) { - Parameter p = get(confEntry.getKey()); - if (p != null) { - if (p.getType() == 's') { + Parameter param = get(confEntry.getKey()); + if (param != null) { + if (param.getType() == 's') { // type 's' Parameters are not overwritten. continue; } - if (!p.setValueFromString(confEntry.getValue())) { + if (!param.setValueFromString(confEntry.getValue())) { /* * automatic conversion failed -- try special cases */ @@ -194,18 +200,17 @@ // split list into directories String[] dirs = FileOps.pathToArray(confEntry.getValue()); for (int j = 0; j < dirs.length; j++) { - // make relative directory paths be inside the - // webapp + // make relative directory paths be inside the webapp dirs[j] = ServletOps.getFile(dirs[j], c); } if (dirs != null) { - p.setValue(dirs); + param.setValue(dirs); } } } } else { // parameter unknown -- just add - newParameter(confEntry.getKey(), null, confEntry.getValue(), 'f'); + newParameter(confEntry.getKey(), null, confEntry.getValue(), 'u'); } } } else { @@ -213,8 +218,7 @@ // update basedir-list String[] dirs = (String[]) this.getValue("basedir-list"); for (int j = 0; j < dirs.length; j++) { - // make relative directory paths be inside the - // webapp + // make relative directory paths be inside the webapp dirs[j] = ServletOps.getFile(dirs[j], c); } } @@ -228,25 +232,26 @@ */ @SuppressWarnings("unchecked") public void configure(ServletContext context) { + DigilibServletConfiguration config = this; super.configure(); /* * configure factories */ try { // initialise MetaFactory - Class<FileMeta> fileMetaClass = (Class<FileMeta>) Class.forName(getAsString("filemeta-class")); - setValue("servlet.filemeta.class", fileMetaClass); + Class<FileMeta> fileMetaClass = (Class<FileMeta>) Class.forName(config.getAsString("filemeta-class")); + config.setValue("servlet.filemeta.class", fileMetaClass); MetaFactory.setFileMetaClass(fileMetaClass); - Class<DirMeta> dirMetaClass = (Class<DirMeta>) Class.forName(getAsString("dirmeta-class")); - setValue("servlet.dirmeta.class", dirMetaClass); + Class<DirMeta> dirMetaClass = (Class<DirMeta>) Class.forName(config.getAsString("dirmeta-class")); + config.setValue("servlet.dirmeta.class", dirMetaClass); MetaFactory.setDirMetaClass(dirMetaClass); } catch (ClassNotFoundException e) { logger.error("Error setting Metadata classes!"); } try { // initialise AuthOpsFactory - Class<AuthOps> authOpsClass = (Class<AuthOps>) Class.forName(getAsString("authops-class")); - setValue("servlet.authops.class", authOpsClass); + Class<AuthOps> authOpsClass = (Class<AuthOps>) Class.forName(config.getAsString("authops-class")); + config.setValue("servlet.authops.class", authOpsClass); AuthOpsFactory.setAuthOpsClass(authOpsClass); } catch (ClassNotFoundException e) { logger.error("Error setting AuthOps class!"); @@ -255,48 +260,48 @@ * configure singletons */ // set up the logger - File logConf = ServletOps.getConfigFile((File) this.getValue("log-config-file"), context); + File logConf = ServletOps.getConfigFile((File) config.getValue("log-config-file"), context); if (logConf.canRead()) { DOMConfigurator.configure(logConf.getAbsolutePath()); - this.setValue("log-config-file", logConf); + config.setValue("log-config-file", logConf); } // say hello in the log file logger.info("***** Digital Image Library Configuration (version " + getVersion() + ") *****"); try { // directory cache - String[] bd = (String[]) this.getValue("basedir-list"); + String[] bd = (String[]) config.getValue("basedir-list"); FileClass[] fcs = { FileClass.IMAGE, FileClass.TEXT }; DocuDirCache dirCache; - if (this.getAsBoolean("use-mapping")) { + if (config.getAsBoolean("use-mapping")) { // with mapping file - File mapConf = ServletOps.getConfigFile((File) this.getValue("mapping-file"), context); - dirCache = new AliasingDocuDirCache(bd, fcs, mapConf, this); - this.setValue("mapping-file", mapConf); + File mapConf = ServletOps.getConfigFile((File) config.getValue("mapping-file"), context); + dirCache = new AliasingDocuDirCache(bd, fcs, mapConf, config); + config.setValue("mapping-file", mapConf); } else { // without mapping dirCache = new DocuDirCache(bd, fcs, this); } - this.setValue("servlet.dir.cache", dirCache); + config.setValue(DIR_CACHE_KEY, dirCache); // useAuthentication - if (this.getAsBoolean("use-authorization")) { + if (config.getAsBoolean("use-authorization")) { AuthOps authOp = AuthOpsFactory.getAuthOpsInstance(); // get config file - File authConf = ServletOps.getConfigFile((File) this.getValue("auth-file"), context); + File authConf = ServletOps.getConfigFile((File) config.getValue("auth-file"), context); if (authConf != null) { authOp.setConfig(authConf); } - this.setValue("servlet.auth.op", authOp); - this.setValue("auth-file", authConf); + config.setValue(AUTH_OP_KEY, authOp); + config.setValue("auth-file", authConf); } // digilib worker threads - int nt = this.getAsInt("worker-threads"); - int mt = this.getAsInt("max-waiting-threads"); - imageExecutor = new DigilibJobCenter<DocuImage>(nt, mt, false, "servlet.worker.imageexecutor"); - this.setValue("servlet.worker.imageexecutor", imageExecutor); + int nt = config.getAsInt("worker-threads"); + int mt = config.getAsInt("max-waiting-threads"); + DigilibJobCenter<DocuImage> imageExecutor = new DigilibJobCenter<DocuImage>(nt, mt, false, IMAGEEXECUTOR_KEY); + config.setValue(IMAGEEXECUTOR_KEY, imageExecutor); /* * set as the servlets main config */ - context.setAttribute("digilib.servlet.configuration", this); + context.setAttribute(SERVLET_CONFIG_KEY, this); } catch (Exception e) { logger.error("Error configuring digilib servlet:", e); } @@ -307,12 +312,12 @@ */ public void contextInitialized(ServletContextEvent cte) { ServletContext context = cte.getServletContext(); - context.log("***** Digital Image Library Configuration (version " + getVersion() + ") *****"); - + context.log("***** Digital Image Library Configuration (" + getVersion() + ") *****"); // see if there is a Configuration instance - DigilibServletConfiguration dlConfig = (DigilibServletConfiguration) context.getAttribute("digilib.servlet.configuration"); + DigilibServletConfiguration dlConfig = getCurrentConfig(context); if (dlConfig == null) { try { + // initialise this instance readConfig(context); configure(context); } catch (Exception e) { @@ -325,11 +330,16 @@ } /** - * clean up local resources + * Clean up local resources * */ - public void contextDestroyed(ServletContextEvent arg0) { + public void contextDestroyed(ServletContextEvent cte) { logger.info("DigilibServletConfiguration shutting down."); + // get current config from servlet context + ServletContext context = cte.getServletContext(); + DigilibServletConfiguration config = getCurrentConfig(context); + @SuppressWarnings("unchecked") + DigilibJobCenter<DocuImage> imageExecutor = (DigilibJobCenter<DocuImage>) config.getValue(IMAGEEXECUTOR_KEY); if (imageExecutor != null) { // shut down image thread pool List<Runnable> rj = imageExecutor.shutdownNow(); @@ -340,4 +350,15 @@ } } + /** + * Returns the current DigilibConfiguration from the context. + * + * @param context + * @return + */ + public static DigilibServletConfiguration getCurrentConfig(ServletContext context) { + DigilibServletConfiguration config = (DigilibServletConfiguration) context.getAttribute(DigilibServletConfiguration.SERVLET_CONFIG_KEY); + return config; + } + }