KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > bin > JahiaConfigurationWizard


1 // $Id: JahiaConfigurationWizard.java 16680 2007-03-09 11:59:35Z bpapez $
2
//
3
// ____.
4
// __/\ ______| |__/\. _______
5
// __ .____| | \ | +----+ \
6
// _______| /--| | | - \ _ | : - \_________
7
// \\______: :---| : : | : | \________>
8
// |__\---\_____________:______: :____|____:_____\
9
// /_____|
10
//
11
// . . . i n j a h i a w e t r u s t . . .
12
//
13
//
14
// JahiaConfigurationWizard
15
//
16
// 25.01.2001 AK added in jahia.
17
// 26.01.2001 AK replace sessions by context attributes, fixe some bugs,
18
// create a real wizard with previous steps and next steps :o)
19
// 29.01.2001 AK fix database check resulting bug, change method to reset
20
// jahia servlet re-init settings, and change context attributes
21
// by adding package in attribute names.
22
// 10.01.2001 AK include design.
23
// 26.02.2001 AK prepare upgrade manager workplace.
24
// 21.03.2001 AK change backup method. flatfile and jahiafiles.
25
// 22.03.2001 AK detect data on database when installing.
26
// 28.03.2001 AK completely change the properties system.
27
// 30.03.2001 AK move database methods to org.jahia.admin.DatabaseConnection
28
// and move database scripts methods to jahia.admin.DatabaseScripts
29
// 16.05.2001 NK create a default site at install.
30
// 13.08.2001 AK fix jahia files path checking bug.
31
// 14.08.2001 AK fix all jahia files dependencies.
32
// 15.08.2001 AK transform "database treatment" (appear if the database is
33
// not empty when the installation is performed) to a internal
34
// developer only feature.
35
//
36
// 23.08.2001 AK version 2.0
37
// . quality improvement in this servlet and jsp files
38
// . better exception management
39
// . code improvement for quality and readability
40
// . transfer getServerInformations() method as a jahia util
41
// . complete and fix javadoc
42
// . rename *installation* in *configuration wizard*
43
// . put some constants in web.xml file for better changes
44
//
45

46
47 package org.jahia.bin;
48
49 import java.io.BufferedReader JavaDoc;
50 import java.io.File JavaDoc;
51 import java.io.FileReader JavaDoc;
52 import java.io.IOException JavaDoc;
53 import java.io.InputStream JavaDoc;
54 import java.net.MalformedURLException JavaDoc;
55 import java.net.URL JavaDoc;
56 import java.util.Enumeration JavaDoc;
57 import java.util.HashMap JavaDoc;
58 import java.util.Locale JavaDoc;
59 import java.util.Properties JavaDoc;
60 import java.util.ResourceBundle JavaDoc;
61 import java.util.Vector JavaDoc;
62
63 import javax.servlet.ServletConfig JavaDoc;
64 import javax.servlet.ServletContext JavaDoc;
65 import javax.servlet.ServletException JavaDoc;
66 import javax.servlet.http.HttpServlet JavaDoc;
67 import javax.servlet.http.HttpServletRequest JavaDoc;
68 import javax.servlet.http.HttpServletResponse JavaDoc;
69
70 import org.jahia.admin.database.DatabaseConnection;
71 import org.jahia.admin.database.DatabaseScripts;
72 import org.jahia.data.templates.JahiaTemplatesPackage;
73 import org.jahia.data.templates.JahiaTemplatesPackageHandler;
74 import org.jahia.data.constants.JahiaConstants;
75 import org.jahia.exceptions.JahiaException;
76 import org.jahia.params.ParamBean;
77 import org.jahia.resourcebundle.JahiaResourceBundle;
78 import org.jahia.services.usermanager.JahiaGroupManagerService;
79 import org.jahia.services.usermanager.JahiaUserManagerService;
80 import org.jahia.utils.ActionHandler;
81 import org.jahia.utils.JahiaTools;
82 import org.jahia.utils.LanguageCodeConverters;
83 import org.jahia.utils.ServletContainerUtils;
84 import org.jahia.utils.properties.PropertiesManager;
85 import org.jahia.utils.zip.JahiaArchiveFileHandler;
86 import org.jahia.security.license.Limit;
87 import org.jahia.security.license.DaysLeftValidator;
88 import org.jahia.engines.EngineMessage;
89 import org.jahia.utils.PathResolver;
90 import org.jahia.utils.WebAppPathResolver;
91
92
93
94
95 /**
96  * This servlet handles the main configuration task.
97  * At the first launch of Jahia, the configuration wizard starts and provide
98  * to you the capability to configure Jahia *as you want*. During the
99  * configuration, you can set the administrator profile, change Jahia
100  * default settings, activate the mail notification, and specify which
101  * database you want to use with your Jahia portal. JahiaConfigurationWizard
102  * runs only one time, at the first launch of Jahia. If you want to change
103  * settings later, please refer to the JahiaAdministration.
104  *
105  * Copyright: Copyright (c) 2002
106  * Company: Jahia Ltd
107  *
108  * @author Alexandre Kraft
109  * @author Khue N'Guyen
110  * @version 2.0
111  */

