KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > admin > database > ManageDatabase


1 /*
2  * ____.
3  * __/\ ______| |__/\. _______
4  * __ .____| | \ | +----+ \
5  * _______| /--| | | - \ _ | : - \_________
6  * \\______: :---| : : | : | \________>
7  * |__\---\_____________:______: :____|____:_____\
8  * /_____|
9  *
10  * . . . i n j a h i a w e t r u s t . . .
11  *
12  *
13  *
14  * ----- BEGIN LICENSE BLOCK -----
15  * Version: JCSL 1.0
16  *
17  * The contents of this file are subject to the Jahia Community Source License
18  * 1.0 or later (the "License"); you may not use this file except in
19  * compliance with the License. You may obtain a copy of the License at
20  * http://www.jahia.org/license
21  *
22  * Software distributed under the License is distributed on an "AS IS" basis,
23  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
24  * for the rights, obligations and limitations governing use of the contents
25  * of the file. The Original and Upgraded Code is the Jahia CMS and Portal
26  * Server. The developer of the Original and Upgraded Code is JAHIA Ltd. JAHIA
27  * Ltd. owns the copyrights in the portions it created. All Rights Reserved.
28  *
29  * The Shared Modifications are Jahia View Helper.
30  *
31  * The Developer of the Shared Modifications is Jahia Solution S�rl.
32  * Portions created by the Initial Developer are Copyright (C) 2002 by the
33  * Initial Developer. All Rights Reserved.
34  *
35  * Contributor(s):
36  * 01-APR-2001, Xo3 SA, Alexandre Kraft : Initial version
37  * 23-MAY-2001, Xo3 SA, Khue Nguyen
38  * 29-AUG-2003, Jahia Solutions Sarl, Fulco Houkes
39  *
40  * ----- END LICENSE BLOCK -----
41  */

42
43
44 package org.jahia.admin.database;
45
46 import java.io.File JavaDoc;
47 import java.io.FileNotFoundException JavaDoc;
48 import java.io.IOException JavaDoc;
49 import java.sql.PreparedStatement JavaDoc;
50 import java.sql.ResultSet JavaDoc;
51 import java.sql.ResultSetMetaData JavaDoc;
52 import java.sql.SQLException JavaDoc;
53 import java.sql.Statement JavaDoc;
54 import java.sql.Types JavaDoc;
55 import java.util.Enumeration JavaDoc;
56 import java.util.HashMap JavaDoc;
57 import java.util.Iterator JavaDoc;
58 import java.util.TreeSet JavaDoc;
59 import java.util.Vector JavaDoc;
60
61 import javax.servlet.ServletException JavaDoc;
62 import javax.servlet.http.HttpServletRequest JavaDoc;
63 import javax.servlet.http.HttpServletResponse JavaDoc;
64 import javax.servlet.http.HttpSession JavaDoc;
65
66 import org.jahia.bin.Jahia;
67 import org.jahia.bin.JahiaAdministration;
68 import org.jahia.data.JahiaData;
69 import org.jahia.exceptions.JahiaException;
70 import org.jahia.params.ParamBean;
71 import org.jahia.resourcebundle.JahiaResourceBundle;
72 import org.jahia.services.usermanager.JahiaUser;
73 import org.jahia.utils.JahiaTools;
74 import org.jahia.utils.properties.PropertiesManager;
75 import org.jahia.utils.PathResolver;
76
77 /**
78  * desc: This class is used by the administration to manage the
79  * database settings, like the database connection settings, or is also
80  * used by jahia to transfer jahia data to an another database. Backup
81  * and restore are alse executed by this class.
82  *
83  * Copyright: Copyright (c) 2002
84  * Company: Jahia Ltd
85  *
86  * @author Alexandre Kraft
87  * @version 1.0
88  */

89 public class ManageDatabase {
90
91     /** logging */
92     private static org.apache.log4j.Logger logger =
93             org.apache.log4j.Logger.getLogger (ManageDatabase.class);
94
95     private static final String JavaDoc CLASS_NAME = JahiaAdministration.CLASS_NAME;
96     private static final String JavaDoc JSP_PATH = JahiaAdministration.JSP_PATH;
97
98     private static DatabaseConnection dbConnect = new DatabaseConnection ();
99     private static DatabaseScripts scriptsManager;
100     private static PropertiesManager properties;
101     private static PathResolver pathResolver;
102
103     private static byte[] mLock = new byte[1];
104
105     /**
106      * Default constructor.
107      *
108      * @param request Servlet request.
109      * @param response Servlet response.
110      * @param session Servlet session for the current user.
111      * @param context Servlet context.
112      */

113     public ManageDatabase (HttpServletRequest JavaDoc request,
114                            HttpServletResponse JavaDoc response,
115                            HttpSession JavaDoc session,
116                            PathResolver pathResolver)
117             throws Throwable JavaDoc {
118         this.pathResolver = pathResolver;
119         properties = new PropertiesManager (Jahia.getJahiaPropertiesFileName ());
120         scriptsManager = new DatabaseScripts ();
121         userRequestDispatcher (request, response, session);
122     } // end constructor
123

124
125     /**
126      * This method is used like a dispatcher for user requests.
127      *
128      * @param request Servlet request.
129      * @param response Servlet response.
130      * @param session Servlet session for the current user.
131      */

132     private void userRequestDispatcher (HttpServletRequest JavaDoc request,
133                                         HttpServletResponse JavaDoc response,
134                                         HttpSession JavaDoc session)
135             throws Throwable JavaDoc {
136         String JavaDoc operation = request.getParameter ("sub");
137
138         if (operation.equals ("display")) {
139             displayChoice (request, response, session);
140         } else if (operation.equals ("choice")) {
141             processChoice (request, response, session);
142         } else if (operation.equals ("backup")) {
143             processBackup (request, response, session);
144         } else if (operation.equals ("restore")) {
145             processRestore (request, response, session);
146         } else if (operation.equals ("flush")) {
147             processFlush (request, response, session);
148         } else if (operation.equals ("transfer")) {
149             processSettings (request, response, session, true);
150         } else if (operation.equals ("change")) {
151             processSettings (request, response, session, false);
152         }
153     } // userRequestDispatcher
154

155
156     /**
157      * Display the page where the user can choose what he want to do. He can
158      * choice to change the database connection settings, transfer the data
159      * from the current database to another database, backup the database
160      * and manage the backup (like restore and flush).
161      *
162      * @param request Servlet request.
163      * @param response Servlet response.
164      * @param session Servlet session for the current user.
165      */

166     private void displayChoice (HttpServletRequest JavaDoc request,
167                                 HttpServletResponse JavaDoc response,
168                                 HttpSession JavaDoc session)
169             throws IOException JavaDoc, ServletException JavaDoc {
170         JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "config_database_which.jsp");
171     } // end displayChoice
172

173
174     /**
175      * Display a page where the user can choose a name and a desc
176      * for the backup that he have requested.
177      *
178      * @param request Servlet request.
179      * @param response Servlet response.
180      * @param session Servlet session for the current user.
181      */

