KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opencms > setup > CmsSetupBean


1 /*
2  * File : $Source: /usr/local/cvs/opencms/src/org/opencms/setup/CmsSetupBean.java,v $
3  * Date : $Date: 2006/07/20 11:06:50 $
4  * Version: $Revision: 1.48 $
5  *
6  * This library is part of OpenCms -
7  * the Open Source Content Mananagement System
8  *
9  * Copyright (c) 2005 Alkacon Software GmbH (http://www.alkacon.com)
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  * Lesser General Public License for more details.
20  *
21  * For further information about Alkacon Software GmbH, please see the
22  * company website: http://www.alkacon.com
23  *
24  * For further information about OpenCms, please see the
25  * project website: http://www.opencms.org
26  *
27  * You should have received a copy of the GNU Lesser General Public
28  * License along with this library; if not, write to the Free Software
29  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30  */

31
32 package org.opencms.setup;
33
34 import org.opencms.configuration.CmsConfigurationException;
35 import org.opencms.configuration.CmsConfigurationManager;
36 import org.opencms.configuration.CmsImportExportConfiguration;
37 import org.opencms.configuration.CmsModuleConfiguration;
38 import org.opencms.configuration.CmsSearchConfiguration;
39 import org.opencms.configuration.CmsSystemConfiguration;
40 import org.opencms.configuration.CmsVfsConfiguration;
41 import org.opencms.configuration.CmsWorkplaceConfiguration;
42 import org.opencms.configuration.I_CmsXmlConfiguration;
43 import org.opencms.db.CmsDbPool;
44 import org.opencms.file.CmsObject;
45 import org.opencms.file.CmsResource;
46 import org.opencms.i18n.CmsEncoder;
47 import org.opencms.loader.CmsImageLoader;
48 import org.opencms.main.CmsLog;
49 import org.opencms.main.CmsRuntimeException;
50 import org.opencms.main.CmsShell;
51 import org.opencms.main.CmsSystemInfo;
52 import org.opencms.main.I_CmsShellCommands;
53 import org.opencms.main.Messages;
54 import org.opencms.main.OpenCms;
55 import org.opencms.main.OpenCmsServlet;
56 import org.opencms.module.CmsModule;
57 import org.opencms.module.CmsModuleManager;
58 import org.opencms.report.CmsShellReport;
59 import org.opencms.setup.comptest.CmsSetupTestResult;
60 import org.opencms.setup.comptest.CmsSetupTestSimapi;
61 import org.opencms.setup.comptest.I_CmsSetupTest;
62 import org.opencms.setup.xml.CmsSetupXmlHelper;
63 import org.opencms.util.CmsFileUtil;
64 import org.opencms.util.CmsPropertyUtils;
65 import org.opencms.util.CmsStringUtil;
66 import org.opencms.util.CmsUUID;
67 import org.opencms.xml.CmsXmlException;
68
69 import java.io.File JavaDoc;
70 import java.io.FileInputStream JavaDoc;
71 import java.io.FileReader JavaDoc;
72 import java.io.FileWriter JavaDoc;
73 import java.io.IOException JavaDoc;
74 import java.io.LineNumberReader JavaDoc;
75 import java.util.ArrayList JavaDoc;
76 import java.util.Collection JavaDoc;
77 import java.util.Collections JavaDoc;
78 import java.util.Comparator JavaDoc;
79 import java.util.HashMap JavaDoc;
80 import java.util.HashSet JavaDoc;
81 import java.util.Iterator JavaDoc;
82 import java.util.List JavaDoc;
83 import java.util.Map JavaDoc;
84 import java.util.Properties JavaDoc;
85 import java.util.SortedMap JavaDoc;
86 import java.util.TreeMap JavaDoc;
87 import java.util.Vector JavaDoc;
88
89 import javax.servlet.ServletConfig JavaDoc;
90 import javax.servlet.http.HttpServletRequest JavaDoc;
91 import javax.servlet.jsp.JspWriter JavaDoc;
92 import javax.servlet.jsp.PageContext JavaDoc;
93
94 import org.apache.commons.collections.ExtendedProperties;
95
96 /**
97  * A java bean as a controller for the OpenCms setup wizard.<p>
98  *
99  * It is not allowed to customize this bean with methods for a specific database server setup!<p>
100  *
101  * Database server specific settings should be set/read using get/setDbProperty, as for example like:
102  *
103  * <pre>
104  * setDbProperty("oracle.defaultTablespace", value);
105  * </pre>
106  * <p>
107  *
108  * @author Thomas Weckert
109  * @author Carsten Weinholz
110  * @author Alexander Kandzior
111  * @author Michael Moossen
112  *
113  * @version $Revision: 1.48 $
114  *
115  * @since 6.0.0
116  */

