View Javadoc

1   /*
2    * Created on Dec 25, 2004 by Justin Sher
3    *
4    *  ginp - Java Web Application for Viewing Photo Collections
5    *
6    *  This library is free software; you can redistribute it and/or
7    *  modify it under the terms of the GNU Lesser General Public
8    *  License as published by the Free Software Foundation; either
9    *  version 2.1 of the License, or any later version.
10   *
11   *  This library is distributed in the hope that it will be useful,
12   *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13   *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14   *  Lesser General Public License for more details.
15   *
16   *  You should have received a copy of the GNU Lesser General Public
17   *  License along with this library; if not, write to the Free Software
18   *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
19   */
20  package net.sf.ginp.config;
21  
22  import java.io.File;
23  import java.io.FileInputStream;
24  import java.io.FileWriter;
25  import java.util.ArrayList;
26  import java.util.Iterator;
27  import java.util.List;
28  
29  import net.sf.ginp.PicCollection;
30  import net.sf.ginp.util.StringTool;
31  import net.sf.ginp.setup.SetupManager;
32  
33  import org.dom4j.Document;
34  import org.dom4j.DocumentHelper;
35  import org.dom4j.Element;
36  import org.dom4j.io.XMLWriter;
37  import org.dom4j.io.OutputFormat;
38  import org.dom4j.tree.DefaultDocumentType;
39  
40  import org.apache.commons.logging.Log;
41  import org.apache.commons.logging.LogFactory;
42  
43  import javax.servlet.http.HttpServletRequest;
44  
45  /**
46   * Represents a parsed ginp.xml configuration
47   * @author Justin Sher
48   */
49  public class Configuration {
50   
51      static int     thumbSize;
52      static int     filmStripThumbSize;
53      static String  picturePageName;
54      static String  collectionPageName;    
55      static String  forcelocale;        
56      static String  characterEncoding    = "UTF-8";
57      static String  configfilelocation;  
58      static boolean configOK             = false;
59      static boolean useDataBase          = false;
60  	private static Document document;
61  	public static final String PATH_TO_CONFIG_FROM_WEBROOT = "/WEB-INF/ginp.xml";
62  	private static Log log = LogFactory.getLog(Configuration.class);
63      
64      
65  	/**
66  	 * Constructor
67  	 */
68      public Configuration(){}  
69  	
70  	/**
71  	 * @param configFile the config file to read
72  	 * @throws java.io.IOException
73  	 * @throws net.sf.ginp.setup.SetupException
74  	 */
75  	private static void readConfig() {
76  		
77          try {
78              
79              //Parse Ginp Config File
80              File confFile = new File(configfilelocation);
81              
82              if (confFile.exists()) {
83  		        FileInputStream fis=new FileInputStream(confFile);		
84  		        SetupManager service = ModelUtil.getSetupManager();
85                  document = service.testValidConfig(fis);
86                  configOK = true;
87              } else {
88                  
89                  // log that we have no config
90                  log.warn("No configuration at: " + configfilelocation);
91                  log.warn("Setting up standard configuration document.");
92                  configOK = false;
93                  
94                  // Make new default config.
95                  DefaultDocumentType docType = new DefaultDocumentType(
96                          "ginp", "-//GINP//DTD ginp XML//EN", "ginp.dtd");
97                  
98                  document = DocumentHelper.createDocument();
99                  document.setDocType(docType);
100                             
101                 Element root = document.addElement("ginp");
102                 root.addAttribute("characterencoding", "UTF-8");
103                 root.addAttribute("thumbsize", "200");
104                 root.addAttribute("filmstripthumbsize",  "100");
105                 root.addAttribute("picturepagename",  "picture.jsp");
106                 root.addAttribute("collectionpagename",  "collection.jsp");
107                 
108                 // TODO: Add Admin
109                 Element user = root.addElement("user")
110                         .addAttribute("fullname", "Administrator")
111                         .addAttribute("username", "admin")
112                         .addAttribute("userpass", "");
113             }
114                 
115             // set static vars once.
116             forcelocale = document.valueOf("/ginp/@forcelocale");
117             thumbSize = document.numberValueOf("/ginp/@thumbsize").intValue();
118             filmStripThumbSize = document.numberValueOf("/ginp/@filmstripthumbsize").intValue();
119             picturePageName = document.valueOf("/ginp/@picturepagename");
120             collectionPageName = document.valueOf("/ginp/@collectionpagename");
121             characterEncoding = document.valueOf("/ginp/@characterencoding");
122             
123             // wrtie to debug output.
124             if (log.isDebugEnabled()) {
125                 log.debug("Setting Configuation: forcelocale=" + forcelocale);
126                 log.debug("Setting Configuation: thumbSize=" + thumbSize);
127                 log.debug("Setting Configuation: filmStripThumbSize=" + filmStripThumbSize);
128                 log.debug("Setting Configuation: getPicturePageName=" + picturePageName);
129                 log.debug("Setting Configuation: getCollectionPageName=" + collectionPageName);
130                 log.debug("Setting Configuation: characterEncoding=" + characterEncoding);
131             }
132             log.info("Read configuration at: " + configfilelocation);
133         } catch (Exception ex) {
134             configOK = false;
135             log.error("Error reading configuration file located at: " 
136                 + configfilelocation, ex);
137         }
138 	}
139 
140 
141 	/**
142 	 * Gets the configurations available to a particular user
143 	 * @param user the name of the user
144 	 * @return the collections available
145 	 */
146 	public static List getCollectionForUser(String user) {
147         //Quote the user value as it's being passed in via the web
148         String escapeUser = StringTool.XMLEscape(user);
149         
150         //Find user collections that have zero users or the given user 
151         List elem = document.selectNodes("/ginp/collection[count(./users/username)=0 or ./users/username='"+escapeUser+"' or ./admins/username='"+escapeUser+"']");
152         
153         //Use XML Elements to initialize collection objects
154         Iterator iter=elem.iterator();
155         ArrayList collections=new ArrayList();
156         while (iter.hasNext())  {
157         	Element object = (Element) iter.next();
158         	collections.add(new PicCollection(object));
159         }
160         return collections;
161 	}
162 
163     public static boolean  useDataBase(){
164         return useDataBase;
165     }
166 	
167     /**
168 	 * Validate a user
169 	 * @param userName username
170 	 * @param userPass password
171 	 * @return if the user is valid or not
172 	 */
173 	public static Boolean accessCheck(String userName, String userPass) {
174         //Find user collections that have zero users or the given user
175 		
176 		String xpath="/ginp/user[@username='"+ StringTool.XMLEscape(userName)+"' and @userpass='"+StringTool.XMLEscape(userPass)+"']";
177         List elem = document.selectNodes(xpath);
178         return new Boolean(elem.size()>0);
179 		
180 	}
181     
182     
183     public static String getForcelocale(){
184         return forcelocale;
185     }
186     
187     /**
188      * Get the maximum dimension of thumbnail images.
189      *
190      * @return  The maximum thumbnail dimension in pixels.
191      */
192     public static int getThumbSize(){
193         return thumbSize;
194     }
195     
196     /**
197      * Get the maximum dimension of the film strip navigator thumbnail images.
198      *
199      * @todo    This config param should come from the XML config file.
200      * @return  The maximum  film strip navigator thumbnail dimension in pixels.
201      */
202     public static int getFilmStripThumbSize(){
203         return filmStripThumbSize;
204     } 
205     
206     /**
207       * This is the name of the page where the individial picture is to be 
208       * displayed.
209       *
210       * @todo    This config param should come from the XML config file.
211       * @return  The name of the page where the picture will be shown.
212       */
213     public static String getPicturePageName() {
214         return picturePageName;
215     }
216     
217     /**
218       * This is the name of the page where the selected set of pictures are 
219       * are to be displayed, as a collection of pictures.
220       *
221       * @todo    This config param should come from the XML config file.
222       * @return  The name of the page where the folder contents will be shown.
223       */
224     public static String getCollectionPageName() {
225         return collectionPageName;
226     }
227     
228     public static String getCharacterEncoding() {
229         return characterEncoding;
230     } 
231     
232    public static boolean configOK(){
233        if (!configOK){
234            readConfig();
235        }
236        return configOK;
237    }
238     
239    /**
240 	 * Returns the value of configfilelocation (path and filename)
241 	 */
242 	public static String getConfigfilelocation(){
243 		return configfilelocation;
244 	}
245 
246    /**
247 	 * Returns the file system path of configfilelocation.
248 	 */
249 	public static String getConfigfilelocationPath(){
250             String confDirPath = null;          // establish the default
251             String confFileLocation = getConfigfilelocation();
252             if(confFileLocation!=null) {
253                 confDirPath = confFileLocation.substring(0,
254                     confFileLocation.lastIndexOf(File.separator));
255             }
256             return confDirPath;
257 	}
258 
259 	/**
260 	 * Sets the value of configfilelocation.
261 	 * @param configfilelocation The value to assign configfilelocation.
262 	 */
263     public static void setConfigfilelocation(HttpServletRequest req) {
264 		setConfigfilelocation(req.getSession().getServletContext().getRealPath(PATH_TO_CONFIG_FROM_WEBROOT));
265 	}
266 	
267     /**
268 	 * Sets the value of configfilelocation.
269 	 * @param configfilelocation The value to assign configfilelocation.
270 	 */
271     public static void setConfigfilelocation(String newConfigFile) {
272 		configfilelocation = newConfigFile;
273 		if (log.isDebugEnabled()) {
274 			log.debug("Config location is: " + newConfigFile);
275 		}
276         readConfig();
277 	}
278     
279 	/**
280 	 * Sets the value of thumbSize.
281 	 * @param thumbSize The value to assign thumbSize.
282 	 */
283 	static public void setThumbSize(String newThumbSize)	{
284         try {
285             Integer iTmp = new Integer(newThumbSize);
286             thumbSize = iTmp.intValue();
287         } catch (Exception ex) {
288             log.error("Error seting thumbSize in Configuration", ex);
289         }
290 	}
291 
292 	/**
293 	 * Sets the value of filmStripThumbSize.
294 	 * @param filmStripThumbSize The value to assign filmStripThumbSize.
295 	 */
296 	static public void setFilmStripThumbSize(String newFilmStripThumbSize){
297         try {
298             Integer iTmp = new Integer(newFilmStripThumbSize);
299             filmStripThumbSize = iTmp.intValue();
300         } catch (Exception ex) {
301             log.error("Error seting filmStripThumbSize in Configuration", ex);
302         }
303 	}
304 
305 	/**
306 	 * Sets the value of picturePageName.
307 	 * @param picturePageName The value to assign picturePageName.
308 	 */
309 	static public void setPicturePageName(String newPicturePageName) {
310 		picturePageName = newPicturePageName;
311 	}
312 
313 	/**
314 	 * Sets the value of collectionPageName.
315 	 * @param collectionPageName The value to assign collectionPageName.
316 	 */
317 	static public void setCollectionPageName(String newCollectionPageName) {
318 		collectionPageName = newCollectionPageName;
319 	}
320 
321 	/**
322 	 * Sets the value of forcelocale.
323 	 * @param forcelocale The value to assign forcelocale.
324 	 */
325 	static public void setForcelocale(String newForcelocale) {
326 		forcelocale = newForcelocale;
327 	}
328 
329 	/**
330 	 * Sets the value of "UTF-8".
331 	 * @param "UTF-8" The value to assign "UTF-8".
332 	 */
333 	static public void setCharacterEncoding(String newCharacterEncoding){
334 		characterEncoding = newCharacterEncoding;
335 	}
336     
337 	static public void setAdminpassword(String newAdminpassword){
338         log.info("Setting new Adminpassword: " + newAdminpassword);
339         /* 
340         ToDo Fix this.
341          */
342         log.info(document.selectSingleNode("/ginp/user[@username='admin']").toString()); 
343         //log.info(document.selectSingleNode("/ginp/user[@username='admin']/userpass").toString()); 
344         document.selectSingleNode("/ginp/user[@username='admin']")
345                 .selectSingleNode("./userpass").setText(newAdminpassword);
346     }
347     
348     /**
349      *  Saves current settings to Disk.
350      */
351     static public void writeConfig(){
352         try {
353             OutputFormat format = OutputFormat.createPrettyPrint();
354             XMLWriter writer = new XMLWriter(new FileWriter(configfilelocation), format);
355             writer.write(document);
356             writer.close();
357             log.info("Writen config file to disk.");
358             
359             // check It
360             try {
361                 FileInputStream fis=new FileInputStream(new File(configfilelocation));
362                 SetupManager service = ModelUtil.getSetupManager();
363                 document = service.testValidConfig(fis);
364                 configOK = true;
365             } catch (Exception ex) {
366                 log.error("Error parsing new config file",ex);
367             }
368         
369         } catch (Exception e) {
370             log.error("Error writing config file to disk.", e);
371         }
372         readConfig();
373         
374     }
375 }