182     private void displayBackup (HttpServletRequest JavaDoc request,
183                                 HttpServletResponse JavaDoc response,
184                                 HttpSession JavaDoc session)
185             throws IOException JavaDoc, ServletException JavaDoc {
186         // retrieve previous form values...
187
String JavaDoc jahiaBackupName = (String JavaDoc)session.getAttribute (CLASS_NAME + "jahiaBackupName");
188         String JavaDoc jahiaBackupDesc = (String JavaDoc)session.getAttribute (CLASS_NAME + "jahiaBackupDesc");
189         String JavaDoc jahiaBackupType = (String JavaDoc)session.getAttribute (CLASS_NAME + "jahiaBackupType");
190
191         // set default values (if necessary)...
192
if (jahiaBackupName == null) {
193             jahiaBackupName = "";
194         }
195         if (jahiaBackupDesc == null) {
196             jahiaBackupDesc = "";
197         }
198         if (jahiaBackupType == null) {
199             jahiaBackupType = "manual";
200         }
201
202         // set request attributes...
203
request.setAttribute ("jahiaBackupName", jahiaBackupName);
204         request.setAttribute ("jahiaBackupDesc", jahiaBackupDesc);
205         request.setAttribute ("jahiaBackupType", jahiaBackupType);
206
207         JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "backup_database.jsp");
208     } // end displayBackup
209

210
211     /**
212      * Display a page where the user can restore a backup or flush/delete
213      * an unwanted backup. This method display the full list of backups.
214      *
215      * @param request Servlet request.
216      * @param response Servlet response.
217      * @param session Servlet session for the current user.
218      */

219     private void displayRestore (HttpServletRequest JavaDoc request,
220                                  HttpServletResponse JavaDoc response,
221                                  HttpSession JavaDoc session)
222             throws IOException JavaDoc, ServletException JavaDoc {
223         int backupCount = 0;
224
225         // get backups path...
226
StringBuffer JavaDoc constructBackupPath = new StringBuffer JavaDoc ();
227         constructBackupPath.append (properties.getProperty ("jahiaVarDiskPath").trim ());
228         constructBackupPath.append (File.separator);
229         constructBackupPath.append ("backup");
230         String JavaDoc backupJahiaFilesPath = JahiaTools.convertContexted (constructBackupPath.toString (), pathResolver);
231
232         // get backups list...
233
TreeSet JavaDoc backupListTree = new TreeSet JavaDoc ();
234         File JavaDoc backupJahiaFilesObject = new File JavaDoc (backupJahiaFilesPath);
235         File JavaDoc[] filesInThisDirectory = backupJahiaFilesObject.listFiles ();
236         try {
237             for (int i = 0; i < filesInThisDirectory.length; i++) {
238                 if (filesInThisDirectory[i].isFile ()) {
239                     backupListTree.add (filesInThisDirectory[i].getPath ());
240                 }
241             }
242         } catch (NullPointerException JavaDoc npe) {
243         }
244
245         // get infos from files...
246
Iterator JavaDoc iteration = backupListTree.iterator ();
247         Vector JavaDoc backupListVector = new Vector JavaDoc ();
248         while (iteration.hasNext ()) {
249             String JavaDoc pathBackupFile = (String JavaDoc)iteration.next ();
250             HashMap JavaDoc backupHash = new HashMap JavaDoc ();
251             PropertiesManager backupProperties = new PropertiesManager (pathBackupFile);
252
253             String JavaDoc epochTime = backupProperties.getProperty ("epoch");
254             backupHash.put ("backup.epoch", epochTime);
255             backupHash.put ("backup.date", JahiaTools.formatDateFromEpoch (epochTime));
256             backupHash.put ("backup.name", backupProperties.getProperty ("name"));
257             backupHash.put ("backup.desc", backupProperties.getProperty ("desc"));
258             backupHash.put ("backup.type", backupProperties.getProperty ("type"));
259             if (backupProperties.getProperty ("build") == null) {
260                 backupHash.put ("backup.build", "0");
261             } else {
262                 backupHash.put ("backup.build", backupProperties.getProperty ("build"));
263             }
264             if (backupProperties.getProperty ("release") == null) {
265                 backupHash.put ("backup.release", "0.0");
266             } else {
267                 backupHash.put ("backup.release", backupProperties.getProperty ("release"));
268             }
269
270             backupListVector.add (backupHash);
271             backupCount++;
272         }
273         backupListVector = JahiaTools.inverseVector (backupListVector);
274
275         // set request attributes...
276
request.setAttribute ("jahiaBackupList", backupListVector.elements ());
277         request.setAttribute ("jahiaBackupCount", new Integer JavaDoc (backupCount));
278
279         JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "restore_database.jsp");
280     } // end displayRestore
281

282
283     /**
284      * Display the settings page. This page is viewed two times. One time for
285      * change the settings for the database connection and other database
286      * settings. The second time, this page is viewed to transfer the database
287      * to an another database. In this case, the inputs values are used like
288      * the destination database connection settings.
289      *
290      * @param request Servlet request.
291      * @param response Servlet response.
292      * @param session Servlet session for the current user.
293      */

294     private void displaySettings (HttpServletRequest JavaDoc request,
295                                   HttpServletResponse JavaDoc response,
296                                   HttpSession JavaDoc session)
297             throws IOException JavaDoc, ServletException JavaDoc {
298         // get which action is requested...
299
Integer JavaDoc jahiaDBWhichAction = (Integer JavaDoc)session.getAttribute (CLASS_NAME + "jahiaDBWhichAction");
300
301         // get script lists...
302
Vector JavaDoc scriptsListInfos = scriptsManager.getDatabaseScriptsInfos (scriptsManager.getDatabaseScriptsFileObjects (), pathResolver);
303
304         // retrieve previous form values...
305
String JavaDoc jahiaDBScript = (String JavaDoc)session.getAttribute (CLASS_NAME + "jahiaDBScript");
306         String JavaDoc jahiaDBDriver = (String JavaDoc)session.getAttribute (CLASS_NAME + "jahiaDBDriver");
307         String JavaDoc jahiaDBUrl = (String JavaDoc)session.getAttribute (CLASS_NAME + "jahiaDBUrl");
308         String JavaDoc jahiaDBUsername = (String JavaDoc)session.getAttribute (CLASS_NAME + "jahiaDBUsername");
309         String JavaDoc jahiaDBPassword = (String JavaDoc)session.getAttribute (CLASS_NAME + "jahiaDBPassword");
310         String JavaDoc jahiaDBMinConnections = (String JavaDoc)session.getAttribute (CLASS_NAME + "jahiaDBMinConnections");
311         String JavaDoc jahiaDBMaxConnections = (String JavaDoc)session.getAttribute (CLASS_NAME + "jahiaDBMaxConnections");
312         String JavaDoc jahiaDBWaitIfBusy = (String JavaDoc)session.getAttribute (CLASS_NAME + "jahiaDBWaitIfBusy");
313         String JavaDoc jahiaDBVerbose = (String JavaDoc)session.getAttribute (CLASS_NAME + "jahiaDBVerbose");
314
315         // set default values...
316
if (jahiaDBScript == null) {
317             jahiaDBScript = properties.getProperty ("db_script");
318         }
319         if (jahiaDBDriver == null) {
320             jahiaDBDriver = properties.getProperty ("db_driver");
321         }
322         if (jahiaDBUrl == null) {
323             jahiaDBUrl = properties.getProperty ("db_url");
324         }
325         if (jahiaDBUsername == null) {
326             jahiaDBUsername = properties.getProperty ("db_username");
327         }
328         if (jahiaDBPassword == null) {
329             jahiaDBPassword = properties.getProperty ("db_password");
330         }
331         if (jahiaDBMinConnections == null) {
332             jahiaDBMinConnections = properties.getProperty ("db_min_connections");
333         }
334         if (jahiaDBMaxConnections == null) {
335             jahiaDBMaxConnections = properties.getProperty ("db_max_connections");
336         }
337         if (jahiaDBWaitIfBusy == null) {
338             jahiaDBWaitIfBusy = properties.getProperty ("db_waitIfBusy");
339         }
340         if (jahiaDBVerbose == null) {
341             jahiaDBVerbose = properties.getProperty ("db_verbose");
342         }
343
344         // set request attributes...
345
request.setAttribute ("jahiaDBWhichAction", jahiaDBWhichAction);
346         request.setAttribute ("jahiaScriptsInfos", scriptsListInfos.elements ());
347         request.setAttribute ("jahiaScriptsJavaScript", scriptsListInfos.elements ());
348         request.setAttribute ("jahiaDBScript", jahiaDBScript);
349         request.setAttribute ("jahiaDBDriver", jahiaDBDriver);
350         request.setAttribute ("jahiaDBUrl", jahiaDBUrl);
351         request.setAttribute ("jahiaDBUsername", jahiaDBUsername);
352         request.setAttribute ("jahiaDBPassword", jahiaDBPassword);
353         request.setAttribute ("jahiaDBMinConnections", jahiaDBMinConnections);
354         request.setAttribute ("jahiaDBMaxConnections", jahiaDBMaxConnections);
355         request.setAttribute ("jahiaDBWaitIfBusy", jahiaDBWaitIfBusy);
356         request.setAttribute ("jahiaDBVerbose", jahiaDBVerbose);
357
358         JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "config_database.jsp");
359     } // end displaySettings
360