117 public class CmsSetupBean extends Object JavaDoc implements Cloneable JavaDoc, I_CmsShellCommands {
118
119     /** Folder constant name.<p> */
120     public static final String JavaDoc FOLDER_BACKUP = "backup" + File.separatorChar;
121
122     /** Folder constant name.<p> */
123     public static final String JavaDoc FOLDER_DATABASE = "database" + File.separatorChar;
124
125     /** Folder constant name.<p> */
126     public static final String JavaDoc FOLDER_LIB = "lib" + File.separatorChar;
127
128     /** Folder constant name.<p> */
129     public static final String JavaDoc FOLDER_SETUP = "setup" + File.separatorChar;
130
131     /** Folder constant name.<p> */
132     public static final String JavaDoc FOLDER_WEBINF = "WEB-INF" + File.separatorChar;
133
134     /** DB provider constant. */
135     public static final String JavaDoc GENERIC_PROVIDER = "generic";
136
137     /** Name of the property file containing HTML fragments for setup wizard and error dialog. */
138     public static final String JavaDoc HTML_MESSAGE_FILE = "org/opencms/setup/htmlmsg.properties";
139
140     /** DB provider constant for maxdb. */
141     public static final String JavaDoc MAXDB_PROVIDER = "maxdb";
142
143     /** DB provider constant for mysql. */
144     public static final String JavaDoc MYSQL_PROVIDER = "mysql";
145
146     /** DB provider constant for oracle. */
147     public static final String JavaDoc ORACLE_PROVIDER = "oracle";
148
149     /** DB provider constant for postgresql. */
150     public static final String JavaDoc POSTGRESQL_PROVIDER = "postgresql";
151
152     /** Required files per database server setup. */
153     public static final String JavaDoc[] REQUIRED_DB_SETUP_FILES = {
154         "step_4_database_setup.jsp",
155         "database.properties",
156         "create_db.sql",
157         "create_tables.sql",
158         "drop_db.sql",
159         "drop_tables.sql"};
160
161     /** Contains HTML fragments for the output in the JSP pages of the setup wizard. */
162     private static Properties JavaDoc m_htmlProps;
163
164     /** A map with all available modules. */
165     protected Map JavaDoc m_availableModules;
166
167     /** A CmsObject to execute shell commands. */
168     protected CmsObject m_cms;
169
170     /** A list with the package names of the modules to be installed .*/
171     protected List JavaDoc m_installModules;
172
173     /** Location for log file. */
174     protected String JavaDoc m_logFile = FOLDER_WEBINF + CmsLog.FOLDER_LOGS + "setup.log";
175
176     /** Location for logs relative to the webapp folder. */
177     protected String JavaDoc m_logsFolder = FOLDER_WEBINF + CmsLog.FOLDER_LOGS;
178
179     /** A map with lists of dependent module package names keyed by module package names. */
180     protected Map JavaDoc m_moduleDependencies;
181
182     /** A map with all available modules filenames. */
183     protected Map JavaDoc m_moduleFilenames;
184
185     /** Location for module archives relative to the webapp folder. */
186     protected String JavaDoc m_modulesFolder = FOLDER_WEBINF + CmsSystemInfo.FOLDER_PACKAGES + CmsSystemInfo.FOLDER_MODULES;
187
188     /** The new logging offset in the workplace import thread. */
189     protected int m_newLoggingOffset;
190
191     /** The lod logging offset in the workplace import thread. */
192     protected int m_oldLoggingOffset;
193
194     /** The absolute path to the home directory of the OpenCms webapp. */
195     protected String JavaDoc m_webAppRfsPath;
196
197     /** The absolute path to the config sub directory of the OpenCms web application. */
198     private String JavaDoc m_configRfsPath;
199
200     /** Key of the selected database server (e.g. "mysql", "generic" or "oracle") */
201     private String JavaDoc m_databaseKey;
202
203     /** List of keys of all available database server setups (e.g. "mysql", "generic" or "oracle") */
204     private List JavaDoc m_databaseKeys;
205
206     /** Map of database setup properties of all available database server setups keyed by their database keys. */
207     private Map JavaDoc m_databaseProperties;
208
209     /** Password used for the JDBC connection when the OpenCms database is created. */
210     private String JavaDoc m_dbCreatePwd;
211
212     /** The name of the default web application (in web.xml). */
213     private String JavaDoc m_defaultWebApplication;
214
215     /** Contains the error messages to be displayed in the setup wizard. */
216     private List JavaDoc m_errors;
217
218     /** Contains the properties of "opencms.properties". */
219     private ExtendedProperties m_extProperties;
220
221     /** The Database Provider used in setup. */
222     private String JavaDoc m_provider;
223
224     /** A map with tokens ${...} to be replaced in SQL scripts. */
225     private Map JavaDoc m_replacer;
226
227     /** The initial servlet configuration. */
228     private ServletConfig JavaDoc m_servletConfig;
229
230     /** The servlet mapping (in web.xml). */
231     private String JavaDoc m_servletMapping;
232
233     /** List of sorted keys by ranking of all available database server setups (e.g. "mysql", "generic" or "oracle") */
234     private List JavaDoc m_sortedDatabaseKeys;
235
236     /** The workplace import thread. */
237     private CmsSetupWorkplaceImportThread m_workplaceImportThread;
238
239     /** Xml read/write helper object. */
240     private CmsSetupXmlHelper m_xmlHelper;
241
242     /**
243      * Default constructor.<p>
244      */

245     public CmsSetupBean() {
246
247         initHtmlParts();
248     }
249
250     /**
251      * Restores the opencms.xml either to or from a backup file, depending
252      * whether the setup wizard is executed the first time (the backup
253      * does not exist) or not (the backup exists).
254      *
255      * @param filename something like e.g. "opencms.xml"
256      * @param originalFilename the configurations real file name, e.g. "opencms.xml.ori"
257      */

258     public void backupConfiguration(String JavaDoc filename, String JavaDoc originalFilename) {
259
260         // ensure backup folder exists
261
File JavaDoc backupFolder = new File JavaDoc(m_configRfsPath + FOLDER_BACKUP);
262         if (!backupFolder.exists()) {
263             backupFolder.mkdirs();
264         }
265
266         // copy file to (or from) backup folder
267
originalFilename = FOLDER_BACKUP + originalFilename;
268         File JavaDoc file = new File JavaDoc(m_configRfsPath + originalFilename);
269         if (file.exists()) {
270             copyFile(originalFilename, filename);
271         } else {
272             copyFile(filename, originalFilename);
273         }
274     }
275
276     /**
277      * Checks the ethernet address value and generates a dummy address, if necessary.<p> *
278      */

279     public void checkEthernetAddress() {
280
281         // check the ethernet address in order to generate a random address, if not available
282
if (CmsStringUtil.isEmpty(getEthernetAddress())) {
283             setEthernetAddress(CmsUUID.getDummyEthernetAddress());
284         }
285     }
286
287     /**
288      * Copies a given file.<p>
289      *
290      * @param source the source file
291      * @param target the destination file
292      */

293     public void copyFile(String JavaDoc source, String JavaDoc target) {
294
295         try {
296             CmsFileUtil.copy(m_configRfsPath + source, m_configRfsPath + target);
297         } catch (IOException JavaDoc e) {
298             m_errors.add("Could not copy " + source + " to " + target + " \n");
299             m_errors.add(e.toString() + "\n");
300         }
301     }
302
303     /**
304      * Returns html code to display an error.<p>
305      *
306      * @param pathPrefix to adjust the path
307      *
308      * @return html code
309      */

310     public String JavaDoc displayError(String JavaDoc pathPrefix) {
311
312         if (pathPrefix == null) {
313             pathPrefix = "";
314         }
315         StringBuffer JavaDoc html = new StringBuffer JavaDoc(512);
316         html.append("<table border='0' cellpadding='5' cellspacing='0' style='width: 100%; height: 100%;'>");
317         html.append("\t<tr>");
318         html.append("\t\t<td style='vertical-align: middle; height: 100%;'>");
319         html.append(getHtmlPart("C_BLOCK_START", "Error"));
320         html.append("\t\t\t<table border='0' cellpadding='0' cellspacing='0' style='width: 100%;'>");
321         html.append("\t\t\t\t<tr>");
322         html.append("\t\t\t\t\t<td><img SRC='").append(pathPrefix).append("resources/error.png' border='0'></td>");
323         html.append("\t\t\t\t\t<td>&nbsp;&nbsp;</td>");
324         html.append("\t\t\t\t\t<td style='width: 100%;'>");
325         html.append("\t\t\t\t\t\tThe Alkacon OpenCms setup wizard has not been started correctly!<br>");
326         html.append("\t\t\t\t\t\tPlease click <a HREF='").append(pathPrefix);
327         html.append("index.jsp'>here</a> to restart the wizard.");
328         html.append("\t\t\t\t\t</td>");
329         html.append("\t\t\t\t</tr>");
330         html.append("\t\t\t</table>");
331         html.append(getHtmlPart("C_BLOCK_END"));
332         html.append("\t\t</td>");
333         html.append("\t</tr>");
334         html.append("</table>");
335         return html.toString();
336     }
337
338     /**
339      * Returns a map with all available modules.<p>
340      *
341      * The map contains maps keyed by module package names. Each of these maps contains various
342      * information about the module such as the module name, version, description, and a list of
343      * it's dependencies. You should refer to the source code of this method to understand the data
344      * structure of the map returned by this method!<p>
345      *
346      * @return a map with all available modules
347      */

348     public Map JavaDoc getAvailableModules() {
349
350         if (m_availableModules == null || m_availableModules.isEmpty()) {
351             m_availableModules = new HashMap JavaDoc();
352             m_moduleDependencies = new HashMap JavaDoc();
353             m_moduleFilenames = new HashMap JavaDoc();
354
355             try {
356                 Map JavaDoc modules = CmsModuleManager.getAllModulesFromPath(getModuleFolder());
357                 Iterator JavaDoc itMods = modules.keySet().iterator();
358                 while (itMods.hasNext()) {
359                     CmsModule module = (CmsModule)itMods.next();
360                     // put the module information into a map keyed by the module packages names
361
m_availableModules.put(module.getName(), module);
362                     m_moduleFilenames.put(module.getName(), modules.get(module));
363                 }
364             } catch (CmsConfigurationException e) {
365                 throw new CmsRuntimeException(e.getMessageContainer());
366             }
367         }
368         return m_availableModules;
369     }
370
371     /**
372      * Returns the "config" path in the OpenCms web application.<p>
373      *
374      * @return the config path
375      */

376     public String JavaDoc getConfigRfsPath() {
377
378         return m_configRfsPath;
379     }
380
381     /**
382      * Returns the key of the selected database server (e.g. "mysql", "generic" or "oracle").<p>
383      *
384      * @return the key of the selected database server (e.g. "mysql", "generic" or "oracle")
385      */

386     public String JavaDoc getDatabase() {
387
388         if (m_databaseKey == null) {
389             m_databaseKey = getExtProperty("db.name");
390         }
391
392         if (CmsStringUtil.isEmpty(m_databaseKey)) {
393             m_databaseKey = (String JavaDoc)getSortedDatabases().get(0);
394         }
395
396         return m_databaseKey;
397     }
398
399     /**
400      * Returns the URI of a database config page (in step 3) for a specified database key.<p>
401      *
402      * @param key the database key (e.g. "mysql", "generic" or "oracle")
403      * @return the URI of a database config page
404      */

405     public String JavaDoc getDatabaseConfigPage(String JavaDoc key) {
406
407         // don't use File.separatorChar here, result must be a valid URL with "/" path delimiters
408
String JavaDoc configUri = FOLDER_DATABASE + key + File.separatorChar + "step_4_database_setup.jsp";
409         return configUri.replace(File.separatorChar, '/');
410     }
411
412     /**
413      * Returns a list of needed jar filenames for a database server setup specified by a database key (e.g. "mysql", "generic" or "oracle").<p>
414      *
415      * @param databaseKey a database key (e.g. "mysql", "generic" or "oracle")
416      *
417      * @return a list of needed jar filenames
418      */

419     public List JavaDoc getDatabaseLibs(String JavaDoc databaseKey) {
420
421         return CmsStringUtil.splitAsList((String JavaDoc)((Map JavaDoc)getDatabaseProperties().get(databaseKey)).get(databaseKey
422             + ".libs"), ',', true);
423     }
424
425     /**
426      * Returns the clear text name for a database server setup specified by a database key (e.g. "mysql", "generic" or "oracle").<p>
427      *
428      * @param databaseKey a database key (e.g. "mysql", "generic" or "oracle")
429      * @return the clear text name for a database server setup
430      */

431     public String JavaDoc getDatabaseName(String JavaDoc databaseKey) {
432
433         return (String JavaDoc)((Map JavaDoc)getDatabaseProperties().get(databaseKey)).get(databaseKey + ".name");
434     }
435
436     /**
437      * Returns a map with the database properties of *all* available database configurations keyed
438      * by their database keys (e.g. "mysql", "generic" or "oracle").<p>
439      *
440      * @return a map with the database properties of *all* available database configurations
441      */

442     public Map JavaDoc getDatabaseProperties() {
443
444         if (m_databaseProperties != null) {
445             return m_databaseProperties;
446         }
447
448         readDatabaseConfig();
449         return m_databaseProperties;
450     }
451
452     /**
453      * Returns a list with they keys (e.g. "mysql", "generic" or "oracle") of all available
454      * database server setups found in "/setup/database/".<p>
455      *
456      * @return a list with they keys (e.g. "mysql", "generic" or "oracle") of all available database server setups
457      */

458     public List JavaDoc getDatabases() {
459
460         File JavaDoc databaseSetupFolder = null;
461         File JavaDoc[] childResources = null;
462         File JavaDoc childResource = null;
463         File JavaDoc setupFile = null;
464         boolean hasMissingSetupFiles = false;
465
466         if (m_databaseKeys != null) {
467             return m_databaseKeys;
468         }
469
470         try {
471             m_databaseKeys = new ArrayList JavaDoc();
472             databaseSetupFolder = new File JavaDoc(m_webAppRfsPath + FOLDER_SETUP + FOLDER_DATABASE);
473
474             if (databaseSetupFolder.exists()) {
475                 childResources = databaseSetupFolder.listFiles();
476
477                 if (childResources != null) {
478                     for (int i = 0; i < childResources.length; i++) {
479                         childResource = childResources[i];
480                         hasMissingSetupFiles = false;
481
482                         if (childResource.exists() && childResource.isDirectory() && childResource.canRead()) {
483                             for (int j = 0; j < REQUIRED_DB_SETUP_FILES.length; j++) {
484                                 setupFile = new File JavaDoc(childResource.getPath()
485                                     + File.separatorChar
486                                     + REQUIRED_DB_SETUP_FILES[j]);
487
488                                 if (!setupFile.exists() || !setupFile.isFile() || !setupFile.canRead()) {
489                                     hasMissingSetupFiles = true;
490                                     System.err.println("["
491                                         + getClass().getName()
492                                         + "] missing or unreadable database setup file: "
493                                         + setupFile.getPath());
494                                     break;
495                                 }
496                             }
497
498                             if (!hasMissingSetupFiles) {
499                                 m_databaseKeys.add(childResource.getName().trim());
500                             }
501                         }
502                     }
503                 }
504             }
505         } catch (Exception JavaDoc e) {
506             System.err.println(e.toString());
507             e.printStackTrace(System.err);
508         }
509
510         return m_databaseKeys;
511     }
512
513     /**
514      * Returns the database name.<p>
515      *
516      * @return the database name
517      */

518     public String JavaDoc getDb() {
519
520         return getDbProperty(m_databaseKey + ".dbname");
521     }
522
523     /**
524      * Returns the JDBC connect URL parameters.<p>
525      *
526      * @return the JDBC connect URL parameters
527      */

528     public String JavaDoc getDbConStrParams() {
529
530         return getDbProperty(m_databaseKey + ".constr.params");
531     }
532
533     /**
534      * Returns the database create statement.<p>
535      *
536      * @return the database create statement
537      */

538     public String JavaDoc getDbCreateConStr() {
539
540         return getDbProperty(m_databaseKey + ".constr");
541     }
542
543     /**
544      * Returns the password used for database creation.<p>
545      *
546      * @return the password used for database creation
547      */

548     public String JavaDoc getDbCreatePwd() {
549
550         return (m_dbCreatePwd != null) ? m_dbCreatePwd : "";
551     }
552
553     /**
554      * Returns the database user that is used to connect to the database.<p>
555      *
556      * @return the database user
557      */

558     public String JavaDoc getDbCreateUser() {
559
560         return getDbProperty(m_databaseKey + ".user");
561     }
562
563     /**
564      * Returns the database driver belonging to the database
565      * from the default configuration.<p>
566      *
567      * @return name of the database driver
568      */

569     public String JavaDoc getDbDriver() {
570
571         return getDbProperty(m_databaseKey + ".driver");
572     }
573
574     /**
575      * Returns the value for a given key from the database properties.
576      *
577      * @param key the property key
578      * @return the string value for a given key
579      */

580     public String JavaDoc getDbProperty(String JavaDoc key) {
581
582         // extract the database key out of the entire key
583
String JavaDoc databaseKey = key.substring(0, key.indexOf('.'));
584         Map JavaDoc databaseProperties = (Map JavaDoc)getDatabaseProperties().get(databaseKey);
585
586         Object JavaDoc value = databaseProperties.get(key);
587         return (value != null) ? (String JavaDoc)value : "";
588     }
589
590     /**
591      * Returns the validation query belonging to the database
592      * from the default configuration .<p>
593      *
594      * @return query used to validate connections
595      */

596     public String JavaDoc getDbTestQuery() {
597
598         return getDbProperty(m_databaseKey + ".testQuery");
599     }
600
601     /**
602      * Returns a connection string.<p>
603      *
604      * @return the connection string used by the OpenCms core
605      */

606     public String JavaDoc getDbWorkConStr() {
607
608         if (m_provider.equals(POSTGRESQL_PROVIDER)) {
609             return getDbProperty(m_databaseKey + ".constr.newDb");
610         } else {
611             return getExtProperty(CmsDbPool.KEY_DATABASE_POOL + '.' + getPool() + ".jdbcUrl");
612         }
613     }
614
615     /**
616      * Returns the password of the database from the properties .<p>
617      *
618      * @return the password for the OpenCms database user
619      */

620     public String JavaDoc getDbWorkPwd() {
621
622         return getExtProperty(CmsDbPool.KEY_DATABASE_POOL + '.' + getPool() + ".password");
623     }
624
625     /**
626      * Returns the user of the database from the properties.<p>
627      *
628      * @return the database user used by the opencms core
629      */

630     public String JavaDoc getDbWorkUser() {
631
632         String JavaDoc user = getExtProperty(CmsDbPool.KEY_DATABASE_POOL + '.' + getPool() + ".user");
633         if (CmsStringUtil.isEmptyOrWhitespaceOnly(user)) {
634             return getDbCreateUser();
635         }
636         return user;
637     }
638
639     /**
640      * Returns the default content encoding.<p>
641      * @return String
642      */

643     public String JavaDoc getDefaultContentEncoding() {
644
645         return getExtProperty("defaultContentEncoding");
646     }
647
648     /**
649      * Returns the name of the default web application, configured in <code>web.xml</code>.<p>
650      *
651      * By default this is <code>"ROOT"</code>.<p>
652      *
653      * @return the name of the default web application, configured in <code>web.xml</code>
654      */

655     public String JavaDoc getDefaultWebApplication() {
656
657         return m_defaultWebApplication;
658     }
659
660     /**
661      * Returns the display string for a given module.<p>
662      *
663      * @param module a module
664      *
665      * @return the display string for the given module
666      */

667     public String JavaDoc getDisplayForModule(CmsModule module) {
668
669         String JavaDoc name = module.getNiceName();
670         String JavaDoc group = module.getGroup();
671         String JavaDoc version = module.getVersion().getVersion();
672         String JavaDoc display = name;
673         if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(group)) {
674             display = group + ": " + display;
675         }
676         if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(version)) {
677             display += " (" + version + ")";
678         }
679         return display;
680     }
681
682     /**
683      * Returns the error messages.<p>
684      *
685      * @return a vector of error messages
686      */

