KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ivata > groupware > admin > struts > HibernateSetupAction


1 /*
2  * Copyright (c) 2001 - 2005 ivata limited.
3  * All rights reserved.
4  * ---------------------------------------------------------
5  * ivata groupware may be redistributed under the GNU General Public
6  * License as published by the Free Software Foundation;
7  * version 2 of the License.
8  *
9  * These programs are free software; you can redistribute them and/or
10  * modify them under the terms of the GNU General Public License
11  * as published by the Free Software Foundation; version 2 of the License.
12  *
13  * These programs are distributed in the hope that they will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16  *
17  * See the GNU General Public License in the file LICENSE.txt for more
18  * details.
19  *
20  * If you would like a copy of the GNU General Public License write to
21  *
22  * Free Software Foundation, Inc.
23  * 59 Temple Place - Suite 330
24  * Boston, MA 02111-1307, USA.
25  *
26  *
27  * To arrange commercial support and licensing, contact ivata at
28  * http://www.ivata.com/contact.jsp
29  * ---------------------------------------------------------
30  * $Log: HibernateSetupAction.java,v $
31  * Revision 1.5 2005/05/10 20:07:14 colinmacleod
32  * Workaround for tomcat 5.0.x (creates
33  * copy of 'res' HSQLDB).
34  *
35  * Revision 1.4 2005/04/30 13:02:36 colinmacleod
36  * Added checking and removal of previous
37  * hibernate lock file.
38  *
39  * Revision 1.3 2005/04/28 18:47:06 colinmacleod
40  * Fixed XHMTL, styles and resin compatibility.
41  * Added support for URL rewriting.
42  *
43  * Revision 1.2 2005/04/22 09:34:21 colinmacleod
44  * Added setup action interface so that
45  * the hibernate action can reset/delete all
46  * actions when the container is reloaded.
47  *
48  * Revision 1.1 2005/04/11 10:03:43 colinmacleod
49  * Added setup feature.
50  *
51  * ---------------------------------------------------------
52  */

53 package com.ivata.groupware.admin.struts;
54
55 import java.io.File JavaDoc;
56 import java.io.FileNotFoundException JavaDoc;
57 import java.io.FileOutputStream JavaDoc;
58 import java.io.FileReader JavaDoc;
59 import java.io.FileWriter JavaDoc;
60 import java.io.IOException JavaDoc;
61 import java.io.InputStream JavaDoc;
62 import java.io.OutputStream JavaDoc;
63 import java.sql.Connection JavaDoc;
64 import java.sql.DriverManager JavaDoc;
65 import java.sql.ResultSet JavaDoc;
66 import java.sql.Statement JavaDoc;
67 import java.util.Map JavaDoc;
68
69 import javax.servlet.http.HttpServletRequest JavaDoc;
70 import javax.servlet.http.HttpServletResponse JavaDoc;
71 import javax.servlet.http.HttpSession JavaDoc;
72
73 import net.sf.hibernate.Hibernate;
74 import net.sf.hibernate.util.DTDEntityResolver;
75
76 import org.apache.log4j.Logger;
77 import org.apache.struts.Globals;
78 import org.apache.struts.action.ActionErrors;
79 import org.apache.struts.action.ActionForm;
80 import org.apache.struts.action.ActionMapping;
81 import org.apache.struts.action.ActionMessage;
82 import org.dom4j.Document;
83 import org.dom4j.DocumentException;
84 import org.dom4j.Element;
85 import org.dom4j.io.OutputFormat;
86 import org.dom4j.io.SAXReader;
87 import org.dom4j.io.XMLWriter;
88
89 import com.ivata.groupware.admin.security.Security;
90 import com.ivata.groupware.admin.security.server.SecuritySession;
91 import com.ivata.groupware.admin.security.struts.LoginGuestAction;
92 import com.ivata.groupware.admin.setting.Settings;
93 import com.ivata.groupware.container.PicoContainerFactory;
94 import com.ivata.groupware.container.persistence.hibernate.HibernateSetupConstants;
95 import com.ivata.groupware.struts.SetupAction;
96 import com.ivata.mask.MaskFactory;
97 import com.ivata.mask.util.StringHandling;
98 import com.ivata.mask.util.SystemException;
99 import com.ivata.mask.util.ThrowableHandling;
100 import com.ivata.mask.web.struts.MaskAction;
101 import com.ivata.mask.web.struts.MaskAuthenticator;
102
103 /**
104  * Setup the application to use a database.
105  *
106  * @since ivata groupware 0.11 (2005-03-25)
107  * @author Colin MacLeod
108  * <a HREF='mailto:colin.macleod@ivata.com'>colin.macleod@ivata.com</a>
109  * @version $Revision: 1.5 $
110  */