361
362     /**
363      * Process the choice of database action. Determine if the user has choosed
364      * to change database connection settings, transfer the current database
365      * to an another database, create a backup, or manage previous backup (like
366      * delete/flush and restore).
367      *
368      * @param request Servlet request.
369      * @param response Servlet response.
370      * @param session Servlet session for the current user.
371      */

372     private void processChoice (HttpServletRequest JavaDoc request,
373                                 HttpServletResponse JavaDoc response,
374                                 HttpSession JavaDoc session)
375             throws IOException JavaDoc, ServletException JavaDoc {
376         // get form values...
377
Integer JavaDoc action = new Integer JavaDoc (request.getParameter ("which_action").trim ());
378
379         // store the action that the user want...
380
session.setAttribute (CLASS_NAME + "jahiaDBWhichAction", action);
381
382         // determine which action are requested...
383
if (action.intValue () == 3) {
384             displayBackup (request, response, session);
385         } else if (action.intValue () == 4) {
386             displayRestore (request, response, session);
387         } else {
388             displaySettings (request, response, session);
389         }
390     } // end processChoice
391

392
393     /**
394      * Process and check the validity of the database backup page. If input(s)
395      * are not valid, display the backup page to the user.
396      *
397      * @param request Servlet request.
398      * @param response Servlet response.
399      * @param session Servlet session for the current user.
400      */

401     private void processBackup (HttpServletRequest JavaDoc request,
402                                 HttpServletResponse JavaDoc response,
403                                 HttpSession JavaDoc session)
404             throws IOException JavaDoc, ServletException JavaDoc {
405
406         synchronized (mLock) {
407
408             JahiaUser user = (JahiaUser)session.getAttribute (ParamBean.SESSION_USER);
409
410             JahiaData jData = (JahiaData)request.getAttribute ("org.jahia.data.JahiaData");
411             ParamBean jParams = null;
412             if (jData != null) {
413                 jParams = jData.params ();
414             }
415
416             if (user == null || !user.isAdminMember (0)) {
417                 String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.illegalAccessOperation.label",
418                         jParams, jParams.getLocale ());
419                 session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
420                 JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "menu.jsp");
421                 return;
422             }
423
424             byte[] jahiaLock = null;
425
426             try {
427                 jahiaLock = Jahia.getLock (user, session);
428                 if (jahiaLock == null) {
429                     String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.notExclusiveLock.label",
430                             jParams, jParams.getLocale ());
431                     session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
432                     JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "menu.jsp");
433                     return;
434                 }
435             } catch (JahiaException je) {
436                 session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", je.getMessage ());
437                 JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "menu.jsp");
438                 return;
439             }
440
441             try {
442
443
444                 boolean processError = true;
445
446                 // get form values...
447
String JavaDoc jahiaBackupName = request.getParameter ("backupname").trim ();
448                 String JavaDoc jahiaBackupDesc = request.getParameter ("backupdesc").trim ();
449                 String JavaDoc jahiaBackupType = request.getParameter ("backuptype").trim ();
450
451                 // check form validity...
452
if (jahiaBackupName.length () == 0) {
453                     String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.backupName_mustSet.label",
454                             jParams, jParams.getLocale ());
455                     session.setAttribute (this.getClass().getName() + "jahiaDisplayMessage", dspMsg);
456                 } else {
457                     processError = false;
458                 }
459
460                 if (processError) {
461                     session.setAttribute (this.getClass().getName() + "jahiaBackupName", jahiaBackupName);
462                     displayBackup (request, response, session);
463                 } else {
464
465                     // grab current database data...
466
String JavaDoc sqlGrab = grabDatabaseData (properties.getProperty ("db_driver"), properties.getProperty ("db_url"), properties.getProperty ("db_username"), properties.getProperty ("db_password"));
467
468                     // used anywhere
469
//Enumeration allGrabbedData = JahiaTools.string2Enumeration (sqlGrab, false);
470

471                     // get current epoch time...
472
String JavaDoc epochTime = new Long JavaDoc (JahiaTools.getCurrentDateInMs ()).toString ();
473
474                     // format paths...
475
String JavaDoc originDataJahiaFilesPath = JahiaTools.convertContexted (properties.getProperty ("jahiaFilesBigTextDiskPath").trim (), pathResolver);
476                     String JavaDoc originTemplatesJahiaFilesPath = JahiaTools.convertContexted (properties.getProperty ("jahiaFilesTemplatesDiskPath").trim (), pathResolver);
477                     String JavaDoc originTemplatesJSPPath = JahiaTools.convertContexted ("$context/" + properties.getProperty ("jahiaTemplatesDiskPath").trim (), pathResolver);
478                     String JavaDoc backupJahiaFilesPath = JahiaTools.convertContexted (properties.getProperty ("jahiaVarDiskPath").trim () + File.separator + "backup", pathResolver);
479                     String JavaDoc thisBackupJahiaFilesPath = backupJahiaFilesPath + File.separator + epochTime;
480                     String JavaDoc backupDataJahiaFilesPath = thisBackupJahiaFilesPath + File.separator + "data";
481                     String JavaDoc backupTemplatesJahiaFilesPath = thisBackupJahiaFilesPath + File.separator + "templates" + File.separator + "xml";
482                     String JavaDoc backupTemplatesJSPPath = thisBackupJahiaFilesPath + File.separator + "templates" + File.separator + "jsp";
483
484                     // backup jahiafiles (data and templates folders)...
485
JahiaTools.copyFolderContent (originDataJahiaFilesPath, backupDataJahiaFilesPath);
486                     JahiaTools.copyFolderContent (originTemplatesJahiaFilesPath, backupTemplatesJahiaFilesPath);
487                     JahiaTools.copyFolderContent (originTemplatesJSPPath, backupTemplatesJSPPath);
488
489                     // create infos text...
490
StringBuffer JavaDoc nfoText = new StringBuffer JavaDoc ();
491                     nfoText.append ("epoch=" + epochTime + "\n");
492                     nfoText.append ("name=" + JahiaTools.string2Property (jahiaBackupName) + "\n");
493                     nfoText.append ("desc=" + JahiaTools.string2Property (jahiaBackupDesc) + "\n");
494                     nfoText.append ("type=" + jahiaBackupType + "\n");
495                     nfoText.append ("build=" + Jahia.BUILD_NUMBER + "\n");
496                     nfoText.append ("release=" + Jahia.RELEASE_NUMBER + "\n");
497
498                     // create backup sql runtime text...
499
JahiaTools.writeStringInFile (thisBackupJahiaFilesPath + File.separator + "sqldata.backup", sqlGrab);
500                     JahiaTools.writeStringInFile (backupJahiaFilesPath + File.separator + "backup_" + epochTime + ".info", nfoText.toString ());
501
502                     // display final...
503
/*
504                     request.setAttribute( "processMessage", "Your database backup has completed successfully." );
505                     session.setAttribute( CLASS_NAME + "jahiaDisplayMessage", Jahia.COPYRIGHT );
506                     JahiaAdministration.doRedirect( request, response, session, JSP_PATH + "finish.jsp" );
507                     */

508                     String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.dbBackupCompleted.label",
509                             jParams, jParams.getLocale ());
510                     session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
511                     displayRestore (request, response, session);
512                 }
513             } catch (Throwable JavaDoc t) {
514                 t.printStackTrace ();
515                 String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.dbError.label",
516                         jParams, jParams.getLocale ());
517                 session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
518                 JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "menu.jsp");
519                 return;
520
521             } finally {
522                 Jahia.releaseLock (jahiaLock);
523             }
524         }
525
526     } // end processBackup
527