687     public List JavaDoc getErrors() {
688
689         return m_errors;
690     }
691
692     /**
693      * Returns the mac ethernet address.<p>
694      *
695      * @return the mac ethernet addess
696      */

697     public String JavaDoc getEthernetAddress() {
698
699         return getExtProperty("server.ethernet.address");
700     }
701
702     /**
703      * Returns a help image icon tag to display a help text in the setup wizard.<p>
704      *
705      * @param id the id of the desired help div
706      * @param pathPrefix the path prefix to the image
707      * @return the HTML part for the help icon or an empty String, if the part was not found
708      */

709     public String JavaDoc getHtmlHelpIcon(String JavaDoc id, String JavaDoc pathPrefix) {
710
711         String JavaDoc value = m_htmlProps.getProperty("C_HELP_IMG");
712         if (value == null) {
713             return "";
714         } else {
715             value = CmsStringUtil.substitute(value, "$replace$", id);
716             return CmsStringUtil.substitute(value, "$path$", pathPrefix);
717         }
718     }
719
720     /**
721      * Returns the specified HTML part of the HTML property file to create the output.<p>
722      *
723      * @param part the name of the desired part
724      * @return the HTML part or an empty String, if the part was not found
725      */

726     public String JavaDoc getHtmlPart(String JavaDoc part) {
727
728         return getHtmlPart(part, "");
729     }
730
731     /**
732      * Returns the specified HTML part of the HTML property file to create the output.<p>
733      *
734      * @param part the name of the desired part
735      * @param replaceString String which is inserted in the found HTML part at the location of "$replace$"
736      * @return the HTML part or an empty String, if the part was not found
737      */

738     public String JavaDoc getHtmlPart(String JavaDoc part, String JavaDoc replaceString) {
739
740         String JavaDoc value = m_htmlProps.getProperty(part);
741         if (value == null) {
742             return "";
743         } else {
744             return CmsStringUtil.substitute(value, "$replace$", replaceString);
745         }
746     }
747
748     /**
749      * Returns the path to the /WEB-INF/lib folder.<p>
750      *
751      * @return the path to the /WEB-INF/lib folder
752      */

753     public String JavaDoc getLibFolder() {
754
755         return getWebAppRfsPath() + FOLDER_WEBINF + FOLDER_LIB;
756     }
757
758     /**
759      * Returns the name of the log file.<p>
760      *
761      * @return the name of the log file
762      */

763     public String JavaDoc getLogName() {
764
765         return new StringBuffer JavaDoc(m_webAppRfsPath).append(m_logFile).toString();
766     }
767
768     /**
769      * Returns a map with lists of dependent module package names keyed by module package names.<p>
770      *
771      * @return a map with lists of dependent module package names keyed by module package names
772      */

773     public Map JavaDoc getModuleDependencies() {
774
775         if (m_moduleDependencies == null || m_moduleDependencies.isEmpty()) {
776             try {
777                 // open the folder "/WEB-INF/packages/modules/"
778
m_moduleDependencies = CmsModuleManager.buildDepsForAllModules(getModuleFolder(), true);
779             } catch (CmsConfigurationException e) {
780                 throw new CmsRuntimeException(e.getMessageContainer());
781             }
782         }
783         return m_moduleDependencies;
784     }
785
786     /**
787      * Returns the absolute path to the module root folder.<p>
788      *
789      * @return the absolute path to the module root folder
790      */

791     public String JavaDoc getModuleFolder() {
792
793         return new StringBuffer JavaDoc(m_webAppRfsPath).append(m_modulesFolder).toString();
794     }
795
796     /**
797      * Returns A list with the package names of the modules to be installed.<p>
798      *
799      * @return A list with the package names of the modules to be installed
800      */

801     public List JavaDoc getModulesToInstall() {
802
803         if (m_installModules == null || m_installModules.isEmpty()) {
804             return Collections.EMPTY_LIST;
805         }
806         return Collections.unmodifiableList(m_installModules);
807     }
808
809     /**
810      * Gets the default pool.<p>
811      *
812      * @return name of the default pool
813      */

814     public String JavaDoc getPool() {
815
816         return CmsStringUtil.splitAsArray(getExtProperty("db.pools"), ",")[0];
817     }
818
819     /**
820      * Returns the extended properties.<p>
821      *
822      * @return the extended properties
823      */

824     public ExtendedProperties getProperties() {
825
826         return m_extProperties;
827     }
828
829     /**
830      * Returns the replacer.<p>
831      *
832      * @return the replacer
833      */

834     public Map JavaDoc getReplacer() {
835
836         return m_replacer;
837     }
838
839     /**
840      * Return the OpenCms server name.<p>
841      *
842      * @return the OpenCms server name
843      */

844     public String JavaDoc getServerName() {
845
846         return getExtProperty("server.name");
847     }
848
849     /**
850      * Returns the initial servlet configuration.<p>
851      *
852      * @return the initial servlet configuration
853      */

854     public ServletConfig JavaDoc getServletConfig() {
855
856         return m_servletConfig;
857     }
858
859     /**
860      * Returns the OpenCms servlet mapping, configured in <code>web.xml</code>.<p>
861      *
862      * By default this is <code>"/opencms/*"</code>.<p>
863      *
864      * @return the OpenCms servlet mapping, configured in <code>web.xml</code>
865      */