111 public class HibernateSetupAction extends LoginGuestAction
112         implements SetupAction {
113     /**
114      * Logger for this class.
115      */

116     private static final Logger logger =
117         Logger.getLogger(HibernateSetupAction.class);
118     /**
119      * Helper to get the appropriate XPath to locate a Hibernate property
120      * element in the config.
121      *
122      * @param propertyName name of the hibernate property.
123      * @return XPath expression for this property.
124      */

125     private static String JavaDoc getHibernateXPath(final String JavaDoc propertyName) {
126         return "/hibernate-configuration/session-factory/property[@name='"
127             + propertyName
128             + "']";
129     }
130     /**
131      * Stores the actions in the request processor, so they can be reset.
132      */

133     private Map JavaDoc actions;
134     /**
135      * Constructor.
136      *
137      * @param securityParam System security object.
138      * @param settingsParam System settings object.
139      * @param maskFactoryParam Creates input and list masks.
140      * @param authenticatorParam Used to check user is auhtorized to see this
141      * page.
142      */

143     public HibernateSetupAction(final Security securityParam,
144             final Settings settingsParam,
145             final MaskFactory maskFactoryParam,
146             final MaskAuthenticator authenticatorParam) {
147         super(securityParam, settingsParam, maskFactoryParam,
148                 authenticatorParam);
149     }
150     /**
151      * Check the database connection specified in the form, and log any errors.
152      * @param setupForm the form from the current request, containing the
153      * database settings to check.
154      * @param errorMessages collection to append error messages to.
155      */

156     private void checkConnection(final HibernateSetupForm setupForm,
157             final ActionErrors errorMessages) {
158         String JavaDoc databaseDriver = setupForm.getDatabaseDriver();
159         String JavaDoc databasePassword = setupForm.getDatabasePassword();
160         String JavaDoc databaseURL = setupForm.getDatabaseURL();
161         String JavaDoc databaseUserName = setupForm.getDatabaseUserName();
162         // first check we can connect to the chosen db
163
// does the database driver exist?
164
try {
165             Class.forName(databaseDriver);
166             try {
167                 Connection JavaDoc connection = DriverManager.getConnection(
168                         databaseURL,
169                         databaseUserName,
170                         databasePassword);
171                 Statement JavaDoc statement = connection.createStatement();
172                 // NOTE: this is about the only SQL in the whole app.
173
ResultSet JavaDoc allSettings = statement.executeQuery(
174                         "select name, value, type from setting where "
175                         + "person_user is null");
176                 if (!allSettings.next()) {
177                     errorMessages.add(null, new ActionMessage(
178                             "errors.setup.databaseSettings",
179                             databaseURL,
180                             databaseUserName));
181                 }
182             } catch (Exception JavaDoc e) {
183                 // if we get in here it means we have a driver but could
184
// not connect
185
logger.error(e.getClass().getName()
186                         + ": connecting to URL '"
187                         + setupForm.getDatabaseURL()
188                         + "'",
189                         e);
190                 Throwable JavaDoc cause = ThrowableHandling.getCause(e);
191                 errorMessages.add(null, new ActionMessage(
192                         "errors.setup.databaseConnection",
193                         databaseURL,
194                         databaseUserName,
195                         cause.getClass().getName(),
196                         StringHandling.getNotNull(cause.getMessage())));
197             }
198         } catch (ClassNotFoundException JavaDoc e) {
199             // if we get in here it means the database driver was not
200
// found
201
logger.error(e.getClass().getName()
202                     + ": looking for driver '"
203                     + setupForm.getDatabaseDriver()
204                     + "'",
205                     e);
206             errorMessages.add(null, new ActionMessage(
207                     "errors.setup.databaseDriver",
208                     databaseDriver));
209         }
210     }
211     /**
212      * Check the form is valid and, if not, return the action forward we should
213      * go to, to sort it out.
214      *
215      * @param mapping current action mapping from <em>Struts</em> config.
216      * @param formParam optional ActionForm bean for this request (if any).
217      * @return <code>null</code> if the action should continue, otherwise the
218      * name of a forward to pass control to.
219      */

220     protected String JavaDoc checkForm(final ActionMapping mappingParam,
221             final ActionForm formParam) {
222         if (!"setupForm".equals(mappingParam.getName())) {
223             return "setupAction";
224         }
225         return null;
226     }
227     /**
228      * Split off from <code>onConfirm</code> to create a new start database.
229      *
230      * @param setupForm the current request form.
231      * @param errorMessages used to append messages to if there is any error
232      * creating the database.
233      * @param dbFile the file representing the path to the automatically
234      * generated <strong>HypersonicSQL</strong> database.
235      * @param propertiesFile file representing the path to the properties file
236      * for the automatically generated <strong>HypersonicSQL</strong> database.
237      * @param lockFile file representing path to the database lock file
238      * for the automatically generated <strong>HypersonicSQL</strong> database.
239      * @param scriptFile file representing the path to the script file
240      * for the automatically generated <strong>HypersonicSQL</strong> database.
241      */

242     private static void copyStartDB(final ActionErrors errorMessages,
243             final File JavaDoc dbFile,
244             final File JavaDoc propertiesFile,
245             final File JavaDoc scriptFile,
246             final File JavaDoc lockFile) {
247         if (logger.isDebugEnabled()) {
248             logger.debug("Creating database.");
249         }
250
251         File JavaDoc dbDirectory = dbFile.getParentFile();
252         // try to create the directory, if it doesn't exist
253
if ((dbDirectory != null)
254                 && !dbDirectory.exists()) {
255             if (!dbDirectory.mkdirs()) {
256                 logger.error("Could not create directory '"
257                         + dbDirectory.getAbsolutePath()
258                         + "'.");
259                 errorMessages.add(null, new ActionMessage(
260                         "errors.setup.databaseDirectory",
261                         dbDirectory.getAbsolutePath()));
262             }
263         }
264         // check the previous step didn't fail.
265
if (dbDirectory.exists()) {
266             // see if there is a previous lock file and remove it if so
267
if (lockFile.exists()) {
268                 logger.warn("Removing previous lock file '"
269                         + lockFile.getAbsolutePath()
270                         + "'.");
271                 if(!lockFile.delete()) {
272                     logger.error("COULD NOT REMOVE previous lock file '"
273                             + lockFile.getAbsolutePath()
274                             + "'.");
275                 }
276             }
277
278             // now we have the directory, and we know the user is cool with
279
// our writing the files out, so next try to extract the start
280
// db into the chosen path
281
try {
282                 byte[] buffer = new byte[1024];
283                 int bytesRead;
284                 InputStream JavaDoc inputStream = Hibernate.class
285                     .getResourceAsStream(HibernateSetupConstants.START_DB
286                             + HibernateSetupConstants.HSQLDB_PROPERTIES_SUFFIX);
287                 if (inputStream == null) {
288                     throw new FileNotFoundException JavaDoc("Could not "
289                             + "locate HypersonicSQL properties file '"
290                             + HibernateSetupConstants.START_DB
291                             + HibernateSetupConstants.HSQLDB_PROPERTIES_SUFFIX
292                             + "'");
293                 }
294
295                 OutputStream JavaDoc outputStream = new FileOutputStream JavaDoc(
296                         propertiesFile);
297                 while ((bytesRead = inputStream.read(buffer, 0,
298                         buffer.length)) != -1) {
299                     outputStream.write(buffer, 0, bytesRead);
300                 }
301                 inputStream = Hibernate.class
302                     .getResourceAsStream(HibernateSetupConstants.START_DB
303                             + HibernateSetupConstants.HSQLDB_SCRIPT_SUFFIX);
304                 if (inputStream == null) {
305                     throw new FileNotFoundException JavaDoc("Could not "
306                             + "locate HypersonicSQL script file '"
307                             + HibernateSetupConstants.START_DB
308                             + HibernateSetupConstants.HSQLDB_SCRIPT_SUFFIX
309                             + "'");
310                 }
311                 outputStream = new FileOutputStream JavaDoc(scriptFile);
312                 while ((bytesRead = inputStream.read(buffer, 0,
313                         buffer.length)) != -1) {
314                     outputStream.write(buffer, 0, bytesRead);
315                 }
316             } catch (Exception JavaDoc e) {
317                 logger.error("Could not copy database resources.", e);
318                 errorMessages.add(null, new ActionMessage(
319                         "errors.setup.databaseResources",
320                         e.getClass().getName(),
321                         e.getMessage()));
322             }
323         }
324     }
325     /**
326      * Create a <strong>HypersonicSQL</strong> database on the local file system.
327      * This is a copy of the start (memory) database shipped with <strong>ivata
328      * groupware</strong>. If the form exists already and the user has confirmed
329      * she doesn't want to overwrite, then the existing form is left as is.
330      *
331      * @param setupForm current form from the request.
332      * @param request current servlet request we are processing.
333      * @param errorMessages if there are any errors, they will be appended to
334      * this collection.
335      * @return <code>true</code> if all is well and the database has been crated
336      * or an existing one can be used, othwerise <code>false</code> if user
337      * confirmation is required before using/overwriting an existing DB.
338      */

339     private static boolean copyStartDB(
340             final ActionErrors errorMessages,
341             final String JavaDoc databaseURL,
342             final String JavaDoc confirmOverwriteString) {
343         String JavaDoc dbPath = databaseURL.substring(
344                 HibernateSetupConstants.AUTOMATIC_DATABASE_URL_START.length());
345         File JavaDoc dbFile = new File JavaDoc(dbPath);
346         if (logger.isDebugEnabled()) {
347             logger.debug("Database path is '"
348                     + dbPath
349                     + "', for URL '"
350                     + databaseURL
351                     + "'");
352         }
353         File JavaDoc propertiesFile = new File JavaDoc(dbPath
354                 + HibernateSetupConstants.HSQLDB_PROPERTIES_SUFFIX);
355         File JavaDoc scriptFile = new File JavaDoc(dbPath
356                 + HibernateSetupConstants.HSQLDB_SCRIPT_SUFFIX);
357         File JavaDoc lockFile = new File JavaDoc(dbPath
358                 + HibernateSetupConstants.HSQLDB_LOCK_SUFFIX);
359         // if either file exists, check the user confirmed we can
360
// overwrite them
361
boolean databaseExists = (propertiesFile.exists()
362                 || scriptFile.exists());
363         boolean confirmOverwrite = "true".equals(confirmOverwriteString);
364         // if the database exists, and we have not asked the user for
365
// confirmation, then go to the user confirmation page
366
if ((confirmOverwriteString == null)
367                 && databaseExists) {
368             return false;
369         }
370         if ((!databaseExists)
371                 || confirmOverwrite) {
372             copyStartDB(errorMessages, dbFile,
373                     propertiesFile, scriptFile, lockFile);
374         }
375         return true;
376     }
377
378     /**
379      * Prepare the form for the first use of the setup page.
380      *
381      * @param mappingParam Refer to {@link MaskAction#execute}.
382      * @param errorsParam Refer to {@link MaskAction#execute}.
383      * @param formParam Refer to {@link MaskAction#execute}.
384      * @param requestParam Refer to {@link MaskAction#execute}.
385      * @param responseParam Refer to {@link MaskAction#execute}.
386      * @param sessionParam Refer to {@link MaskAction#execute}.
387      * @return Refer to {@link MaskAction#execute}.
388      * @throws SystemException Refer to {@link MaskAction#execute}.
389      */

390     public String JavaDoc execute(ActionMapping mappingParam, ActionErrors errorsParam,
391             ActionForm formParam, HttpServletRequest JavaDoc requestParam,
392             HttpServletResponse JavaDoc responseParam, HttpSession JavaDoc session)
393             throws SystemException {
394         // if there is no security session
395
SecuritySession securitySession = (SecuritySession)
396             session.getAttribute("securitySession");
397         if (securitySession == null) {
398             super.execute(mappingParam, errorsParam, formParam, requestParam,
399                     responseParam, session);
400             securitySession = (SecuritySession)
401                 session.getAttribute("securitySession");
402         }
403         if (formParam == null) {
404             return "setup";
405         }
406         HibernateSetupForm setupForm = (HibernateSetupForm) formParam;
407         // by default create database automatically, if we are using the memory
408
// db already
409
ActionErrors errorMessages = new ActionErrors();
410         Document document = readHibernateConfig(errorMessages);
411         String JavaDoc uRL = HibernateSetupConstants.AUTOMATIC_DATABASE_MEMORY_URL;
412         if (errorMessages.isEmpty()) {
413             // note here - if there were errors, we will just default to create
414
// a db automatically below
415
Element element = (Element)
416                 document.selectSingleNode(getHibernateXPath(
417                         HibernateSetupConstants
418                             .HIBERNATE_PROPERTY_DATABASE_URL));
419             if (element != null) {
420                 uRL = element.getTextTrim();
421             }
422         }
423         // if you are logged on as guest and the default (memory) URL is not
424
// used (i.e. this is a real, not test system), you need to log in first
425
if (securitySession.isGuest()
426                 && !HibernateSetupConstants.AUTOMATIC_DATABASE_MEMORY_URL
427                     .equals(uRL)) {
428             return "setupSecurity";
429         }
430         // by deafult, create the database automatically for the user, if she
431
// is still using the memory db
432
if (HibernateSetupConstants.AUTOMATIC_DATABASE_MEMORY_URL.equals(uRL)) {
433             setupForm.setCreateDatabaseAutomatically(true);
434         } else {
435             // default the form values from the hibernate config
436
setupForm.setCreateDatabaseAutomatically(false);
437             setupForm.setDatabaseURL(uRL);
438             Element element = (Element)
439                 document.selectSingleNode(getHibernateXPath(
440                     HibernateSetupConstants
441                         .HIBERNATE_PROPERTY_DATABASE_DIALECT));
442             setupForm.setDatabaseDialect(element.getTextTrim());
443             element = (Element)
444                 document.selectSingleNode(getHibernateXPath(
445                     HibernateSetupConstants
446                         .HIBERNATE_PROPERTY_DATABASE_DRIVER));
447             setupForm.setDatabaseDriver(element.getTextTrim());
448             element = (Element)
449             document.selectSingleNode(getHibernateXPath(
450                 HibernateSetupConstants
451                     .HIBERNATE_PROPERTY_DATABASE_PASSWORD));
452             setupForm.setDatabasePassword(element.getTextTrim());
453             element = (Element)
454             document.selectSingleNode(getHibernateXPath(
455                 HibernateSetupConstants.HIBERNATE_PROPERTY_DATABASE_USER_NAME));
456             setupForm.setDatabaseUserName(element.getTextTrim());
457         }
458         return null;
459     }
460     /**
461      * Called when the user clicks the 'OK' button to continue with the chosen
462      * setup options. If you chose hibernate settings, this will write them
463      * out.
464      *
465      * @param mappingParam Refer to {@link MaskAction#onConfirm}.
466      * @param errorsParam Refer to {@link MaskAction#onConfirm}.
467      * @param formParam Refer to {@link MaskAction#onConfirm}.
468      * @param requestParam Refer to {@link MaskAction#onConfirm}.
469      * @param responseParam Refer to {@link MaskAction#onConfirm}.
470      * @param sessionParam Refer to {@link MaskAction#onConfirm}.
471      * @param defaultForwardParam Refer to {@link MaskAction#onConfirm}.
472      * @return Refer to {@link MaskAction#onConfirm}.
473      * @throws SystemException Refer to {@link MaskAction#onConfirm}.
474      */

475     public String JavaDoc onConfirm(ActionMapping mappingParam,
476             ActionErrors errorMessages, ActionForm formParam,
477             HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc responseParam,
478             HttpSession JavaDoc session, String JavaDoc defaultForwardParam)
479             throws SystemException {
480         HibernateSetupForm setupForm = (HibernateSetupForm)formParam;
481         if (formParam == null) {
482             return "setup";
483         }
484         // if we should create the database automatically, do that first
485
if (setupForm.isCreateDatabaseAutomatically()) {
486             // the method fails if it needs user confirmation
487
String JavaDoc confirmOverwriteString =
488                 request.getParameter("confirmOverwrite");
489             if (!copyStartDB(
490                     errorMessages, setupForm.getDatabaseURL(),
491                     confirmOverwriteString)) {
492                 return "setupConfirm";
493             }
494         }
495
496         // if there was no error till this point, that means any automatic
497
// process went smoothly. in that case, perform validation checks
498
// on the db
499
if (errorMessages.isEmpty()) {
500             checkConnection(setupForm, errorMessages);
501         }
502         // if there are no errors thus far, try writing out the new hibernate
503
// configuration
504
// first read in the existing hibernate config
505
Document document = null;
506         if (errorMessages.isEmpty()) {
507             document = readHibernateConfig(errorMessages);
508         }
509         // if that went well, update the settings in the config
510
if ((document != null)
511                 && errorMessages.isEmpty()) {
512             updateHibernateConfig(document, setupForm, errorMessages);
513         }
514         // finally, write out the changed Hibernate config
515
if ((document != null)
516                 && errorMessages.isEmpty()) {
517             writeHibernateConfig(document, errorMessages);
518         }
519
520         // now, if all is well, reset the pico container factory to use
521
// the new settings database. then update the mail settings to the
522
// values shown
523
if (errorMessages.isEmpty()) {
524             // login as guest to force a re-login after this process
525
SecuritySession securitySession = (SecuritySession)
526                 session.getAttribute("securitySession");
527             if ((securitySession == null)
528                     || !securitySession.isGuest()) {
529                 super.execute(mappingParam, errorMessages, formParam, request,
530                         responseParam, session);
531             }
532             // FIXME: this is dirty. I need a nicer way to trigger a reset of
533
// all cached actions in the request processor at this point
534
assert (actions != null);
535             actions.clear();
536             resetFactoryUpdateSettings(setupForm, (SecuritySession)
537                     session.getAttribute("securitySession"), session);
538         }
539
540         // did we get error messages? if not, continue as normal to the results
541
// page
542
if (errorMessages.isEmpty()) {
543             // confirm that the application is set-up, in case the memory
544
// database is still used. Note, in this case, the user will have to
545
// go thru' the setup again, the next time the app is restarted -
546
// "that's not a bug, it's a feature" ;-)
547
servlet.getServletContext().setAttribute(
548                     HibernateSetupConstants.CONFIRM_ATTRIBUTE,
549                     Boolean.TRUE);
550             return defaultForwardParam;
551         }
552
553         // if there were errors, return to the setup input page
554
request.setAttribute(Globals.ERROR_KEY, errorMessages);
555         return null;
556     }
557     /**
558      * Read in the current hibernate config so we can update the changed
559      * <strong>Hibernate</strong> configuration.
560      * @param errorMessages any error will be added to this collection.
561      * @return <strong>DOM4J</strong> document containing the
562      * <strong>Hibernate</strong> configuration.
563      */

564     private Document readHibernateConfig(final ActionErrors errorMessages) {
565         String JavaDoc hibernateConfigPath =
566             servlet.getServletContext().getRealPath(
567                     HibernateSetupConstants.HIBERNATE_CONFIG);
568         SAXReader reader = new SAXReader();
569         Document document = null;
570         // first read in the existing Hibernate config
571
try {
572             // use an entity resolver so the DTD is found even if you have
573
// no internet
574
reader.setEntityResolver(new DTDEntityResolver());
575             // without the FileReader, it fails on resin
576
document = reader.read(new FileReader JavaDoc(hibernateConfigPath));
577         } catch (FileNotFoundException JavaDoc e) {
578             logger.error(e.getClass().getName()
579                     + ": reading the hibernate config '"
580                     + HibernateSetupConstants.HIBERNATE_CONFIG
581                     + "', real path '"
582                     + hibernateConfigPath
583                     + "'",
584                     e);
585             errorMessages.add(null, new ActionMessage(
586                     "errors.setup.hibernateConfigRead",
587                     e.getClass().getName(),
588                     HibernateSetupConstants.HIBERNATE_CONFIG,
589                     hibernateConfigPath,
590                     e.getMessage()));
591         } catch (DocumentException e) {
592             logger.error(e.getClass().getName()
593                     + ": reading the hibernate config '"
594                     + HibernateSetupConstants.HIBERNATE_CONFIG
595                     + "', real path '"
596                     + hibernateConfigPath
597                     + "'",
598                     e);
599             errorMessages.add(null, new ActionMessage(
600                     "errors.setup.hibernateConfigRead",
601                     e.getClass().getName(),
602                     HibernateSetupConstants.HIBERNATE_CONFIG,
603                     hibernateConfigPath,
604                     e.getMessage()));
605         }
606         return document;
607     }
608     /**
609      * Reset the pico container factory. Override this method toupdate settings
610      * in the new factory.
611      * @param setupForm the form from the current request.
612      * @param securitySession guest security session, used to access settings.
613      * @param session current HTTP session.
614      * @throws SystemException if any setting cannot be set.
615      */

616     protected void resetFactoryUpdateSettings(
617             final HibernateSetupForm hibernateSetupForm,
618             final SecuritySession securitySession,
619             final HttpSession JavaDoc session)
620             throws SystemException {
621         PicoContainerFactory factory = PicoContainerFactory.getInstance();
622         factory.reset();
623         factory.initialize();
624     }
625     /**
626      * This method should only ever be called by the request processor,
627      * to set the actions so they can be reset at the appropriate time.
628      *
629      * @param actionsParam map of all action instances.
630      */

631     public void setActions(Map JavaDoc actionsParam) {
632         this.actions = actionsParam;
633     }
634     /**
635      * Helper to select a single property node from the hibernate config
636      * file, set its text and handle any error.
637      * @param propertyName name of the property to search for.
638      * @param text new value of the text for this element, if found.
639      * @param document hibernate config document.
640      * @param errorMessages any error will be added to this collection.
641      */

642     private void setHibernateProperty(final String JavaDoc propertyName,
643             final String JavaDoc text, final Document document,
644             final ActionErrors errorMessages) {
645         // change the config to match the new settings
646
String JavaDoc xPath = getHibernateXPath(propertyName);
647         Element element = (Element)
648             document.selectSingleNode(
649                     xPath);
650         if (element == null) {
651             errorMessages.add(null, new ActionMessage(
652                     "errors.setup.hibernateConfigElement",
653                     HibernateSetupConstants.HIBERNATE_CONFIG,
654                     xPath));
655         } else {
656             element.setText(text);
657         }
658     }
659     /**
660      * Update the entries in the <strong>DOM4J</strong> document to represent
661      * the new <strong>Hibernate</strong> config values.
662      *
663      * @param document <strong>DOM4J</strong> document representing the
664      * <strong>Hibernate</strong> config values.
665      * @param setupForm current form we are processing from the request.
666      * @param errorMessages any error will be added to this collection.
667      */

668     private void updateHibernateConfig(final Document document,
669             final HibernateSetupForm setupForm,
670             final ActionErrors errorMessages) {
671         setHibernateProperty(
672                 HibernateSetupConstants.HIBERNATE_PROPERTY_DATABASE_DRIVER,
673                 setupForm.getDatabaseDriver(),
674                 document,
675                 errorMessages);
676         setHibernateProperty(
677                 HibernateSetupConstants.HIBERNATE_PROPERTY_DATABASE_URL,
678                 setupForm.getDatabaseURL(),
679                 document,
680                 errorMessages);
681         setHibernateProperty(
682                 HibernateSetupConstants.HIBERNATE_PROPERTY_DATABASE_DIALECT,
683                 setupForm.getDatabaseDialect(),
684                 document,
685                 errorMessages);
686         setHibernateProperty(
687                 HibernateSetupConstants.HIBERNATE_PROPERTY_DATABASE_USER_NAME,
688                 setupForm.getDatabaseUserName(),
689                 document,
690                 errorMessages);
691         setHibernateProperty(
692                 HibernateSetupConstants.HIBERNATE_PROPERTY_DATABASE_PASSWORD,
693                 setupForm.getDatabasePassword(),
694                 document,
695                 errorMessages);
696     }
697     /**
698      * Write out the hibernate config to the file.
699      * @param document the current <strong>DOM4J</strong>, with updated
700      * settings.
701      * @param errorMessages if the file cannot be written, a message is logged
702      * here.
703      */

704     private void writeHibernateConfig(final Document document,
705             final ActionErrors errorMessages) throws SystemException {
706         // store the filename so we read the same config in next time
707
String JavaDoc hibernateConfigPath =
708             servlet.getServletContext().getRealPath(
709                     HibernateSetupConstants.HIBERNATE_CONFIG);
710         PicoContainerFactory.getInstance().setHibernateConfigFileName(
711                 hibernateConfigPath);
712         SAXReader reader = new SAXReader();
713         // now this is the bit where we write the config out
714
try {
715             XMLWriter writer = new XMLWriter(
716                     new FileWriter JavaDoc(hibernateConfigPath),
717                     new OutputFormat(" ", true));
718             writer.write(document);
719             writer.close();
720         } catch (IOException JavaDoc e) {
721             logger.error(e.getClass().getName()
722                     + ": writing the hibernate config '"
723                     + HibernateSetupConstants.HIBERNATE_CONFIG
724                     + "', real path '"
725                     + hibernateConfigPath
726                     + "'",
727                     e);
728             errorMessages.add(null, new ActionMessage(
729                     "errors.setup.hibernateConfigRead",
730                     e.getClass().getName(),
731                     HibernateSetupConstants.HIBERNATE_CONFIG,
732                     hibernateConfigPath,
733                     e.getMessage()));
734         }
735     }
736 }
737
Popular Tags