528
529     /**
530      * Process the restoration of a database backup.
531      *
532      * @param request Servlet request.
533      * @param response Servlet response.
534      * @param session Servlet session for the current user.
535      */

536     private void processRestore (HttpServletRequest JavaDoc request,
537                                  HttpServletResponse JavaDoc response,
538                                  HttpSession JavaDoc session)
539             throws IOException JavaDoc, ServletException JavaDoc {
540
541         synchronized (mLock) {
542
543             byte[] jahiaLock = null;
544             boolean freeLock = true;
545
546             JahiaUser user = (JahiaUser)session.getAttribute (ParamBean.SESSION_USER);
547             JahiaData jData = (JahiaData)request.getAttribute ("org.jahia.data.JahiaData");
548             ParamBean jParams = null;
549             if (jData != null) {
550                 jParams = jData.params ();
551             }
552
553             if (user == null || !user.isAdminMember (0)) {
554                 String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.illegalAccessOperation.label",
555                         jParams, jParams.getLocale ());
556                 session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
557                 JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "menu.jsp");
558                 return;
559             }
560
561             try {
562                 jahiaLock = Jahia.getLock (user, session);
563                 if (jahiaLock == null) {
564                     String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.noJahiaLock.label",
565                             jParams, jParams.getLocale ());
566                     session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
567                     JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "menu.jsp");
568                     return;
569                 }
570             } catch (JahiaException je) {
571                 session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", je.getMessage ());
572                 JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "menu.jsp");
573                 return;
574             }
575
576             try {
577
578                 // get url epoch values...
579
String JavaDoc jahiaBackupEpoch = "";
580                 if (request.getParameter ("epoch") != null) {
581                     jahiaBackupEpoch = request.getParameter ("epoch").trim ();
582                 }
583
584                 // get parameters
585
String JavaDoc backupBuild = "";
586                 if (request.getParameter ("build") != null) {
587                     backupBuild = request.getParameter ("build").trim ();
588                 }
589
590                 String JavaDoc backupRelease = "";
591                 if (request.getParameter ("release") != null) {
592                     backupRelease = request.getParameter ("release").trim ();
593                 }
594
595                 if (backupBuild == null || backupBuild.equals ("")) {
596                     backupBuild = "-1";
597                 }
598                 if (backupRelease == null || backupRelease.equals ("")) {
599                     backupRelease = "-1.0";
600                 }
601
602
603                 // format paths...
604
String JavaDoc originDataJahiaFilesPath = JahiaTools.convertContexted (properties.getProperty ("jahiaFilesBigTextDiskPath").trim (), pathResolver);
605                 String JavaDoc originTemplatesJahiaFilesPath = JahiaTools.convertContexted (properties.getProperty ("jahiaFilesTemplatesDiskPath").trim (), pathResolver);
606                 String JavaDoc originTemplatesJSPPath = JahiaTools.convertContexted ("$context/" + properties.getProperty ("jahiaTemplatesDiskPath").trim (), pathResolver);
607                 String JavaDoc backupJahiaFilesPath = JahiaTools.convertContexted (properties.getProperty ("jahiaVarDiskPath").trim () + File.separator + "backup", pathResolver);
608                 String JavaDoc thisBackupJahiaFilesPath = backupJahiaFilesPath + File.separator + jahiaBackupEpoch;
609                 String JavaDoc backupDataJahiaFilesPath = thisBackupJahiaFilesPath + File.separator + "data";
610                 String JavaDoc backupTemplatesJahiaFilesPath = thisBackupJahiaFilesPath + File.separator + "templates" + File.separator + "xml";
611                 String JavaDoc backupTemplatesJSPPath = thisBackupJahiaFilesPath + File.separator + "templates" + File.separator + "jsp";
612
613                 // restore jahiafiles (data and templates folders)...
614
JahiaTools.deleteFile (new File JavaDoc (originDataJahiaFilesPath));
615                 JahiaTools.deleteFile (new File JavaDoc (originTemplatesJahiaFilesPath));
616                 JahiaTools.deleteFile (new File JavaDoc (originTemplatesJSPPath));
617                 JahiaTools.copyFolderContent (backupDataJahiaFilesPath, originDataJahiaFilesPath);
618                 JahiaTools.copyFolderContent (backupTemplatesJahiaFilesPath, originTemplatesJahiaFilesPath);
619                 JahiaTools.copyFolderContent (backupTemplatesJSPPath, originTemplatesJSPPath);
620
621                 // execute backup sql runtime text...
622
Enumeration JavaDoc allGrabbedData = JahiaTools.string2Enumeration (thisBackupJahiaFilesPath + File.separator + "sqldata.backup", true);
623                 insertDatabaseData (allGrabbedData, properties.getProperty ("db_driver"), properties.getProperty ("db_url"), properties.getProperty ("db_username"), properties.getProperty ("db_password"));
624
625
626                 // Check to restore patch or not
627
String JavaDoc patchPath = JahiaTools.convertContexted (properties.getProperty ("jahiaVarDiskPath").trim () + File.separator + "patch", pathResolver);
628                 File JavaDoc f = new File JavaDoc (patchPath);
629                 File JavaDoc[] files = f.listFiles ();
630                 for (int i = 0; i < files.length; i++) {
631                     if (files[i].getName ().endsWith (".property")) {
632                         logger.debug("Find patch file " + files[i].getName ());
633                         PropertiesManager patch = new PropertiesManager (files[i].getAbsolutePath ());
634                         try {
635                             if (Integer.parseInt (patch.getProperty ("build").trim ()) > Integer.parseInt (backupBuild)) {
636                                 patch = null;
637                                 logger.debug ("Delete patch file " + files[i].getName ());
638                                 files[i].delete ();
639                             }
640                         } catch (Throwable JavaDoc t) {
641                             logger.warn (t);
642                         }
643                     }
644                 }
645
646
647                 // NK, we do not free the lock.
648
// Doing so, we force the admin to restart the server ! ugly isn't ?
649
freeLock = false;
650
651                 // display final...
652
String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.processMessage.dbRestoreCompleted.label",
653                         jParams, jParams.getLocale ());
654                 request.setAttribute ("processMessage", dspMsg);
655                 session.setAttribute (CLASS_NAME + "jahiaDisplayMessage",
656                     JahiaResourceBundle.getAdminResource("org.jahia.admin.copyright",
657                         jParams, jParams.getLocale()));
658                 JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "finish.jsp");
659
660
661             } catch (Throwable JavaDoc t) {
662                 t.printStackTrace ();
663                 String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.dbError.label",
664                         jParams, jParams.getLocale ());
665                 session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
666                 JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "menu.jsp");
667                 return;
668
669             } finally {
670                 if (freeLock) {
671                     Jahia.releaseLock (jahiaLock);
672                 }
673             }
674         }
675
676
677     } // end processRestore
678