866     public String JavaDoc getServletMapping() {
867
868         return m_servletMapping;
869     }
870
871     /**
872      * Returns a sorted list with they keys (e.g. "mysql", "generic" or "oracle") of all available
873      * database server setups found in "/setup/database/" sorted by their ranking property.<p>
874      *
875      * @return a sorted list with they keys (e.g. "mysql", "generic" or "oracle") of all available database server setups
876      */

877     public List JavaDoc getSortedDatabases() {
878
879         if (m_sortedDatabaseKeys == null) {
880             List JavaDoc databases = m_databaseKeys;
881             List JavaDoc sortedDatabases = new ArrayList JavaDoc(databases.size());
882             SortedMap JavaDoc mappedDatabases = new TreeMap JavaDoc();
883             for (int i = 0; i < databases.size(); i++) {
884                 String JavaDoc key = (String JavaDoc)databases.get(i);
885                 Integer JavaDoc ranking = new Integer JavaDoc(0);
886                 try {
887                     ranking = Integer.valueOf(getDbProperty(key + ".ranking"));
888                 } catch (Exception JavaDoc e) {
889                     // ignore
890
}
891                 mappedDatabases.put(ranking, key);
892             }
893
894             while (mappedDatabases.size() > 0) {
895                 // get database with highest ranking
896
Integer JavaDoc key = (Integer JavaDoc)mappedDatabases.lastKey();
897                 String JavaDoc database = (String JavaDoc)mappedDatabases.get(key);
898                 sortedDatabases.add(database);
899                 mappedDatabases.remove(key);
900             }
901             m_sortedDatabaseKeys = sortedDatabases;
902         }
903         return m_sortedDatabaseKeys;
904     }
905
906     /**
907      * Returns the absolute path to the OpenCms home directory.<p>
908      *
909      * @return the path to the OpenCms home directory
910      */

911     public String JavaDoc getWebAppRfsPath() {
912
913         return m_webAppRfsPath;
914     }
915
916     /**
917      * Checks if the setup wizard is enabled.<p>
918      *
919      * @return true if the setup wizard is enables, false otherwise
920      */

921     public boolean getWizardEnabled() {
922
923         return Boolean.valueOf(getExtProperty("wizard.enabled")).booleanValue();
924     }
925
926     /**
927      * Returns the workplace import thread.<p>
928      *
929      * @return the workplace import thread
930      */

931     public CmsSetupWorkplaceImportThread getWorkplaceImportThread() {
932
933         return m_workplaceImportThread;
934     }
935
936     /**
937      * Return the OpenCms workplace site.<p>
938      *
939      * @return the OpenCms workplace site
940      */

941     public String JavaDoc getWorkplaceSite() {
942
943         return getExtProperty("site.workplace");
944     }
945
946     /**
947      * Returns the xml Helper object.<p>
948      *
949      * @return the xml Helper object
950      */

951     public CmsSetupXmlHelper getXmlHelper() {
952
953         if (m_xmlHelper == null) {
954             // lazzy initialization
955
m_xmlHelper = new CmsSetupXmlHelper(getConfigRfsPath());
956         }
957         return m_xmlHelper;
958     }
959
960     /**
961      * Returns html code for the module descriptions in help ballons.<p>
962      *
963      * @return html code
964      */

965     public String JavaDoc htmlModuleHelpDescriptions() {
966
967         StringBuffer JavaDoc html = new StringBuffer JavaDoc(1024);
968         Iterator JavaDoc itModules = sortModules(getAvailableModules().values()).iterator();
969         for (int i = 0; itModules.hasNext(); i++) {
970             String JavaDoc moduleName = (String JavaDoc)itModules.next();
971             CmsModule module = (CmsModule)getAvailableModules().get(moduleName);
972             if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(module.getDescription())) {
973                 html.append(getHtmlPart("C_HELP_START", "" + i));
974                 html.append(module.getDescription());
975                 html.append("\n");
976                 html.append(getHtmlPart("C_HELP_END"));
977                 html.append("\n");
978             }
979         }
980         return html.toString();
981     }
982
983     /**
984      * Returns html for displaying a module selection box.<p>
985      *
986      * @return html code
987      */

988     public String JavaDoc htmlModules() {
989
990         StringBuffer JavaDoc html = new StringBuffer JavaDoc(1024);
991         Iterator JavaDoc itModules = sortModules(getAvailableModules().values()).iterator();
992         for (int i = 0; itModules.hasNext(); i++) {
993             String JavaDoc moduleName = (String JavaDoc)itModules.next();
994             CmsModule module = (CmsModule)getAvailableModules().get(moduleName);
995             html.append(htmlModule(module, i));
996         }
997         return html.toString();
998     }
999
1000    /**
1001     * Installed all modules that have been set using {@link #setInstallModules(String)}.<p>
1002     *
1003     * This method is invoked as a shell command.<p>
1004     *
1005     * @throws Exception if something goes wrong
1006     */

1007    public void importModulesFromSetupBean() throws Exception JavaDoc {
1008
1009        // read here how the list of modules to be installed is passed from the setup bean to the
1010
// setup thread, and finally to the shell process that executes the setup script:
1011
// 1) the list with the package names of the modules to be installed is saved by setInstallModules
1012
// 2) the setup thread gets initialized in a JSP of the setup wizard
1013
// 3) the instance of the setup bean is passed to the setup thread by setAdditionalShellCommand
1014
// 4) the setup bean is passed to the shell by startSetup
1015
// 5) because the setup bean implements I_CmsShellCommands, the shell constructor can pass the shell's CmsObject back to the setup bean
1016
// 6) thus, the setup bean can do things with the Cms
1017

1018        if (m_cms != null && m_installModules != null) {
1019            for (int i = 0; i < m_installModules.size(); i++) {
1020                String JavaDoc filename = (String JavaDoc)m_moduleFilenames.get(m_installModules.get(i));
1021                try {
1022                    importModuleFromDefault(filename);
1023                } catch (Exception JavaDoc e) {
1024                    // log a exception during module import, but make sure the next module is still imported
1025
e.printStackTrace(System.err);
1026                }
1027            }
1028        }
1029    }
1030
1031    /**
1032     * Creates a new instance of the setup Bean from a JSP page.<p>
1033     *
1034     * @param pageContext the JSP's page context
1035     */

1036    public void init(PageContext JavaDoc pageContext) {
1037
1038        // check for OpenCms installation directory path
1039
String JavaDoc webAppRfsPath = pageContext.getServletConfig().getServletContext().getRealPath("/");
1040
1041        // read the the OpenCms servlet mapping from the servlet context parameters
1042
String JavaDoc servletMapping = pageContext.getServletContext().getInitParameter(
1043            OpenCmsServlet.SERVLET_PARAM_OPEN_CMS_SERVLET);
1044
1045        // read the the default context name from the servlet context parameters
1046
String JavaDoc defaultWebApplication = pageContext.getServletContext().getInitParameter(
1047            OpenCmsServlet.SERVLET_PARAM_DEFAULT_WEB_APPLICATION);
1048
1049        m_servletConfig = pageContext.getServletConfig();
1050
1051        init(webAppRfsPath, servletMapping, defaultWebApplication);
1052    }
1053
1054    /**
1055     * Creates a new instance of the setup Bean.<p>
1056     *
1057     * @param webAppRfsPath path to the OpenCms web application
1058     * @param servletMapping the OpenCms servlet mapping
1059     * @param defaultWebApplication the name of the default web application
1060     *
1061     */

1062    public void init(String JavaDoc webAppRfsPath, String JavaDoc servletMapping, String JavaDoc defaultWebApplication) {
1063
1064        try {
1065            // explicit set to null to overwrite exiting values from session
1066
m_availableModules = null;
1067            m_databaseKey = null;
1068            m_databaseKeys = null;
1069            m_databaseProperties = null;
1070            m_extProperties = null;
1071            m_installModules = null;
1072            m_moduleDependencies = null;
1073            m_sortedDatabaseKeys = null;
1074            m_moduleFilenames = null;
1075
1076            if (servletMapping == null) {
1077                servletMapping = "/opencms/*";
1078            }
1079            if (defaultWebApplication == null) {
1080                defaultWebApplication = "ROOT";
1081            }
1082            m_servletMapping = servletMapping;
1083            m_defaultWebApplication = defaultWebApplication;
1084
1085            setWebAppRfsPath(webAppRfsPath);
1086            m_errors = new ArrayList JavaDoc();
1087
1088            if (CmsStringUtil.isNotEmpty(webAppRfsPath)) {
1089                // workaround for JUnit test cases, this must not be executed in a test case
1090
m_extProperties = loadProperties(m_configRfsPath + CmsSystemInfo.FILE_PROPERTIES);
1091                readDatabaseConfig();
1092            }
1093
1094            if (m_workplaceImportThread != null) {
1095                if (m_workplaceImportThread.isAlive()) {
1096                    m_workplaceImportThread.kill();
1097                }
1098                m_workplaceImportThread = null;
1099                m_newLoggingOffset = 0;
1100                m_oldLoggingOffset = 0;
1101            }
1102        } catch (Exception JavaDoc e) {
1103            e.printStackTrace();
1104            m_errors.add(e.toString());
1105        }
1106    }
1107
1108    /**
1109     * This method reads the properties from the htmlmsg.property file
1110     * and sets the HTML part properties with the matching values.<p>
1111     */

1112    public void initHtmlParts() {
1113
1114        if (m_htmlProps != null) {
1115            // html already initialized
1116
return;
1117        }
1118        try {
1119            m_htmlProps = new Properties JavaDoc();
1120            m_htmlProps.load(getClass().getClassLoader().getResourceAsStream(HTML_MESSAGE_FILE));
1121        } catch (Exception JavaDoc e) {
1122            e.printStackTrace();
1123            m_errors.add(e.toString());
1124        }
1125    }
1126
1127    /**
1128     * @see org.opencms.main.I_CmsShellCommands#initShellCmsObject(org.opencms.file.CmsObject, org.opencms.main.CmsShell)
1129     */