112
113 public class JahiaConfigurationWizard extends HttpServlet JavaDoc
114 {
115     private static org.apache.log4j.Logger logger =
116             org.apache.log4j.Logger.getLogger(JahiaConfigurationWizard.class);
117
118     private static ServletContext JavaDoc context = null;
119     private static ServletConfig JavaDoc config = null;
120     private static PathResolver pathResolver = null;
121
122     private static PropertiesManager properties = null;
123     private static ActionHandler actionHandler = null;
124     private DatabaseConnection db = new DatabaseConnection();
125     private DatabaseScripts scripts = new DatabaseScripts();
126
127     private static HashMap JavaDoc serverInfos = null;
128     private static HashMap JavaDoc values = new HashMap JavaDoc();
129
130     private static String JavaDoc methods = null;
131     private static String JavaDoc dbScriptsPath = null;
132     private static String JavaDoc old_database = null;
133     private static String JavaDoc createTables = null;
134
135     private static String JavaDoc servletPath = null;
136     private static String JavaDoc contentServletPath = null;
137     private static Locale JavaDoc defaultLocale = Locale.ENGLISH;
138     private static Locale JavaDoc newSelectedLocale = null;
139
140     private static final String JavaDoc JSP = "/jsp/jahia/configuration_wizard/includer.jsp?jsp=";
141     private static final String JavaDoc HTTP_FILES = "/jsp/jahia/engines";
142     protected static final String JavaDoc CLASS_NAME = "org.jahia.bin.JahiaConfigurationWizard";
143
144     private static final String JavaDoc INIT_PARAM_CONTENT_SERVLET_PATH = "content_servlet_path";
145     private static final String JavaDoc INIT_PARAM_DEFAULT_LOCALE = "default_locale";
146
147     /**
148      * Default init method, inherited from HttpServlet. This method get two
149      * servlet container environment properties: its *home* filesystem path and
150      * its type (tomcat, orion, etc), and get the local context.
151      * @author Alexandre Kraft
152      *
153      * @param config servlet configuration (inherited).
154      * @exception ServletException a servlet exception occured during the process.
155      */

156     public void init( ServletConfig JavaDoc config )
157     throws ServletException JavaDoc
158     {
159         // get local context and config...
160
context = config.getServletContext();
161         JahiaConfigurationWizard.config = config;
162         pathResolver = new WebAppPathResolver(context);
163
164         // get server informations...
165
serverInfos = ServletContainerUtils.getServerInformations( config );
166
167         // get xml init parameters...
168
methods = context.getRealPath( config.getInitParameter("methods") );
169         dbScriptsPath = context.getRealPath( config.getInitParameter("dbScriptsPath") );
170         old_database = config.getInitParameter("old_database");
171         createTables = config.getInitParameter("create_tables");
172         contentServletPath = config.getInitParameter(INIT_PARAM_CONTENT_SERVLET_PATH);
173         if (contentServletPath == null) {
174             logger.debug("Missing " + INIT_PARAM_CONTENT_SERVLET_PATH +
175                          ", defaulting to /content/...");
176             contentServletPath = "/content/";
177         }
178         String JavaDoc defaultLanguageCode = context.getInitParameter(INIT_PARAM_DEFAULT_LOCALE);
179         if (defaultLanguageCode == null) {
180             defaultLanguageCode = Locale.ENGLISH.toString();
181         }
182         defaultLocale = LanguageCodeConverters.languageCodeToLocale(defaultLanguageCode);
183
184         // get actionhandler...
185
actionHandler = new ActionHandler( methods, CLASS_NAME );
186
187         // fill in default values in *values* hashmap...
188
fillDefaultValues();
189     }
190     // end init( ServletConfig )
191

192
193
194
195     /**
196      * Default service method, inherited from HttpServlet. Jahia servlet must be
197      * inited, because JahiaConfigurationWizard needs to access to some data
198      * (like paths, constants, etc).
199      * @author Alexandre Kraft
200      *
201      * @param request servlet request (inherited).
202      * @param response servlet response (inherited).
203      * @exception IOException an I/O exception occured during the process.
204      * @exception ServletException a servlet exception occured during the process.
205      */

206     public void service (HttpServletRequest JavaDoc request,
207                          HttpServletResponse JavaDoc response) throws IOException JavaDoc,
208         ServletException JavaDoc {
209         logger.debug("--[ " + request.getMethod() + " Request Start URI='" +
210                      request.getRequestURI() + "' query='" +
211                      request.getQueryString() + "'] --");
212         boolean connect = false;
213
214         if (JahiaConfigurationWizard.servletPath == null) {
215             servletPath = request.getServletPath();
216         }
217
218         // get *go* parameter...
219
if (request.getParameter("go") != null) {
220             if (request.getParameter("go").equals("connect")) {
221                 connect = true;
222             }
223         }
224
225         if (Jahia.jahiaBasicFileName == null) { // the user call JahiaConfigurationWizard in standalone...
226
doRedirect(request, response, JSP + "error_standalone");
227         } else {
228             if (JahiaTools.checkFileExists(Jahia.getJahiaPropertiesFileName()) &&
229                 !connect) {
230                 doRedirect(request, response, JSP + "error_configured"); // jahia is already installed and configured...
231
} else {
232                 if (Jahia.initException != null) { // jahia has an init exception, redirect on jahia to display it...
233
doRedirect(request, response, contentServletPath);
234                 } else {
235                     dispatcher(request, response); // ok good use case, continue process...
236
}
237             }
238         }
239         logger.debug("--[ " + request.getMethod() + " Request End ] --");
240     }
241
242     // end service( HttpServletRequest, HttpServletResponse )
243

244     public static String JavaDoc getServletPath() { return servletPath; }
245
246     /**
247      * Static method to generate URLs for the administration. This should be
248      * used by all JSPs and java code that is called by the administration.
249      * @param request the current request object, used to generate the context
250      * path part of the URL
251      *
252      * @param response the current response object, used to make a call to
253      * encodeURL to generate session information in the case that cookies cannot
254      * be used
255      * @param doAction a String representing the action we are linking to. This
256      * is then encoded as a ?do=doAction string
257      * @param extraQueryParams a string including any other parameters that will
258      * be directly appended after the doAction string. This is done because this
259      * way we offer the possibility to do an encodeURL over the whole string.
260      * Note that this string may be null.
261      *
262      * @return a String containing an URL with jsessionid generated and in the
263      * form : /contextPath/servletPath/?do=doActionextraQueryParams
264      */

265     public static String JavaDoc composeActionURL ( HttpServletRequest JavaDoc request,
266                                             HttpServletResponse JavaDoc response,
267                                             String JavaDoc doAction,
268                                             String JavaDoc extraQueryParams ) {
269         String JavaDoc internalDoAction = "";
270         String JavaDoc internalQueryParams = "";
271
272         if (doAction != null) {
273             internalDoAction = "/?call=" + doAction;
274         }
275
276         if (extraQueryParams != null) {
277             internalQueryParams = extraQueryParams;
278         }
279
280         return response.encodeURL ( request.getContextPath() +
281                                     getServletPath() +
282                                     internalDoAction +
283                                     internalQueryParams );
284     }
285
286     /**
287      * Forward the servlet request and servlet response objects, using the request
288      * dispatcher (from the ServletContext). Note: please be careful, use only
289      * context relative path.
290      * @author Alexandre Kraft
291      *
292      * @param request servlet request.
293      * @param response servlet response.
294      * @param target target, context-relative path.
295      * @exception IOException an I/O exception occured during the process.
296      * @exception ServletException a servlet exception occured during the process.
297      */

298     private void doRedirect( HttpServletRequest JavaDoc request,
299                              HttpServletResponse JavaDoc response,
300                              String JavaDoc target )
301     throws IOException JavaDoc, ServletException JavaDoc
302     {
303         logger.debug("Dispatching to target=[" + target +"]");
304         try
305         {
306             // check null jsp bottom message, and fill in if necessary...
307
if( request.getAttribute("msg") == null ) {
308                 request.setAttribute("msg", Jahia.COPYRIGHT);
309             }
310
311             // check null jahia display message, and fill in if necessary...
312
if( request.getAttribute("focus") == null ) {
313                 request.setAttribute("focus", "-none-");
314             }
315
316             // check null configuration step title, and fill in if necessary...
317
if( request.getAttribute("title") == null ) {
318                 request.setAttribute("title", "Jahia Configuration Wizard");
319             }
320
321             // set input values on request...
322
request.setAttribute( "values", values );
323
324             // add http files path in request...
325
request.setAttribute( "url", request.getContextPath() + HTTP_FILES );
326
327             // get browser entity...
328
Integer JavaDoc navigator = new Integer JavaDoc(0);
329             if (request.getHeader("user-agent") != null) {
330                 navigator = (request.getHeader("user-agent").indexOf("IE")) != -1 ? new Integer JavaDoc(0) : new Integer JavaDoc(1);
331             } else {
332                 logger.debug("Couldn't reader user-agent header ! Why ?");
333             }
334             request.setAttribute("navigator", navigator);
335
336             // set browser response content type
337
String JavaDoc contentTypeStr = "text/html;charset=";
338             String JavaDoc acceptCharset = request.getHeader("accept-charset");
339             boolean acceptsUTF8 = false;
340             if (acceptCharset != null) {
341                 if (acceptCharset.toLowerCase().indexOf("utf-8") != -1) {
342                     acceptsUTF8 = true;
343                 }
344             }
345             if (acceptsUTF8) {
346                 contentTypeStr = contentTypeStr + "UTF-8";
347             } else {
348                 contentTypeStr = contentTypeStr + "ISO8859-1";
349             }
350             request.setAttribute("content-type", contentTypeStr);
351
352             // redirect!
353
context.getRequestDispatcher( target ).forward( request, response );
354
355         } catch (IOException JavaDoc ie) {
356             logger.debug("IOException in doRedirect", ie);
357         } catch (ServletException JavaDoc se) {
358             logger.debug("Servlet Exception in doRedirect", se);
359             logger.debug("Servlet Exception in doRedirect root cause", se.getRootCause());
360         }
361     }
362     // end doRedirect( HttpServletRequest, HttpServletResponse, String )
363

364
365
366
367     /**
368      * This method is used like a dispatcher for user HTTP requests, like
369      * GET and POST (it works also with DELETE, TRACE and PUT) requests.
370      * @author Alexandre Kraft
371      *
372      * @param request servlet request.
373      * @param response servlet response.
374      * @exception IOException an I/O exception occured during the process.
375      * @exception ServletException a servlet exception occured during the process.
376      */

377     private void dispatcher( HttpServletRequest JavaDoc request,
378                              HttpServletResponse JavaDoc response )
379     throws IOException JavaDoc, ServletException JavaDoc
380     {
381         // get the parameter *call*...
382
String JavaDoc call = request.getParameter("call") == null ? "welcome" : request.getParameter("call");
383
384         // call the action handler...
385
actionHandler.call( this, call, request, response );
386
387     }
388     // end dispatcher( HttpServletRequest, HttpServletResponse )
389

390
391
392
393     /**
394      * This method display the welcome page.
395      * @author Alexandre Kraft
396      *
397      * @param request servlet request.
398      * @param response servlet response.
399      * @exception IOException an I/O exception occured during the process.
400      * @exception ServletException a servlet exception occured during the process.
401      */

402     public void displayWelcome( HttpServletRequest JavaDoc request,
403                                 HttpServletResponse JavaDoc response )
404     throws IOException JavaDoc, ServletException JavaDoc
405     {
406         // get system properties...
407
Properties JavaDoc sys = System.getProperties();
408
409         // set java infos on request...
410
request.setAttribute( "javaversion", sys.getProperty("java.version") );
411         request.setAttribute( "javavendor", sys.getProperty("java.vendor") );
412         request.setAttribute( "os", sys.getProperty("os.name") );
413         request.setAttribute( "osVersion", sys.getProperty("os.version"));
414         request.setAttribute( "osArch", sys.getProperty("os.arch"));
415
416         // set server infos on request...
417
request.setAttribute( "server", serverInfos.get("info") );
418
419         // now let's test for the available resource bundles for the interface
420
Locale JavaDoc[] locales = Locale.getAvailableLocales();
421         Vector JavaDoc availableBundleLocales = new Vector JavaDoc();
422         // first let's add the default locale if it exists.
423
if (ResourceBundle.getBundle(JahiaResourceBundle.
424                                      MESSAGE_DEFAULT_RESOURCE_BUNDLE, Locale.getDefault()) != null) {
425             availableBundleLocales.add(defaultLocale);
426         }
427         ResourceBundle JavaDoc res = null;
428         for (int i=0; i < locales.length; i++) {
429             Locale JavaDoc curLocale = locales[i];
430             res = ResourceBundle.getBundle(JahiaResourceBundle.
431                                            MESSAGE_DEFAULT_RESOURCE_BUNDLE, curLocale);
432             if (res != null) {
433                 if (res.getLocale().equals(curLocale) && (!curLocale.equals(defaultLocale))) {
434                     availableBundleLocales.add(curLocale);
435                 }
436             }
437         }
438         request.setAttribute( "availableBundleLocales", availableBundleLocales );
439
440         // now let's set the selected locale according to what we know about
441
// locales so far...
442
Locale JavaDoc selectedLocale = null;
443         String JavaDoc selectedLanguageCode = (String JavaDoc) values.get("welcome_newLocale");
444         if (selectedLanguageCode != null) {
445             selectedLocale = LanguageCodeConverters.languageCodeToLocale(selectedLanguageCode);
446         }
447         if (selectedLocale == null) {
448             if (request.getLocale() != null) {
449                 selectedLocale = request.getLocale();
450             } else {
451                 selectedLocale = defaultLocale;
452             }
453         }
454         if (availableBundleLocales.contains(selectedLocale)) {
455             values.put("welcome_newLocale", selectedLocale.toString());
456         }
457
458         // forward to the jsp...
459
doRedirect( request, response, JSP + "welcome" );
460
461         // force objects to garbage collector...
462
sys = null;
463     }
464     // end displayWelcome( HttpServletRequest, HttpServletResponse )
465

466
467
468
469     /**
470      * This method display the root settings page.
471      * @author Alexandre Kraft
472      *
473      * @param request servlet request.
474      * @param response servlet response.
475      * @exception IOException an I/O exception occured during the process.
476      * @exception ServletException a servlet exception occured during the process.
477      */

478     public void displayRoot( HttpServletRequest JavaDoc request,
479                              HttpServletResponse JavaDoc response )
480     throws IOException JavaDoc, ServletException JavaDoc
481     {
482         // set focus it it's null...
483
if( request.getAttribute("focus") == null ) {
484             request.setAttribute( "focus", "pwd" );
485         }
486
487         // set configuration step title...
488
request.setAttribute( "title", "SuperUser (administrator) settings" );
489
490         // forward to the jsp...
491
doRedirect( request, response, JSP + "root" );
492     }
493     // end displayRoot( HttpServletRequest, HttpServletResponse )
494

495
496     /**
497      * Process the welcome page language selection form. Then displays the root
498      * user settings page.
499      * @author Serge Huber
500      *
501      * @param request servlet request.
502      * @param response servlet response.
503      * @exception IOException an I/O exception occured during the process.
504      * @exception ServletException a servlet exception occured during the process.
505      */

506     public void processWelcome( HttpServletRequest JavaDoc request,
507                                 HttpServletResponse JavaDoc response )
508         throws IOException JavaDoc, ServletException JavaDoc {
509         // by default, the user makes at least one error :o)
510
boolean error = true;
511         String JavaDoc msg = null;
512
513         // save form values...
514
values.put( "welcome_newLocale", (String JavaDoc) request.getParameter("newLocale").trim() );
515
516         // set the chosen language in the session, so the rest of the configuration
517
// wizard will have access to it as well as Jahia.
518
if( request.getParameter("go").equals("next") )
519         {
520             String JavaDoc newLocaleStr = (String JavaDoc) request.getParameter("newLocale");
521             if (newLocaleStr != null) {
522                 Locale JavaDoc newLocale = LanguageCodeConverters.languageCodeToLocale(newLocaleStr);
523                 if (newLocale != null) {
524                     request.getSession().setAttribute(ParamBean.SESSION_LOCALE, newLocale);
525                     Locale.setDefault(newLocale);
526                     newSelectedLocale = newLocale;
527                     values.put( "org.jahia.multilang.default_language_code", (String JavaDoc) newSelectedLocale.toString() );
528                 }
529             }
530             error = false; // everything is okay, continue...
531
}
532         // call the appropriate method...
533
if( error ) {
534             request.setAttribute( "msg", msg );
535             displayWelcome( request, response );
536         } else {
537             if( request.getParameter("go").equals("next") ) { // step next requested...
538
displayRoot( request, response );
539             } else if( request.getParameter("go").equals("back") ) { // step back requested...
540
displayWelcome( request, response );
541             }
542         }
543
544         // force objects to garbage collector...
545
msg = null;
546     }
547
548
549
550     /**
551      * Process and check the validity of the root username, password, the
552      * confirmation of the password, first name, last name and mail address
553      * from the root settings page. If they are valid, display the server
554      * settings page. Otherwise, re-display the root settings page to the user.
555      * @author Alexandre Kraft
556      *
557      * @param request servlet request.
558      * @param response servlet response.
559      * @exception IOException an I/O exception occured during the process.
560      * @exception ServletException a servlet exception occured during the process.
561      */

562     public void processRoot( HttpServletRequest JavaDoc request,
563                              HttpServletResponse JavaDoc response )
564     throws IOException JavaDoc, ServletException JavaDoc
565     {
566         // by default, the user makes at least one error :o)
567
boolean error = true;
568         String JavaDoc msg = null;
569
570         // save form values...
571
values.put( "root_user", (String JavaDoc) request.getParameter("user").trim() );
572         values.put( "root_pwd", (String JavaDoc) request.getParameter("pwd").trim() );
573         values.put( "root_confirm", (String JavaDoc) request.getParameter("confirm").trim() );
574         values.put( "root_firstname", (String JavaDoc) request.getParameter("firstname").trim() );
575         values.put( "root_lastname", (String JavaDoc) request.getParameter("lastname").trim() );
576         values.put( "root_mail", (String JavaDoc) request.getParameter("mail").trim() );
577
578         // check root settings validity... if the user want to go next
579
if( request.getParameter("go").equals("next") )
580         {
581             if( ((String JavaDoc)values.get("root_user")).length() < 4 ) { // check username length [minimum 4 chars]
582
request.setAttribute( "focus", "user" );
583                 msg = JahiaResourceBundle.getMessageResource("org.jahia.bin.JahiaConfigurationWizard.JahiaConfigurationMsg.usernameshort.label",
584                      newSelectedLocale);
585             } else if( !JahiaTools.isAlphaValid(((String JavaDoc)values.get("root_user"))) ) { // check username is alpha valid
586
request.setAttribute( "focus", "user" );
587                 msg = JahiaResourceBundle.getMessageResource("org.jahia.bin.JahiaConfigurationWizard.JahiaConfigurationMsg.usernameinvalid.label",
588                     newSelectedLocale);
589             } else if( ((String JavaDoc)values.get("root_pwd")).length() < 8 ) { // check password length [minimum 8 chars]
590
request.setAttribute( "focus", "pwd" );
591                 msg = JahiaResourceBundle.getMessageResource("org.jahia.bin.JahiaConfigurationWizard.JahiaConfigurationMsg.passwordshort.label",
592                     newSelectedLocale);
593             } else if( !JahiaTools.isAlphaValid(((String JavaDoc)values.get("root_pwd"))) ) { // check password is alpha valid
594
request.setAttribute( "focus", "pwd" );
595                 msg = JahiaResourceBundle.getMessageResource("org.jahia.bin.JahiaConfigurationWizard.JahiaConfigurationMsg.passwordinvalid.label",
596                     newSelectedLocale);
597             } else if( ((String JavaDoc)values.get("root_confirm")).length() == 0 ) { // check confirmation length [minimum 8 chars]
598
request.setAttribute( "focus", "confirm" );
599                 msg = JahiaResourceBundle.getMessageResource("org.jahia.bin.JahiaConfigurationWizard.JahiaConfigurationMsg.passwordmustsame.label",
600                     newSelectedLocale);
601             } else if( !((String JavaDoc)values.get("root_pwd")).equals(((String JavaDoc)values.get("root_confirm"))) ) { // check password and confirmation must be equals
602
request.setAttribute( "focus", "pwd" );
603                 msg = JahiaResourceBundle.getMessageResource("org.jahia.bin.JahiaConfigurationWizard.JahiaConfigurationMsg.passwordmustsame.label",
604                     newSelectedLocale);
605             } else if( ((String JavaDoc)values.get("root_firstname")).length() == 0 ) { // check firstname length [minimum 1 char]
606
request.setAttribute( "focus", "firstname" );
607                 msg = JahiaResourceBundle.getMessageResource("org.jahia.bin.JahiaConfigurationWizard.JahiaConfigurationMsg.firstnamemustset.label",
608                     newSelectedLocale);
609             } else if( ((String JavaDoc)values.get("root_lastname")).length() == 0 ) { // check lastname length [minimum 1 char]
610
request.setAttribute( "focus", "lastname" );
611                 msg = JahiaResourceBundle.getMessageResource("org.jahia.bin.JahiaConfigurationWizard.JahiaConfigurationMsg.lastnamemustset.label",
612                     newSelectedLocale);
613             } else {
614                 error = false; // everything is okay, continue...
615
}
616         } else {
617             error = false; // default, the user want to go back.
618
}
619
620         // call the appropriate method...
621
if( error ) {
622             request.setAttribute( "msg", msg );
623             displayRoot( request, response );
624         } else {
625             if( request.getParameter("go").equals("next") ) { // step next requested...
626
displayServer( request, response );
627             } else if( request.getParameter("go").equals("back") ) { // step back requested...
628
displayWelcome( request, response );
629             }
630         }
631
632         // force objects to garbage collector...
633
msg = null;
634     }
635     // end processRoot( HttpServletRequest, HttpServletResponse )
636

637
638
639
640     /**
641      * This method display the server settings page.
642      * @author Alexandre Kraft
643      *
644      * @param request servlet request.
645      * @param response servlet response.
646      * @exception IOException an I/O exception occured during the process.
647      * @exception ServletException a servlet exception occured during the process.
648      */

649     public void displayServer( HttpServletRequest JavaDoc request,
650                                HttpServletResponse JavaDoc response )
651     throws IOException JavaDoc, ServletException JavaDoc
652     {
653         // determine the host url... now i've the request :o)
654
if( ((String JavaDoc)values.get("server_url")) == null ) {
655             values.put( "server_url", request.getScheme() +"://"+request.getHeader("host") );
656         }
657
658         if( ((String JavaDoc)values.get("webapps_deploybaseurl")) == null ) {
659             URL JavaDoc deployURL = null;
660             try {
661                 deployURL = new java.net.URL JavaDoc( request.getScheme() +"://"+request.getHeader("host") );
662             } catch (MalformedURLException JavaDoc mue) {
663                 logger.debug("Error", mue);
664             }
665             values.put( "webapps_deploybaseurl", deployURL.toString() );
666         }
667
668         // set focus it it's null...
669
if( request.getAttribute("focus") == null ) {
670             request.setAttribute( "focus", "home" );
671         }
672
673         // set configuration step title...
674
request.setAttribute( "title", "Server settings" );
675
676         // forward to the jsp...
677
doRedirect( request, response, JSP + "server" );
678     }
679     // end displayServer( HttpServletRequest, HttpServletResponse )
680

681
682
683
684     /**
685      * Process and check the validity of the servlet container home disk path,
686      * the host url and the path (filesystem or context-relative) to jahia
687      * files, from the server settings page. If they are valid, display the
688      * next page, but... the user can choose to display *advanced settings* or
689      * to go back. Otherwise, re-display the server settings page to the user.
690      * @author Alexandre Kraft
691      *
692      * @param request servlet request.
693      * @param response servlet response.
694      * @exception IOException an I/O exception occured during the process.
695      * @exception ServletException a servlet exception occured during the process.
696      */

697     public void processServer( HttpServletRequest JavaDoc request,
698                                HttpServletResponse JavaDoc response )
699     throws IOException JavaDoc, ServletException JavaDoc
700     {
701         // by default, the user makes at least one error :o)
702
boolean error = true;
703         boolean dbError = false;
704         String JavaDoc msg = null;
705         String JavaDoc dbMsg = null;
706
707         // save form values...
708
values.put( "server_home", (String JavaDoc) request.getParameter("home").trim() );
709         values.put( "server_url", (String JavaDoc) request.getParameter("hosturl").trim() );
710         values.put( "webapps_deploybaseurl", (String JavaDoc) request.getParameter("webappsdeploybaseurl").trim() );
711         values.put( "server_jahiafiles", (String JavaDoc) request.getParameter("jahiafiles").trim() );
712
713         // check server settings validity...if the user want to go next
714
if( request.getParameter("go").equals("next") )
715         {
716             if( ((String JavaDoc)values.get("server_home")).length() == 0 ) { // check servlet container home path
717
request.setAttribute( "focus", "home" );
718                 msg = JahiaResourceBundle.getMessageResource("org.jahia.bin.JahiaConfigurationWizard.JahiaConfigurationMsg.servletcontainer_homepath_mustset.lable",
719                     newSelectedLocale);
720             } else if( ((String JavaDoc)values.get("server_url")).length() == 0 ) { // check host url
721
request.setAttribute( "focus", "hosturl" );
722                 msg = JahiaResourceBundle.getMessageResource("org.jahia.bin.JahiaConfigurationWizard.JahiaConfigurationMsg.hosturl_mustset.label",
723                     newSelectedLocale);
724             } else if( ((String JavaDoc)values.get("webapps_deploybaseurl")).length() == 0 ) { // check host url
725
request.setAttribute( "focus", "webappsdeploybaseurl" );
726                 msg = JahiaResourceBundle.getMessageResource("org.jahia.bin.JahiaConfigurationWizard.JahiaConfigurationMsg.appdeploy_baseurl_mustset.label",
727                     newSelectedLocale);
728             } else if( ((String JavaDoc)values.get("server_jahiafiles")).length() == 0 ) { // check jahia files path
729
request.setAttribute( "focus", "jahiafiles" );
730                 msg = JahiaResourceBundle.getMessageResource("org.jahia.bin.JahiaConfigurationWizard.JahiaConfigurationMsg.jahiafiles_path_mustset.label",
731                     newSelectedLocale);
732             } else {
733                 error = false; // everything is okay, continue...
734
}
735
736             // check *slashs* validity of the inputs values...
737
checkServerSlashs();
738
739             // try some operations which can return customs exceptions...
740
try
741             {
742                 // try the servlet container home disk path...
743
tryServerHome();
744
745                 /**
746                  * Deactivated because :
747                  * - it's specific to Tomcat
748                  * - doesn't work when Jahia is installed in ROOT context.
749                 if (serverInfos.get("type").equals(JahiaConstants.SERVER_TOMCAT)) {
750                     // try the host url connection...
751                     tryHostURL();
752
753                     // try the host url connection...
754                     tryWebAppsDeployBaseURL();
755                 }
756                 */

757
758                 // try the path to jahia files (permissions, etc)...
759
tryJahiaFilesPath();
760             } catch (Exception JavaDoc e) {
761                 msg = e.getMessage();
762                 error = true;
763             }
764
765             // reset default values if the user has specified invalid database settings...
766
if( ((Boolean JavaDoc)values.get("database_custom")) == Boolean.FALSE ) {
767                 fillDefaultValues( false, true );
768             }
769
770             // test the database connection... (only if the user want continue by *next*)
771
HashMap JavaDoc test = testDBConnection();
772             dbError = ((Boolean JavaDoc)test.get("testDatabaseConnectionError")).booleanValue();
773             dbMsg = (String JavaDoc)test.get("testDatabaseConnectionMessage");
774             if (dbMsg != null && dbMsg.length() > 0) {
775                 request.setAttribute( "msg", dbMsg );
776             }
777
778         } else {
779             error = false; // default, the user don't want to go next.
780
}
781
782         // call the appropriate method...
783
if( error ) { // process generates errors...
784
request.setAttribute( "msg", msg );
785             displayServer( request, response );
786         } else if( dbError ) { // database settings are not correct...
787
request.setAttribute( "msg", dbMsg );
788             values.put( "database_requested", Boolean.FALSE );
789             displayAdvSettings( request, response );
790         } else {
791             if( request.getParameter("go").equals("next") ) { // step next requested...
792
displayMail( request, response );
793             } else if( request.getParameter("go").equals("back") ) { // step back requested...
794
displayRoot( request, response );
795             } else if( request.getParameter("go").equals("advanced") ) { // step database requested...
796
values.put( "database_requested", Boolean.TRUE );
797                 displayAdvSettings( request, response );
798             }
799         }
800
801         // force objects to garbage collector...
802
msg = null;
803         dbMsg = null;
804     }
805     // end processServer( HttpServletRequest, HttpServletResponse )
806

807
808
809
810     /**
811      * This method display the database (advanced) settings page.
812      * @author Alexandre Kraft
813      *
814      * @param request servlet request.
815      * @param response servlet response.
816      * @exception IOException an I/O exception occured during the process.
817      * @exception ServletException a servlet exception occured during the process.
818      */

819     public void displayAdvSettings( HttpServletRequest JavaDoc request,
820                                     HttpServletResponse JavaDoc response )
821     throws IOException JavaDoc, ServletException JavaDoc
822     {
823         // get script lists...
824
Vector JavaDoc scriptsInfos = scripts.getDatabaseScriptsInfos( scripts.getDatabaseScriptsFileObjects(), pathResolver );
825         values.put( "database_test", scripts);
826
827         // set java infos on request...
828
request.setAttribute( "scripts", scriptsInfos.elements() );
829         request.setAttribute( "jsscripts", scriptsInfos.elements() );
830
831         // set focus it it's null...
832
if( request.getAttribute("focus") == null ) {
833             request.setAttribute( "focus", "driver" );
834         }
835
836         // set configuration step title...
837
request.setAttribute( "title", "Advanced settings" );
838
839         // forward to the jsp...
840
doRedirect( request, response, JSP + "adv_settings" );
841     }
842
843     /**
844      * Process and check the validity of the database driver, url, password and
845      * username, from the database settings page. If they are valid, display the
846      * mail page (if invoqued) or back to the server settings page. If the user
847      * press *back* or *cancel*, don't process the verification of the data.
848      * @author Alexandre Kraft
849      *
850      * @param request Servlet request.
851      * @param response Servlet response.
852      */

853     public void processAdvSettings( HttpServletRequest JavaDoc request,
854                                     HttpServletResponse JavaDoc response )
855     throws IOException JavaDoc, ServletException JavaDoc
856     {
857         // by default, the user makes at least one error :o)
858
boolean error = true;
859         boolean dbError = false;
860         String JavaDoc msg = null;
861         String JavaDoc dbMsg = null;
862
863         // save form values...
864
values.put( "database_script", (String JavaDoc) request.getParameter("script").trim() );
865         values.put( "database_driver", (String JavaDoc) request.getParameter("driver").trim() );
866         values.put( "database_url", (String JavaDoc) request.getParameter("dburl").trim() );
867         values.put( "database_user", (String JavaDoc) request.getParameter("user").trim() );
868         values.put( "database_pwd", (String JavaDoc) request.getParameter("pwd").trim() );
869         values.put( "database_support_embedded_select_statement", (String JavaDoc) request.getParameter("database_support_embedded_select_statement").trim() );
870
871         String JavaDoc utf8Encoding = request.getParameter("utf8Encoding");
872         if (utf8Encoding == null) utf8Encoding = "false";
873         values.put( "utf8Encoding", utf8Encoding );
874
875         // check database settings validity...if the user want to go next (or apply)
876
if( request.getParameter("go").equals("next") ||
877             request.getParameter("go").equals("apply") )
878         {
879             if( ((String JavaDoc)values.get("database_driver")).length() == 0 ) { // check database driver
880
request.setAttribute( "focus", "driver" );
881                 msg = JahiaResourceBundle.getMessageResource("org.jahia.bin.JahiaConfigurationWizard.JahiaConfigurationMsg.dbdriver_mustset.label",
882                     newSelectedLocale);
883             } else if( ((String JavaDoc)values.get("database_url")).length() == 0 ) { // check database url
884
request.setAttribute( "focus", "dburl" );
885                 msg = JahiaResourceBundle.getMessageResource("org.jahia.bin.JahiaConfigurationWizard.JahiaConfigurationMsg.dburl_mustset.label",
886                     newSelectedLocale);
887             } else {
888                 error = false; // everything is okay, continue...
889
}
890
891             // test the database connection...
892
HashMap JavaDoc test = testDBConnection();
893             dbError = ((Boolean JavaDoc)test.get("testDatabaseConnectionError")).booleanValue();
894             dbMsg = (String JavaDoc)test.get("testDatabaseConnectionMessage");
895
896         } else {
897             error = false; // default, the user don't want to go next.
898
}
899
900         // call the appropriate method...
901
if( error ) { // process generates errors...
902
request.setAttribute( "msg", msg );
903             displayAdvSettings( request, response );
904         } else if( dbError ) { // database settings are not correct...
905
request.setAttribute( "msg", dbMsg );
906             displayAdvSettings( request, response );
907         } else {
908             // fill with db other settings
909
if( request.getParameter("go").equals("apply") ) { // step apply (return to server) requested...
910
values.put( "database_custom", Boolean.TRUE );
911                 displayServer( request, response );
912             } else if( request.getParameter("go").equals("next") ) { // step next requested...
913
values.put( "database_custom", Boolean.TRUE );
914                 displayMail( request, response );
915             }
916         }
917
918         // force objects to garbage collector...
919
msg = null;
920         dbMsg = null;
921     }
922
923     /**
924      * This method display the mail settings page.
925      * @author Alexandre Kraft
926      *
927      * @param request servlet request.
928      * @param response servlet response.
929      * @exception IOException an I/O exception occured during the process.
930      * @exception ServletException a servlet exception occured during the process.
931      */

932     public void displayMail( HttpServletRequest JavaDoc request,
933                              HttpServletResponse JavaDoc response )
934     throws IOException JavaDoc, ServletException JavaDoc
935     {
936         // set focus it it's null...
937
if( request.getAttribute("focus") == null ) {
938             request.setAttribute( "focus", "server" );
939         }
940
941         // set configuration step title...
942
request.setAttribute( "title", "Mail settings" );
943
944         // forward to the jsp...
945
doRedirect( request, response, JSP + "mail" );
946     }
947     // end displayMail( HttpServletRequest, HttpServletResponse )
948

949
950
951
952     /**
953      * Process and check the validity of the database driver, url, password and
954      * username, from the database settings page. If they are valid, display the
955      * mail page (if invoqued) or back to the server settings page. If the user
956      * press *back* or *cancel*, don't process the verification of the data.
957      * @author Alexandre Kraft
958      *
959      * @param request Servlet request.
960      * @param response Servlet response.
961      */

962     public void processMail( HttpServletRequest JavaDoc request,
963                              HttpServletResponse JavaDoc response )
964     throws IOException JavaDoc, ServletException JavaDoc
965     {
966         // by default, the user makes at least one error :o)
967
boolean error = true;
968         String JavaDoc msg = null;
969
970         // save form values...
971
values.put( "mail_server", (String JavaDoc) request.getParameter("server").trim() );
972         values.put( "mail_recipient", (String JavaDoc) request.getParameter("rcpt").trim() );
973         values.put( "mail_from", (String JavaDoc) request.getParameter("from").trim() );
974         values.put( "mail_parano", (String JavaDoc) request.getParameter("parano").trim() );
975
976         // check mail settings validity...if the user want to go next
977
if( request.getParameter("go").equals("next") )
978         {
979             if( !((String JavaDoc)values.get("mail_parano")).equals("Disabled") ) // check paranoia settings
980
{
981                 if( ((String JavaDoc)values.get("mail_server")).length() == 0 ) { // check mail server
982
request.setAttribute( "focus", "server" );
983                     msg = JahiaResourceBundle.getMessageResource("org.jahia.bin.JahiaConfigurationWizard.JahiaConfigurationMsg.mailserver_mustset.label",
984                         newSelectedLocale);
985                 } else if( ((String JavaDoc)values.get("mail_recipient")).length() == 0 ) { // check mail recipient
986
request.setAttribute( "focus", "rcpt" );
987                     msg = JahiaResourceBundle.getMessageResource("org.jahia.bin.JahiaConfigurationWizard.JahiaConfigurationMsg.mailrecipient_mustset.label",
988                         newSelectedLocale);
989                 } else if( ((String JavaDoc)values.get("mail_from")).length() == 0 ) { // check mail from address
990
request.setAttribute( "focus", "from" );
991                     msg = JahiaResourceBundle.getMessageResource("org.jahia.bin.JahiaConfigurationWizard.JahiaConfigurationMsg.mailfromaddress_mustset.label",
992                         newSelectedLocale);
993                 } else {
994                     error = false; // default, the user don't want to go next.
995
}
996             } else {
997                 error = false; // default, the user don't want to go next.
998
}
999         } else {
1000            error = false; // default, the user don't want to go next.
1001
}
1002
1003        // call the appropriate method...
1004
if( error ) { // process generates errors...
1005
request.setAttribute( "msg", msg );
1006            displayMail( request, response );
1007        } else {
1008            if( request.getParameter("go").equals("back") ) { // step back requested...
1009
if( ((Boolean JavaDoc)values.get("database_requested")).booleanValue() ) {
1010                    displayServer( request, response ); // step back when database isn't forced...
1011
} else {
1012                    displayAdvSettings( request, response ); // step back when database is forced...
1013
}
1014            } else if( request.getParameter("go").equals("next") ) { // step next requested...
1015
displayTemplates( request, response );
1016            }
1017        }
1018
1019        // force objects to garbage collector...
1020
msg = null;
1021    }
1022    // end processMail( HttpServletRequest, HttpServletResponse )
1023

1024
1025
1026
1027    /**
1028     * This method display the values confirmation (before save options) page.
1029     * @author Alexandre Kraft
1030     *
1031     * @param request servlet request.
1032     * @param response servlet response.
1033     * @exception IOException an I/O exception occured during the process.
1034     * @exception ServletException a servlet exception occured during the process.
1035     */

1036    public void displayTemplates( HttpServletRequest JavaDoc request,
1037                                  HttpServletResponse JavaDoc response )
1038    throws IOException JavaDoc, ServletException JavaDoc
1039    {
1040        // set java infos on request...
1041
request.setAttribute( "packages", listTemplatesFiles() );
1042
1043        // set configuration step title...
1044
request.setAttribute( "title", "Choose a base templates package" );
1045
1046        // forward to the jsp...
1047
doRedirect( request, response, JSP + "templates" );
1048    }
1049    // end displayTemplates( HttpServletRequest, HttpServletResponse )
1050

1051
1052
1053
1054    /**
1055     * Process and check the validity of the database driver, url, password and
1056     * username, from the database settings page. If they are valid, display the
1057     * mail page (if invoqued) or back to the server settings page. If the user
1058     * press *back* or *cancel*, don't process the verification of the data.
1059     * @author Alexandre Kraft
1060     *
1061     * @param request Servlet request.
1062     * @param response Servlet response.
1063     */

1064    public void processTemplates( HttpServletRequest JavaDoc request,
1065                                  HttpServletResponse JavaDoc response )
1066    throws IOException JavaDoc, ServletException JavaDoc
1067    {
1068        // by default, the user makes at least one error :o)
1069
boolean error = true;
1070        String JavaDoc msg = null;
1071
1072        // save form values...
1073
String JavaDoc choice = (String JavaDoc) request.getParameter("choice");
1074        if ( choice == null || choice.equals("0")){
1075            choice = properties.getProperty("default_templates_set").trim();
1076        }
1077        values.put( "templates", choice );
1078
1079        // check mail settings validity...if the user want to go next
1080
if( request.getParameter("go").equals("next") )
1081        {
1082            if( values.get("templates") == null ) { // check template selected
1083
msg = JahiaResourceBundle.getMessageResource("org.jahia.bin.JahiaConfigurationWizard.JahiaConfigurationMsg.package_mustselect.label",
1084                  newSelectedLocale);
1085            } else {
1086                error = false;
1087            }
1088        } else {
1089            error = false; // default, the user don't want to go next.
1090
}
1091
1092        // call the appropriate method...
1093
if( error ) { // process generates errors...
1094
request.setAttribute( "msg", msg );
1095            values.put("templates", properties.getProperty("default_templates_set").trim());
1096            displayTemplates( request, response );
1097        } else {
1098            if( request.getParameter("go").equals("back") ) { // step back requested...
1099
displayTemplates( request, response );
1100            } else if( request.getParameter("go").equals("next") ) { // step next requested...
1101
displayValues( request, response );
1102            } else if ( request.getParameter("go").equals("change") ){
1103                displayTemplates( request, response );
1104            }
1105        }
1106
1107        // force objects to garbage collector...
1108
msg = null;
1109    }
1110    // end processTemplates( HttpServletRequest, HttpServletResponse )
1111

1112
1113
1114
1115   /**
1116     * Get an enumeration containing all the templates archives files paths.
1117     * @author Alexandre Kraft
1118     *
1119     * @return Enumeration containing all scripts in File objects.
1120     */

1121    private Enumeration JavaDoc listTemplatesFiles()
1122    throws IOException JavaDoc
1123    {
1124        Vector JavaDoc vec = new Vector JavaDoc();
1125
1126        String JavaDoc path = ((String JavaDoc)values.get("server_jahiafiles_default")).substring(8, ((String JavaDoc)values.get("server_jahiafiles_default")).length()) + File.separator + "var" + File.separator + "shared_templates";
1127        File JavaDoc file = new File JavaDoc( context.getRealPath(path) );
1128        File JavaDoc[] list = file.listFiles();
1129
1130        for(int i=0; i<list.length; i++) {
1131            if(!list[i].isDirectory() && list[i].getName().endsWith(".jar")) {
1132                String JavaDoc name = list[i].getName().substring( 0, list[i].getName().lastIndexOf(".") );
1133                vec.add( name );
1134            }
1135        }
1136
1137        return vec.elements();
1138    }
1139    // listTemplatesFiles()
1140

1141
1142
1143
1144    /**
1145     * This method display the values confirmation (before save options) page.
1146     * @author Alexandre Kraft
1147     *
1148     * @param request servlet request.
1149     * @param response servlet response.
1150     * @exception IOException an I/O exception occured during the process.
1151     * @exception ServletException a servlet exception occured during the process.
1152     */

1153    public void displayValues( HttpServletRequest JavaDoc request,
1154                               HttpServletResponse JavaDoc response )
1155    throws IOException JavaDoc, ServletException JavaDoc
1156    {
1157        // set configuration step title...
1158
request.setAttribute( "title", "Confirm your values" );
1159
1160        // forward to the jsp...
1161
doRedirect( request, response, JSP + "values" );
1162    }
1163    // end displayValues( HttpServletRequest, HttpServletResponse )
1164

1165
1166
1167
1168    /**
1169     * Save the values from the HashMap in the database and properties file,
1170     * since the user has confirmed the values displayed in the page. Launch
1171     * some methods to compose the final jahia properties file, insert
1172     * database tables, data and remove old templates xml files if necessary.
1173     * @author Alexandre Kraft
1174     *
1175     * @param request Servlet request.
1176     * @param response Servlet response.
1177     */

1178    public void processValues( HttpServletRequest JavaDoc request,
1179                               HttpServletResponse JavaDoc response )
1180    throws IOException JavaDoc, ServletException JavaDoc
1181    {
1182        // by default, the user makes at least one error :o)
1183
boolean error = true;
1184        String JavaDoc msg = null;
1185
1186        // try to execute the last operations... any error will stop the process
1187
try
1188        {
1189            // overwrite the database if the user has not specified the opposite...
1190
if( !old_database.equals("true") )
1191            {
1192                if (!"false".equals(createTables)) {
1193                createDBTables();
1194                }
1195                insertDBCustomContent();
1196                insertDBDefaultContent();
1197
1198                // it also include templates...
1199
copyDefaultTemplates( "myjahiasite" );
1200                //copySharedTemplates( "myjahiasite" );
1201

1202                // and also the default site property...
1203
properties.setProperty( "defautSite", "myjahiasite" );
1204
1205                // and also the xml templates files...
1206
folderXMLtemplates();
1207            }
1208
1209            // copy the shared components
1210
copySharedComponents("myjahiasite");
1211
1212            // move jahia files on their final directories... if needed.
1213
moveJahiaFiles();
1214
1215            // close the connection with the database connection admin manager...
1216
db.databaseClose();
1217
1218            // set new properties...
1219
setPropertiesObject();
1220
1221            // store jahia.properties file...
1222
properties.storeProperties( Jahia.getJahiaPropertiesFileName() );
1223
1224            // okay, everthing is okay... set error to false
1225
error = false;
1226
1227        } catch (Exception JavaDoc e) {
1228            logger.debug("Exception", e);
1229            msg = e.getMessage();
1230        }
1231
1232        // call the appropriate method...
1233
if( error ) { // process generates errors...
1234
request.setAttribute( "errormsg", msg );
1235            displayError( request, response );
1236        } else {
1237            displayFinalStep( request, response ); // everything is okay, continue...
1238
}
1239
1240        // force objects to garbage collector...
1241
msg = null;
1242    }
1243    // end processValues( HttpServletRequest, HttpServletResponse )
1244

1245
1246
1247
1248    /**
1249     * This method display some errors during the save process.
1250     * @author Alexandre Kraft
1251     *
1252     * @param request servlet request.
1253     * @param response servlet response.
1254     * @exception IOException an I/O exception occured during the process.
1255     * @exception ServletException a servlet exception occured during the process.
1256     */

1257    public void displayError( HttpServletRequest JavaDoc request,
1258                              HttpServletResponse JavaDoc response )
1259    throws IOException JavaDoc, ServletException JavaDoc
1260    {
1261        // set configuration step title...
1262
request.setAttribute( "title", "Error" );
1263
1264        // forward to the jsp...
1265
doRedirect( request, response, JSP + "error_save" );
1266    }
1267    // end displayError( HttpServletRequest, HttpServletResponse )
1268

1269
1270
1271
1272    /**
1273     * This method display the final step (congratulations).
1274     * @author Alexandre Kraft
1275     *
1276     * @param request servlet request.
1277     * @param response servlet response.
1278     * @exception IOException an I/O exception occured during the process.
1279     * @exception ServletException a servlet exception occured during the process.
1280     */

1281    public void displayFinalStep( HttpServletRequest JavaDoc request,
1282                                  HttpServletResponse JavaDoc response )
1283    throws IOException JavaDoc, ServletException JavaDoc
1284    {
1285        // set configuration step title...
1286
request.setAttribute( "title", "Congratulations!" );
1287
1288        Limit daysLeftLimit = Jahia.getCoreLicense().getLimit("maxUsageDays");
1289        // the limit might be null if a license has been created without
1290
// this limit.
1291
if (daysLeftLimit != null) {
1292            DaysLeftValidator daysLeftValidator = (DaysLeftValidator)
1293                daysLeftLimit.getValidator();
1294            int maxDays = Integer.parseInt(daysLeftLimit.getValueStr());
1295            request.setAttribute("allowedDays", new Integer JavaDoc(maxDays));
1296            EngineMessage allowedDaysMsg = new EngineMessage("org.jahia.bin.JahiaConfigurationWizard.congratulations.daysLeftInLicense.label", new Integer JavaDoc(maxDays));
1297            request.setAttribute("allowedDaysMsg", allowedDaysMsg);
1298        }
1299
1300        // forward to the jsp...
1301
doRedirect( request, response, JSP + "congratulations" );
1302    }
1303    // end displayFinalStep( HttpServletRequest, HttpServletResponse )
1304

1305
1306
1307
1308    /**
1309     * This method redirect to jahia and bypass the login.
1310     * @author Alexandre Kraft
1311     *
1312     * @param request servlet request.
1313     * @param response servlet response.
1314     * @exception IOException an I/O exception occured during the process.
1315     * @exception ServletException a servlet exception occured during the process.
1316     */

1317    public void redirectToJahia( HttpServletRequest JavaDoc request,
1318                                 HttpServletResponse JavaDoc response )
1319    throws IOException JavaDoc, ServletException JavaDoc
1320    {
1321        // add attributes to the request to *bypass* the login engine in the administration...
1322
request.setAttribute( CLASS_NAME + ".finishedInstallation", "true" );
1323        request.setAttribute( CLASS_NAME + ".rootName", (String JavaDoc)values.get("root_user") );
1324        request.setAttribute( CLASS_NAME + ".rootPass", (String JavaDoc)values.get("root_pwd") );
1325
1326        // forward to jahia !!
1327
doRedirect( request, response, contentServletPath );
1328    }
1329    // end redirectToJahia( HttpServletRequest, HttpServletResponse )
1330

1331
1332
1333
1334    /**
1335     * Check *slashs* validity of the inputs values from the server
1336     * settings page (servlet container home, host url, path jahia files).
1337     * @author Alexandre Kraft
1338     */

1339    private void checkServerSlashs()
1340    {
1341        if( !((String JavaDoc)values.get("server_home")).endsWith(File.separator) ) { // server home must ends with file separator
1342
values.put( "server_home",
1343                        ((String JavaDoc)values.get("server_home"))+File.separator );
1344        }
1345        if( ((String JavaDoc)values.get("server_url")).endsWith("/") ) { // host url must ends without "/"
1346
values.put( "server_url",
1347                        ((String JavaDoc)values.get("server_url")).substring(0,
1348                            ((String JavaDoc)values.get("server_url")).length()-1 ) );
1349        }
1350        if( ((String JavaDoc)values.get("server_jahiafiles")).endsWith(File.separator) ) { // jahia files must ends without file separator
1351
values.put( "server_jahiafiles",
1352                        ((String JavaDoc)values.get("server_jahiafiles")).substring(0,
1353                            ((String JavaDoc)values.get("server_jahiafiles")).length()-1 ) );
1354        }
1355    }
1356    // end checkServerSlashs()
1357

1358
1359
1360
1361    /**
1362     * Check the Servlet Container home disk path indicates by the user on
1363     * the server settings page, throws custom exceptions.
1364     * @author Alexandre Kraft
1365     *
1366     * @exception Exception an exception occured during the process.
1367     *
1368     * @todo FIXME (shuber) this is TERRIBLY container specific and only works on Tomcat.
1369     * We deactivate this call for the moment because in Tomcat's server.xml
1370     * we may put deployment directories elsewhere...
1371     */

1372    private void tryServerHome()
1373    throws Exception JavaDoc
1374    {
1375
1376        /*
1377        // set catalina.jar path...
1378        StringBuffer catalina = new StringBuffer( ((String)values.get("server_home")) );
1379        catalina.append( File.separator );
1380        catalina.append( "server" );
1381        catalina.append( File.separator );
1382        catalina.append( "lib" );
1383        catalina.append( File.separator );
1384        catalina.append( "catalina.jar" );
1385
1386        File lib = new File( catalina.toString() );
1387
1388        if( !lib.exists() ) {
1389            throw new Exception( "Please verify your servlet container home disk path." );
1390        }
1391        */

1392    }
1393    // end tryServerHome()
1394

1395
1396
1397
1398    /**
1399     * Try to establish a connection with the host url indicates by the user
1400     * on the server settings page, and check some error(s) (like HTTP-403, etc).
1401     * @author Alexandre Kraft
1402     *
1403     * @exception Exception an exception occured during the process.
1404     */

1405    private void tryHostURL()
1406    throws Exception JavaDoc
1407    {
1408        URL JavaDoc url = null;
1409        InputStream JavaDoc istream = null;
1410
1411        try
1412        {
1413            url = new URL JavaDoc( ((String JavaDoc)values.get("server_url")) );
1414            istream = url.openStream();
1415            istream.close();
1416
1417        } catch (Exception JavaDoc e) {
1418            logger.error("Error while connecting to server URL " + url, e);
1419            throw new Exception JavaDoc( "Cannot connect to your server URL at " + url );
1420        }
1421
1422        // force objects to garbage collector...
1423
istream = null;
1424        url = null;
1425    }
1426    // end tryHostURL()
1427

1428
1429    /**
1430     * Try to establish a connection with the host url indicates by the user
1431     * on the server settings page, and check some error(s) (like HTTP-403, etc).
1432     * @author Serge Huber
1433     *
1434     * @exception Exception an exception occured during the process.
1435     */

1436    private void tryWebAppsDeployBaseURL()
1437    throws Exception JavaDoc
1438    {
1439        URL JavaDoc url = null;
1440        InputStream JavaDoc istream = null;
1441
1442        try
1443        {
1444            url = new URL JavaDoc( ((String JavaDoc)values.get("webapps_deploybaseurl")) );
1445            istream = url.openStream();
1446            istream.close();
1447
1448        } catch (Exception JavaDoc e) {
1449            logger.debug("Error while connecting to web apps deployment URL at : " + url, e);
1450            throw new Exception JavaDoc( "Cannot connect to the web applications deployment base URL at " + url );
1451        }
1452
1453        // force objects to garbage collector...
1454
istream = null;
1455        url = null;
1456    }
1457    // end tryHostURL()
1458

1459
1460
1461    /**
1462     * Try to create the path to jahia files indicates by the user on the
1463     * server settings page, and check some error(s) (like permissions, etc).
1464     * @author Alexandre Kraft
1465     *
1466     * @exception Exception an exception occured during the process.
1467     */

1468    private void tryJahiaFilesPath()
1469    throws Exception JavaDoc
1470    {
1471        String JavaDoc jahiaFiles = null;
1472
1473        try
1474        {
1475            // transform context-relative path in filesystem if needed...
1476
if( ((String JavaDoc)values.get("server_jahiafiles")).substring(0,9).equals("$context/") ) {
1477                jahiaFiles = context.getRealPath(
1478                                 ((String JavaDoc)values.get("server_jahiafiles")).substring(
1479                                     8, ((String JavaDoc)values.get("server_jahiafiles")).length() ) );
1480            } else {
1481                throw new StringIndexOutOfBoundsException JavaDoc();
1482            }
1483        } catch (StringIndexOutOfBoundsException JavaDoc sioobe) {
1484            jahiaFiles = (String JavaDoc)values.get("server_jahiafiles");
1485        }
1486
1487        // a filepath must contain at least one file separator...
1488
if( jahiaFiles.indexOf(File.separator) == -1 ) {
1489            throw new Exception JavaDoc( "Jahia Files must be a valid filesystem or context-relative path." );
1490        }
1491
1492        // create the File object...
1493
File JavaDoc jf = new File JavaDoc( jahiaFiles );
1494        File JavaDoc parent = null;
1495
1496        // check if the location exists... or not.
1497
if( jf.exists() )
1498        {
1499            if( jf.isFile() ) { // check if it's a file ?!
1500
throw new Exception JavaDoc( "Jahia Files must be a directory, and not a file." );
1501            }
1502            if( !jf.canRead() ) { // check if i have permissions to read on it...
1503
throw new Exception JavaDoc( "Can't read in Jahia Files directory. Please verify permissions." );
1504            }
1505            if( !jf.canWrite() ) { // check if i have permissions to write on it...
1506
throw new Exception JavaDoc( "Can't write in Jahia Files directory. Please verify permissions." );
1507            }
1508
1509        } else {
1510            // get parent directory...
1511
parent = jf.getParentFile();
1512
1513            // check if the parent exists... or not.
1514
if( parent.exists() ) {
1515                if( !parent.canWrite() ) { // check if i have permissions to write on parent...
1516
throw new Exception JavaDoc( "Jahia can't create your directory (write permissions)." );
1517                }
1518            } else {
1519                if( !parent.mkdirs() ) { // the parent don't exists... create it if possible.
1520
throw new Exception JavaDoc( "Jahia can't create your directory (write permissions)." );
1521                }
1522            }
1523        }
1524
1525        // force objects to garbage collector...
1526
parent = null;
1527        jf = null;
1528        jahiaFiles = null;
1529    }
1530    // end tryJahiaFilesPath()
1531

1532
1533
1534
1535    /**
1536     * Read the database script requested by the user, get the test table line and
1537     * execute the self-test in the databaseconnection static object of jahia
1538     * administration.
1539     * @author Alexandre Kraft
1540     *
1541     * @return HashMap containing the results of the database test.
1542     */

1543    private HashMap JavaDoc testDBConnection()
1544    {
1545        String JavaDoc line;
1546        // get script runtime...
1547
try {
1548            BufferedReader JavaDoc inBuffer = new BufferedReader JavaDoc(
1549                                      new FileReader JavaDoc(dbScriptsPath + File.separator +
1550                                                     values.get("database_script")));
1551            while ((line = inBuffer.readLine()) != null) {
1552                if (line.indexOf("jahia_db_test", 13) >= 0) {
1553                    break;
1554                }
1555            }
1556        } catch (IOException JavaDoc ioe) {
1557            line = "unknown";
1558        }
1559        // test database...
1560
return db.databaseTest( (String JavaDoc)values.get("database_script"), (String JavaDoc)values.get("database_driver"),
1561                                (String JavaDoc)values.get("database_url"), (String JavaDoc)values.get("database_user"),
1562                                (String JavaDoc)values.get("database_pwd"), line,
1563                                "true".equals(values.get("utf8Encoding")), !"false".equals(createTables) );
1564    }
1565
1566    /**
1567     * Insert the database tables described in the database script. Before the
1568     * insertion, since you're sure that the user want overwrite his database,
1569     * each table is dropped, table after table.
1570     * @author Alexandre Kraft
1571     *
1572     * @exception Exception an exception occured during the process.
1573     */

1574    private void createDBTables()
1575    throws Exception JavaDoc
1576    {
1577        File JavaDoc object = null;
1578        Enumeration JavaDoc runtime = null;
1579        String JavaDoc line = null;
1580
1581        logger.debug("Creating database tables...");
1582
1583        // construct script path...
1584
StringBuffer JavaDoc script = new StringBuffer JavaDoc( dbScriptsPath );
1585        script.append( File.separator );
1586        script.append( (String JavaDoc)values.get("database_script") );
1587
1588        // get script runtime...
1589
try {
1590            object = new File JavaDoc( script.toString() );
1591            runtime = scripts.getDatabaseScriptsRuntime( object );
1592        } catch (Exception JavaDoc e) {
1593            throw new Exception JavaDoc( "Jahia can't read the appropriate database script." );
1594        }
1595
1596        // drop each tables (if present) and (re-)create it after...
1597
while( runtime.hasMoreElements() ) {
1598            line = (String JavaDoc) runtime.nextElement();
1599            String JavaDoc lowerCaseLine = line.toLowerCase();
1600            int tableNamePos = lowerCaseLine.indexOf("create table");
1601            if (tableNamePos != -1) {
1602                String JavaDoc tableName = line.substring("create table".length() +
1603                                                  tableNamePos,
1604                                                  line.indexOf("(")).trim();
1605                logger.debug("Creating table [" + tableName + "] ...");
1606                try {
1607                    db.query("DROP TABLE " + tableName);
1608                } catch (Exception JavaDoc e) {
1609                    // nothing to do...... i don't care if the drop doesn't work.
1610
// simply because table might not have ever existed...
1611
}
1612            }
1613            try {
1614                db.query( line );
1615            } catch (Exception JavaDoc e) {
1616                logger.error("Error while trying to execute query : " + line + " from script " + script.toString());
1617                // continue to propagate the exception upwards.
1618
throw e;
1619            }
1620        }
1621
1622        // force objects to garbage collector...
1623
object = null;
1624        script = null;
1625        runtime = null;
1626        line = null;
1627    }
1628    // end createDBTables()
1629

1630
1631
1632
1633    /**
1634     * Insert database custom data, like root user and properties.
1635     * @author Alexandre Kraft
1636     * @author Khue Nguyen
1637     *
1638     * @exception Exception an exception occured during the process.
1639     */

1640    private void insertDBCustomContent()
1641    throws Exception JavaDoc
1642    {
1643
1644        logger.debug("Inserting customized settings into database...");
1645
1646        // get two keys...
1647
String JavaDoc rootName = (String JavaDoc)values.get("root_user");
1648        int siteID0 = 0;
1649        int siteID1 = 1;
1650        String JavaDoc rootKey = rootName + ":" + siteID0;
1651        String JavaDoc grpKey0 = JahiaGroupManagerService.ADMINISTRATORS_GROUPNAME + ":" + siteID0;
1652        String JavaDoc grpKey1 = JahiaGroupManagerService.ADMINISTRATORS_GROUPNAME + ":" + siteID1;
1653
1654        // query insert root user...
1655
StringBuffer JavaDoc sqlRootUser = new StringBuffer JavaDoc();
1656        sqlRootUser.append( "INSERT INTO jahia_users(id_jahia_users, name_jahia_users, password_jahia_users, key_jahia_users, siteid_jahia_users) VALUES(0, '" );
1657        sqlRootUser.append( rootName + "', '");
1658        sqlRootUser.append( JahiaUserManagerService.encryptPassword( (String JavaDoc)values.get("root_pwd") ) );
1659        sqlRootUser.append( "','" + rootKey + "', " + siteID0 + ")" );
1660            db.query( sqlRootUser.toString() );
1661
1662        // query insert root first name...
1663
sqlRootUser = new StringBuffer JavaDoc();
1664        sqlRootUser.append( "INSERT INTO jahia_user_prop(id_jahia_users, name_jahia_user_prop, value_jahia_user_prop, provider_jahia_user_prop, userkey_jahia_user_prop) VALUES(0, 'firstname', '" );
1665        sqlRootUser.append( JahiaTools.replacePattern((String JavaDoc)values.get("root_firstname"), "'", "''") + "'," );
1666        sqlRootUser.append( "'jahia', '" + rootKey + "')" );
1667        db.query( sqlRootUser.toString() );
1668
1669        // query insert root last name...
1670
sqlRootUser = new StringBuffer JavaDoc();
1671        sqlRootUser.append( "INSERT INTO jahia_user_prop(id_jahia_users, name_jahia_user_prop, value_jahia_user_prop, provider_jahia_user_prop, userkey_jahia_user_prop) VALUES(0, 'lastname', '" );
1672        sqlRootUser.append( JahiaTools.replacePattern((String JavaDoc)values.get("root_lastname"), "'", "''") + "'," );
1673        sqlRootUser.append( "'jahia', '" + rootKey + "')" );
1674        db.query( sqlRootUser.toString() );
1675
1676        // query insert root e-mail address...
1677
sqlRootUser = new StringBuffer JavaDoc();
1678        sqlRootUser.append( "INSERT INTO jahia_user_prop(id_jahia_users, name_jahia_user_prop, value_jahia_user_prop, provider_jahia_user_prop, userkey_jahia_user_prop) VALUES(0, 'email', '" );
1679        sqlRootUser.append( (String JavaDoc)values.get("root_mail") + "'," );
1680        sqlRootUser.append( "'jahia', '" + rootKey + "')" );
1681            db.query( sqlRootUser.toString() );
1682
1683        // query insert administrators group...
1684
sqlRootUser = new StringBuffer JavaDoc();
1685        sqlRootUser.append( "INSERT INTO jahia_grps(id_jahia_grps, name_jahia_grps, key_jahia_grps, siteid_jahia_grps) VALUES(");
1686        sqlRootUser.append( siteID0 + ", '");
1687        sqlRootUser.append( JahiaGroupManagerService.ADMINISTRATORS_GROUPNAME + "','" );
1688        sqlRootUser.append( grpKey0 + "', " + siteID0 + ")" );
1689            db.query( sqlRootUser.toString() );
1690
1691        // query insert administrators group access...
1692
sqlRootUser = new StringBuffer JavaDoc();
1693        sqlRootUser.append( "INSERT INTO jahia_grp_access(id_jahia_member, id_jahia_grps, membertype_grp_access) VALUES('" );
1694        sqlRootUser.append( rootKey + "', '" + grpKey0 + "', 1)" ); // 1 = user type
1695
db.query( sqlRootUser.toString() );
1696
1697        // query insert group access for the root user with initial site admin group
1698
sqlRootUser = new StringBuffer JavaDoc();
1699        sqlRootUser.append( "INSERT INTO jahia_grp_access(id_jahia_member, id_jahia_grps, membertype_grp_access) VALUES('" );
1700        sqlRootUser.append( rootKey + "','" + grpKey1 + "', 1)" ); // 1 = user type
1701
db.query( sqlRootUser.toString() );
1702
1703        // query insert site user...
1704
sqlRootUser = new StringBuffer JavaDoc();
1705        sqlRootUser.append( "INSERT INTO jahia_sites_users(username_sites_users, siteid_sites_users, userid_sites_users) VALUES('" );
1706        sqlRootUser.append( rootName + "', " + siteID1 + ", '" + rootKey + "')" );
1707        db.query( sqlRootUser.toString() );
1708
1709    }
1710    // end insertDBCustomContent()
1711

1712
1713
1714
1715    /**
1716     * Insert database default data, like default users, default users properties,
1717     * default groups, templates, etc. It also set auto-incrementors id... it's
1718     * very important, be careful about this.
1719     * @author Alexandre Kraft
1720     * @author Khue Nguyen
1721     *
1722     * @exception Exception an exception occured during the process.
1723     */

1724    private void insertDBDefaultContent()
1725    throws Exception JavaDoc
1726    {
1727        // read from the file...
1728
File JavaDoc object = null;
1729        Enumeration JavaDoc runtime = null;
1730        String JavaDoc line = null;
1731
1732
1733        // construct script path...
1734
StringBuffer JavaDoc script = new StringBuffer JavaDoc( dbScriptsPath );
1735        script.append( File.separator );
1736        // Fixme: I only add a simple method to find the database value file with newly selected locale
1737
if ( values.get("templates") != null ){
1738            script.append( "default_"+JahiaTools.removeFileExtension((String JavaDoc)values.get("templates"),".jar") );
1739            if (newSelectedLocale != null) {
1740              StringBuffer JavaDoc tmpFileName1 = new StringBuffer JavaDoc(script.toString());
1741              StringBuffer JavaDoc tmpFileName2 = new StringBuffer JavaDoc(script.toString());
1742              if (newSelectedLocale.toString().length() == 6) {
1743                  tmpFileName1.append("_" +
1744                                      newSelectedLocale.toString().
1745                                      substring(0, 5) + ".values");
1746              }
1747              tmpFileName2.append("_" + newSelectedLocale.toString().substring(0,2) + ".values");
1748                File JavaDoc tmpFile1 = new File JavaDoc(tmpFileName1.toString());
1749                File JavaDoc tmpFile2 = new File JavaDoc(tmpFileName2.toString());
1750                if ((newSelectedLocale.toString().length() == 6) && (tmpFile1.exists())) {
1751                  script.append("_" + newSelectedLocale.toString().substring(0,5));
1752                } else if (tmpFile2.exists()) {
1753                  script.append("_" + newSelectedLocale.toString().substring(0,2));
1754                }
1755                tmpFileName1 = null;
1756                tmpFileName2 = null;
1757                tmpFile1 = null;
1758                tmpFile2 = null;
1759            }
1760            script.append(".values");
1761        }
1762
1763        // get script runtime...
1764
try {
1765            logger.debug("Inserting default database content from file " + script.toString() + "...");
1766            object = new File JavaDoc( script.toString() );
1767            runtime = scripts.getDatabaseScriptsRuntime( object );
1768        } catch (Exception JavaDoc e) {
1769            logger.error("Jahia can't read the file containing database values.", e);
1770            throw e;
1771        }
1772
1773        // execute each line of the script...
1774
int count = 0;
1775        while( runtime.hasMoreElements() ) {
1776            line = (String JavaDoc) runtime.nextElement();
1777            count++;
1778            try {
1779                db.query( line );
1780            } catch (Exception JavaDoc e) {
1781                logger.error("Error while processing line "+count+"[" + line + "]");
1782                throw e;
1783            }
1784        }
1785
1786        // force objects to garbage collector...
1787
object = null;
1788        script = null;
1789        runtime = null;
1790        line = null;
1791    }
1792    // end insertDBDefaultContent()
1793

1794
1795
1796
1797    /**
1798     * Create the folder where jahia must store the xml templates files.
1799     * If this folder already exists and have some content, remove it.
1800     * @author Alexandre Kraft
1801     */

1802    private void folderXMLtemplates()
1803    throws Exception JavaDoc
1804    {
1805        File JavaDoc folder = new File JavaDoc( Jahia.jahiaTemplatesScriptsPath );
1806        if(!folder.exists()) {
1807            folder.mkdirs();
1808        } else {
1809            File JavaDoc[] list = folder.listFiles();
1810            for(int i=0; i<list.length; i++) {
1811                JahiaTools.deleteFile( list[i] );
1812            }
1813            list = null;
1814        }
1815        folder = null;
1816    }
1817    // end folderXMLtemplates()
1818

1819
1820
1821
1822   /**
1823    * Set the properties object, using data containing in the *values* hashmap,
1824    * using the jahia's propertiesmanager object.
1825    * @author Alexandre Kraft
1826    */

1827    private void setPropertiesObject()
1828    {
1829        String JavaDoc appsService = null;
1830
1831        // resolve inside http path...
1832
StringBuffer JavaDoc jahiaInsideHttpPath = new StringBuffer JavaDoc();
1833        // jahiaInsideHttpPath.append( (String)values.get("server_url") );
1834
jahiaInsideHttpPath.append( Jahia.getContextPath() );
1835        jahiaInsideHttpPath.append( properties.getProperty( "jahiaJspDiskPath" ) );
1836
1837        // use appropriate webapps deployer service depending the servlet container type..
1838
if( ((String JavaDoc)serverInfos.get("type")).equals("orion") ) {
1839            appsService = "org.jahia.services.webapps_deployer.JahiaOrionWebAppsDeployerBaseService";
1840        } else if( ((String JavaDoc)serverInfos.get("type")).indexOf("JBoss") != -1 ) {
1841            appsService = "org.jahia.services.webapps_deployer.JahiaJBossWebAppsDeployerBaseService";
1842        } else if( ((String JavaDoc)serverInfos.get("type")).indexOf("Tomcat") != -1 ) {
1843            appsService = "org.jahia.services.webapps_deployer.JahiaTomcatWebAppsDeployerBaseService";
1844        } else {
1845            appsService = "org.jahia.services.webapps_deployer.GenericWebAppsDeployerBaseService";
1846        }
1847
1848        // find release number...
1849
String JavaDoc release = new Double JavaDoc(Jahia.RELEASE_NUMBER).toString() + "." + new Integer JavaDoc(Jahia.SERVICE_PACK_NUMBER).toString();
1850        if (! "".equals(Jahia.PATCH_STRING)) {
1851            release = release + "_" + Jahia.PATCH_STRING;
1852        }
1853
1854        // set new values in the PropertiesManager...
1855
properties.setProperty("release", release );
1856        properties.setProperty("server", (String JavaDoc)serverInfos.get("type") );
1857        properties.setProperty("serverHomeDiskPath", (String JavaDoc)values.get("server_home") );
1858        properties.setProperty("jahiaFilesDiskPath", (String JavaDoc)values.get("server_jahiafiles") );
1859        properties.setProperty("jahiaEtcDiskPath", (String JavaDoc)values.get("server_jahiafiles")+"/etc/" );
1860        properties.setProperty("jahiaVarDiskPath", (String JavaDoc)values.get("server_jahiafiles")+"/var/" );
1861        properties.setProperty("jahiaFilesBigTextDiskPath", (String JavaDoc)values.get("server_jahiafiles")+"/var/content/bigtext/" );
1862        properties.setProperty("slideContentDiskPath", (String JavaDoc)values.get("server_jahiafiles")+"/var/content/slide/" );
1863        properties.setProperty("tmpContentDiskPath", (String JavaDoc)values.get("server_jahiafiles")+"/var/content/tmp/" );
1864        properties.setProperty("jahiaFilesTemplatesDiskPath", (String JavaDoc)values.get("server_jahiafiles")+"/var/templates/" );
1865        properties.setProperty("jahiaNewTemplatesDiskPath", (String JavaDoc)values.get("server_jahiafiles")+"/var/new_templates/" );
1866        properties.setProperty("jahiaNewWebAppsDiskPath", (String JavaDoc)values.get("server_jahiafiles")+"/var/new_webapps/" );
1867        properties.setProperty("jahiaSharedComponentsDiskPath", (String JavaDoc)values.get("server_jahiafiles")+"/var/shared_components/" );
1868        properties.setProperty("jahiaSharedTemplatesDiskPath", (String JavaDoc)values.get("server_jahiafiles")+"/var/shared_templates/" );
1869        properties.setProperty("jahiaFileRepositoryDiskPath", (String JavaDoc)values.get("server_jahiafiles")+"/var/content/filemanager/" );
1870        // properties.setProperty("jahiaHostHttpPath", (String)values.get("server_url") );
1871
properties.setProperty("jahiaHostHttpPath", "" );
1872        properties.setProperty("jahiaCoreHttpPath", Jahia.getRelativeServletURI() );
1873        properties.setProperty("jahiaTemplatesHttpPath", jahiaInsideHttpPath.toString() + "templates/" );
1874        properties.setProperty("jahiaEnginesHttpPath", jahiaInsideHttpPath.toString() + "engines/" );
1875        properties.setProperty("jahiaJavaScriptHttpPath", jahiaInsideHttpPath.toString() + "javascript/jahia.js" );
1876        properties.setProperty("mail_server", (String JavaDoc)values.get("mail_server") );
1877        properties.setProperty("mail_administrator", (String JavaDoc)values.get("mail_recipient") );
1878        properties.setProperty("mail_from", (String JavaDoc)values.get("mail_from") );
1879        properties.setProperty("mail_paranoia", (String JavaDoc)values.get("mail_parano") );
1880        properties.setProperty("db_script", (String JavaDoc)values.get("database_script") );
1881        properties.setProperty("db_driver", (String JavaDoc)values.get("database_driver") );
1882        properties.setProperty("db_url", (String JavaDoc)values.get("database_url") );
1883        properties.setProperty("db_username", (String JavaDoc)values.get("database_user") );
1884        properties.setProperty("db_password", (String JavaDoc)values.get("database_pwd") );
1885        properties.setProperty("db_transactions", (String JavaDoc)values.get("database_transactions") );
1886        properties.setProperty("db_support_embedded_select_statement", (String JavaDoc)values.get("database_support_embedded_select_statement") );
1887        String JavaDoc utf8Encoding = (String JavaDoc)values.get("utf8Encoding");
1888        properties.setProperty("utf8Encoding", utf8Encoding);
1889        if ("true".equalsIgnoreCase(utf8Encoding)) {
1890            properties.setProperty("defaultResponseBodyEncoding", "UTF-8");
1891        } else {
1892            properties.setProperty("defaultResponseBodyEncoding", "ISO-8859-1");
1893        }
1894        if ( appsService.length() != 0 ) {
1895            properties.setProperty("JahiaWebAppsDeployerService", appsService );
1896            properties.setProperty("jahiaWebAppsDeployerBaseURL", (String JavaDoc) values.get("webapps_deploybaseurl"));
1897        }
1898        properties.setProperty("org.jahia.multilang.default_language_code", (String JavaDoc)values.get("org.jahia.multilang.default_language_code") );
1899
1900        // force objects to garbage collector...
1901
appsService = null;
1902        release = null;
1903
1904    } // setPropertiesObject
1905

1906
1907
1908
1909    /**
1910     * Get *skeleton* init parameter and read the skeleton files values to
1911     * fill in the default hashmap values with the results.
1912     * @author Alexandre Kraft
1913     */

1914    private void fillDefaultValues()
1915    {
1916        fillDefaultValues( true, true );
1917    }
1918    // end fillDefaultValues();
1919

1920
1921
1922
1923    /**
1924     * Get *skeleton* init parameter and read the skeleton files values to
1925     * fill in the default hashmap values with the results.
1926     * @author Alexandre Kraft
1927     *
1928     * @param all redefine database default values.
1929     * @param database redefine database default values.
1930     */

1931    private void fillDefaultValues( boolean all, boolean database )
1932    {
1933        // get init parameter and read jahia skeleton properties...
1934
properties = new PropertiesManager( context.getRealPath(config.getInitParameter("skeleton")) );
1935
1936        // root settings ...
1937
if( all ) {
1938            values.put( "root_user", "root" );
1939            values.put( "root_pwd", "" );
1940            values.put( "root_confirm", "" );
1941            values.put( "root_firstname", "Jahia" );
1942            values.put( "root_lastname", "Super Administrator" );
1943            values.put( "root_mail", "" );
1944        }
1945
1946        // server settings...
1947
if( all ) {
1948            values.put( "server_home", (String JavaDoc)serverInfos.get("home") );
1949            values.put( "server_url", null );
1950            values.put( "server_jahiafiles", properties.getProperty("jahiaFilesDiskPath").trim() );
1951            values.put( "server_jahiafiles_default", properties.getProperty("jahiaFilesDiskPath").trim() );
1952        }
1953
1954        // database settings...
1955
if( database || all ) {
1956            values.put( "database_script", properties.getProperty("db_script").trim() );
1957            if( ((String JavaDoc)serverInfos.get("type")).indexOf("JBoss") != -1 ) {
1958                values.put( "database_script", "jboss.script" );
1959            }
1960            values.put( "database_driver", properties.getProperty("db_driver").trim() );
1961            values.put( "database_url", properties.getProperty("db_url").trim() );
1962            values.put( "database_user", properties.getProperty("db_username").trim() );
1963            values.put( "database_pwd", properties.getProperty("db_password").trim() );
1964            values.put ("database_transactions", properties.getProperty("db_transactions").trim());
1965            values.put ("database_support_embedded_select_statement", properties.getProperty("db_support_embedded_select_statement").trim());
1966            values.put( "utf8Encoding", properties.getProperty("utf8Encoding").trim() );
1967            values.put( "database_custom", Boolean.FALSE );
1968            values.put( "database_requested", Boolean.FALSE );
1969            try {
1970                // let's try to copy the values from the script that's set as
1971
// the default.
1972
Vector JavaDoc scriptsInfos = scripts.getDatabaseScriptsInfos(scripts.
1973                    getDatabaseScriptsFileObjects(), pathResolver);
1974                Enumeration JavaDoc scriptInfoEnum = scriptsInfos.elements();
1975                while (scriptInfoEnum.hasMoreElements()) {
1976                    HashMap JavaDoc curDatabaseHash = (HashMap JavaDoc) scriptInfoEnum.nextElement();
1977                    String JavaDoc scriptFileName = (String JavaDoc) curDatabaseHash.get("jahia.database.script");
1978                    if (scriptFileName.equals(values.get("database_script"))) {
1979                        logger.debug("Found script " + scriptFileName + ", copying default values");
1980                        values.put ("database_driver", ((String JavaDoc) curDatabaseHash.get("jahia.database.driver")).trim());
1981                        values.put ("database_url", ((String JavaDoc) curDatabaseHash.get("jahia.database.url")).trim());
1982                        values.put ("database_user", ((String JavaDoc) curDatabaseHash.get("jahia.database.user")).trim());
1983                        values.put ("database_pwd", ((String JavaDoc) curDatabaseHash.get("jahia.database.pass")).trim());
1984                        values.put ("database_transactions", ((String JavaDoc) curDatabaseHash.get("jahia.database.transactions")).trim());
1985                        values.put ("database_support_embedded_select_statement", ((String JavaDoc) curDatabaseHash.get("jahia.database.support_embedded_select_statement")).trim());
1986
1987                    }
1988                }
1989            } catch (IOException JavaDoc ioe) {
1990                logger.debug("Error while loading default values from database scripts", ioe);
1991            }
1992        }
1993
1994        // mail settings...
1995
if( all ) {
1996            values.put( "mail_server", "" );
1997            values.put( "mail_recipient", "" );
1998            values.put( "mail_from", "" );
1999            values.put( "mail_parano", "" );
2000        }
2001
2002        // default templates set
2003
if( all ) {
2004            values.put( "templates", properties.getProperty("default_templates_set").trim() );
2005        }
2006    }
2007    // end fillDefaultValues( boolean, boolean )
2008

2009
2010
2011
2012
2013
2014
2015    /*
2016     *
2017     * -------> THESE METHODS ARE NOT CHANGED <-------------------------------
2018     * ----------------------------------------------------------------------<
2019     */

2020
2021
2022
2023    /**
2024     * Move Jahia Files on their final directories (only if needed).
2025     * @author Alexandre Kraft
2026     */

2027    private void moveJahiaFiles()
2028    throws Exception JavaDoc
2029    {
2030        // get jahia files paths...
2031
String JavaDoc choosed_path = (String JavaDoc)values.get("server_jahiafiles");
2032        String JavaDoc original_path = context.getRealPath(
2033                                    ((String JavaDoc)values.get("server_jahiafiles_default")).substring( 8,
2034                                        ((String JavaDoc)values.get("server_jahiafiles_default")).length()) );
2035
2036        // convert if choosed_path is a $context relative path...
2037
try {
2038            if(choosed_path.substring(0,9).equals("$context/")) {
2039                choosed_path = context.getRealPath( choosed_path.substring(8, choosed_path.length()) );
2040            }
2041        } catch (StringIndexOutOfBoundsException JavaDoc sioobe) {
2042        }
2043
2044        // try to check if they represent the same directory...
2045
File JavaDoc choosedFolder = new File JavaDoc( choosed_path );
2046        File JavaDoc originalFolder = new File JavaDoc( original_path );
2047
2048        // move files only if the jahia files path is not the default path...
2049
if( !choosedFolder.equals( originalFolder ) ) {
2050            File JavaDoc[] originalFolderContent = originalFolder.listFiles();
2051            HashMap JavaDoc originalContent = new HashMap JavaDoc();
2052            for(int i=0; i<originalFolderContent.length; i++) {
2053                originalContent.put( (String JavaDoc)originalFolderContent[i].getName(), (String JavaDoc)originalFolderContent[i].getPath() );
2054            }
2055
2056            // remove directories for non-move...
2057
originalContent.remove( "database" );
2058            originalContent.remove( "config" );
2059
2060            // create final content list...
2061
Object JavaDoc[] originalContentFinal = originalContent.values().toArray();
2062            File JavaDoc startFile;
2063
2064            // copy whole list... (it's a move.... :o)
2065
for(int i=0; i<originalContentFinal.length; i++) {
2066                startFile = new File JavaDoc( originalContentFinal[i].toString() );
2067                String JavaDoc endFile = choosedFolder.getPath() + File.separator + startFile.getName();
2068                try {
2069                    JahiaTools.copyFolderContent( startFile.getPath(), endFile );
2070                } catch (IOException JavaDoc ioe) {
2071                }
2072            }
2073
2074            // remove original folders...
2075
for(int i=0; i<originalContentFinal.length; i++) {
2076                startFile = new File JavaDoc( originalContentFinal[i].toString() );
2077                JahiaTools.deleteFile(startFile);
2078            }
2079
2080        }
2081    } // end moveJahiaFiles
2082

2083
2084
2085
2086
2087    //--------------------------------------------------------------------------
2088
/**
2089     * copy all shared templates package (.jar) found in the
2090     * jahiafiles/shared_templates to jahiafiles/new_templates/<sitekey>
2091     *
2092     * @param siteKey
2093     * @author NK
2094     */

2095    protected void copySharedTemplates(String JavaDoc siteKey)
2096    throws Exception JavaDoc
2097    {
2098        // get the shared templates folder
2099
String JavaDoc sharedTemplatesFolder = ((String JavaDoc)values.get("server_jahiafiles_default")).substring(8, ((String JavaDoc)values.get("server_jahiafiles_default")).length()) + File.separator + "var" + File.separator + "shared_templates";
2100
2101        File JavaDoc f = new File JavaDoc( context.getRealPath(sharedTemplatesFolder) + File.separator + (String JavaDoc)values.get("templates") + ".jar");
2102
2103        if ( f.isFile() ){
2104            // get the new templates folder for the site, create it if not exists
2105
String JavaDoc newTemplatesFolder = ((String JavaDoc)values.get("server_jahiafiles_default")).substring(8, ((String JavaDoc)values.get("server_jahiafiles_default")).length()) + File.separator + "var" + File.separator + "new_templates" + File.separator + siteKey;
2106            File JavaDoc newTemplate = new File JavaDoc(context.getRealPath(newTemplatesFolder));
2107            newTemplate.mkdirs();
2108
2109            f.renameTo(new File JavaDoc(newTemplate.getAbsolutePath()+File.separator+f.getName()));
2110        }
2111
2112    }
2113
2114
2115    //--------------------------------------------------------------------------
2116
/**
2117     * copy default template folder
2118     * jahia/jsp/jahia/templates/default to jahia/jsp/jahia/templates/<sitekey>/default
2119     *
2120     * @param siteKey
2121     * @author NK
2122     */

2123    protected void copyDefaultTemplates(String JavaDoc siteKey)
2124    throws Exception JavaDoc
2125    {
2126
2127        logger.debug("Installing templates...");
2128
2129        // get the root folder for all templates
2130
String JavaDoc JahiaFilesTemplatesDiskPath =
2131        context.getRealPath( properties.getProperty("jahiaTemplatesDiskPath").trim() );
2132
2133        if ( JahiaFilesTemplatesDiskPath != null ){
2134
2135            File JavaDoc defaultTemplate = new File JavaDoc(JahiaFilesTemplatesDiskPath + File.separator + "default");
2136
2137            if ( defaultTemplate.isDirectory() ){
2138
2139                try {
2140                    //logger.debug(" copying default templates" );
2141
JahiaTools.copyFolderContent(defaultTemplate.getAbsolutePath(),
2142                                JahiaFilesTemplatesDiskPath + File.separator + siteKey + File.separator + "default");
2143
2144                } catch (IOException JavaDoc ioe) {
2145                    logger.debug("error copying default templates " + ioe.getMessage());
2146                }
2147            }
2148        }
2149
2150        // get the shared templates folder
2151
logger.debug("jahiaSettingsPathJahiaFiles is " + ((String JavaDoc)values.get("server_jahiafiles_default")) );
2152        String JavaDoc sharedTemplatesFolder = ((String JavaDoc)values.get("server_jahiafiles_default")).substring(8, ((String JavaDoc)values.get("server_jahiafiles_default")).length()) + File.separator + "var" + File.separator + "shared_templates";
2153
2154        boolean result = deployTemplate( JahiaFilesTemplatesDiskPath,
2155                        siteKey,
2156                        context.getRealPath(sharedTemplatesFolder + File.separator + (String JavaDoc)values.get("templates")+".jar" ),
2157                        (String JavaDoc)values.get("templates"));
2158
2159        if (!result){
2160            File JavaDoc f = new File JavaDoc( context.getRealPath(sharedTemplatesFolder + File.separator + (String JavaDoc)values.get("templates")+".jar" ) );
2161            logger.debug(" sharedTemplatesFolder is " + f.getAbsolutePath() );
2162            if ( f.isFile() ){
2163                JahiaArchiveFileHandler zip = null;
2164                try {
2165                    zip = new JahiaArchiveFileHandler(f.getAbsolutePath());
2166                    File JavaDoc destFile = new File JavaDoc(JahiaFilesTemplatesDiskPath + File.separator + siteKey + File.separator + (String JavaDoc)values.get("templates"));
2167                    destFile.mkdirs();
2168                    zip.unzip(destFile.getAbsolutePath());
2169                } catch ( JahiaException je ){
2170                    throw new Exception JavaDoc( je.getMessage() );
2171                } catch ( IOException JavaDoc ioe ){
2172                    throw new Exception JavaDoc( ioe.getMessage() );
2173                } finally {
2174                    zip.closeArchiveFile();
2175                }
2176            }
2177        }
2178    }
2179
2180    /**
2181     * Deploy a template .jar file.
2182     *
2183     * @param jahiaTemplateDiskPath
2184     * @param siteKey
2185     * @param filePath
2186     * @return
2187     * @throws JahiaException
2188     */

2189    public boolean deployTemplate(String JavaDoc jahiaTemplateDiskPath, String JavaDoc siteKey, String JavaDoc filePath, String JavaDoc rootFolder){
2190
2191        boolean success = true;
2192        String JavaDoc fullPath = null;
2193        JahiaTemplatesPackageHandler ph = null;
2194        try {
2195
2196            ph = new JahiaTemplatesPackageHandler(filePath);
2197
2198            JahiaTemplatesPackage tempPack = ph.getPackage();
2199
2200            if ( tempPack == null ){
2201                String JavaDoc errMsg =" cannot create a JahiaTemplatesPackage on file " + filePath ;
2202                logger.debug(errMsg);
2203                return false;
2204            }
2205
2206            StringBuffer JavaDoc strBuf = new StringBuffer JavaDoc(1024);
2207            strBuf.append(jahiaTemplateDiskPath);
2208            strBuf.append(File.separator);
2209            strBuf.append(siteKey);
2210            strBuf.append(File.separator);
2211            if ( tempPack.getRootFolder() != null
2212                 && !tempPack.getRootFolder().trim().equals("") ){
2213                strBuf.append(tempPack.getRootFolder());
2214            } else {
2215                strBuf.append(rootFolder);
2216            }
2217
2218            // Full path to the templates root folder
2219
fullPath = strBuf.toString();
2220
2221            // Check that the root folder for the new template doesn't exist
2222
File JavaDoc f = new File JavaDoc(fullPath);
2223            if ( f != null && !f.isDirectory() ){
2224                // create the dir
2225
f.mkdirs();
2226            }
2227            ph.unzip(fullPath);
2228            // extract the classes file
2229
if ( tempPack.hasClasses () ){
2230                String JavaDoc classesFilePath = fullPath + File.separator + tempPack.getClassesFile();
2231
2232                File JavaDoc tmpFile = new File JavaDoc(classesFilePath);
2233                try{
2234                    if ( tmpFile != null && tmpFile.isFile() ){
2235                        JahiaArchiveFileHandler arch = new JahiaArchiveFileHandler(classesFilePath);
2236                        arch.unzip(context.getRealPath(properties.getProperty("classDiskPath")) + File.separator + "jahiatemplates");
2237                    }
2238                } catch ( IOException JavaDoc ioe ){
2239                    String JavaDoc errMsg = "Failed creating JahiaArchiveFileHandler on classes file " ;
2240                    logger.debug(errMsg + "\n" + ioe.toString());
2241                    return false;
2242                }
2243            }
2244        } catch ( Throwable JavaDoc t ) {
2245            String JavaDoc errMsg = "Failed handling templates file " ;
2246            logger.debug(errMsg, t);
2247            success = false;
2248        } finally {
2249            if ( ph != null ){
2250                ph.closeArchiveFile();
2251            }
2252        }
2253        return success;
2254    }
2255
2256    //--------------------------------------------------------------------------
2257
/**
2258     * copy all shared webapps package found in the
2259     * jahiafiles\shared_components to jahiafiles\new_webapps\<sitekey>
2260     *
2261     * @param siteKey the siteKey
2262     * @author NK
2263     */

2264    protected void copySharedComponents(String JavaDoc siteKey)
2265    throws Exception JavaDoc
2266    {
2267        logger.debug("Installing web applications...");
2268
2269        // get the shared components folder
2270
String JavaDoc sharedComponentsFolder = ((String JavaDoc)values.get("server_jahiafiles_default")).substring(8, ((String JavaDoc)values.get("server_jahiafiles_default")).length()) + File.separator + "var" + File.separator + "shared_components";
2271        File JavaDoc f = new File JavaDoc( context.getRealPath(sharedComponentsFolder) );
2272
2273        // get the new components folder for the site, create it if not exists
2274
String JavaDoc newComponentsFolder = ((String JavaDoc)values.get("server_jahiafiles_default")).substring(8, ((String JavaDoc)values.get("server_jahiafiles_default")).length()) + File.separator + "var" + File.separator + "new_webapps" + File.separator + siteKey;
2275        File JavaDoc newComponent = new File JavaDoc(context.getRealPath(newComponentsFolder));
2276        newComponent.mkdirs();
2277
2278        try {
2279            // copy all shared package to the new components folder for the site
2280
JahiaTools.copyFolderContent(f.getAbsolutePath(),
2281                        newComponent.getAbsolutePath());
2282        } catch ( Exception JavaDoc e ){
2283            // msg..
2284
}
2285
2286    }
2287
2288
2289
2290}
2291// end JahiaConfigurationWizard
2292
Popular Tags