679
680     /**
681      * Process the delete / flush of a database backup.
682      *
683      * @param request Servlet request.
684      * @param response Servlet response.
685      * @param session Servlet session for the current user.
686      */

687     private void processFlush (HttpServletRequest JavaDoc request,
688                                HttpServletResponse JavaDoc response,
689                                HttpSession JavaDoc session)
690             throws IOException JavaDoc, ServletException JavaDoc
691     {
692         synchronized (mLock) {
693             // get url epoch values...
694
String JavaDoc jahiaFlushEpoch = request.getParameter ("epoch").trim ();
695
696             // format paths...
697
String JavaDoc backupJahiaFilesPath = JahiaTools.convertContexted (properties.getProperty ("jahiaVarDiskPath").trim () + File.separator + "backup", pathResolver);
698             String JavaDoc thisBackupJahiaFilesPath = backupJahiaFilesPath + File.separator + jahiaFlushEpoch;
699
700             // flush jahiafiles...
701
File JavaDoc f = new File JavaDoc (backupJahiaFilesPath + File.separator + "backup_" + jahiaFlushEpoch + ".info");
702             f.delete ();
703             logger.debug ("Delete file " + f.getAbsolutePath ());
704             JahiaTools.deleteFile (new File JavaDoc (backupJahiaFilesPath + File.separator + "backup_" + jahiaFlushEpoch + ".info"));
705             JahiaTools.deleteFile (new File JavaDoc (thisBackupJahiaFilesPath));
706
707             // display final...
708
JahiaData jData = (JahiaData)request.getAttribute ("org.jahia.data.JahiaData");
709             ParamBean jParams = null;
710             if (jData != null) {
711                 jParams = jData.params ();
712             }
713             String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.processMessage.selectedBackupFlushed.label",
714                     jParams, jParams.getLocale ());
715             request.setAttribute ("processMessage", dspMsg);
716             session.setAttribute (CLASS_NAME + "jahiaDisplayMessage",
717                 JahiaResourceBundle.getAdminResource("org.jahia.admin.copyright",
718                     jParams, jParams.getLocale()));
719             displayRestore (request, response, session);
720         }
721     }
722
723
724     /**
725      * Process and check validity of inputs from the database settings page.
726      * This method is used for change settings and transfer settings. The
727      * difference between these two cases is just some internal actions.
728      *
729      * @param request Servlet request.
730      * @param response Servlet response.
731      * @param session Servlet session for the current user.
732      * @param transfer <code>true</code> if the user has requested a transfer.
733      * <code>false</code> if the user want just to change
734      * in the database settings.
735      */