1130    public void initShellCmsObject(CmsObject cms, CmsShell shell) {
1131
1132        m_cms = cms;
1133    }
1134
1135    /**
1136     * Over simplistic helper to compare two strings to check radio buttons.
1137     *
1138     * @param value1 the first value
1139     * @param value2 the second value
1140     * @return "checked" if both values are equal, the empty String "" otherwise
1141     */

1142    public String JavaDoc isChecked(String JavaDoc value1, String JavaDoc value2) {
1143
1144        if (value1 == null || value2 == null) {
1145            return "";
1146        }
1147
1148        if (value1.trim().equalsIgnoreCase(value2.trim())) {
1149            return "checked";
1150        }
1151
1152        return "";
1153    }
1154
1155    /**
1156     * Returns true if this setup bean is correctly initialized.<p>
1157     *
1158     * @return true if this setup bean is correctly initialized
1159     */

1160    public boolean isInitialized() {
1161
1162        return m_extProperties != null;
1163    }
1164
1165    /**
1166     * Returns js code with array definition for the available module dependencies.<p>
1167     *
1168     * @return js code
1169     */

1170    public String JavaDoc jsModuleDependencies() {
1171
1172        List JavaDoc moduleNames = sortModules(getAvailableModules().values());
1173
1174        StringBuffer JavaDoc jsCode = new StringBuffer JavaDoc(1024);
1175        jsCode.append("\t// an array holding the dependent modules for the n-th module\n");
1176        jsCode.append("\tvar moduleDependencies = new Array(");
1177        jsCode.append(moduleNames.size());
1178        jsCode.append(");\n");
1179        for (int i = 0; i < moduleNames.size(); i++) {
1180            String JavaDoc moduleName = (String JavaDoc)moduleNames.get(i);
1181            List JavaDoc dependencies = (List JavaDoc)getModuleDependencies().get(moduleName);
1182            jsCode.append("\tmoduleDependencies[" + i + "] = new Array(");
1183            if (dependencies != null) {
1184                for (int j = 0; j < dependencies.size(); j++) {
1185                    jsCode.append("\"" + dependencies.get(j) + "\"");
1186                    if (j < dependencies.size() - 1) {
1187                        jsCode.append(", ");
1188                    }
1189                }
1190            }
1191            jsCode.append(");\n");
1192        }
1193        jsCode.append("\n\n");
1194        return jsCode.toString();
1195    }
1196
1197    /**
1198     * Returns js code with array definition for the available module names.<p>
1199     *
1200     * @return js code
1201     */

1202    public String JavaDoc jsModuleNames() {
1203
1204        List JavaDoc moduleNames = sortModules(getAvailableModules().values());
1205        StringBuffer JavaDoc jsCode = new StringBuffer JavaDoc(1024);
1206        jsCode.append("\t// an array from 1...n holding the module package names\n");
1207        jsCode.append("\tvar modulePackageNames = new Array(");
1208        jsCode.append(moduleNames.size());
1209        jsCode.append(");\n");
1210        for (int i = 0; i < moduleNames.size(); i++) {
1211            String JavaDoc moduleName = (String JavaDoc)moduleNames.get(i);
1212            jsCode.append("\tmodulePackageNames[" + i + "] = \"" + moduleName + "\";\n");
1213        }
1214        jsCode.append("\n\n");
1215        return jsCode.toString();
1216    }
1217
1218    /**
1219     * Loads the default OpenCms properties.<p>
1220     *
1221     * @param file the file tp read the properties from
1222     * @return the initialized OpenCms properties
1223     * @throws IOException in case of IO errors
1224     */

1225    public ExtendedProperties loadProperties(String JavaDoc file) throws IOException JavaDoc {
1226
1227        return CmsPropertyUtils.loadProperties(file);
1228    }
1229
1230    /**
1231     * Locks (i.e. disables) the setup wizard.<p>
1232     *
1233     */

1234    public void lockWizard() {
1235
1236        setExtProperty("wizard.enabled", CmsStringUtil.FALSE);
1237    }
1238
1239    /**
1240     * Prepares step 10 of the setup wizard.<p>
1241     */

1242    public void prepareStep10() {
1243
1244        if (isInitialized()) {
1245            // lock the wizard for further use
1246
lockWizard();
1247            // save Properties to file "opencms.properties"
1248
saveProperties(getProperties(), CmsSystemInfo.FILE_PROPERTIES, false);
1249        }
1250    }
1251
1252    /**
1253     * Prepares step 8 of the setup wizard.<p>
1254     *
1255     * @return true if the workplace should be imported
1256     *
1257     * @throws CmsXmlException if something goes wrong
1258     */

1259    public boolean prepareStep8() throws CmsXmlException {
1260
1261        if (isInitialized()) {
1262            checkEthernetAddress();
1263            // backup the XML configuration
1264
backupConfiguration(
1265                CmsImportExportConfiguration.DEFAULT_XML_FILE_NAME,
1266                CmsImportExportConfiguration.DEFAULT_XML_FILE_NAME + CmsConfigurationManager.POSTFIX_ORI);
1267            backupConfiguration(
1268                CmsModuleConfiguration.DEFAULT_XML_FILE_NAME,
1269                CmsModuleConfiguration.DEFAULT_XML_FILE_NAME + CmsConfigurationManager.POSTFIX_ORI);
1270            backupConfiguration(
1271                CmsSearchConfiguration.DEFAULT_XML_FILE_NAME,
1272                CmsSearchConfiguration.DEFAULT_XML_FILE_NAME + CmsConfigurationManager.POSTFIX_ORI);
1273            backupConfiguration(
1274                CmsSystemConfiguration.DEFAULT_XML_FILE_NAME,
1275                CmsSystemConfiguration.DEFAULT_XML_FILE_NAME + CmsConfigurationManager.POSTFIX_ORI);
1276            backupConfiguration(CmsVfsConfiguration.DEFAULT_XML_FILE_NAME, CmsVfsConfiguration.DEFAULT_XML_FILE_NAME
1277                + CmsConfigurationManager.POSTFIX_ORI);
1278            backupConfiguration(
1279                CmsWorkplaceConfiguration.DEFAULT_XML_FILE_NAME,
1280                CmsWorkplaceConfiguration.DEFAULT_XML_FILE_NAME + CmsConfigurationManager.POSTFIX_ORI);
1281            backupConfiguration(
1282                CmsConfigurationManager.DEFAULT_XML_FILE_NAME,
1283                CmsConfigurationManager.DEFAULT_XML_FILE_NAME + CmsConfigurationManager.POSTFIX_ORI);
1284            // save Properties to file "opencms.properties"
1285
saveProperties(getProperties(), CmsSystemInfo.FILE_PROPERTIES, true);
1286
1287            CmsSetupTestResult testResult = new CmsSetupTestSimapi().execute(this);
1288            if (testResult.getResult().equals(I_CmsSetupTest.RESULT_FAILED)) {
1289                // "/opencms/vfs/resources/resourceloaders/loader[@class='org.opencms.loader.CmsImageLoader']/param[@name='image.scaling.enabled']";
1290
StringBuffer JavaDoc xp = new StringBuffer JavaDoc(256);
1291                xp.append("/").append(CmsConfigurationManager.N_ROOT);
1292                xp.append("/").append(CmsVfsConfiguration.N_VFS);
1293                xp.append("/").append(CmsVfsConfiguration.N_RESOURCES);
1294                xp.append("/").append(CmsVfsConfiguration.N_RESOURCELOADERS);
1295                xp.append("/").append(CmsVfsConfiguration.N_LOADER);
1296                xp.append("[@").append(I_CmsXmlConfiguration.A_CLASS);
1297                xp.append("='").append(CmsImageLoader.class.getName());
1298                xp.append("']/").append(I_CmsXmlConfiguration.N_PARAM);
1299                xp.append("[@").append(I_CmsXmlConfiguration.A_NAME);
1300                xp.append("='").append(CmsImageLoader.CONFIGURATION_SCALING_ENABLED).append("']");
1301
1302                getXmlHelper().setValue(
1303                    CmsVfsConfiguration.DEFAULT_XML_FILE_NAME,
1304                    xp.toString(),
1305                    Boolean.FALSE.toString());
1306            }
1307            // /opencms/system/sites/workplace-server
1308
StringBuffer JavaDoc xp = new StringBuffer JavaDoc(256);
1309            xp.append("/").append(CmsConfigurationManager.N_ROOT);
1310            xp.append("/").append(CmsSystemConfiguration.N_SYSTEM);
1311            xp.append("/").append(CmsSystemConfiguration.N_SITES);
1312            xp.append("/").append(CmsSystemConfiguration.N_WORKPLACE_SERVER);
1313
1314            getXmlHelper().setValue(CmsSystemConfiguration.DEFAULT_XML_FILE_NAME, xp.toString(), getWorkplaceSite());
1315
1316            // /opencms/system/sites/site[@uri='/sites/default/']/@server
1317
xp = new StringBuffer JavaDoc(256);
1318            xp.append("/").append(CmsConfigurationManager.N_ROOT);
1319            xp.append("/").append(CmsSystemConfiguration.N_SYSTEM);
1320            xp.append("/").append(CmsSystemConfiguration.N_SITES);
1321            xp.append("/").append(I_CmsXmlConfiguration.N_SITE);
1322            xp.append("[@").append(I_CmsXmlConfiguration.A_URI);
1323            xp.append("='").append(CmsResource.VFS_FOLDER_SITES);
1324            xp.append("/default/']/@").append(CmsSystemConfiguration.A_SERVER);
1325
1326            getXmlHelper().setValue(CmsSystemConfiguration.DEFAULT_XML_FILE_NAME, xp.toString(), getWorkplaceSite());
1327
1328            getXmlHelper().writeAll();
1329        }
1330        return true;
1331    }
1332
1333    /**
1334     * Prepares step 8b of the setup wizard.<p>
1335     */

1336    public void prepareStep8b() {
1337
1338        if (!isInitialized()) {
1339            return;
1340        }
1341
1342        if ((m_workplaceImportThread != null) && (m_workplaceImportThread.isFinished())) {
1343            // setup is already finished, just wait for client to collect final data
1344
return;
1345        }
1346
1347        if (m_workplaceImportThread == null) {
1348            m_workplaceImportThread = new CmsSetupWorkplaceImportThread(this);
1349        }
1350
1351        if (!m_workplaceImportThread.isAlive()) {
1352            m_workplaceImportThread.start();
1353        }
1354    }
1355
1356    /**
1357     * Generates the output for step 8b of the setup wizard.<p>
1358     *
1359     * @param out the JSP print stream
1360     * @throws IOException in case errors occur while writing to "out"
1361     */

