Java tutorial
/* * ginp - Java Web Application for Viewing Photo Collections * Copyright (C) 2004 Douglas John Culnane <doug@culnane.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA */ package net.sf.ginp.config; import net.sf.ginp.PicCollection; import net.sf.ginp.setup.SetupManager; import net.sf.ginp.util.StringTool; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import org.dom4j.tree.DefaultDocumentType; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; /** * Represents a parsed ginp.xml configuration. * @author Justin Sher */ public final class Configuration { static int thumbSize; static int filmStripThumbSize; static String picturePageName; static String collectionPageName; static String forcelocale; static String characterEncoding = "UTF-8"; static String configfilelocation; static boolean configOK = false; static boolean useDataBase = false; private static Document document; public static final String PATH_TO_CONFIG_FROM_WEBROOT = "/WEB-INF/ginp.xml"; /** * apache Commons Logger specific to this class. */ private static Log log = LogFactory.getLog(Configuration.class); /** * static-only utility classes should not have a * public Constructor. */ private Configuration() { } /** * @throws java.io.IOException * @throws net.sf.ginp.setup.SetupException */ private static void readConfig() { try { //Parse Ginp Config File File confFile = new File(configfilelocation); if (confFile.exists()) { FileInputStream fis = new FileInputStream(confFile); SetupManager service = ModelUtil.getSetupManager(); document = service.testValidConfig(fis); configOK = true; } else { // log that we have no config log.warn("No configuration at: " + configfilelocation); log.warn("Setting up standard configuration document."); configOK = false; // Make new default config. DefaultDocumentType docType = new DefaultDocumentType("ginp", "-//GINP//DTD ginp XML//EN", "ginp.dtd"); document = DocumentHelper.createDocument(); document.setDocType(docType); Element root = document.addElement("ginp"); root.addAttribute("characterencoding", "UTF-8"); root.addAttribute("thumbsize", "200"); root.addAttribute("filmstripthumbsize", "100"); root.addAttribute("picturepagename", "picture.jsp"); root.addAttribute("collectionpagename", "collection.jsp"); // TODO: Add Admin Element user = root.addElement("user").addAttribute("fullname", "Administrator") .addAttribute("username", "admin").addAttribute("userpass", ""); } // set static vars once. forcelocale = document.valueOf("/ginp/@forcelocale"); thumbSize = document.numberValueOf("/ginp/@thumbsize").intValue(); filmStripThumbSize = document.numberValueOf("/ginp/@filmstripthumbsize").intValue(); picturePageName = document.valueOf("/ginp/@picturepagename"); collectionPageName = document.valueOf("/ginp/@collectionpagename"); characterEncoding = document.valueOf("/ginp/@characterencoding"); // wrtie to debug output. if (log.isDebugEnabled()) { log.debug("Setting Configuation: forcelocale=" + forcelocale); log.debug("Setting Configuation: thumbSize=" + thumbSize); log.debug("Setting Configuation: filmStripThumbSize=" + filmStripThumbSize); log.debug("Setting Configuation: getPicturePageName=" + picturePageName); log.debug("Setting Configuation: getCollectionPageName=" + collectionPageName); log.debug("Setting Configuation: characterEncoding=" + characterEncoding); } log.info("Read configuration at: " + configfilelocation); } catch (Exception ex) { configOK = false; log.error("Error reading configuration file located at: " + configfilelocation, ex); } } /** * Gets the configurations available to a particular user. * @param user the name of the user * @return the collections available */ public static List getCollectionForUser(final String user) { //Quote the user value as it's being passed in via the web String escapeUser = StringTool.XMLEscape(user); //Find user collections that have zero users or the given user List elem = document.selectNodes("/ginp/collection[count(./users/username)=0 or ./users/username='" + escapeUser + "' or ./admins/username='" + escapeUser + "']"); //Use XML Elements to initialize collection objects Iterator iter = elem.iterator(); ArrayList collections = new ArrayList(); while (iter.hasNext()) { Element object = (Element) iter.next(); collections.add(new PicCollection(object)); } return collections; } public static boolean useDataBase() { return useDataBase; } /** * Validate a user. * @param userName username * @param userPass password * @return if the user is valid or not */ public static Boolean accessCheck(final String userName, final String userPass) { //Find user collections that have zero users or the given user String xpath = "/ginp/user[@username='" + StringTool.XMLEscape(userName) + "' and @userpass='" + StringTool.XMLEscape(userPass) + "']"; List elem = document.selectNodes(xpath); return new Boolean(elem.size() > 0); } public static String getForcelocale() { return forcelocale; } /** * Get the maximum dimension of thumbnail images. * * @return The maximum thumbnail dimension in pixels. */ public static int getThumbSize() { return thumbSize; } /** * Get the maximum dimension of the film strip navigator thumbnail images. * * @todo This config param should come from the XML config file. * @return The maximum film strip navigator thumbnail dimension in pixels. */ public static int getFilmStripThumbSize() { return filmStripThumbSize; } /** * This is the name of the page where the individial picture is to be * displayed. * * @todo This config param should come from the XML config file. * @return The name of the page where the picture will be shown. */ public static String getPicturePageName() { return picturePageName; } /** * This is the name of the page where the selected set of pictures are * are to be displayed, as a collection of pictures. * * @todo This config param should come from the XML config file. * @return The name of the page where the folder contents will be shown. */ public static String getCollectionPageName() { return collectionPageName; } public static String getCharacterEncoding() { return characterEncoding; } public static boolean configOK() { if (!configOK) { readConfig(); } return configOK; } /** * Returns the value of configfilelocation (path and filename). */ public static String getConfigfilelocation() { return configfilelocation; } /** * Returns the file system path of configfile location. */ public static String getConfigfilelocationPath() { String confDirPath = null; // establish the default String confFileLocation = getConfigfilelocation(); if (confFileLocation != null) { confDirPath = confFileLocation.substring(0, confFileLocation.lastIndexOf(File.separator)); } return confDirPath; } /** * Sets the default value of configfilelocation. * @param req The current servlet request */ public static void setConfigfilelocation(final HttpServletRequest req) { setConfigfilelocation(req.getSession().getServletContext().getRealPath(PATH_TO_CONFIG_FROM_WEBROOT)); } /** * Sets the value of configfilelocation. * @param newConfigFile The value to assign configfilelocation. */ public static void setConfigfilelocation(final String newConfigFile) { configfilelocation = newConfigFile; if (log.isDebugEnabled()) { log.debug("Config location is: " + newConfigFile); } readConfig(); } /** * Sets the value of thumbSize. * @param newThumbSize The value to assign thumbSize. */ public static void setThumbSize(final String newThumbSize) { try { Integer iTmp = new Integer(newThumbSize); thumbSize = iTmp.intValue(); } catch (Exception ex) { log.error("Error seting thumbSize in Configuration", ex); } } /** * Sets the value of filmStripThumbSize. * @param newFilmStripThumbSize The value to assign filmStripThumbSize. */ public static void setFilmStripThumbSize(final String newFilmStripThumbSize) { try { Integer iTmp = new Integer(newFilmStripThumbSize); filmStripThumbSize = iTmp.intValue(); } catch (Exception ex) { log.error("Error seting filmStripThumbSize in Configuration", ex); } } /** * Sets the value of picturePageName. * @param newPicturePageName The value to assign picturePageName. */ public static void setPicturePageName(final String newPicturePageName) { picturePageName = newPicturePageName; } /** * Sets the value of collectionPageName. * @param newCollectionPageName The value to assign collectionPageName. */ public static void setCollectionPageName(final String newCollectionPageName) { collectionPageName = newCollectionPageName; } /** * Sets the value of forcelocale. * @param newForcelocale The value to assign forcelocale. */ public static void setForcelocale(final String newForcelocale) { forcelocale = newForcelocale; } /** * Sets the value of "UTF-8". * @param newCharacterEncoding The value to assign "UTF-8". */ public static void setCharacterEncoding(final String newCharacterEncoding) { characterEncoding = newCharacterEncoding; } public static void setAdminpassword(final String newAdminpassword) { log.info("Setting new Adminpassword: " + newAdminpassword); /* ToDo Fix this. */ log.info(document.selectSingleNode("/ginp/user[@username='admin']").toString()); //log.info(document.selectSingleNode( //"/ginp/user[@username='admin']/userpass").toString()); document.selectSingleNode("/ginp/user[@username='admin']").selectSingleNode("./userpass") .setText(newAdminpassword); } /** * Saves current settings to Disk. */ public static void writeConfig() { try { OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter(configfilelocation), format); writer.write(document); writer.close(); log.info("Writen config file to disk."); // check It try { FileInputStream fis = new FileInputStream(new File(configfilelocation)); SetupManager service = ModelUtil.getSetupManager(); document = service.testValidConfig(fis); configOK = true; } catch (Exception ex) { log.error("Error parsing new config file", ex); } } catch (Exception e) { log.error("Error writing config file to disk.", e); } readConfig(); } }