736     private void processSettings (HttpServletRequest JavaDoc request,
737                                   HttpServletResponse JavaDoc response,
738                                   HttpSession JavaDoc session,
739                                   boolean transfer)
740             throws IOException JavaDoc, ServletException JavaDoc {
741
742         synchronized (mLock) {
743
744             boolean processError = true;
745
746             String JavaDoc runtimeTestSQL = "";
747             int jahiaDBMinConnectionsInt = 0;
748             int jahiaDBMaxConnectionsInt = 0;
749
750             // get form values...
751
String JavaDoc jahiaDBScript = request.getParameter ("dbtype").trim ();
752             String JavaDoc jahiaDBDriver = request.getParameter ("dbdriver").trim ();
753             String JavaDoc jahiaDBUrl = request.getParameter ("dburl").trim ();
754             String JavaDoc jahiaDBUsername = request.getParameter ("dbusername").trim ();
755             String JavaDoc jahiaDBPassword = request.getParameter ("dbpassword").trim ();
756             String JavaDoc jahiaDBMinConnections = request.getParameter ("dbminconnect");
757             String JavaDoc jahiaDBMaxConnections = request.getParameter ("dbmaxconnect");
758             String JavaDoc jahiaDBWaitIfBusy = request.getParameter ("dbwait");
759             String JavaDoc jahiaDBVerbose = request.getParameter ("dbverbose");
760
761             // check special settings validity (if required)...
762
if (!transfer) {
763                 try {
764                     jahiaDBMinConnectionsInt = Integer.parseInt (jahiaDBMinConnections.trim ());
765                 } catch (NumberFormatException JavaDoc nfe) {
766                     jahiaDBMinConnectionsInt = 0;
767                 }
768                 try {
769                     jahiaDBMaxConnectionsInt = Integer.parseInt (jahiaDBMaxConnections.trim ());
770                 } catch (NumberFormatException JavaDoc nfe) {
771                     jahiaDBMaxConnectionsInt = 0;
772                 }
773             }
774
775             // check form validity...
776
JahiaData jData = (JahiaData)request.getAttribute ("org.jahia.data.JahiaData");
777             ParamBean jParams = null;
778             if (jData != null) {
779                 jParams = jData.params ();
780             }
781             if (jahiaDBDriver.length () == 0) {
782                 String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.dbDriver_mustSet.label",
783                         jParams, jParams.getLocale ());
784                 session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
785             } else if (jahiaDBUrl.length () == 0) {
786                 String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.dbURL_mustSet.label",
787                         jParams, jParams.getLocale ());
788                 session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
789             } else {
790                 if (!transfer) {
791                     if (jahiaDBMinConnections.length () == 0) {
792                         String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.dbMinConn_mustSet.label",
793                                 jParams, jParams.getLocale ());
794                         session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
795                     } else if (jahiaDBMinConnectionsInt < 1) {
796                         String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.dbMinConn_higherZero.label",
797                                 jParams, jParams.getLocale ());
798                         session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
799                     } else if (jahiaDBMaxConnections.length () == 0) {
800                         String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.dbMaxConn_mustSet.label",
801                                 jParams, jParams.getLocale ());
802                         session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
803                     } else if (jahiaDBMaxConnectionsInt < 1) {
804                         String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.dbMaxConn_higherZero.label",
805                                 jParams, jParams.getLocale ());
806                         session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
807                     } else if (jahiaDBMaxConnectionsInt <= jahiaDBMinConnectionsInt) {
808                         String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.dbMaxConn_higherMin.label",
809                                 jParams, jParams.getLocale ());
810                         session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
811                     } else {
812                         processError = false;
813                     }
814                 } else {
815                     processError = false;
816                 }
817             }
818
819             // get script runtime...
820
StringBuffer JavaDoc constructDBScript = new StringBuffer JavaDoc ();
821             constructDBScript.append (Jahia.jahiaDatabaseScriptsPath);
822             constructDBScript.append (File.separator);
823             constructDBScript.append (jahiaDBScript);
824
825             // get the script runtime...
826
try {
827                 File JavaDoc scriptsFileObject = new File JavaDoc (constructDBScript.toString ());
828                 Enumeration JavaDoc scriptsListRuntime = scriptsManager.getDatabaseScriptsRuntime (scriptsFileObject);
829                 runtimeTestSQL = (String JavaDoc)scriptsListRuntime.nextElement ();
830             } catch (FileNotFoundException JavaDoc fnfe) {
831                 String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.dbNotOpen.label",
832                         jParams, jParams.getLocale ());
833                 session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
834                 processError = true;
835             }
836
837             // test the connection...
838
if (!processError) {
839                 HashMap JavaDoc testDatabaseConnectionHashMap = dbConnect.databaseTest (jahiaDBScript, jahiaDBDriver, jahiaDBUrl, jahiaDBUsername, jahiaDBPassword, runtimeTestSQL, false, true);
840                 Boolean JavaDoc testDatabaseConnectionError = (Boolean JavaDoc)testDatabaseConnectionHashMap.get ("testDatabaseConnectionError");
841                 String JavaDoc testDatabaseConnectionMessage = (String JavaDoc)testDatabaseConnectionHashMap.get ("testDatabaseConnectionMessage");
842
843                 if (testDatabaseConnectionError.booleanValue ()) {
844                     logger.debug ("Database test failed.\n");
845                     session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", testDatabaseConnectionMessage);
846                     processError = true;
847                 } else {
848                     logger.debug ("Database test passed successfully!\n");
849                 }
850             }
851
852             // set new values...
853
session.setAttribute (CLASS_NAME + "jahiaDBScript", jahiaDBScript);
854             session.setAttribute (CLASS_NAME + "jahiaDBDriver", jahiaDBDriver);
855             session.setAttribute (CLASS_NAME + "jahiaDBUrl", jahiaDBUrl);
856             session.setAttribute (CLASS_NAME + "jahiaDBUsername", jahiaDBUsername);
857             session.setAttribute (CLASS_NAME + "jahiaDBPassword", jahiaDBPassword);
858             if (!transfer) {
859                 session.setAttribute (CLASS_NAME + "jahiaDBMinConnections", jahiaDBMinConnections);
860                 session.setAttribute (CLASS_NAME + "jahiaDBMaxConnections", jahiaDBMaxConnections);
861                 session.setAttribute (CLASS_NAME + "jahiaDBWaitIfBusy", jahiaDBWaitIfBusy);
862                 session.setAttribute (CLASS_NAME + "jahiaDBVerbose", jahiaDBVerbose);
863             }
864
865             if (processError) {
866                 displaySettings (request, response, session);
867             } else { // no error(s) detected, continue...
868
if (!transfer) {
869                     storeSettings (request, response, session, transfer);
870                 } else {
871                     if (!checkSameDatabase (jahiaDBUrl)) {
872                         //String sqlGrab = grabDatabaseData (properties.getProperty ("db_driver"), properties.getProperty ("db_url"), properties.getProperty ("db_username"), properties.getProperty ("db_password"));
873
//Enumeration allGrabbedData = JahiaTools.string2Enumeration (sqlGrab, false);
874
//insertDatabaseTables (jahiaDBScript, jahiaDBDriver, jahiaDBUrl, jahiaDBUsername, jahiaDBPassword);
875
//insertDatabaseData (allGrabbedData, jahiaDBDriver, jahiaDBUrl, jahiaDBUsername, jahiaDBPassword);
876

877                         //grabDatabaseData (properties.getProperty ("db_driver"), properties.getProperty ("db_url"), properties.getProperty ("db_username"), properties.getProperty ("db_password"));
878
insertDatabaseTables (jahiaDBScript, jahiaDBDriver, jahiaDBUrl, jahiaDBUsername, jahiaDBPassword);
879
880                         DatabaseConnection fromDB = null;
881                         DatabaseConnection toDB = null;
882                         try {
883                             fromDB = new DatabaseConnection();
884                             fromDB.databaseOpen (properties.getProperty ("db_driver"),
885                                     properties.getProperty ("db_url"),
886                                     properties.getProperty ("db_username"),
887                                     properties.getProperty ("db_password"));
888
889                             toDB = new DatabaseConnection();
890                             toDB.databaseOpen (jahiaDBDriver, jahiaDBUrl,
891                                     jahiaDBUsername, jahiaDBPassword);
892
893                             transfertDatabaseData(fromDB,toDB);
894
895                         } catch (Exception JavaDoc e) {
896                             e.printStackTrace();
897                         } finally {
898                             if ( fromDB != null ){
899                                 fromDB.databaseClose();
900                             }
901                             if ( toDB != null ){
902                                 toDB.databaseClose();
903                             }
904                         }
905                         storeSettings (request, response, session, transfer);
906                     } else {
907                         String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.useCurrentDB.label",
908                                 jParams, jParams.getLocale ());
909                         session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
910                         displaySettings (request, response, session);
911                     }
912                 }
913             }
914         }
915
916     } // end processSettings
917

918     /**
919      * Transfering data between two db, they must be different, no check
920      * Implementation that works with timestamp, etc...
921      *
922      * @param fromDB
923      * @param toDB
924      * @author NK
925      */