1362    public void prepareStep8bOutput(JspWriter JavaDoc out) throws IOException JavaDoc {
1363
1364        m_oldLoggingOffset = m_newLoggingOffset;
1365        m_newLoggingOffset = m_workplaceImportThread.getLoggingThread().getMessages().size();
1366        if (isInitialized()) {
1367            for (int i = m_oldLoggingOffset; i < m_newLoggingOffset; i++) {
1368                String JavaDoc str = m_workplaceImportThread.getLoggingThread().getMessages().get(i).toString();
1369                str = CmsEncoder.escapeWBlanks(str, CmsEncoder.ENCODING_UTF_8);
1370                out.println("output[" + (i - m_oldLoggingOffset) + "] = \"" + str + "\";");
1371            }
1372        } else {
1373            out.println("output[0] = 'ERROR';");
1374        }
1375
1376        boolean threadFinished = m_workplaceImportThread.isFinished();
1377        boolean allWritten = m_oldLoggingOffset >= m_workplaceImportThread.getLoggingThread().getMessages().size();
1378
1379        out.println("function initThread() {");
1380        if (isInitialized()) {
1381            out.print("send();");
1382            if (threadFinished && allWritten) {
1383                out.println("setTimeout('top.display.finish()', 1000);");
1384            } else {
1385                int timeout = 5000;
1386                if (getWorkplaceImportThread().getLoggingThread().getMessages().size() < 20) {
1387                    timeout = 2000;
1388                }
1389                out.println("setTimeout('location.reload()', " + timeout + ");");
1390            }
1391        }
1392        out.println("}");
1393    }
1394
1395    /**
1396     * Saves properties to specified file.<p>
1397     *
1398     * @param properties the properties to be saved
1399     * @param file the file to save the properties to
1400     * @param backup if true, create a backupfile
1401     */

1402    public void saveProperties(ExtendedProperties properties, String JavaDoc file, boolean backup) {
1403
1404        if (new File JavaDoc(m_configRfsPath + file).isFile()) {
1405            String JavaDoc backupFile = file + CmsConfigurationManager.POSTFIX_ORI;
1406            String JavaDoc tempFile = file + ".tmp";
1407
1408            m_errors.clear();
1409
1410            if (backup) {
1411                // make a backup copy
1412
copyFile(file, FOLDER_BACKUP + backupFile);
1413            }
1414
1415            //save to temporary file
1416
copyFile(file, tempFile);
1417
1418            // save properties
1419
save(properties, tempFile, file);
1420
1421            // delete temp file
1422
File JavaDoc temp = new File JavaDoc(m_configRfsPath + tempFile);
1423            temp.delete();
1424        } else {
1425            m_errors.add("No valid file: " + file + "\n");
1426        }
1427
1428    }
1429
1430    /**
1431     * Sets the database drivers to the given value.<p>
1432     *
1433     * @param databaseKey the key of the selected database server (e.g. "mysql", "generic" or "oracle")
1434     */

1435    public void setDatabase(String JavaDoc databaseKey) {
1436
1437        m_databaseKey = databaseKey;
1438
1439        String JavaDoc vfsDriver = getDbProperty(m_databaseKey + ".vfs.driver");
1440        String JavaDoc userDriver = getDbProperty(m_databaseKey + ".user.driver");
1441        String JavaDoc projectDriver = getDbProperty(m_databaseKey + ".project.driver");
1442        String JavaDoc workflowDriver = getDbProperty(m_databaseKey + ".workflow.driver");
1443        String JavaDoc backupDriver = getDbProperty(m_databaseKey + ".backup.driver");
1444        String JavaDoc sqlManager = getDbProperty(m_databaseKey + ".sqlmanager");
1445
1446        setExtProperty("db.name", m_databaseKey);
1447        setExtProperty("db.vfs.driver", vfsDriver);
1448        setExtProperty("db.vfs.sqlmanager", sqlManager);
1449        setExtProperty("db.user.driver", userDriver);
1450        setExtProperty("db.user.sqlmanager", sqlManager);
1451        setExtProperty("db.project.driver", projectDriver);
1452        setExtProperty("db.project.sqlmanager", sqlManager);
1453        setExtProperty("db.workflow.driver", workflowDriver);
1454        setExtProperty("db.workflow.sqlmanager", sqlManager);
1455        setExtProperty("db.backup.driver", backupDriver);
1456        setExtProperty("db.backup.sqlmanager", sqlManager);
1457    }
1458
1459    /**
1460     * Sets the database name.<p>
1461     *
1462     * @param db the database name to set
1463     */

1464    public void setDb(String JavaDoc db) {
1465
1466        setDbProperty(m_databaseKey + ".dbname", db);
1467    }
1468
1469    /**
1470     * Sets the JDBC connect URL parameters.<p>
1471     *
1472     * @param value the JDBC connect URL parameters
1473     */

1474    public void setDbConStrParams(String JavaDoc value) {
1475
1476        setDbProperty(m_databaseKey + ".constr.params", value);
1477    }
1478
1479    /**
1480     * Sets the database create statement.<p>
1481     *
1482     * @param dbCreateConStr the database create statement
1483     */

1484    public void setDbCreateConStr(String JavaDoc dbCreateConStr) {
1485
1486        setDbProperty(m_databaseKey + ".constr", dbCreateConStr);
1487    }
1488
1489    /**
1490     * Sets the password used for the initial OpenCms database creation.<p>
1491     *
1492     * This password will not be stored permanently,
1493     * but used only in the setup wizard.<p>
1494     *
1495     * @param dbCreatePwd the password used for the initial OpenCms database creation
1496     */

1497    public void setDbCreatePwd(String JavaDoc dbCreatePwd) {
1498
1499        m_dbCreatePwd = dbCreatePwd;
1500    }
1501
1502    /**
1503     * Set the database user that is used to connect to the database.<p>
1504     *
1505     * @param dbCreateUser the user to set
1506     */

1507    public void setDbCreateUser(String JavaDoc dbCreateUser) {
1508
1509        setDbProperty(m_databaseKey + ".user", dbCreateUser);
1510    }
1511
1512    /**
1513     * Sets the database driver belonging to the database.<p>
1514     *
1515     * @param driver name of the opencms driver
1516     */

1517    public void setDbDriver(String JavaDoc driver) {
1518
1519        setDbProperty(m_databaseKey + ".driver", driver);
1520    }
1521
1522    /**
1523     * Sets the needed database parameters.<p>
1524     *
1525     * @param request the http request
1526     * @param provider the db provider
1527     *
1528     * @return true if already submitted
1529     */

1530    public boolean setDbParamaters(HttpServletRequest JavaDoc request, String JavaDoc provider) {
1531
1532        String JavaDoc conStr = request.getParameter("dbCreateConStr");
1533
1534        // store the DB provider
1535
m_provider = provider;
1536
1537        boolean isFormSubmitted = ((request.getParameter("submit") != null) && (conStr != null));
1538        if (conStr == null) {
1539            conStr = "";
1540        }
1541        String JavaDoc database = "";
1542        if (provider.equals(MYSQL_PROVIDER)) {
1543            database = request.getParameter("db");
1544        } else if (provider.equals(POSTGRESQL_PROVIDER)) {
1545            database = request.getParameter("dbName");
1546        }
1547        if (provider.equals(MYSQL_PROVIDER) || provider.equals(POSTGRESQL_PROVIDER)) {
1548            isFormSubmitted = (isFormSubmitted && (database != null));
1549        }
1550
1551        if (isInitialized()) {
1552            String JavaDoc createDb = request.getParameter("createDb");
1553            if (createDb == null) {
1554                createDb = "";
1555            }
1556
1557            String JavaDoc createTables = request.getParameter("createTables");
1558            if (createTables == null) {
1559                createTables = "";
1560            }
1561
1562            if (isFormSubmitted) {
1563                if (provider.equals(POSTGRESQL_PROVIDER)) {
1564                    setDb(database);
1565
1566                    String JavaDoc templateDb = request.getParameter("templateDb");
1567                    setDbProperty(getDatabase() + ".templateDb", templateDb);
1568                    setDbProperty(getDatabase() + ".newDb", database);
1569
1570                    if (!conStr.endsWith("/")) {
1571                        conStr += "/";
1572                    }
1573                    setDbProperty(getDatabase() + ".constr", conStr + getDbProperty(getDatabase() + ".templateDb"));
1574                    setDbProperty(getDatabase() + ".constr.newDb", conStr + getDbProperty(getDatabase() + ".newDb"));
1575                    conStr += database;
1576                } else if (provider.equals(MYSQL_PROVIDER) || provider.equals(POSTGRESQL_PROVIDER)) {
1577                    if (!conStr.endsWith("/")) {
1578                        conStr += "/";
1579                    }
1580                    conStr += database;
1581                }
1582                setDbWorkConStr(conStr);
1583                if (provider.equals(POSTGRESQL_PROVIDER)) {
1584                    setDb(database);
1585                }
1586                String JavaDoc dbCreateUser = request.getParameter("dbCreateUser");
1587                String JavaDoc dbCreatePwd = request.getParameter("dbCreatePwd");
1588
1589                String JavaDoc dbWorkUser = request.getParameter("dbWorkUser");
1590                String JavaDoc dbWorkPwd = request.getParameter("dbWorkPwd");
1591
1592                setDbCreateUser(dbCreateUser);
1593                setDbCreatePwd(dbCreatePwd);
1594
1595                if (dbWorkUser.equals("")) {
1596                    dbWorkUser = request.getContextPath();
1597                }
1598                if (dbWorkUser.equals("")) {
1599                    dbWorkUser = "opencms";
1600                }
1601                if (dbWorkUser.startsWith("/")) {
1602                    dbWorkUser = dbWorkUser.substring(1, dbWorkUser.length());
1603                }
1604                setDbWorkUser(dbWorkUser);
1605                setDbWorkPwd(dbWorkPwd);
1606
1607                if (provider.equals(ORACLE_PROVIDER)) {
1608                    String JavaDoc dbDefaultTablespace = request.getParameter("dbDefaultTablespace");
1609                    String JavaDoc dbTemporaryTablespace = request.getParameter("dbTemporaryTablespace");
1610                    String JavaDoc dbIndexTablespace = request.getParameter("dbIndexTablespace");
1611
1612                    setDbProperty(getDatabase() + ".defaultTablespace", dbDefaultTablespace);
1613                    setDbProperty(getDatabase() + ".temporaryTablespace", dbTemporaryTablespace);
1614                    setDbProperty(getDatabase() + ".indexTablespace", dbIndexTablespace);
1615                }
1616                Map JavaDoc replacer = new HashMap JavaDoc();
1617                if (!provider.equals(MYSQL_PROVIDER)) {
1618                    replacer.put("${user}", dbWorkUser);
1619                    replacer.put("${password}", dbWorkPwd);
1620                }
1621                if (provider.equals(MYSQL_PROVIDER) || provider.equals(POSTGRESQL_PROVIDER)) {
1622                    replacer.put("${database}", database);
1623                }
1624                if (provider.equals(ORACLE_PROVIDER)) {
1625                    replacer.put("${defaultTablespace}", getDbProperty(getDatabase() + ".defaultTablespace"));
1626                    replacer.put("${indexTablespace}", getDbProperty(getDatabase() + ".indexTablespace"));
1627                    replacer.put("${temporaryTablespace}", getDbProperty(getDatabase() + ".temporaryTablespace"));
1628                }
1629                setReplacer(replacer);
1630
1631                if (provider.equals(GENERIC_PROVIDER)
1632                    || provider.equals(ORACLE_PROVIDER)
1633                    || provider.equals(MAXDB_PROVIDER)) {
1634                    request.getSession().setAttribute("createTables", createTables);
1635                }
1636                request.getSession().setAttribute("createDb", createDb);
1637            } else {
1638                String JavaDoc dbName = "opencms";
1639                // initialize the database name with the app name
1640
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(request.getContextPath())) {
1641                    dbName = request.getContextPath().substring(1);
1642                }
1643                if (provider.equals(ORACLE_PROVIDER)
1644                    || provider.equals(POSTGRESQL_PROVIDER)
1645                    || provider.equals(MAXDB_PROVIDER)) {
1646                    setDbWorkUser(dbName);
1647                } else {
1648                    setDb(dbName);
1649                }
1650            }
1651        }
1652        return isFormSubmitted;
1653    }
1654
1655    /**
1656     * This method sets the value for a given key in the database properties.<p>
1657     *
1658     * @param key The key of the property
1659     * @param value The value of the property
1660     */

1661    public void setDbProperty(String JavaDoc key, String JavaDoc value) {
1662
1663        // extract the database key out of the entire key
1664
String JavaDoc databaseKey = key.substring(0, key.indexOf('.'));
1665        Map JavaDoc databaseProperties = (Map JavaDoc)getDatabaseProperties().get(databaseKey);
1666        databaseProperties.put(key, value);
1667    }
1668
1669    /**
1670     * Sets the connection string to the database to the given value.<p>
1671     *
1672     * @param dbWorkConStr the connection string used by the OpenCms core
1673     */

1674    public void setDbWorkConStr(String JavaDoc dbWorkConStr) {
1675
1676        String JavaDoc driver = getDbProperty(m_databaseKey + ".driver");
1677        String JavaDoc pool = '.' + getPool() + '.';
1678
1679        setExtProperty(CmsDbPool.KEY_DATABASE_POOL + pool + CmsDbPool.KEY_JDBC_DRIVER, driver);
1680        setExtProperty(CmsDbPool.KEY_DATABASE_POOL + pool + CmsDbPool.KEY_JDBC_URL, dbWorkConStr);
1681        setExtProperty(CmsDbPool.KEY_DATABASE_POOL + pool + CmsDbPool.KEY_TEST_QUERY, getDbTestQuery());
1682        setExtProperty(CmsDbPool.KEY_DATABASE_POOL + pool + CmsDbPool.KEY_JDBC_URL_PARAMS, getDbConStrParams());
1683    }
1684
1685    /**
1686     * Sets the password of the database to the given value.<p>
1687     *
1688     * @param dbWorkPwd the password for the OpenCms database user
1689     */

1690    public void setDbWorkPwd(String JavaDoc dbWorkPwd) {
1691
1692        setExtProperty(CmsDbPool.KEY_DATABASE_POOL + '.' + getPool() + '.' + CmsDbPool.KEY_PASSWORD, dbWorkPwd);
1693    }
1694
1695    /**
1696     * Sets the user of the database to the given value.<p>
1697     *
1698     * @param dbWorkUser the database user used by the opencms core
1699     */

1700    public void setDbWorkUser(String JavaDoc dbWorkUser) {
1701
1702        setExtProperty(CmsDbPool.KEY_DATABASE_POOL + '.' + getPool() + '.' + CmsDbPool.KEY_POOL_USER, dbWorkUser);
1703    }
1704
1705    /**
1706     * Set the mac ethernet address, required for UUID generation.<p>
1707     *
1708     * @param ethernetAddress the mac addess to set
1709     */

1710    public void setEthernetAddress(String JavaDoc ethernetAddress) {
1711
1712        setExtProperty("server.ethernet.address", ethernetAddress);
1713    }
1714
1715    /**
1716     * Sets the list with the package names of the modules to be installed.<p>
1717     *
1718     * @param value a string with the package names of the modules to be installed delimited by the pipe symbol "|"
1719     */

1720    public void setInstallModules(String JavaDoc value) {
1721
1722        m_installModules = CmsStringUtil.splitAsList(value, "|", true);
1723        try {
1724            m_installModules = CmsModuleManager.topologicalSort(m_installModules, getModuleFolder());
1725        } catch (CmsConfigurationException e) {
1726            throw new RuntimeException JavaDoc(e);
1727        }
1728    }
1729
1730    /**
1731     * Sets the replacer.<p>
1732     *
1733     * @param map the replacer to set
1734     */

1735    public void setReplacer(Map JavaDoc map) {
1736
1737        m_replacer = map;
1738    }
1739
1740    /**
1741     * Sets the OpenCms server name.<p>
1742     *
1743     * @param name the OpenCms server name
1744     */

1745    public void setServerName(String JavaDoc name) {
1746
1747        setExtProperty("server.name", name);
1748    }
1749
1750    /**
1751     * Sets the OpenCms workplace site.<p>
1752     *
1753     * @param newSite the OpenCms workplace site
1754     */

1755    public void setWorkplaceSite(String JavaDoc newSite) {
1756
1757        String JavaDoc oldSite = getWorkplaceSite();
1758        // get the site list
1759
String JavaDoc siteList = getExtProperty("site.root.list");
1760        // replace old site URL in site list with new site URL
1761
siteList = CmsStringUtil.substitute(siteList, oldSite, newSite);
1762        setExtProperty("site.root.list", siteList);
1763        setExtProperty("site.workplace", newSite);
1764    }
1765
1766    /**
1767     * @see org.opencms.main.I_CmsShellCommands#shellExit()
1768     */

1769    public void shellExit() {
1770
1771        System.out.println();
1772        System.out.println();
1773        System.out.println("The setup is finished!\nThe OpenCms system used for the setup will now shut down.");
1774    }
1775
1776    /**
1777     * @see org.opencms.main.I_CmsShellCommands#shellStart()
1778     */

1779    public void shellStart() {
1780
1781        System.out.println();
1782        System.out.println("Starting Workplace import and database setup for OpenCms!");
1783
1784        String JavaDoc[] copy = Messages.COPYRIGHT_BY_ALKACON;
1785        for (int i = copy.length - 1; i >= 0; i--) {
1786            System.out.println(copy[i]);
1787        }
1788        System.out.println("This is OpenCms " + OpenCms.getSystemInfo().getVersionName());
1789        System.out.println();
1790        System.out.println();
1791    }
1792
1793    /**
1794     * Sorts the modules for display.<p>
1795     *
1796     * @param modules the list of {@link CmsModule} objects
1797     *
1798     * @return a sorted list of module names
1799     */

1800    public List JavaDoc sortModules(Collection JavaDoc modules) {
1801
1802        List JavaDoc aux = new ArrayList JavaDoc(modules);
1803        Collections.sort(aux, new Comparator JavaDoc() {
1804
1805            public int compare(Object JavaDoc o1, Object JavaDoc o2) {
1806
1807                CmsModule module1 = (CmsModule)o1;
1808                CmsModule module2 = (CmsModule)o2;
1809                return getDisplayForModule(module1).compareTo(getDisplayForModule(module2));
1810            }
1811        });
1812
1813        List JavaDoc ret = new ArrayList JavaDoc(aux.size());
1814        for (Iterator JavaDoc it = aux.iterator(); it.hasNext();) {
1815            CmsModule module = (CmsModule)it.next();
1816            ret.add(module.getName());
1817        }
1818        return ret;
1819    }
1820
1821    /**
1822     * Checks the jdbc driver.<p>
1823     *
1824     * @return <code>true</code> if at least one of the recommended drivers is found
1825     */

1826    public boolean validateJdbc() {
1827
1828        boolean result = false;
1829        String JavaDoc libFolder = getLibFolder();
1830        Iterator JavaDoc it = getDatabaseLibs(getDatabase()).iterator();
1831        while (it.hasNext()) {
1832            String JavaDoc libName = (String JavaDoc)it.next();
1833            File JavaDoc libFile = new File JavaDoc(libFolder, libName);
1834            if (libFile.exists()) {
1835                result = true;
1836            }
1837        }
1838        return result;
1839    }
1840
1841    /**
1842     * Returns the value for a given key from the extended properties.
1843     *
1844     * @param key the property key
1845     * @return the string value for a given key
1846     */