926     private void transfertDatabaseData(DatabaseConnection fromDB,
927                                        DatabaseConnection toDB){
928         try {
929             ResultSet JavaDoc tablesResultSet = fromDB.getConnection()
930                                       .getMetaData().getTables (null, null, null,
931                                       new String JavaDoc[]{"TABLE"});
932
933             StringBuffer JavaDoc sqlInsertCurrentValues = new StringBuffer JavaDoc ();
934             Vector JavaDoc tablesResultSetVector = new Vector JavaDoc ();
935
936             while (tablesResultSet.next ()) {
937                 tablesResultSetVector.add (tablesResultSet.getString ("TABLE_NAME").toLowerCase ());
938             }
939             tablesResultSet.close ();
940
941             Enumeration JavaDoc tablesResultSetEnum = tablesResultSetVector.elements ();
942             PreparedStatement JavaDoc pstmt = null;
943             while (tablesResultSetEnum.hasMoreElements ()) {
944                 String JavaDoc table_name = (String JavaDoc)tablesResultSetEnum.nextElement ();
945                 ResultSet JavaDoc columnsResultSet = null;
946                 try {
947                     if (table_name.toLowerCase().startsWith("jahia_")) {
948                         StringBuffer JavaDoc sqlColumnsList = new StringBuffer JavaDoc ();
949                         columnsResultSet = fromDB.getStatement()
950                                 .executeQuery ("SELECT * FROM " + table_name);
951                         ResultSetMetaData JavaDoc columnsMetaData = columnsResultSet.getMetaData ();
952                         int columnCount = columnsMetaData.getColumnCount ();
953
954                         // prepared insert statement
955
StringBuffer JavaDoc valuesBuff = new StringBuffer JavaDoc(" VALUES (");
956                         StringBuffer JavaDoc buff = new StringBuffer JavaDoc("INSERT INTO ");
957                         buff.append(table_name);
958                         buff.append(" (");
959                         for (int column = 1; column <= columnCount; column++) {
960                             if (column > 1) {
961                                buff.append(", ");
962                                valuesBuff.append(", ");
963                             }
964                             buff.append (columnsMetaData.getColumnLabel(column).toLowerCase ());
965                             valuesBuff.append("?");
966                         }
967                         buff.append(" )");
968                         valuesBuff.append(" )");
969                         String JavaDoc sqlInsertStatement = buff.toString() + valuesBuff.toString();
970                         //logger.debug("SQL Insert Statement : " + sqlInsertStatement + "\n");
971
//StringBuffer sqlDebug = new StringBuffer("TABLE[" + table_name + "],VALUES[");
972
while (columnsResultSet.next ()) {
973                             try {
974                                 pstmt = toDB.getConnection().prepareStatement(sqlInsertStatement);
975                                 for (int column = 1; column <= columnCount; column++) {
976                                     String JavaDoc column_name = columnsMetaData.getColumnLabel(column).toLowerCase();
977                                     Object JavaDoc column_value = columnsResultSet.getObject(column);
978                                     /*
979                                     if (column > 1) {
980                                         if ( column_value != null ){
981                                             sqlDebug.append(column_value.toString());
982                                         } else {
983                                             sqlDebug.append("null value");
984                                         }
985                                     }*/

986                                     pstmt.setObject(column,column_value);
987                                 }
988                                 //logger.debug("SQL =" + sqlDebug);
989
pstmt.executeUpdate();
990                             } catch ( Throwable JavaDoc t ){
991                                 logger.debug(t);
992                             } finally {
993                                 if ( pstmt != null ){
994                                     try {
995                                         pstmt.close();
996                                     } catch ( Throwable JavaDoc t ){
997                                         logger.debug(t);
998                                     }
999                                 }
1000                            }
1001                        }
1002                    }
1003                } catch (IndexOutOfBoundsException JavaDoc ioobe) {
1004                    logger.debug(ioobe);
1005                } catch (SQLException JavaDoc sqle) {
1006                    logger.debug(sqle);
1007                } finally {
1008                    if ( columnsResultSet != null ){
1009                        try {
1010                            columnsResultSet.close();
1011                        } catch ( Throwable JavaDoc t ){
1012                            logger.debug(t);
1013                        }
1014                    }
1015                }
1016            }
1017        } catch (Exception JavaDoc e) {
1018            logger.debug(e);
1019        }
1020    }
1021
1022    /**
1023     * Store new settings for the server page and redirect to the final page.
1024     *
1025     * @param request Servlet request.
1026     * @param response Servlet response.
1027     * @param session Servlet session for the current user.
1028     * @param transfer <code>true</code> if the user has requested a transfer.
1029     * <code>false</code> if the user want just to change
1030     * in the database settings.
1031     */

1032    private void storeSettings (HttpServletRequest JavaDoc request,
1033                                HttpServletResponse JavaDoc response,
1034                                HttpSession JavaDoc session,
1035                                boolean transfer)
1036            throws IOException JavaDoc, ServletException JavaDoc {
1037
1038        // set new values in the properties manager...
1039
properties.setProperty ("db_script", (String JavaDoc)session.getAttribute (CLASS_NAME + "jahiaDBScript"));
1040        properties.setProperty ("db_driver", (String JavaDoc)session.getAttribute (CLASS_NAME + "jahiaDBDriver"));
1041        properties.setProperty ("db_url", (String JavaDoc)session.getAttribute (CLASS_NAME + "jahiaDBUrl"));
1042        properties.setProperty ("db_username", (String JavaDoc)session.getAttribute (CLASS_NAME + "jahiaDBUsername"));
1043        properties.setProperty ("db_password", (String JavaDoc)session.getAttribute (CLASS_NAME + "jahiaDBPassword"));
1044        if (!transfer) {
1045            properties.setProperty ("db_min_connections", (String JavaDoc)session.getAttribute (CLASS_NAME + "jahiaDBMinConnections"));
1046            properties.setProperty ("db_max_connections", (String JavaDoc)session.getAttribute (CLASS_NAME + "jahiaDBMaxConnections"));
1047            properties.setProperty ("db_waitIfBusy", (String JavaDoc)session.getAttribute (CLASS_NAME + "jahiaDBWaitIfBusy"));
1048            properties.setProperty ("db_verbose", (String JavaDoc)session.getAttribute (CLASS_NAME + "jahiaDBVerbose"));
1049        }
1050
1051        // write in the jahia properties file...
1052
properties.storeProperties ();
1053
1054        JahiaData jData = (JahiaData)request.getAttribute ("org.jahia.data.JahiaData");
1055        ParamBean jParams = null;
1056        if (jData != null) {
1057            jParams = jData.params ();
1058        }
1059        String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.processMessage.restartJahiaAfterDBChange.label",
1060                jParams, jParams.getLocale ());
1061        request.setAttribute ("processMessage", dspMsg);
1062        session.setAttribute (CLASS_NAME + "jahiaDisplayMessage",
1063            JahiaResourceBundle.getAdminResource("org.jahia.admin.copyright",
1064                jParams, jParams.getLocale()));
1065        JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "finish.jsp");
1066    } // end storeSettings
1067

1068
1069    /**
1070     * Grab all the content of a database and create a real SQL dump string.
1071     * This method automatically open and close the database connection.
1072     *
1073     * @param driver The database driver.
1074     * @param url The database url.
1075     * @param username The database username.
1076     * @param password The database password.
1077     * @return Returns a big string containing a SQL dump.
1078     */

1079    private String JavaDoc grabDatabaseData (String JavaDoc driver,
1080                                     String JavaDoc url,
1081                                     String JavaDoc username,
1082                                     String JavaDoc password) {
1083        String JavaDoc sqlOutput = "";
1084
1085        try {
1086            dbConnect.databaseOpen (driver, url, username, password);
1087
1088            ResultSet JavaDoc tablesResultSet = dbConnect.getConnection ().getMetaData ().getTables (null, null, null, new String JavaDoc[]{"TABLE"});
1089            StringBuffer JavaDoc sqlInsertCurrentValues = new StringBuffer JavaDoc ();
1090            Vector JavaDoc tablesResultSetVector = new Vector JavaDoc ();
1091
1092            while (tablesResultSet.next ()) {
1093                tablesResultSetVector.add (tablesResultSet.getString ("TABLE_NAME").toLowerCase ());
1094            }
1095            tablesResultSet.close ();
1096
1097            Enumeration JavaDoc tablesResultSetEnum = tablesResultSetVector.elements ();
1098
1099            String JavaDoc pattern = "\\" + "n";
1100
1101            while (tablesResultSetEnum.hasMoreElements ()) {
1102                String JavaDoc table_name = (String JavaDoc)tablesResultSetEnum.nextElement ();
1103                try {
1104                    if (table_name.substring (0, 6).equals ("jahia_")) {
1105                        StringBuffer JavaDoc sqlColumnsList = new StringBuffer JavaDoc ();
1106                        ResultSet JavaDoc columnsResultSet = dbConnect.getStatement ().executeQuery ("SELECT * FROM " + table_name);
1107                        ResultSetMetaData JavaDoc columnsMetaData = columnsResultSet.getMetaData ();
1108                        int columnCount = columnsMetaData.getColumnCount ();
1109
1110                        for (int column = 1; column <= columnCount; column++) {
1111                            if (column > 1) {
1112                                sqlColumnsList.append (", ");
1113                            }
1114                            sqlColumnsList.append (columnsMetaData.getColumnLabel (column).toLowerCase ());
1115                        }
1116
1117                        while (columnsResultSet.next ()) {
1118                            StringBuffer JavaDoc sqlValuesList = new StringBuffer JavaDoc ();
1119                            for (int column = 1; column <= columnCount; column++) {
1120                                String JavaDoc column_name = columnsResultSet.getString (column);
1121                                int column_type = columnsMetaData.getColumnType (column);
1122                                boolean isText = false;
1123                                if (column > 1) {
1124                                    sqlValuesList.append (", ");
1125                                }
1126                                if (column_name != null) {
1127                                    if ((column_type == Types.VARCHAR) || (column_type == Types.CHAR) || (column_type == Types.BLOB) || (column_type == Types.LONGVARCHAR)) {
1128                                        isText = true;
1129                                    } else if (column_type == Types.OTHER) {
1130                                        try {
1131                                            int testConversion = Integer.parseInt (column_name);
1132                                        } catch (NumberFormatException JavaDoc nfe) {
1133                                            isText = true;
1134                                        }
1135                                    }
1136                                }
1137
1138                                if (isText) {
1139                                    sqlValuesList.append ("'");
1140                                }
1141                                sqlValuesList.append (column_name);
1142                                if (isText) {
1143                                    sqlValuesList.append ("'");
1144                                }
1145                            }
1146
1147                            String JavaDoc parsedString = JahiaTools.replacePattern (sqlValuesList.toString (), "\n", pattern);
1148                            parsedString = JahiaTools.replacePattern (parsedString, "\r", "");
1149
1150                            sqlInsertCurrentValues.append ("INSERT INTO " + table_name + "(" + sqlColumnsList.toString ().toLowerCase () + ") VALUES(" + parsedString + ")\n");
1151                        }
1152                        columnsResultSet.close ();
1153                    }
1154                } catch (IndexOutOfBoundsException JavaDoc ioobe) {
1155                } catch (SQLException JavaDoc sqle) {
1156                }
1157            }
1158            dbConnect.databaseClose ();
1159
1160            sqlOutput = sqlInsertCurrentValues.toString ();
1161
1162        } catch (Exception JavaDoc e) {
1163        }
1164
1165        return sqlOutput;
1166    } // end grabDatabaseData
1167