1847    protected String JavaDoc getExtProperty(String JavaDoc key) {
1848
1849        Object JavaDoc value = m_extProperties.get(key);
1850        return (value != null) ? value.toString() : "";
1851    }
1852
1853    /**
1854     * Returns html for the given module to fill the selection list.<p>
1855     *
1856     * @param module the module to generate the code for
1857     * @param pos the position in the list
1858     *
1859     * @return html code
1860     */

1861    protected String JavaDoc htmlModule(CmsModule module, int pos) {
1862
1863        StringBuffer JavaDoc html = new StringBuffer JavaDoc(256);
1864        html.append("\t<tr>\n");
1865        html.append("\t\t<td style='vertical-align: top;'>\n");
1866        html.append("\t\t\t<input type='checkbox' name='availableModules' value='");
1867        html.append(module.getName());
1868        html.append("' checked='checked' onClick=\"checkDependencies('");
1869        html.append(module.getName());
1870        html.append("');\">\n");
1871        html.append("\t\t</td>\n");
1872        html.append("\t\t<td style='vertical-align: top; width: 100%; padding-top: 4px;'>\n\t\t\t");
1873        html.append(getDisplayForModule(module));
1874        html.append("\n\t\t</td>\n");
1875        html.append("\t\t<td style='vertical-align: top; text-align: right;'>\n");
1876        if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(module.getDescription())) {
1877            html.append("\t\t\t");
1878            html.append(getHtmlHelpIcon("" + pos, ""));
1879        }
1880        html.append("\t\t</td>\n");
1881        html.append("\t</tr>\n");
1882        return html.toString();
1883    }
1884
1885    /**
1886     * Imports a module (zipfile) from the default module directory,
1887     * creating a temporary project for this.<p>
1888     *
1889     * @param importFile the name of the import module located in the default module directory
1890     * @throws Exception if something goes wrong
1891     * @see org.opencms.importexport.CmsImportExportManager#importData(CmsObject, String, String, org.opencms.report.I_CmsReport)
1892     */

1893    protected void importModuleFromDefault(String JavaDoc importFile) throws Exception JavaDoc {
1894
1895        String JavaDoc fileName = getModuleFolder() + importFile;
1896        OpenCms.getImportExportManager().importData(
1897            m_cms,
1898            fileName,
1899            null,
1900            new CmsShellReport(m_cms.getRequestContext().getLocale()));
1901    }
1902
1903    /**
1904     * Stores the properties of all available database configurations in a
1905     * map keyed by their database key names (e.g. "mysql", "generic" or "oracle").<p>
1906     */

1907    protected void readDatabaseConfig() {
1908
1909        String JavaDoc databaseKey = null;
1910        FileInputStream JavaDoc input = null;
1911        String JavaDoc configPath = null;
1912        Properties JavaDoc databaseProperties = null;
1913        File JavaDoc databaseSetupFolder = null;
1914        File JavaDoc[] childResources = null;
1915        File JavaDoc childResource = null;
1916        File JavaDoc setupFile = null;
1917        boolean hasMissingSetupFiles = false;
1918
1919        m_databaseKeys = new ArrayList JavaDoc();
1920        m_databaseProperties = new HashMap JavaDoc();
1921
1922        try {
1923            databaseSetupFolder = new File JavaDoc(m_webAppRfsPath + FOLDER_SETUP + FOLDER_DATABASE);
1924
1925            if (databaseSetupFolder.exists()) {
1926                childResources = databaseSetupFolder.listFiles();
1927
1928                if (childResources != null) {
1929                    for (int i = 0; i < childResources.length; i++) {
1930                        childResource = childResources[i];
1931                        hasMissingSetupFiles = false;
1932
1933                        if (childResource.exists() && childResource.isDirectory() && childResource.canRead()) {
1934                            for (int j = 0; j < REQUIRED_DB_SETUP_FILES.length; j++) {
1935                                setupFile = new File JavaDoc(childResource.getPath()
1936                                    + File.separatorChar
1937                                    + REQUIRED_DB_SETUP_FILES[j]);
1938
1939                                if (!setupFile.exists() || !setupFile.isFile() || !setupFile.canRead()) {
1940                                    hasMissingSetupFiles = true;
1941                                    System.err.println("["
1942                                        + getClass().getName()
1943                                        + "] missing or unreadable database setup file: "
1944                                        + setupFile.getPath());
1945                                    break;
1946                                }
1947
1948                                if (!hasMissingSetupFiles) {
1949                                    m_databaseKeys.add(childResource.getName().trim());
1950                                }
1951                            }
1952                        }
1953                    }
1954                }
1955
1956                for (int i = 0; i < m_databaseKeys.size(); i++) {
1957                    databaseKey = (String JavaDoc)m_databaseKeys.get(i);
1958                    configPath = m_webAppRfsPath
1959                        + "setup"
1960                        + File.separatorChar
1961                        + "database"
1962                        + File.separatorChar
1963                        + databaseKey
1964                        + File.separatorChar
1965                        + "database.properties";
1966
1967                    try {
1968                        input = new FileInputStream JavaDoc(new File JavaDoc(configPath));
1969                        databaseProperties = new Properties JavaDoc();
1970                        databaseProperties.load(input);
1971                        m_databaseProperties.put(databaseKey, databaseProperties);
1972                    } catch (Exception JavaDoc e) {
1973                        System.err.println(e.toString());
1974                        e.printStackTrace(System.err);
1975                        continue;
1976                    }
1977                }
1978            }
1979        } catch (Exception JavaDoc e) {
1980            System.err.println(e.toString());
1981            e.printStackTrace(System.err);
1982        } finally {
1983            try {
1984                if (input != null) {
1985                    input.close();
1986                }
1987            } catch (Exception JavaDoc e) {
1988                // noop
1989
}
1990        }
1991    }
1992
1993    /**
1994     * This method sets the value for a given key in the extended properties.
1995     * @param key The key of the property
1996     * @param value The value of the property
1997     */

1998    protected void setExtProperty(String JavaDoc key, String JavaDoc value) {
1999
2000        m_extProperties.put(key, value);
2001    }
2002
2003    /**
2004     * Saves the properties to a file.<p>
2005     *
2006     * @param properties the properties to be saved
2007     * @param source the source file to get the keys from
2008     * @param target the target file to save the properties to
2009     */

2010    private void save(ExtendedProperties properties, String JavaDoc source, String JavaDoc target) {
2011
2012        try {
2013            HashSet JavaDoc alreadyWritten = new HashSet JavaDoc();
2014
2015            LineNumberReader JavaDoc lnr = new LineNumberReader JavaDoc(new FileReader JavaDoc(new File JavaDoc(m_configRfsPath + source)));
2016
2017            FileWriter JavaDoc fw = new FileWriter JavaDoc(new File JavaDoc(m_configRfsPath + target));
2018
2019            while (true) {
2020                String JavaDoc line = lnr.readLine();
2021                if (line == null) {
2022                    break;
2023                }
2024                line = line.trim();
2025
2026                if ("".equals(line)) {
2027                    // output empty line
2028
fw.write("\n");
2029                } else if (line.startsWith("#")) {
2030                    // output comment
2031
fw.write(line);
2032                    fw.write("\n");
2033                } else {
2034
2035                    int index = line.indexOf('=');
2036                    int index1 = line.indexOf("\\=");
2037                    if (line.indexOf('=') > -1 && index1 != index - 1) {
2038
2039                        String JavaDoc key = line.substring(0, line.indexOf('=')).trim();
2040                        if (alreadyWritten.contains(key)) {
2041                            continue;
2042                        }
2043                        // write key
2044
fw.write((key + "="));
2045                        try {
2046                            Object JavaDoc obj = properties.get(key);
2047                            String JavaDoc value = "";
2048
2049                            if (obj != null && obj instanceof Vector JavaDoc) {
2050                                String JavaDoc[] values = {};
2051                                values = (String JavaDoc[])((Vector JavaDoc)obj).toArray(values);
2052                                StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
2053
2054                                for (int i = 0; i < values.length; i++) {
2055
2056                                    // escape commas and equals in value
2057
values[i] = CmsStringUtil.substitute(values[i], ",", "\\,");
2058                                    values[i] = CmsStringUtil.substitute(values[i], "=", "\\=");
2059
2060                                    buf.append("\t" + values[i] + ((i < values.length - 1) ? ",\\\n" : ""));
2061                                }
2062                                value = buf.toString();
2063
2064                                // write it
2065
fw.write("\\\n" + value);
2066
2067                            } else if (obj != null) {
2068
2069                                value = ((String JavaDoc)obj).trim();
2070
2071                                // escape commas and equals in value
2072
value = CmsStringUtil.substitute(value, ",", "\\,");
2073                                value = CmsStringUtil.substitute(value, "=", "\\=");
2074
2075                                // write it
2076
fw.write(value);
2077                            }
2078
2079                        } catch (NullPointerException JavaDoc e) {
2080                            // no value found - do nothing
2081
}
2082                        // add trailing line feed
2083
fw.write("\n");
2084
2085                        // remember that this properties is already written (multi values)
2086
alreadyWritten.add(key);
2087                    }
2088                }
2089            }
2090
2091            lnr.close();
2092            fw.close();
2093        } catch (Exception JavaDoc e) {
2094            m_errors.add("Could not save properties to " + target + " \n");
2095            m_errors.add(e.toString() + "\n");
2096        }
2097    }
2098
2099    /**
2100     * Sets the path to the OpenCms home directory.<p>
2101     *
2102     * @param webInfRfsPath path to OpenCms home directory
2103     */

2104    private void setWebAppRfsPath(String JavaDoc webInfRfsPath) {
2105
2106        m_webAppRfsPath = webInfRfsPath;
2107        if ("".equals(webInfRfsPath)) {
2108            // required for test cases
2109
m_configRfsPath = "";
2110            return;
2111        }
2112        if (!m_webAppRfsPath.endsWith(File.separator)) {
2113            // make sure that Path always ends with a separator, not always the case in different
2114
// environments since getServletContext().getRealPath("/") does not end with a "/" in
2115
// all servlet runtimes
2116
m_webAppRfsPath += File.separator;
2117        }
2118        m_configRfsPath = m_webAppRfsPath + FOLDER_WEBINF + CmsSystemInfo.FOLDER_CONFIG;
2119    }
2120}
Popular Tags