1168
1169    /**
1170     * Insert data into a database via the previously grabbed SQL dump.
1171     *
1172     * @param allGrabbedData The SQL dump (get it with grabDatabaseData method).
1173     * @param driver The database driver.
1174     * @param url The database url.
1175     * @param username The database username.
1176     * @param password The database password.
1177     */

1178    private void insertDatabaseData (Enumeration JavaDoc allGrabbedData,
1179                                     String JavaDoc driver,
1180                                     String JavaDoc url,
1181                                     String JavaDoc username,
1182                                     String JavaDoc password) {
1183        String JavaDoc lastTableName = "";
1184
1185        // try to execute the SQL query...
1186
try {
1187            dbConnect.databaseOpen (driver, url, username, password);
1188
1189            while (allGrabbedData.hasMoreElements ()) {
1190                try {
1191                    String JavaDoc runtimeSQL = (String JavaDoc)allGrabbedData.nextElement ();
1192                    String JavaDoc runtimeTableName = runtimeSQL.substring (runtimeSQL.indexOf ("jahia_"), runtimeSQL.indexOf ("(")).trim ();
1193                    try {
1194                        if (!runtimeTableName.equals (lastTableName)) {
1195                            Statement JavaDoc stmt = dbConnect.getStatement ();
1196                            stmt.executeUpdate ("DELETE FROM " + runtimeTableName);
1197                        }
1198                    } catch (SQLException JavaDoc sqle) {
1199                    }
1200                    try {
1201                        Statement JavaDoc stmt = dbConnect.getStatement ();
1202                        stmt.executeUpdate (JahiaTools.replacePattern (runtimeSQL, "\\n", "\n"));
1203                    } catch (SQLException JavaDoc sqle) {
1204                    }
1205                    lastTableName = runtimeTableName;
1206                } catch (IndexOutOfBoundsException JavaDoc ioobe) {
1207                }
1208            }
1209
1210            dbConnect.databaseClose ();
1211        } catch (NullPointerException JavaDoc npe) {
1212            logger.error ("Error:", npe);
1213        } catch (ClassNotFoundException JavaDoc cnfe) {
1214            logger.error ("Database driver not found :", cnfe);
1215        } catch (SQLException JavaDoc sqle) {
1216            logger.error ("Error while executing query : ", sqle);
1217        }
1218    } // end insertDatabaseData
1219

1220
1221    /**
1222     * Create tables into a database for the previously grabbed SQL dump.
1223     * This option run via the database script.
1224     *
1225     * @param scriptFileName The filename of the database script.
1226     * @param driver The database driver.
1227     * @param url The database url.
1228     * @param username The database username.
1229     * @param password The database password.
1230     */

1231    private void insertDatabaseTables (String JavaDoc scriptFileName,
1232                                       String JavaDoc driver,
1233                                       String JavaDoc url,
1234                                       String JavaDoc username,
1235                                       String JavaDoc password)
1236    {
1237        // try to execute the SQL query...
1238
try {
1239            dbConnect.databaseOpen (driver, url, username, password);
1240
1241            // get script runtime...
1242
File JavaDoc scriptsFileObject = new File JavaDoc (Jahia.jahiaDatabaseScriptsPath + File.separator + scriptFileName);
1243            Enumeration JavaDoc scriptsListRuntime = scriptsManager.getDatabaseScriptsRuntime (scriptsFileObject);
1244
1245            while (scriptsListRuntime.hasMoreElements ()) {
1246                try {
1247                    String JavaDoc runtimeSQL = (String JavaDoc)scriptsListRuntime.nextElement ();
1248                    String JavaDoc runtimeTableName = runtimeSQL.substring (runtimeSQL.indexOf ("jahia_"), runtimeSQL.indexOf ("(")).trim ();
1249                    try {
1250                        dbConnect.getStatement ().execute ("DROP TABLE " + runtimeTableName);
1251                    } catch (SQLException JavaDoc sqle) {
1252                    }
1253                    try {
1254                        dbConnect.getStatement ().execute (runtimeSQL);
1255                    } catch (SQLException JavaDoc sqle) {
1256                    }
1257                } catch (IndexOutOfBoundsException JavaDoc ioobe) {
1258                }
1259            }
1260
1261            dbConnect.databaseClose ();
1262        } catch (NullPointerException JavaDoc npe) {
1263            logger.error ("Null pointer exception:", npe);
1264        } catch (IOException JavaDoc ioe) {
1265            logger.error ("IOException:", ioe);
1266        } catch (ClassNotFoundException JavaDoc cnfe) {
1267            logger.error ("Error while using database driver :", cnfe);
1268        } catch (SQLException JavaDoc sqle) {
1269            logger.error ("SQL Exception :", sqle);
1270        }
1271    } // end insertDatabaseTables
1272

1273
1274    /**
1275     * This method check if the database url setted in the formular by
1276     * the user is the same or not as the current database. If it's the same
1277     * return an error (i don't want to transfer a database on herself :o)
1278     *
1279     * @param db_url the database url to check.
1280     * @return <code>true</code> if the user has indicate the same database,
1281     * <code>false</code> if the user has indicate one another database.
1282     */

1283    private boolean checkSameDatabase (String JavaDoc db_url)
1284            throws IOException JavaDoc, ServletException JavaDoc {
1285        boolean theSameDatabase = false;
1286        if (db_url.equals (properties.getProperty ("db_url"))) {
1287            theSameDatabase = true;
1288        }
1289        return theSameDatabase;
1290    }
1291
1292
1293}
1294
Popular Tags