KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > admin > sites > ExtractDeploySite


1 // $Id: ExtractDeploySite.java 16439 2007-02-14 16:46:05Z 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
// ExtractDeploySite
15
//
16
// 23.07.2001 NK added in jahia.
17
//
18

19 package org.jahia.admin.sites;
20
21 import java.io.File JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.sql.Connection JavaDoc;
24 import java.sql.SQLException JavaDoc;
25 import java.sql.Statement JavaDoc;
26 import java.util.Enumeration JavaDoc;
27 import java.util.Hashtable JavaDoc;
28 import java.util.Vector JavaDoc;
29
30 import javax.servlet.ServletException JavaDoc;
31 import javax.servlet.http.HttpServletRequest JavaDoc;
32 import javax.servlet.http.HttpServletResponse JavaDoc;
33 import javax.servlet.http.HttpSession JavaDoc;
34
35 import org.jahia.admin.database.DatabaseScripts;
36 import org.jahia.bin.Jahia;
37 import org.jahia.bin.JahiaAdministration;
38 import org.jahia.data.JahiaDOMObject;
39 import org.jahia.data.JahiaData;
40 import org.jahia.data.applications.ApplicationBean;
41 import org.jahia.data.constants.JahiaConstants;
42 import org.jahia.exceptions.JahiaException;
43 import org.jahia.params.ParamBean;
44 import org.jahia.registries.ServicesRegistry;
45 import org.jahia.resourcebundle.JahiaResourceBundle;
46 import org.jahia.services.acl.JahiaACLManagerService;
47 import org.jahia.services.applications.JahiaApplicationsManagerService;
48 import org.jahia.services.audit.JahiaAuditLogManagerService;
49 import org.jahia.services.containers.JahiaContainersService;
50 import org.jahia.services.database.JahiaIncrementorsDBService;
51 import org.jahia.services.fields.JahiaFieldService;
52 import org.jahia.services.filemanager.JahiaFilemanagerService;
53 import org.jahia.services.files.JahiaTextFileService;
54 import org.jahia.services.homepages.JahiaHomepagesService;
55 import org.jahia.services.pages.JahiaPageService;
56 import org.jahia.services.pages.JahiaPageTemplateService;
57 import org.jahia.services.search.JahiaSearchService;
58 import org.jahia.services.shares.AppsShareService;
59 import org.jahia.services.sites.JahiaSite;
60 import org.jahia.services.sites.JahiaSitesService;
61 import org.jahia.services.templates_deployer.JahiaTemplatesDeployerService;
62 import org.jahia.services.usermanager.JahiaGroupManagerService;
63 import org.jahia.services.usermanager.JahiaSiteGroupManagerService;
64 import org.jahia.services.usermanager.JahiaSiteUserManagerService;
65 import org.jahia.services.usermanager.JahiaUser;
66 import org.jahia.services.usermanager.JahiaUserManagerService;
67 import org.jahia.services.usermanager.UserManagerProviderBean;
68 import org.jahia.utils.DBRowDataFilter;
69 import org.jahia.utils.JahiaChrono;
70 import org.jahia.utils.JahiaTools;
71 import org.jahia.utils.properties.PropertiesManager;
72 import org.jahia.utils.xml.DOM2DB;
73 import org.jahia.utils.xml.XMLParser;
74 import org.w3c.dom.Element JavaDoc;
75 import org.jahia.utils.PathResolver;
76
77
78 /**
79  * This class is used by the administration to manage site extraction and
80  * redeployment.
81  *
82  * Copyright: Copyright (c) 2002
83  * Company: Jahia Ltd
84  *
85  * @author Khue Nguyen
86  * @version 1.0
87  */

88 public class ExtractDeploySite {
89     private static org.apache.log4j.Logger logger =
90             org.apache.log4j.Logger.getLogger (ExtractDeploySite.class);
91
92
93     private static final String JavaDoc CLASS_NAME = "ExtractDeploySite";
94     private static final String JavaDoc JSP_PATH = JahiaAdministration.JSP_PATH;
95
96     private static final String JavaDoc mXMLDOC = "xmldocs";
97     private static final String JavaDoc mAPPS = "apps";
98     private static final String JavaDoc mDATA = "data";
99     private static final String JavaDoc mCONTENT = "content";
100     private static final String JavaDoc mCONTENT_BIGTEXT = "bigtext";
101     private static final String JavaDoc mCONTENT_FILEMANAGER = "filemanager";
102     private static final String JavaDoc mTEMPLATES = "templates";
103     private static final String JavaDoc mXMLPORTLETS = "xmlportlets";
104
105     private static final String JavaDoc mEXTROOTFOLDER = "site_extraction";
106     private static final String JavaDoc mFILEMANAGER = "filemanager";
107     private static final String JavaDoc mNEW_WEBAPPS = "new_webapps";
108     private static final String JavaDoc mNEW_TEMPLATES = "new_templates";
109     private static final String JavaDoc mTOMCATWEBAPPS = "webapps";
110     private static final String JavaDoc mSEARCHINDEX = "search_indexes";
111
112     /**
113      * the server type
114      */

115     private static String JavaDoc mServerType = "";
116
117     /**
118      * Extraction root folder full path
119      */

120     private static String JavaDoc mERFFullPath = "";
121
122     /**
123      * Filemanager root folder full path
124      */

125     private static String JavaDoc mFilemanagerFullPath = "";
126
127
128     private static PropertiesManager properties;
129     private static PathResolver pathResolver;
130
131     private static ServicesRegistry sReg;
132     private static JahiaSitesService siteServ;
133
134     private static byte[] mLock = new byte[1];
135
136     private ACLDataFilter aclFilter;
137
138
139     /**
140      * the extraction folder
141      */

142     private String JavaDoc mSiteExtractionFolder = "";
143
144
145     /**
146      * Default constructor.
147      *
148      * @param request Servlet request.
149      * @param response Servlet response.
150      * @param session Servlet session for the current user.
151      * @param context Servlet context.
152      */

153     public ExtractDeploySite (HttpServletRequest JavaDoc request,
154                               HttpServletResponse JavaDoc response,
155                               HttpSession JavaDoc session,
156                               PathResolver pathResolver)
157             throws Throwable JavaDoc {
158         ExtractDeploySite.pathResolver = pathResolver;
159
160         sReg = ServicesRegistry.getInstance ();
161
162         // load Jahia settings
163
if (properties == null) {
164             properties = new PropertiesManager (Jahia.getJahiaPropertiesFileName ());
165             if (properties == null) {
166                 throw new JahiaException ("Error occured while processing your request",
167                         CLASS_NAME + ": Cannot load jahia properties file",
168                         JahiaException.CONFIG_ERROR,
169                         JahiaException.ERROR_SEVERITY);
170             }
171
172             // set the server type
173
if (properties.getProperty ("server") == null) {
174                 throw new JahiaException ("Error occured while processing your request",
175                         CLASS_NAME + ": Cannot retrieve the Type of running Server ",
176                         JahiaException.CONFIG_ERROR,
177                         JahiaException.ERROR_SEVERITY);
178             }
179
180             mServerType = properties.getProperty ("server").trim ();
181             if (mServerType.equals ("")) {
182                 throw new JahiaException ("Error occured while processing your request",
183                         CLASS_NAME + ": Cannot retrieve the Type of running Server ",
184                         JahiaException.CONFIG_ERROR,
185                         JahiaException.ERROR_SEVERITY);
186             }
187
188             // check extraction root folder
189
StringBuffer JavaDoc buff = new StringBuffer JavaDoc (
190                     properties.getProperty ("jahiaVarDiskPath").trim ());
191             buff.append (File.separator);
192             buff.append (mEXTROOTFOLDER);
193
194             mERFFullPath = JahiaTools.convertContexted (buff.toString (), pathResolver);
195
196             // set filemanager directory
197
buff = null;
198             buff = new StringBuffer JavaDoc (
199                     properties.getProperty ("jahiaVarDiskPath").trim ());
200             buff.append (File.separator);
201             buff.append (mFILEMANAGER);
202             //mFilemanagerFullPath = JahiaTools.convertContexted(buff.toString(),context);
203

204             mFilemanagerFullPath = ServicesRegistry.getInstance ()
205                     .getJahiaFilemanagerService ().getFileRepositoryRootPath ();
206
207
208             File JavaDoc f = new File JavaDoc (mERFFullPath);
209             if (!f.isDirectory ()) {
210                 // try to create it
211
f.mkdirs ();
212                 if (!f.isDirectory () || !f.canWrite ()) {
213                     throw new JahiaException ("Error occured while processing your request",
214                             CLASS_NAME + ": Cannot create extraction root folder",
215                             JahiaException.FILE_ERROR,
216                             JahiaException.ERROR_SEVERITY);
217                 }
218             }
219         }
220
221         if (sReg != null) {
222             siteServ = sReg.getJahiaSitesService ();
223         }
224
225         userRequestDispatcher (request, response, session);
226     }
227
228
229     /**
230      * This method is used like a dispatcher for user requests.
231      *
232      * @param request Servlet request.
233      * @param response Servlet response.
234      * @param session Servlet session for the current user.
235      */

236     private void userRequestDispatcher (HttpServletRequest JavaDoc request,
237                                         HttpServletResponse JavaDoc response,
238                                         HttpSession JavaDoc session)
239             throws IOException JavaDoc, ServletException JavaDoc {
240
241         JahiaData jData = (JahiaData)request.getAttribute ("org.jahia.data.JahiaData");
242         ParamBean jParams = null;
243         if (jData != null) {
244             jParams = jData.params ();
245         }
246
247         try {
248
249             // clean session
250
session.setAttribute (CLASS_NAME + "warningMsg", null);
251
252             String JavaDoc operation = request.getParameter ("sub");
253
254             if (operation.equals ("display")) {
255                 displayChoice (request, response, session);
256             } else if (operation.equals ("opchoice")) {
257                 processChoice (request, response, session);
258             } else if (operation.equals ("displayExtract")) {
259                 displayExtract (request, response, session);
260             } else if (operation.equals ("extract")) {
261                 processExtract (request, response, session);
262             } else if (operation.equals ("detail")) {
263                 displayDetail (request, response, session);
264             } else if (operation.equals ("extractlist")) {
265                 displayManageExtractions (request, response, session);
266             } else if (operation.equals ("flush")) {
267                 processFlush (request, response, session);
268             } else if (operation.equals ("displayRestore")) {
269                 displayRestore (request, response, session);
270             } else if (operation.equals ("restore")) {
271                 processRestore (request, response, session);
272             }
273
274         } catch (Throwable JavaDoc t) {
275
276             t.printStackTrace ();
277             String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
278                     jParams, jParams.getLocale ());
279             request.setAttribute ("jahiaDisplayMessage", dspMsg);
280             displayChoice (request, response, session);
281
282         }
283
284     }
285
286
287     /**
288      * Display the page where the user can choose what he want to do. He can
289      * choice to extract of deploy site.
290      *
291      * @param request Servlet request.
292      * @param response Servlet response.
293      * @param session Servlet session for the current user.
294      */

295     private void displayChoice (HttpServletRequest JavaDoc request,
296                                 HttpServletResponse JavaDoc response,
297                                 HttpSession JavaDoc session)
298             throws IOException JavaDoc, ServletException JavaDoc {
299
300         String JavaDoc warningMsg = (String JavaDoc)session.getAttribute (CLASS_NAME + "warningMsg");
301         if (warningMsg == null) {
302             warningMsg = "";
303         }
304
305         request.setAttribute ("warningMsg", warningMsg);
306         JahiaAdministration.doRedirect (request, response, session,
307                 JSP_PATH + "extdep_site.jsp");
308     }
309
310
311     /**
312      * Process the operation choice.
313      *
314      * @param request Servlet request.
315      * @param response Servlet response.
316      * @param session Servlet session for the current user.
317      */

318     private void processChoice (HttpServletRequest JavaDoc request,
319                                 HttpServletResponse JavaDoc response,
320                                 HttpSession JavaDoc session)
321             throws IOException JavaDoc, ServletException JavaDoc {
322         logger.debug ("started");
323
324         // get form values...
325
Integer JavaDoc action = new Integer JavaDoc (request.getParameter ("which_action").trim ());
326
327         // store the action that the user want...
328
session.setAttribute (CLASS_NAME + "jahiaWhichAction", action);
329
330         // determine which action are requested...
331
if (action.intValue () == 1) {
332             // reset session variables
333
session.setAttribute (CLASS_NAME + "selSiteIDs", null);
334             session.setAttribute (CLASS_NAME + "jahiaExtractName", "");
335             session.setAttribute (CLASS_NAME + "jahiaExtractDesc", "");
336
337             displayExtract (request, response, session);
338         } else if (action.intValue () == 2) {
339             // reset session variables
340
session.setAttribute (CLASS_NAME + "selSiteKeys", null);
341             displayManageExtractions (request, response, session);
342         }
343     }
344
345
346
347     //--------------------------------------------------------------------------
348
//
349
// EXTRACT SECTION
350
//
351
//--------------------------------------------------------------------------
352

353
354     /**
355      * Display the list of site the user can choose to extract
356      *
357      * @param request Servlet request.
358      * @param response Servlet response.
359      * @param session Servlet session for the current user.
360      */

361     private void displayExtract (HttpServletRequest JavaDoc request,
362                                  HttpServletResponse JavaDoc response,
363                                  HttpSession JavaDoc session)
364             throws IOException JavaDoc, ServletException JavaDoc {
365
366         logger.debug ("started");
367         JahiaData jData = (JahiaData)request.getAttribute ("org.jahia.data.JahiaData");
368         ParamBean jParams = null;
369         if (jData != null) {
370             jParams = jData.params ();
371         }
372         try {
373
374             Enumeration JavaDoc enumeration = siteServ.getSites ();
375             request.setAttribute ("sitesList", enumeration);
376
377             // retrieve previous form values...
378
Vector JavaDoc selSiteIDs = (Vector JavaDoc)session.getAttribute (CLASS_NAME
379                     + "selSiteIDs");
380             String JavaDoc jahiaExtractName = (String JavaDoc)session.getAttribute (CLASS_NAME
381                     + "jahiaExtractName");
382             String JavaDoc jahiaExtractDesc = (String JavaDoc)session.getAttribute (CLASS_NAME
383                     + "jahiaExtractDesc");
384             String JavaDoc warningMsg = (String JavaDoc)session.getAttribute (CLASS_NAME
385                     + "warningMsg");
386
387
388             // set default values (if necessary)...
389
if (selSiteIDs == null) {
390                 selSiteIDs = new Vector JavaDoc ();
391             }
392             if (jahiaExtractName == null) {
393                 jahiaExtractName = "";
394             }
395             if (jahiaExtractDesc == null) {
396                 jahiaExtractDesc = "";
397             }
398             if (warningMsg == null) {
399                 warningMsg = "";
400             }
401
402             // set request attributes...
403
request.setAttribute ("selSiteIDs", selSiteIDs);
404             request.setAttribute ("jahiaExtractName", jahiaExtractName);
405             request.setAttribute ("jahiaExtractDesc", jahiaExtractDesc);
406             request.setAttribute ("warningMsg", warningMsg);
407
408             JahiaAdministration.doRedirect (request, response, session,
409                     JSP_PATH + "extdep_site_extract.jsp");
410
411         } catch (JahiaException je) {
412             String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
413                     jParams, jParams.getLocale ());
414             request.setAttribute ("jahiaDisplayMessage", dspMsg);
415             JahiaAdministration.doRedirect (request,
416                     response,
417                     session,
418                     JSP_PATH + "menu.jsp");
419         }
420     }
421
422
423     /**
424      * Display the extraction confirmation screen
425      *
426      * @param request Servlet request.
427      * @param response Servlet response.
428      * @param session Servlet session for the current user.
429      */

430     private void displayExtractConfirmation (HttpServletRequest JavaDoc request,
431                                              HttpServletResponse JavaDoc response,
432                                              HttpSession JavaDoc session)
433             throws IOException JavaDoc, ServletException JavaDoc {
434
435         logger.debug ("started");
436         JahiaData jData = (JahiaData)request.getAttribute ("org.jahia.data.JahiaData");
437         ParamBean jParams = null;
438         if (jData != null) {
439             jParams = jData.params ();
440         }
441         try {
442
443             Enumeration JavaDoc enumeration = siteServ.getSites ();
444             request.setAttribute ("sitesList", enumeration);
445
446             // retrieve previous form values...
447
Vector JavaDoc selSiteIDs = (Vector JavaDoc)session.getAttribute (CLASS_NAME
448                     + "selSiteIDs");
449             String JavaDoc jahiaExtractName = (String JavaDoc)session.getAttribute (CLASS_NAME
450                     + "jahiaExtractName");
451             String JavaDoc jahiaExtractDesc = (String JavaDoc)session.getAttribute (CLASS_NAME
452                     + "jahiaExtractDesc");
453             String JavaDoc warningMsg = (String JavaDoc)session.getAttribute (CLASS_NAME
454                     + "warningMsg");
455
456
457             // set default values (if necessary)...
458
if (selSiteIDs == null) {
459                 selSiteIDs = new Vector JavaDoc ();
460             }
461             if (jahiaExtractName == null) {
462                 jahiaExtractName = "";
463             }
464             if (jahiaExtractDesc == null) {
465                 jahiaExtractDesc = "";
466             }
467             if (warningMsg == null) {
468                 warningMsg = "";
469             }
470
471             // set request attributes...
472
request.setAttribute ("selSiteIDs", selSiteIDs);
473             request.setAttribute ("jahiaExtractName", jahiaExtractName);
474             request.setAttribute ("jahiaExtractDesc", jahiaExtractDesc);
475             request.setAttribute ("warningMsg", warningMsg);
476
477             JahiaAdministration.doRedirect (request, response, session,
478                     JSP_PATH + "extdep_site_extractconfirmation.jsp");
479
480         } catch (JahiaException je) {
481             String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
482                     jParams, jParams.getLocale ());
483             request.setAttribute ("jahiaDisplayMessage", dspMsg);
484             JahiaAdministration.doRedirect (request,
485                     response,
486                     session,
487                     JSP_PATH + "extdep_site_extractconfirmation.jsp");
488         }
489     }
490
491     /**
492      * Process and check the validity of extraction options.
493      *
494      * @param request Servlet request.
495      * @param response Servlet response.
496      * @param session Servlet session for the current user.
497      */

498     private void processExtract (HttpServletRequest JavaDoc request,
499                                  HttpServletResponse JavaDoc response,
500                                  HttpSession JavaDoc session)
501             throws IOException JavaDoc, ServletException JavaDoc, JahiaException {
502         logger.debug ("started");
503         JahiaData jData = (JahiaData)request.getAttribute ("org.jahia.data.JahiaData");
504         ParamBean jParams = null;
505         if (jData != null) {
506             jParams = jData.params ();
507         }
508
509         // start the chrono...
510
long startTime = JahiaChrono.getInstance ().start ();
511
512         synchronized (mLock) {
513
514             // Try to get the excluse lock on Jahia
515
JahiaUser user = (JahiaUser)session.getAttribute (ParamBean.SESSION_USER);
516
517             if (user == null || !user.isAdminMember (0)) {
518                 String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.illegalAccessOperation.label",
519                         jParams, jParams.getLocale ());
520                 session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
521                 JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "menu.jsp");
522                 return;
523             }
524
525             byte[] jahiaLock = null;
526             boolean freeLock = true;
527
528             try {
529                 jahiaLock = Jahia.getLock (user, session);
530                 if (jahiaLock == null) {
531                     String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.noLockJahiaExclusively.label",
532                             jParams, jParams.getLocale ());
533                     session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
534                     JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "menu.jsp");
535                     return;
536                 }
537             } catch (JahiaException je) {
538                 session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", je.getMessage ());
539                 JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "menu.jsp");
540                 return;
541             }
542
543             try {
544                 String JavaDoc confirmExtraction = request.getParameter ("confirmExtraction");
545
546                 // the extraction folder
547
File JavaDoc extFolder = null;
548
549                 // error status
550
boolean err = false;
551
552                 // sites to extract
553
String JavaDoc[] siteIDsArr = null;
554                 Vector JavaDoc selSiteIDs = null;
555
556                 String JavaDoc jahiaExtractName = null;
557
558                 String JavaDoc jahiaExtractDesc = null;
559
560                 if (confirmExtraction == null || !confirmExtraction.equals ("yes")) {
561
562                     // sites to extract
563
siteIDsArr = request.getParameterValues ("sitesList");
564                     selSiteIDs = new Vector JavaDoc ();
565
566                     if (siteIDsArr != null) {
567                         for (int i = 0; i < siteIDsArr.length; i++) {
568                             int selSiteID = -1;
569                             try {
570                                 selSiteID = Integer.parseInt (siteIDsArr[i]);
571                             } catch (Throwable JavaDoc t) {
572                                 String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
573                                         jParams, jParams.getLocale ());
574                                 request.setAttribute ("jahiaDisplayMessage", dspMsg);
575                                 JahiaAdministration.doRedirect (request,
576                                         response,
577                                         session,
578                                         JSP_PATH + "menu.jsp");
579                             }
580                             selSiteIDs.add (new Integer JavaDoc (selSiteID));
581                         }
582                     }
583
584
585                     jahiaExtractName = request.getParameter ("jahiaExtractName");
586
587                     jahiaExtractDesc = request.getParameter ("jahiaExtractDesc");
588
589                     if (jahiaExtractDesc == null || jahiaExtractDesc.trim ().equals ("")) {
590                         jahiaExtractDesc = "No description";
591                     }
592
593                     session.setAttribute (CLASS_NAME + "selSiteIDs", selSiteIDs);
594                     session.setAttribute (CLASS_NAME + "jahiaExtractName", jahiaExtractName);
595                     session.setAttribute (CLASS_NAME + "jahiaExtractDesc", jahiaExtractDesc);
596
597                     if (selSiteIDs.size () == 0) {
598                         String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.oneSiteMustSelected.label",
599                                 jParams, jParams.getLocale ());
600                         session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
601                         displayExtract (request, response, session);
602                         return;
603                     }
604
605                     // set default values (if necessary)...
606
if (jahiaExtractName == null) {
607                         jahiaExtractName = "";
608                     }
609                     if (jahiaExtractDesc == null) {
610                         jahiaExtractDesc = "";
611                     }
612
613                     // check user input validity
614
if ((jahiaExtractName == null)
615                             || (jahiaExtractName.trim ().length () == 0)) {
616                         String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.completeRequestInfo.label",
617                                 jParams, jParams.getLocale ());
618                         session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
619                         err = true;
620                     } else if (jahiaExtractName.indexOf (" ") != -1) {
621                         String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.extractNameMustUnique.label",
622                                 jParams, jParams.getLocale ());
623                         session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
624                         err = true;
625                     } else if (!isExtractNameValid (jahiaExtractName)) {
626                         String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.invalidExtractName.label",
627                                 jParams, jParams.getLocale ());
628                         session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
629                         err = true;
630                     } else if (checkExtractionFolder (jahiaExtractName)) {
631                         String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.chooseExtractName.label",
632                                 jParams, jParams.getLocale ());
633                         session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
634                         err = true;
635                     }
636
637
638                     if (!err) {
639                         displayExtractConfirmation (request, response, session);
640                     } else {
641                         displayExtract (request, response, session);
642                     }
643                     return;
644                 }
645
646
647
648                 // Get confirmation so start extraction
649

650                 // retrieve previous form values...
651
selSiteIDs = (Vector JavaDoc)session.getAttribute (CLASS_NAME
652                         + "selSiteIDs");
653                 jahiaExtractName = (String JavaDoc)session.getAttribute (CLASS_NAME
654                         + "jahiaExtractName");
655                 jahiaExtractDesc = (String JavaDoc)session.getAttribute (CLASS_NAME
656                         + "jahiaExtractDesc");
657
658                 if (selSiteIDs == null ||
659                         jahiaExtractName == null ||
660                         jahiaExtractDesc == null) {
661
662                     String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
663                             jParams, jParams.getLocale ());
664                     request.setAttribute ("jahiaDisplayMessage", dspMsg);
665                     throw new JahiaException ("Error occured while processing your request",
666                             CLASS_NAME + ": Invalid data in session",
667                             JahiaException.FILE_ERROR,
668                             JahiaException.ERROR_SEVERITY);
669                 }
670
671                 // create the extraction folder
672
extFolder = createExtractionFolder (jahiaExtractName);
673                 if (!extFolder.isDirectory ()) {
674                     String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
675                             jParams, jParams.getLocale ());
676                     dspMsg += "\n" + JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.noCreateExtractFolder.label",
677                             jParams, jParams.getLocale ());
678                     request.setAttribute ("jahiaDisplayMessage", dspMsg);
679                     throw new JahiaException ("Error occured while processing your request",
680                             CLASS_NAME + ": Cannot create extraction folder",
681                             JahiaException.FILE_ERROR,
682                             JahiaException.ERROR_SEVERITY);
683                 }
684
685                 mSiteExtractionFolder = extFolder.getAbsolutePath ();
686
687                 // set request attributes...
688
if (err) {
689                     displayExtract (request, response, session);
690                 } else {
691
692                     // change session time out to 1 hour ( the extraction can be very long !)
693
int timeOut = session.getMaxInactiveInterval ();
694
695                     try {
696
697                         session.setMaxInactiveInterval (7200);
698
699                         try {
700                             jahiaLock = Jahia.getLock (user, session);
701                             if (jahiaLock == null) {
702                                 String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.noLockJahiaExclusively.label",
703                                         jParams, jParams.getLocale ());
704                                 session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
705                                 JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "menu.jsp");
706                                 return;
707                             }
708                         } catch (JahiaException je) {
709                             session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", je.getMessage ());
710                             JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "menu.jsp");
711                             return;
712                         }
713
714                         // start extraction here
715
logger.debug ("start extract " + selSiteIDs.size () + " sites");
716
717                         // EXTRACT SERVER INFO
718
extractServerInfo ();
719
720                         Vector JavaDoc sites = new Vector JavaDoc ();
721
722                         int size = selSiteIDs.size ();
723                         Integer JavaDoc I = null;
724                         for (int i = 0; i < size; i++) {
725                             I = (Integer JavaDoc)selSiteIDs.get (i);
726                             JahiaSite site = siteServ.getSite (I.intValue ());
727                             if (site != null) {
728                                 extractSite (site);
729                                 sites.add (site);
730                             } else {
731                                 throw new JahiaException ("Error occured while processing your request",
732                                         CLASS_NAME + ": Site to extract is null",
733                                         JahiaException.ERROR_SEVERITY,
734                                         JahiaException.ERROR_SEVERITY);
735                             }
736                         }
737
738
739                         //------------------------------------------------------------------
740
// CREATE THE DESCRIPTION FILE
741
if (!createDescrFile (jahiaExtractName,
742                                 jahiaExtractDesc,
743                                 sites)) {
744                             throw new JahiaException ("Error occured while processing your request",
745                                     CLASS_NAME + ": Error creating the description file",
746                                     JahiaException.ERROR_SEVERITY,
747                                     JahiaException.ERROR_SEVERITY);
748                         }
749
750                         logger.debug ("Extraction Done successfully\n");
751
752                         String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.siteExtDepMsg.extractionDone.label",
753                                 jParams, jParams.getLocale ());
754                         request.setAttribute ("siteExtDepMsg", dspMsg);
755                         request.setAttribute ("siteExtPath", composeExtractionFolder (jahiaExtractName));
756                         JahiaAdministration.doRedirect (request,
757                                 response,
758                                 session,
759                                 JSP_PATH + "extdep_site_extract_done.jsp");
760
761                     } catch (Throwable JavaDoc t) {
762
763                         // clean extraction
764
File JavaDoc f = new File JavaDoc (mSiteExtractionFolder);
765                         if (f.isDirectory ()) {
766                             File JavaDoc dest = new File JavaDoc (mSiteExtractionFolder + "_error");
767                             f.renameTo (dest);
768                             JahiaTools.deleteFile (dest);
769                         }
770
771
772                         logger.error ("exception occured, try clean extraction folder " + f.getAbsolutePath () + "\n");
773                         t.printStackTrace ();
774
775                         String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.warningMsg.processingRequestError.label",
776                                 jParams, jParams.getLocale ());
777                         session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
778
779                         displayChoice (request, response, session);
780                     } finally {
781                         // restore time out
782
session.setMaxInactiveInterval (timeOut);
783                     }
784                 }
785             } catch (Throwable JavaDoc t) {
786                 t.printStackTrace ();
787             } finally {
788                 Jahia.releaseLock (jahiaLock);
789             }
790         }
791
792         logger.debug ("extraction time [" +
793                 JahiaChrono.getInstance ().read (startTime) + "ms]");
794
795     }
796
797
798     /**
799      * Extract a site.
800      *
801      * @param site the site to extract
802      */

803     private void extractSite (JahiaSite site)
804             throws IOException JavaDoc, ServletException JavaDoc, JahiaException {
805         logger.debug ("start extract site " + site.getServerName ());
806
807         // start the chrono...
808
long startTime = JahiaChrono.getInstance ().start ();
809
810         try {
811
812             JahiaDOMObject dom = null;
813
814             // create an extraction folder for this site
815
String JavaDoc siteKey = site.getSiteKey ();
816
817             // get services
818
JahiaPageService pageServ = sReg.getJahiaPageService ();
819             JahiaPageTemplateService pageDefServ = sReg.getJahiaPageTemplateService ();
820             JahiaFieldService fieldServ = sReg.getJahiaFieldService ();
821             JahiaContainersService ctnServ = sReg.getJahiaContainersService ();
822             JahiaFilemanagerService fmngServ = sReg.getJahiaFilemanagerService ();
823             JahiaUserManagerService userServ = sReg.getJahiaUserManagerService ();
824             JahiaGroupManagerService grpServ = sReg.getJahiaGroupManagerService ();
825             JahiaSiteUserManagerService siteUsrServ = sReg.getJahiaSiteUserManagerService ();
826             JahiaSiteGroupManagerService siteGrpServ = sReg.getJahiaSiteGroupManagerService ();
827             JahiaApplicationsManagerService appServ = sReg.getJahiaApplicationsManagerService ();
828             AppsShareService appShareServ = sReg.getAppsShareService ();
829             JahiaAuditLogManagerService logServ = sReg.getJahiaAuditLogManagerService ();
830             JahiaACLManagerService aclServ = sReg.getJahiaACLManagerService ();
831             JahiaHomepagesService homepageServ = sReg.getJahiaHomepagesService ();
832
833             // Create the xml_document folder
834
File JavaDoc xmlDocFolder = createSubExtractionFolder (siteKey + File.separator + mXMLDOC);
835
836             // EXTRACT SITE DEFINITION
837
dom = siteServ.getSiteAsDOM (site.getID ());
838             if (dom != null) {
839                 saveDOMDocument (dom, xmlDocFolder,
840                         ExtDepSiteConstants.SITE_FILE);
841             }
842
843             // EXTRACT SITE PROPS
844
dom = siteServ.getSitePropsAsDOM (site.getID ());
845             if (dom != null) {
846                 saveDOMDocument (dom, xmlDocFolder,
847                         ExtDepSiteConstants.SITEPROPS_FILE);
848             }
849
850             // EXTRACT PAGE DATA
851
dom = null;
852             dom = pageServ.getPagesAsDOM (site.getID ());
853             if (dom != null) {
854                 saveDOMDocument (dom, xmlDocFolder,
855                         ExtDepSiteConstants.PAGES_FILE);
856             }
857
858             // EXTRACT PAGE DEF
859
dom = null;
860             dom = pageDefServ.getPageDefsAsDOM (site.getID ());
861             if (dom != null) {
862                 saveDOMDocument (dom, xmlDocFolder,
863                         ExtDepSiteConstants.PAGEDEFS_FILE);
864             }
865
866             // EXTRACT PAGE DEF PROPERTIES
867
dom = null;
868             dom = pageDefServ.getPageDefPropsAsDOM (site.getID ());
869             if (dom != null) {
870                 saveDOMDocument (dom, xmlDocFolder,
871                         ExtDepSiteConstants.PAGEDEFPROPS_FILE);
872             }
873
874             startTime = JahiaChrono.getInstance ().start ();
875
876             // EXTRACT FIELD DATA
877
dom = null;
878             dom = fieldServ.getFieldsAsDOM (site.getID ());
879             if (dom != null) {
880                 saveDOMDocument (dom, xmlDocFolder,
881                         ExtDepSiteConstants.FIELDS_FILE);
882             }
883             dom = null;
884             //System.gc();
885

886             logger.debug ("Field data extraction time [" +
887                     JahiaChrono.getInstance ().read (startTime) + "ms]");
888
889             // EXTRACT FIELDS DEF
890
dom = fieldServ.getFieldDefsAsDOM (site.getID ());
891             if (dom != null) {
892                 saveDOMDocument (dom, xmlDocFolder,
893                         ExtDepSiteConstants.FIELDDEFS_FILE);
894             }
895
896             // EXTRACT FIELDS DEF PROP
897
dom = null;
898             dom = fieldServ.getFieldDefPropsAsDOM (site.getID ());
899             if (dom != null) {
900                 saveDOMDocument (dom, xmlDocFolder,
901                         ExtDepSiteConstants.FIELDDEFPROPS_FILE);
902             }
903
904             // EXTRACT CONTAINERS
905
dom = null;
906             dom = ctnServ.getContainersAsDOM (site.getID ());
907             if (dom != null) {
908                 saveDOMDocument (dom, xmlDocFolder,
909                         ExtDepSiteConstants.CONTAINERS_FILE);
910             }
911
912             // EXTRACT CONTAINER LISTS
913
dom = null;
914             dom = ctnServ.getContainerListsAsDOM (site.getID ());
915             if (dom != null) {
916                 saveDOMDocument (dom, xmlDocFolder,
917                         ExtDepSiteConstants.CONTAINERLISTS_FILE);
918             }
919
920             // EXTRACT CONTAINER LIST PROPS
921
dom = null;
922             dom = ctnServ.getContainerListPropsAsDOM (site.getID ());
923             if (dom != null) {
924                 saveDOMDocument (dom, xmlDocFolder,
925                         ExtDepSiteConstants.CONTAINERLISTPROPS_FILE);
926             }
927
928             // EXTRACT CONTAINER DEFS
929
dom = null;
930             dom = ctnServ.getContainerDefsAsDOM (site.getID ());
931             if (dom != null) {
932                 saveDOMDocument (dom, xmlDocFolder,
933                         ExtDepSiteConstants.CONTAINERDEFS_FILE);
934             }
935
936             // EXTRACT CONTAINER DEF PROPS
937
dom = null;
938             dom = ctnServ.getContainerDefPropsAsDOM (site.getID ());
939             if (dom != null) {
940                 saveDOMDocument (dom, xmlDocFolder,
941                         ExtDepSiteConstants.CONTAINERDEFPROPS_FILE);
942             }
943
944             // EXTRACT CONTAINER EXTENDED PROPS
945
dom = null;
946             dom = ctnServ.getContainerExtendedPropsAsDOM (site.getID ());
947             if (dom != null) {
948                 saveDOMDocument (dom, xmlDocFolder,
949                         ExtDepSiteConstants.CONTAINEREXTENDEDPROPS_FILE);
950             }
951
952             // EXTRACT CONTAINER STRUCTS
953
dom = null;
954             dom = ctnServ.getContainerStructsAsDOM (site.getID ());
955             if (dom != null) {
956                 saveDOMDocument (dom, xmlDocFolder,
957                         ExtDepSiteConstants.CONTAINERSTRUCTS_FILE);
958             }
959
960             // EXTRACT FILEMANAGER
961
dom = null;
962             dom = fmngServ.getFileMgrAsDOM (site.getID ());
963             if (dom != null) {
964                 saveDOMDocument (dom, xmlDocFolder,
965                         ExtDepSiteConstants.FILEMGR_FILE);
966             }
967
968             // EXTRACT FILEMANAGER FOLDERS
969
dom = null;
970             dom = fmngServ.getFileMgrFoldersAsDOM (site.getID ());
971             if (dom != null) {
972                 saveDOMDocument (dom, xmlDocFolder,
973                         ExtDepSiteConstants.FILEMGRFOLDERS_FILE);
974             }
975
976             // EXTRACT FILEMANAGER FILES
977
dom = null;
978             dom = fmngServ.getFileMgrFilesAsDOM (site.getID ());
979             if (dom != null) {
980                 saveDOMDocument (dom, xmlDocFolder,
981                         ExtDepSiteConstants.FILEMGRFILES_FILE);
982             }
983
984             // EXTRACT FILE FIELDS
985
dom = null;
986             dom = fmngServ.getFileMgrFileFieldsAsDOM (site.getID ());
987             if (dom != null) {
988                 saveDOMDocument (dom, xmlDocFolder,
989                         ExtDepSiteConstants.FILEFIELDS_FILE);
990             }
991
992             // EXTRACT APP DEFINITIONS
993
dom = null;
994             dom = appServ.getApplicationDefsAsDOM (site.getID ());
995             if (dom != null) {
996                 saveDOMDocument (dom, xmlDocFolder,
997                         ExtDepSiteConstants.APPDEFS_FILE);
998             }
999
1000            // EXTRACT APPLICATION SHARES
1001
dom = null;
1002            dom = appShareServ.getApplicationSharesAsDOM (site.getID ());
1003            if (dom != null) {
1004                saveDOMDocument (dom, xmlDocFolder,
1005                        ExtDepSiteConstants.APPSHARES_FILE);
1006            }
1007
1008            // EXTRACT APPLICATION GROUPS
1009
dom = null;
1010            dom = grpServ.getAppRoleGroupsAsDOM (site.getID ());
1011            if (dom != null) {
1012                saveDOMDocument (dom, xmlDocFolder,
1013                        ExtDepSiteConstants.APPGROUPS_FILE);
1014            }
1015
1016            // EXTRACT USERS
1017
/*
1018            dom = null;
1019            dom = userServ.getUsersAsDOM("jahia_db", site.getID());
1020            if ( dom != null ){
1021                saveDOMDocument(dom,xmlDocFolder,
1022                                ExtDepSiteConstants.USERS_FILE);
1023            }
1024            */

1025
1026            UserManagerProviderBean usrProviderBean;
1027            Vector JavaDoc usrProviders = userServ.getProviderList ();
1028            int size = usrProviders.size ();
1029
1030            // EXTRACT USERS
1031
dom = null;
1032            for (int i = 0; i < size; i++) {
1033                usrProviderBean = (UserManagerProviderBean)usrProviders.get (i);
1034                dom = usrProviderBean.getInstance ().getUsersAsDOM (site.getID ());
1035                if (dom != null) {
1036                    saveDOMDocument (dom, xmlDocFolder,
1037                            usrProviderBean.getKey () + "_" + ExtDepSiteConstants.USERS_FILE);
1038                }
1039            }
1040
1041
1042            // EXTRACT USER PROPS
1043
/*
1044            dom = null;
1045            dom = userServ.getUserPropsAsDOM("jahia_db", site.getID());
1046
1047            if ( dom != null ){
1048                saveDOMDocument(dom,xmlDocFolder,
1049                                ExtDepSiteConstants.USERPROPS_FILE);
1050            }
1051            */

1052            dom = null;
1053            for (int i = 0; i < size; i++) {
1054                usrProviderBean = (UserManagerProviderBean)usrProviders.get (i);
1055                dom = usrProviderBean.getInstance ().getUserPropsAsDOM (site.getID ());
1056                if (dom != null) {
1057                    saveDOMDocument (dom, xmlDocFolder,
1058                            usrProviderBean.getKey () + "_" + ExtDepSiteConstants.USERPROPS_FILE);
1059                }
1060            }
1061
1062            // EXTRACT GROUPS
1063
dom = null;
1064            dom = grpServ.getGroupsAsDOM (site.getID ());
1065            if (dom != null) {
1066                saveDOMDocument (dom, xmlDocFolder,
1067                        ExtDepSiteConstants.GROUPS_FILE);
1068            }
1069
1070            // EXTRACT GROUP PROPS
1071
dom = null;
1072            dom = grpServ.getGroupPropsAsDOM (site.getID ());
1073            if (dom != null) {
1074                saveDOMDocument (dom, xmlDocFolder,
1075                        ExtDepSiteConstants.GROUPPROPS_FILE);
1076            }
1077
1078
1079            // EXTRACT USER SITE MEMBERSHIPS
1080
dom = null;
1081            dom = siteUsrServ.getUserMembershipsAsDOM (site.getID ());
1082            if (dom != null) {
1083                saveDOMDocument (dom, xmlDocFolder,
1084                        ExtDepSiteConstants.USERMEMBERSHIPS_FILE);
1085            }
1086
1087            // EXTRACT GROUP SITE MEMBERSHIPS
1088
dom = null;
1089            dom = siteGrpServ.getGroupMembershipsAsDOM (site.getID ());
1090            if (dom != null) {
1091                saveDOMDocument (dom, xmlDocFolder,
1092                        ExtDepSiteConstants.GROUPMEMBERSHIPS_FILE);
1093            }
1094
1095            /*
1096            // EXTRACT AUTHORIZED EXTERNAL USERS ( FROM OTHER SITES )
1097            dom = null;
1098            dom = siteUsrServ.getAuthExternalUsersAsDOM(site.getID());
1099            if ( dom != null ){
1100                saveDOMDocument(dom,xmlDocFolder,
1101                                ExtDepSiteConstants.EXTERNALUSERS_FILE);
1102            }
1103
1104            // EXTRACT AUTHORIZED EXTERNAL GROUPS ( FROM OTHER SITES )
1105            dom = null;
1106            dom = siteGrpServ.getAuthExternalGroupsAsDOM(site.getID());
1107            if ( dom != null ){
1108                saveDOMDocument(dom,xmlDocFolder,
1109                                ExtDepSiteConstants.EXTERNALGROUPS_FILE);
1110            }
1111            */

1112
1113            // EXTRACT USER GROUP ACCESS
1114
dom = null;
1115            dom = grpServ.getUserGroupAccessAsDOM (site.getID ());
1116            if (dom != null) {
1117                saveDOMDocument (dom, xmlDocFolder,
1118                        ExtDepSiteConstants.USERGROUPACCESS_FILE);
1119            }
1120
1121            // EXTRACT APPLICATION GROUP ACCESS
1122
dom = null;
1123            dom = grpServ.getAppGroupAccessAsDOM (site.getID ());
1124            if (dom != null) {
1125                saveDOMDocument (dom, xmlDocFolder,
1126                        ExtDepSiteConstants.APPGROUPACCESS_FILE);
1127            }
1128
1129            // EXTRACT LOGS
1130
dom = null;
1131            dom = logServ.getLogsAsDOM (site.getSiteKey ());
1132            if (dom != null) {
1133                saveDOMDocument (dom, xmlDocFolder,
1134                        ExtDepSiteConstants.LOGS_FILE);
1135            }
1136
1137            // EXTRACT HOMEPAGE DEFINITIONS
1138
dom = null;
1139            dom = homepageServ.getHomepageDefsAsDOM (site.getSiteKey ());
1140            if (dom != null) {
1141                saveDOMDocument (dom, xmlDocFolder,
1142                        ExtDepSiteConstants.HOMEPAGEDEFS_FILE);
1143            }
1144
1145            // EXTRACT HOMEPAGE DEFINITION PROPERTIES
1146
dom = null;
1147            dom = homepageServ.getHomepageDefPropsAsDOM (site.getSiteKey ());
1148            if (dom != null) {
1149                saveDOMDocument (dom, xmlDocFolder,
1150                        ExtDepSiteConstants.HOMEPAGEDEFPROPS_FILE);
1151            }
1152
1153            //System.gc();
1154

1155            startTime = JahiaChrono.getInstance ().start ();
1156
1157            // EXTRACT ACL
1158
Vector JavaDoc aclIDs = new Vector JavaDoc ();
1159
1160            // site's acl
1161
aclIDs.add (new Integer JavaDoc (site.getAclID ()));
1162
1163            // pages acl
1164
addNewIDs (aclIDs, pageServ.getAclIDs (site.getID ()));
1165
1166            // page definitions (templates) acl
1167
addNewIDs (aclIDs, pageDefServ.getAclIDs (site.getID ()));
1168
1169            // home page definition acl
1170
addNewIDs (aclIDs, homepageServ.getAclIDs (site.getSiteKey ()));
1171
1172            // fields acl
1173
addNewIDs (aclIDs, fieldServ.getAclIDs (site.getID ()));
1174
1175            // containers acl
1176
addNewIDs (aclIDs, ctnServ.getAclIDs (site.getID ()));
1177
1178            // container lists view fields acl
1179
addNewIDs (aclIDs, ctnServ.getCtnListFieldAclIDs (site.getID ()));
1180
1181            // EXTRACT ACL WITH ALL PARENTS HIERARCHY
1182
dom = null;
1183            dom = aclServ.getAclsAsDOM (aclIDs, true);
1184            if (dom != null) {
1185                saveDOMDocument (dom, xmlDocFolder,
1186                        ExtDepSiteConstants.ACLS_FILE);
1187            }
1188
1189            logger.debug ("Acl extraction time ["
1190                    + JahiaChrono.getInstance ().read (startTime) + "ms]");
1191
1192            //System.gc();
1193

1194            startTime = JahiaChrono.getInstance ().start ();
1195
1196            // EXTRACT ACL ENTRIES :
1197
dom = null;
1198            dom = aclServ.getAclEntriesAsDOM (aclIDs);
1199            if (dom != null) {
1200                saveDOMDocument (dom, xmlDocFolder,
1201                        ExtDepSiteConstants.ACLENTRIES_FILE);
1202            }
1203            dom = null;
1204
1205            logger.debug ("Acl entries extraction time ["
1206                    + JahiaChrono.getInstance ().read (startTime) + "ms]");
1207
1208            //------------------------------------------------------------------
1209
// EXTRACT BIG TEXT
1210
if (!extractBigText (site)) {
1211                throw new JahiaException ("Error occured while processing your request",
1212                        CLASS_NAME + ": Error extracting big text files",
1213                        JahiaException.FILE_ERROR,
1214                        JahiaException.ERROR_SEVERITY);
1215            }
1216
1217            //------------------------------------------------------------------
1218
// EXTRACT SEARCH INDEX
1219
extractSearchIndex (site);
1220
1221
1222            //------------------------------------------------------------------
1223
// EXTRACT FILES
1224
if (!extractFiles (site)) {
1225                throw new JahiaException ("Error occured while processing your request",
1226                        CLASS_NAME + ": Error extracting files",
1227                        JahiaException.FILE_ERROR,
1228                        JahiaException.ERROR_SEVERITY);
1229            }
1230
1231
1232            //------------------------------------------------------------------
1233
// EXTRACT APPLICATIONS
1234
if (mServerType.startsWith (JahiaConstants.SERVER_TOMCAT)) {
1235                if (!extractTomcatApplications (site)) {
1236                    throw new JahiaException ("Error occured while processing your request",
1237                            CLASS_NAME + ": Error extracting applications",
1238                            JahiaException.FILE_ERROR,
1239                            JahiaException.ERROR_SEVERITY);
1240                }
1241            }
1242
1243
1244            //------------------------------------------------------------------
1245
// EXTRACT TEMPLATES JSP FILES
1246
if (!extractTemplates (site)) {
1247                throw new JahiaException ("Error occured while processing your request",
1248                        CLASS_NAME + ": Error extracting templates JSP files",
1249                        JahiaException.FILE_ERROR,
1250                        JahiaException.ERROR_SEVERITY);
1251            }
1252
1253            //------------------------------------------------------------------
1254
// EXTRACT NEW WEB APPS FOLDER
1255
if (!extractNewWebApps (site)) {
1256                throw new JahiaException ("Error occured while processing your request",
1257                        CLASS_NAME + ": Error extracting new WebApps",
1258                        JahiaException.FILE_ERROR,
1259                        JahiaException.ERROR_SEVERITY);
1260            }
1261
1262            //------------------------------------------------------------------
1263
// EXTRACT NEW TEMPLATES FOLDER
1264
if (!extractNewTemplates (site)) {
1265                throw new JahiaException ("Error occured while processing your request",
1266                        CLASS_NAME + ": Error extracting new templates",
1267                        JahiaException.FILE_ERROR,
1268                        JahiaException.ERROR_SEVERITY);
1269            }
1270
1271            //------------------------------------------------------------------
1272
// EXTRACT XML PORTLET FILES
1273
if (!extractXmlPortletFiles (site)) {
1274                throw new JahiaException ("Error occured while processing your request",
1275                        CLASS_NAME + ": Error extracting xml portlets files",
1276                        JahiaException.FILE_ERROR,
1277                        JahiaException.ERROR_SEVERITY);
1278            }
1279
1280
1281        } catch (Throwable JavaDoc t) {
1282            logger.warn (" exception "
1283                    + t.getMessage ());
1284            t.printStackTrace ();
1285
1286            throw new JahiaException ("Error occured while processing your request",
1287                    CLASS_NAME + "extractSite: " + t.toString (),
1288                    JahiaException.ERROR_SEVERITY,
1289                    JahiaException.ERROR_SEVERITY);
1290        }
1291    }
1292
1293
1294    /**
1295     * Extract server information.That is the root admin user,...
1296     */

1297    private void extractServerInfo ()
1298            throws IOException JavaDoc, ServletException JavaDoc, JahiaException {
1299        logger.debug ("started");
1300        try {
1301
1302            JahiaDOMObject dom = null;
1303
1304            // get services
1305
JahiaUserManagerService userServ = sReg.getJahiaUserManagerService ();
1306            JahiaGroupManagerService grpServ = sReg.getJahiaGroupManagerService ();
1307            JahiaIncrementorsDBService dbIncServ = sReg.getJahiaIncrementorsDBService ();
1308
1309            // Create the xml_document folder
1310
File JavaDoc xmlDocFolder = createSubExtractionFolder (ExtDepSiteConstants.SERVER + File.separator + mXMLDOC);
1311
1312
1313            // EXTRACT SERVER ADMIN USER
1314
dom = null;
1315
1316            UserManagerProviderBean usrProviderBean;
1317            Vector JavaDoc usrProviders = userServ.getProviderList ();
1318            int size = usrProviders.size ();
1319            for (int i = 0; i < size; i++) {
1320                usrProviderBean = (UserManagerProviderBean)usrProviders.get (i);
1321                dom = usrProviderBean.getInstance ().getUsersAsDOM (0);
1322                if (dom != null) {
1323                    saveDOMDocument (dom, xmlDocFolder,
1324                            usrProviderBean.getKey () + "_" + ExtDepSiteConstants.SERVERADMINUSER_FILE);
1325                }
1326            }
1327            /*
1328            dom = userServ.getUsersAsDOM("jahia_db", 0);
1329            if ( dom != null ){
1330                saveDOMDocument(dom,xmlDocFolder,
1331                                ExtDepSiteConstants.SERVERADMINUSER_FILE);
1332            }
1333            */

1334
1335            // EXTRACT SERVER ADMIN USER PROPS
1336
dom = null;
1337            for (int i = 0; i < size; i++) {
1338                usrProviderBean = (UserManagerProviderBean)usrProviders.get (i);
1339                dom = usrProviderBean.getInstance ().getUserPropsAsDOM (0);
1340                if (dom != null) {
1341                    saveDOMDocument (dom, xmlDocFolder,
1342                            usrProviderBean.getKey () + "_" + ExtDepSiteConstants.SERVERADMINUSERPROPS_FILE);
1343                }
1344            }
1345            /*
1346            dom = userServ.getUserPropsAsDOM("jahia_db", 0);
1347            if ( dom != null ){
1348                saveDOMDocument(dom,xmlDocFolder,
1349                                ExtDepSiteConstants.SERVERADMINUSERPROPS_FILE);
1350            }
1351            */

1352            // EXTRACT SERVER ADMIN GROUP
1353
dom = null;
1354            dom = grpServ.getGroupsAsDOM (0);
1355            if (dom != null) {
1356                saveDOMDocument (dom, xmlDocFolder,
1357                        ExtDepSiteConstants.SERVERADMINGROUP_FILE);
1358            }
1359
1360            // EXTRACT SERVER ADMIN GROUP PROPS
1361
dom = null;
1362            dom = grpServ.getGroupPropsAsDOM (0);
1363            if (dom != null) {
1364                saveDOMDocument (dom, xmlDocFolder,
1365                        ExtDepSiteConstants.SERVERADMINGROUPPROPS_FILE);
1366            }
1367
1368            // EXTRACT USER GROUP ACCESS
1369
dom = null;
1370            dom = grpServ.getUserGroupAccessAsDOM (0);
1371            if (dom != null) {
1372                saveDOMDocument (dom, xmlDocFolder,
1373                        ExtDepSiteConstants.USERGROUPACCESS_FILE);
1374            }
1375
1376            // EXTRACT APPLICATION GROUP ACCESS
1377
dom = null;
1378            dom = grpServ.getAppGroupAccessAsDOM (0);
1379            if (dom != null) {
1380                saveDOMDocument (dom, xmlDocFolder,
1381                        ExtDepSiteConstants.APPGROUPACCESS_FILE);
1382            }
1383
1384            // EXTRACT AUTO IDS
1385
dom = null;
1386            dom = dbIncServ.getAutoIdsAsDOM ();
1387            if (dom != null) {
1388                saveDOMDocument (dom, xmlDocFolder,
1389                        ExtDepSiteConstants.AUTOIDS_FILE);
1390            }
1391
1392            dom = null;
1393            xmlDocFolder = null;
1394
1395        } catch (Throwable JavaDoc t) {
1396            logger.error (" exception "
1397                    + t.getMessage ());
1398            t.printStackTrace ();
1399
1400            throw new JahiaException ("Error occured while processing your request",
1401                    CLASS_NAME + "extractServerInfo: " + t.toString (),
1402                    JahiaException.ERROR_SEVERITY,
1403                    JahiaException.ERROR_SEVERITY);
1404
1405        }
1406    }
1407
1408
1409    /**
1410     * Extract Big Text for a gived Site
1411     *
1412     * @param site the site.
1413     * @return false on error
1414     */

1415    private boolean extractBigText (JahiaSite site)
1416            throws JahiaException {
1417
1418        // start the chrono...
1419
long startTime = JahiaChrono.getInstance ().start ();
1420
1421        JahiaTextFileService fileServ = sReg.getJahiaTextFileService ();
1422
1423        if (site == null || fileServ == null) {
1424            return false;
1425        }
1426
1427        File JavaDoc f = new File JavaDoc (mSiteExtractionFolder
1428                + File.separator
1429                + site.getSiteKey ()
1430                + File.separator
1431                + mDATA);
1432        f.mkdirs ();
1433
1434        if (!f.isDirectory ()) {
1435            throw new JahiaException ("Error occured while processing your request",
1436                    CLASS_NAME + ": Cannot create directory to store big text",
1437                    JahiaException.FILE_ERROR,
1438                    JahiaException.ERROR_SEVERITY);
1439
1440        }
1441
1442        try {
1443            if (fileServ.copySiteBigText (site.getID (), f.getAbsolutePath ()) < 0) {
1444                throw new JahiaException ("Error occured while processing your request",
1445                        CLASS_NAME + ": Error copying big text files",
1446                        JahiaException.FILE_ERROR,
1447                        JahiaException.ERROR_SEVERITY);
1448            }
1449        } catch (IOException JavaDoc ioe) {
1450            throw new JahiaException ("Error occured while processing your request",
1451                    CLASS_NAME + ": Error copying big text files",
1452                    JahiaException.FILE_ERROR,
1453                    JahiaException.ERROR_SEVERITY);
1454        }
1455
1456        logger.debug ("Bigtext extraction time ["
1457                + JahiaChrono.getInstance ().read (startTime) + "ms]");
1458
1459        return true;
1460    }
1461
1462    /**
1463     * Extract Search indexes for a given Site
1464     *
1465     * @param site the site.
1466     * @return false on error
1467     */

1468    private boolean extractSearchIndex (JahiaSite site)
1469            throws JahiaException {
1470
1471        if (site == null) {
1472            return false;
1473        }
1474
1475        JahiaSearchService searchServ = ServicesRegistry.getInstance ().getJahiaSearchService ();
1476        if (searchServ == null) {
1477            return false;
1478        }
1479
1480        String JavaDoc indexPath = searchServ.getSiteIndex (site.getID ());
1481        if (indexPath == null) {
1482            return false;
1483        }
1484        File JavaDoc f = null;
1485        f = new File JavaDoc (indexPath);
1486        if (f.isDirectory () && f.canRead ()) {
1487            StringBuffer JavaDoc destFolder = new StringBuffer JavaDoc (mSiteExtractionFolder);
1488            destFolder.append (File.separator);
1489            destFolder.append (site.getSiteKey ());
1490            destFolder.append (File.separator);
1491            destFolder.append (mSEARCHINDEX);
1492            destFolder.append (File.separator);
1493            destFolder.append (site.getSiteKey ());
1494
1495            try {
1496                File JavaDoc dest = new File JavaDoc (destFolder.toString ());
1497                dest.mkdirs ();
1498                dest = null;
1499                JahiaTools.copyFolderContent (f.getAbsolutePath (), destFolder.toString ());
1500            } catch (IOException JavaDoc ioe) {
1501                throw new JahiaException ("Error occured while processing your request",
1502                        CLASS_NAME + ": Exception while copying files from " + f.getAbsolutePath (),
1503                        JahiaException.FILE_ERROR,
1504                        JahiaException.ERROR_SEVERITY);
1505            }
1506        }
1507        f = null;
1508        return true;
1509    }
1510
1511
1512    /**
1513     * Extract Files for a gived Site
1514     *
1515     * @param site the site.
1516     * @return false on error
1517     */

1518    private boolean extractFiles (JahiaSite site)
1519            throws JahiaException {
1520
1521        // start the chrono...
1522
long startTime = JahiaChrono.getInstance ().start ();
1523
1524        if (site == null) {
1525            return false;
1526        }
1527
1528        File JavaDoc f = null;
1529        f = new File JavaDoc (mFilemanagerFullPath + File.separator + site.getSiteKey ());
1530        if (f.isDirectory () && f.canRead ()) {
1531            StringBuffer JavaDoc destFolder = new StringBuffer JavaDoc (mSiteExtractionFolder);
1532            destFolder.append (File.separator);
1533            destFolder.append (site.getSiteKey ());
1534            destFolder.append (File.separator);
1535            destFolder.append (mFILEMANAGER);
1536            destFolder.append (File.separator);
1537            destFolder.append (site.getSiteKey ());
1538
1539            try {
1540                File JavaDoc dest = new File JavaDoc (destFolder.toString ());
1541                dest.mkdirs ();
1542                dest = null;
1543                JahiaTools.copyFolderContent (f.getAbsolutePath (), destFolder.toString ());
1544            } catch (IOException JavaDoc ioe) {
1545                throw new JahiaException ("Error occured while processing your request",
1546                        CLASS_NAME + ": Exception while copying files from " + f.getAbsolutePath (),
1547                        JahiaException.FILE_ERROR,
1548                        JahiaException.ERROR_SEVERITY);
1549            }
1550        }
1551        f = null;
1552
1553        logger.debug ("Files extraction time ["
1554                + JahiaChrono.getInstance ().read (startTime) + "ms]");
1555
1556
1557        return true;
1558    }
1559
1560
1561    /**
1562     * Extract a site's applications for Tomcat server.
1563     *
1564     * @param site the site.
1565     * @return false on error
1566     */

1567    private boolean extractTomcatApplications (JahiaSite site)
1568            throws JahiaException {
1569
1570        // start the chrono...
1571
long startTime = JahiaChrono.getInstance ().start ();
1572
1573        //JahiaConsole.println(CLASS_NAME+".extractTomcatApplications","started");
1574
JahiaApplicationsManagerService appServ =
1575                sReg.getJahiaApplicationsManagerService ();
1576
1577        if (site == null || appServ == null) {
1578            return false;
1579        }
1580
1581        String JavaDoc serverPath = properties.getProperty ("serverHomeDiskPath").trim ();
1582        if ((serverPath == null) || serverPath.equals ("")) {
1583            return false;
1584        }
1585
1586        File JavaDoc f = new File JavaDoc (serverPath);
1587        if (!f.isDirectory ()) {
1588            return false;
1589        }
1590
1591        // create the extraction folder for web applications
1592
f = null;
1593
1594        StringBuffer JavaDoc buff = new StringBuffer JavaDoc (mSiteExtractionFolder);
1595        buff.append (File.separator);
1596        buff.append (site.getSiteKey ());
1597        buff.append (File.separator);
1598        buff.append (mAPPS);
1599        buff.append (File.separator);
1600
1601        // create the extract folder
1602
String JavaDoc appsExtractFolder = buff.toString ();
1603        f = new File JavaDoc (appsExtractFolder);
1604        f.mkdirs ();
1605
1606        String JavaDoc tomcatWebAppsFolder = serverPath + mTOMCATWEBAPPS + File.separator;
1607
1608        /*
1609        JahiaConsole.println(CLASS_NAME+".extractTomcatApplications",
1610                                        "extract path is " + appsExtractFolder);
1611        */

1612
1613        Vector JavaDoc v = appServ.getApplications (site.getID ());
1614        int size = v.size ();
1615        ApplicationBean appBean = null;
1616        String JavaDoc appContext = null;
1617        for (int i = 0; i < size; i++) {
1618            appBean = (ApplicationBean)v.get (i);
1619            if ((appBean != null)
1620                    && (appBean.getContext () != null)
1621                    && (!appBean.getContext ().equals (""))) {
1622
1623                appContext = appBean.getContext ().substring (1, appBean.getContext ().length ());
1624
1625                if (!appContext.equals ("jahia")) { // FIXME : should not be hc.
1626
f = new File JavaDoc (tomcatWebAppsFolder + appContext);
1627                    if (f.isDirectory ()) {
1628
1629                        try {
1630                            JahiaTools.copyFolderContent (f.getAbsolutePath (),
1631                                    appsExtractFolder + appContext);
1632                        } catch (IOException JavaDoc ioe) {
1633                            throw new JahiaException ("Error occured while processing your request",
1634                                    CLASS_NAME + ": Exception while copying application " + f.getAbsolutePath (),
1635                                    JahiaException.FILE_ERROR,
1636                                    JahiaException.ERROR_SEVERITY);
1637                        }
1638                    }
1639                    f = null;
1640                }
1641            }
1642        }
1643
1644        logger.debug ("WebApp extraction time ["
1645                + JahiaChrono.getInstance ().read (startTime) + "ms]");
1646
1647        return true;
1648    }
1649
1650
1651    /**
1652     * Extract a site's JSP Template files.
1653     *
1654     * @param site the site.
1655     * @return false on error
1656     */

1657    private boolean extractTemplates (JahiaSite site)
1658            throws JahiaException {
1659
1660        // start the chrono...
1661
long startTime = JahiaChrono.getInstance ().start ();
1662
1663        //JahiaConsole.println(CLASS_NAME+".extractTemplates","started");
1664
JahiaTemplatesDeployerService templateServ =
1665                sReg.getJahiaTemplatesDeployerService ();
1666
1667        if (site == null || templateServ == null) {
1668            return false;
1669        }
1670
1671        String JavaDoc templateRootPath = templateServ.getTemplateRootPath ();
1672        if (templateRootPath == null || templateRootPath.trim ().equals ("")) {
1673            return false;
1674        }
1675
1676        // create the extraction folder for templates
1677

1678        StringBuffer JavaDoc buff = new StringBuffer JavaDoc (mSiteExtractionFolder);
1679        buff.append (File.separator);
1680        buff.append (site.getSiteKey ());
1681        buff.append (File.separator);
1682        buff.append (mTEMPLATES);
1683        buff.append (File.separator);
1684        buff.append (site.getSiteKey ());
1685        String JavaDoc templatesExtractFolder = buff.toString ();
1686
1687        try {
1688            File JavaDoc f = new File JavaDoc (templatesExtractFolder);
1689            f.mkdirs ();
1690            f = null;
1691            JahiaTools.copyFolderContent (templateRootPath + File.separator + site.getSiteKey (),
1692                    templatesExtractFolder);
1693        } catch (IOException JavaDoc ioe) {
1694            throw new JahiaException ("Error occured while processing your request",
1695                    CLASS_NAME + ": Exception while copying templates "
1696                    + templateRootPath + File.separator + site.getSiteKey (),
1697                    JahiaException.FILE_ERROR,
1698                    JahiaException.ERROR_SEVERITY);
1699        }
1700
1701        logger.debug ("Templates extraction time ["
1702                + JahiaChrono.getInstance ().read (startTime) + "ms]");
1703
1704        return true;
1705    }
1706
1707
1708    /**
1709     * Extract a site's new web apps folder.
1710     *
1711     * @param site the site.
1712     * @return false on error
1713     */

1714    private boolean extractNewWebApps (JahiaSite site)
1715            throws JahiaException {
1716
1717        logger.debug ("For site " + site.getServerName ());
1718
1719        if (site == null) {
1720            return false;
1721        }
1722
1723        // get the new web apps folder for this site
1724
if (properties.getProperty ("jahiaNewWebAppsDiskPath") == null) {
1725            return false;
1726        }
1727
1728        logger.debug ("jahiaNewWebAppsDiskPath not null ");
1729
1730        String JavaDoc srcPath = JahiaTools.convertContexted ((properties.getProperty ("jahiaNewWebAppsDiskPath")).trim (), pathResolver);
1731        File JavaDoc src = new File JavaDoc (srcPath + File.separator + site.getSiteKey ());
1732
1733        logger.debug ("source is " + src.getAbsolutePath ());
1734
1735        if (!src.isDirectory ()) {
1736            return true;
1737        }
1738
1739        logger.debug ("Source = " + src.getAbsolutePath ());
1740
1741        // create the extraction folder for new web apps
1742
StringBuffer JavaDoc buff = new StringBuffer JavaDoc (mSiteExtractionFolder);
1743        buff.append (File.separator);
1744        buff.append (site.getSiteKey ());
1745        buff.append (File.separator);
1746        buff.append (mNEW_WEBAPPS);
1747        buff.append (File.separator);
1748        buff.append (site.getSiteKey ());
1749
1750        File JavaDoc dest = null;
1751        try {
1752            dest = new File JavaDoc (buff.toString ());
1753            dest.mkdirs ();
1754
1755            logger.debug ("Dest = " + dest.getAbsolutePath ());
1756
1757            JahiaTools.copyFolderContent (src.getAbsolutePath (),
1758                    dest.getAbsolutePath ());
1759
1760        } catch (IOException JavaDoc ioe) {
1761            throw new JahiaException ("Error occured while processing your request",
1762                    CLASS_NAME + ": Exception while copying new webapps "
1763                    + src.getAbsolutePath (),
1764                    JahiaException.FILE_ERROR,
1765                    JahiaException.ERROR_SEVERITY);
1766        } finally {
1767            src = null;
1768            dest = null;
1769        }
1770
1771        return true;
1772    }
1773
1774
1775    /**
1776     * Extract a site's new template folder.
1777     *
1778     * @param site the site.
1779     * @return false on error
1780     */

1781    private boolean extractNewTemplates (JahiaSite site)
1782            throws JahiaException {
1783
1784
1785        if (site == null) {
1786            return false;
1787        }
1788
1789        // get the new web apps folder for this site
1790
if (properties.getProperty ("jahiaNewTemplatesDiskPath") == null) {
1791            return false;
1792        }
1793        String JavaDoc srcPath = JahiaTools.convertContexted (
1794                properties.getProperty ("jahiaNewTemplatesDiskPath").trim (), pathResolver);
1795        File JavaDoc src = new File JavaDoc (srcPath + File.separator + site.getSiteKey ());
1796        if (!src.isDirectory ()) {
1797            return true; // not exist
1798
}
1799
1800        // create the extraction folder for new web apps
1801
StringBuffer JavaDoc buff = new StringBuffer JavaDoc (mSiteExtractionFolder);
1802        buff.append (File.separator);
1803        buff.append (site.getSiteKey ());
1804        buff.append (File.separator);
1805        buff.append (mNEW_TEMPLATES);
1806        buff.append (File.separator);
1807        buff.append (site.getSiteKey ());
1808
1809        File JavaDoc dest = null;
1810        try {
1811            dest = new File JavaDoc (buff.toString ());
1812            dest.mkdirs ();
1813            JahiaTools.copyFolderContent (src.getAbsolutePath (),
1814                    dest.getAbsolutePath ());
1815
1816        } catch (IOException JavaDoc ioe) {
1817            throw new JahiaException ("Error occured while processing your request",
1818                    CLASS_NAME + ": Exception while copying new templates "
1819                    + src.getAbsolutePath (),
1820                    JahiaException.FILE_ERROR,
1821                    JahiaException.ERROR_SEVERITY);
1822        } finally {
1823            src = null;
1824            dest = null;
1825        }
1826
1827        return true;
1828    }
1829
1830
1831    /**
1832     * Extract a site's XML Portlets files.
1833     *
1834     * @param site the site.
1835     * @return false on error
1836     */

1837    private boolean extractXmlPortletFiles (JahiaSite site)
1838            throws JahiaException {
1839
1840        //JahiaConsole.println(CLASS_NAME+".extractXmlPortletFiles","started");
1841

1842        if (site == null) {
1843            return false;
1844        }
1845
1846        StringBuffer JavaDoc buff =
1847                new StringBuffer JavaDoc (properties.getProperty ("jahiaVarDiskPath").trim ());
1848        buff.append (File.separator);
1849        buff.append ("templates");
1850        buff.append (File.separator);
1851        buff.append ("site_");
1852        buff.append (site.getID ());
1853        File JavaDoc f = new File JavaDoc (JahiaTools.convertContexted (buff.toString (), pathResolver));
1854
1855        // create the extraction folder for templates
1856
buff = new StringBuffer JavaDoc (mSiteExtractionFolder);
1857        buff.append (File.separator);
1858        buff.append (site.getSiteKey ());
1859        buff.append (File.separator);
1860        buff.append (mXMLPORTLETS);
1861        buff.append (File.separator);
1862        buff.append ("site_");
1863        buff.append (site.getID ());
1864        String JavaDoc templatesExtractFolder = buff.toString ();
1865        File JavaDoc destFolder = new File JavaDoc (templatesExtractFolder);
1866        destFolder.mkdirs ();
1867        destFolder = null;
1868        if (f.exists ()) {
1869
1870
1871            try {
1872                JahiaTools.copyFolderContent (f.getAbsolutePath (),
1873                        templatesExtractFolder);
1874            } catch (IOException JavaDoc ioe) {
1875                throw new JahiaException ("Error occured while processing your request",
1876                        CLASS_NAME + ": Exception while copying xml portlets files "
1877                        + f.getAbsolutePath (),
1878                        JahiaException.FILE_ERROR,
1879                        JahiaException.ERROR_SEVERITY);
1880            }
1881        }
1882
1883        return true;
1884    }
1885
1886
1887    /**
1888     * Create the description file
1889     *
1890     * @param extractName
1891     * @param extractDescr
1892     * @param sites the list of extracted site
1893     *
1894     * @return boolean false on error
1895     */

1896    private boolean createDescrFile (String JavaDoc extractName,
1897                                     String JavaDoc extractDescr,
1898                                     Vector JavaDoc sites) {
1899
1900        if (sites == null
1901                || (sites.size () == 0)
1902                || extractName == null
1903                || extractName.equals ("")) {
1904            return false;
1905        }
1906
1907        boolean err = false;
1908
1909        StringBuffer JavaDoc buff = new StringBuffer JavaDoc (mSiteExtractionFolder);
1910        buff.append (File.separator);
1911        buff.append (ExtDepSiteConstants.DESCRFILE);
1912
1913        File JavaDoc f = new File JavaDoc (buff.toString ());
1914        if (f.isFile ()) {
1915            f.delete ();
1916        }
1917
1918        PropertiesManager prop = null;
1919
1920        try {
1921            if (f.createNewFile ()) {
1922
1923                // compose the list of sites
1924
int size = sites.size ();
1925                JahiaSite site = null;
1926                buff = new StringBuffer JavaDoc ();
1927                for (int i = 0; i < size; i++) {
1928                    site = (JahiaSite)sites.get (i);
1929                    if (site != null) {
1930                        buff.append (site.getServerName ());
1931                        buff.append ("@@@");
1932                        buff.append (site.getSiteKey ());
1933                        if (i < (size - 1)) {
1934                            buff.append (",");
1935                        }
1936                    }
1937                }
1938
1939                prop = new PropertiesManager ();
1940                prop.setProperty (ExtDepSiteConstants.DESCRFILE_BUILD, Long.toString (Jahia.BUILD_NUMBER));
1941                prop.setProperty (ExtDepSiteConstants.DESCRFILE_RELEASE, Double.toString (Jahia.RELEASE_NUMBER));
1942                prop.setProperty (ExtDepSiteConstants.DESCRFILE_DATE, Long.toString (System.currentTimeMillis ()));
1943                prop.setProperty (ExtDepSiteConstants.DESCRFILE_NAME, extractName);
1944                prop.setProperty (ExtDepSiteConstants.DESCRFILE_DESCR, extractDescr);
1945                prop.setProperty (ExtDepSiteConstants.DESCRFILE_SITES, buff.toString ());
1946                prop.storeProperties (f.getAbsolutePath ());
1947            } else {
1948                return false;
1949            }
1950        } catch (IOException JavaDoc ioe) {
1951            err = true;
1952        } finally {
1953            prop = null;
1954            f = null;
1955        }
1956        return (!err);
1957    }
1958
1959
1960
1961
1962
1963
1964
1965
1966    //--------------------------------------------------------------------------
1967
//
1968
// RESTORE SECTION
1969
//
1970
//--------------------------------------------------------------------------
1971

1972    /**
1973     * Display a page where the user can restore an extraction or flush/delete
1974     * an unwanted extraction. This method display the full list of extractions.
1975     *
1976     * @param request Servlet request.
1977     * @param response Servlet response.
1978     * @param session Servlet session for the current user.
1979     */

1980    private void displayManageExtractions (HttpServletRequest JavaDoc request,
1981                                           HttpServletResponse JavaDoc response,
1982                                           HttpSession JavaDoc session)
1983            throws IOException JavaDoc, ServletException JavaDoc {
1984        // reset session
1985
session.setAttribute (CLASS_NAME + "selSiteKeys", null);
1986        session.setAttribute (CLASS_NAME + "extractName", null);
1987        session.setAttribute (CLASS_NAME + "warningMsg", null);
1988
1989        //JahiaConsole.println(CLASS_NAME+".displayManageExtractions","started");
1990

1991        // load extraction lists
1992
Vector JavaDoc v = new Vector JavaDoc ();
1993        String JavaDoc descrFile = File.separator + ExtDepSiteConstants.DESCRFILE;
1994        File JavaDoc f = new File JavaDoc (mERFFullPath);
1995        if (f.isDirectory ()) {
1996
1997            File JavaDoc[] files = f.listFiles ();
1998            File JavaDoc fileItem = null;
1999            for (int i = 0; i < files.length; i++) {
2000                if (files[i].isDirectory () && !files[i].getName ().endsWith ("_error")) {
2001                    /*
2002                    JahiaConsole.println(CLASS_NAME+".displayManageExtractions",
2003                    "found directory" + files[i].getAbsolutePath());
2004                    */

2005                    fileItem = new File JavaDoc (files[i].getAbsolutePath () + descrFile);
2006                    if (fileItem.isFile () && fileItem.canRead ()) {
2007
2008                        try {
2009                            SiteExtractionBean seBean =
2010                                    new SiteExtractionBean (fileItem.getAbsolutePath ());
2011                            // add it in the vector but ordering by date
2012
v.add (seBean);
2013                            logger.debug ("added extraction " + seBean.getName ());
2014                        } catch (Throwable JavaDoc t) {
2015                            logger.error ("invalid Site Extraction " + fileItem.getAbsolutePath ());
2016                        } finally {
2017                            fileItem = null;
2018                        }
2019                    }
2020                }
2021            }
2022        }
2023
2024        // order the extraction list
2025
v = orderExtraction (v);
2026
2027        request.setAttribute ("extractList", v.elements ());
2028        // forward to JSP
2029
JahiaAdministration.doRedirect (request, response, session,
2030                JSP_PATH + "extdep_site_manage.jsp");
2031
2032    }
2033
2034
2035    /**
2036     * Display details about the extraction to restore.
2037     * The user can choose which site to restore
2038     *
2039     * @param request Servlet request.
2040     * @param response Servlet response.
2041     * @param session Servlet session for the current user.
2042     */

2043    private void displayRestore (
2044            HttpServletRequest JavaDoc request,
2045            HttpServletResponse JavaDoc response,
2046            HttpSession JavaDoc session)
2047            throws IOException JavaDoc, ServletException JavaDoc {
2048
2049        logger.debug ("started");
2050
2051        JahiaData jData = (JahiaData)request.getAttribute ("org.jahia.data.JahiaData");
2052        ParamBean jParams = null;
2053        if (jData != null) {
2054            jParams = jData.params ();
2055        }
2056        // retrieve previous form values...
2057
Vector JavaDoc selSiteKeys = (Vector JavaDoc)session.getAttribute (CLASS_NAME
2058                + "selSiteKeys");
2059        String JavaDoc extractName = (String JavaDoc)session.getAttribute (CLASS_NAME
2060                + "extractName");
2061        String JavaDoc warningMsg = (String JavaDoc)session.getAttribute (CLASS_NAME
2062                + "warningMsg");
2063
2064        if (extractName == null) {
2065
2066            // try to get from request
2067
extractName = request.getParameter ("name");
2068            if (extractName == null) {
2069                String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
2070                        jParams, jParams.getLocale ());
2071                request.setAttribute ("jahiaDisplayMessage", dspMsg);
2072                JahiaAdministration.doRedirect (request,
2073                        response,
2074                        session,
2075                        JSP_PATH + "menu.jsp");
2076            }
2077        }
2078
2079        // set default values (if necessary)...
2080
if (selSiteKeys == null) {
2081            selSiteKeys = new Vector JavaDoc ();
2082        }
2083        if (warningMsg == null) {
2084            warningMsg = "";
2085        }
2086
2087        // set request attributes...
2088
request.setAttribute ("selSiteKeys", selSiteKeys);
2089        request.setAttribute ("warningMsg", warningMsg);
2090
2091        // load extraction descr file
2092
StringBuffer JavaDoc buff = new StringBuffer JavaDoc (mERFFullPath);
2093        buff.append (File.separator);
2094        buff.append (extractName);
2095        buff.append (File.separator);
2096        buff.append (ExtDepSiteConstants.DESCRFILE);
2097        File JavaDoc f = new File JavaDoc (buff.toString ());
2098        if (f.isFile () && f.canRead ()) {
2099
2100            logger.debug ("found file"
2101                    + f.getAbsolutePath ());
2102
2103            SiteExtractionBean seBean = null;
2104            try {
2105                seBean = new SiteExtractionBean (f.getAbsolutePath ());
2106
2107            } catch (Throwable JavaDoc t) {
2108                logger.debug ("invalid Site Extraction " + f.getAbsolutePath ());
2109
2110                String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
2111                        jParams, jParams.getLocale ());
2112                request.setAttribute ("jahiaDisplayMessage", dspMsg);
2113                JahiaAdministration.doRedirect (request,
2114                        response,
2115                        session,
2116                        JSP_PATH + "menu.jsp");
2117                return;
2118            } finally {
2119                f = null;
2120            }
2121
2122            request.setAttribute ("extractionProps", seBean);
2123            // forward to JSP
2124
JahiaAdministration.doRedirect (request, response, session,
2125                    JSP_PATH + "extdep_site_restore.jsp");
2126
2127        } else {
2128            logger.debug ("Cannot find file " + f.getAbsolutePath ());
2129
2130            String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
2131                    jParams, jParams.getLocale ());
2132            request.setAttribute ("jahiaDisplayMessage", dspMsg);
2133            JahiaAdministration.doRedirect (request,
2134                    response,
2135                    session,
2136                    JSP_PATH + "menu.jsp");
2137        }
2138    }
2139
2140
2141    /**
2142     * Display the restore confirmation screen.
2143     *
2144     * @param extractName the extraction identifier
2145     * @param request Servlet request.
2146     * @param response Servlet response.
2147     * @param session Servlet session for the current user.
2148     */

2149    private void displayRestoreConfirmation (String JavaDoc extractName,
2150                                             HttpServletRequest JavaDoc request,
2151                                             HttpServletResponse JavaDoc response,
2152                                             HttpSession JavaDoc session)
2153            throws IOException JavaDoc, ServletException JavaDoc {
2154
2155        logger.debug ("started");
2156
2157        JahiaData jData = (JahiaData)request.getAttribute ("org.jahia.data.JahiaData");
2158        ParamBean jParams = null;
2159        if (jData != null) {
2160            jParams = jData.params ();
2161        }
2162        // retrieve previous form values...
2163
Vector JavaDoc selSiteKeys = (Vector JavaDoc)session.getAttribute (CLASS_NAME
2164                + "selSiteKeys");
2165        String JavaDoc warningMsg = (String JavaDoc)session.getAttribute (CLASS_NAME
2166                + "warningMsg");
2167
2168        // set default values (if necessary)...
2169
if (selSiteKeys == null) {
2170            selSiteKeys = new Vector JavaDoc ();
2171        }
2172        if (warningMsg == null) {
2173            warningMsg = "";
2174        }
2175
2176        // set request attributes...
2177
request.setAttribute ("selSiteKeys", selSiteKeys);
2178        request.setAttribute ("warningMsg", warningMsg);
2179
2180        // load extraction descr file
2181
StringBuffer JavaDoc buff = new StringBuffer JavaDoc (mERFFullPath);
2182        buff.append (File.separator);
2183        buff.append (extractName);
2184        buff.append (File.separator);
2185        buff.append (ExtDepSiteConstants.DESCRFILE);
2186        File JavaDoc f = new File JavaDoc (buff.toString ());
2187        if (f.isFile () && f.canRead ()) {
2188
2189            logger.debug ("found file"
2190                    + f.getAbsolutePath ());
2191
2192            SiteExtractionBean seBean = null;
2193            try {
2194                seBean = new SiteExtractionBean (f.getAbsolutePath ());
2195            } catch (Throwable JavaDoc t) {
2196                logger.debug ("invalid Site Extraction " + f.getAbsolutePath ());
2197
2198                String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
2199                        jParams, jParams.getLocale ());
2200                request.setAttribute ("jahiaDisplayMessage", dspMsg);
2201                JahiaAdministration.doRedirect (request,
2202                        response,
2203                        session,
2204                        JSP_PATH + "menu.jsp");
2205                return;
2206            } finally {
2207                f = null;
2208            }
2209
2210            request.setAttribute ("extractionProps", seBean);
2211            // forward to JSP
2212
JahiaAdministration.doRedirect (request, response, session,
2213                    JSP_PATH + "extdep_site_restoreconfirmation.jsp");
2214
2215        } else {
2216            logger.debug ("Cannot find file " + f.getAbsolutePath ());
2217
2218            String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
2219                    jParams, jParams.getLocale ());
2220            request.setAttribute ("jahiaDisplayMessage", dspMsg);
2221            JahiaAdministration.doRedirect (request,
2222                    response,
2223                    session,
2224                    JSP_PATH + "menu.jsp");
2225        }
2226    }
2227
2228
2229    /**
2230     * Display details about an extraction.
2231     *
2232     * @param request Servlet request.
2233     * @param response Servlet response.
2234     * @param session Servlet session for the current user.
2235     */

2236    private void displayDetail (HttpServletRequest JavaDoc request,
2237                                HttpServletResponse JavaDoc response,
2238                                HttpSession JavaDoc session)
2239            throws IOException JavaDoc, ServletException JavaDoc {
2240
2241        logger.debug ("started");
2242
2243        String JavaDoc extractName = request.getParameter ("name");
2244
2245        if (extractName == null || extractName.trim ().equals ("")) {
2246            displayManageExtractions (request, response, session);
2247            return;
2248        }
2249
2250        StringBuffer JavaDoc buff = new StringBuffer JavaDoc (mERFFullPath);
2251        buff.append (File.separator);
2252        buff.append (extractName);
2253        buff.append (File.separator);
2254        buff.append (ExtDepSiteConstants.DESCRFILE);
2255        File JavaDoc f = new File JavaDoc (buff.toString ());
2256        if (!f.isFile ()) {
2257            displayManageExtractions (request, response, session);
2258            return;
2259        }
2260
2261        try {
2262            SiteExtractionBean seBean = new SiteExtractionBean (f.getAbsolutePath ());
2263            request.setAttribute ("extractionProps", seBean);
2264            // forward to JSP
2265
JahiaAdministration.doRedirect (request, response, session,
2266                    JSP_PATH + "extdep_site_details.jsp");
2267        } catch (Throwable JavaDoc t) {
2268            JahiaAdministration.doRedirect (request, response, session,
2269                    JSP_PATH + "extdep_site_manage.jsp");
2270        }
2271    }
2272
2273
2274    /**
2275     * Process the restoration of an extraction.
2276     *
2277     * @param request Servlet request.
2278     * @param response Servlet response.
2279     * @param session Servlet session for the current user.
2280     */

2281    private void processRestore (HttpServletRequest JavaDoc request,
2282                                 HttpServletResponse JavaDoc response,
2283                                 HttpSession JavaDoc session)
2284            throws IOException JavaDoc, ServletException JavaDoc, JahiaException {
2285        logger.debug ("started");
2286
2287        synchronized (mLock) {
2288
2289            // Try to get the excluse lock on Jahia
2290
JahiaUser user = (JahiaUser)session.getAttribute (ParamBean.SESSION_USER);
2291            JahiaData jData = (JahiaData)request.getAttribute ("org.jahia.data.JahiaData");
2292            ParamBean jParams = null;
2293            if (jData != null) {
2294                jParams = jData.params ();
2295            }
2296
2297            if (user == null || !user.isAdminMember (0)) {
2298                String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.illegalAccessOperation.label",
2299                        jParams, jParams.getLocale ());
2300                session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
2301                JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "menu.jsp");
2302                return;
2303            }
2304
2305            byte[] jahiaLock = null;
2306            boolean freeLock = true;
2307
2308            try {
2309                jahiaLock = Jahia.getLock (user, session);
2310                if (jahiaLock == null) {
2311                    String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.noLockJahiaExclusively.label",
2312                            jParams, jParams.getLocale ());
2313                    session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
2314                    JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "menu.jsp");
2315                    return;
2316                }
2317            } catch (JahiaException je) {
2318                session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", je.getMessage ());
2319                JahiaAdministration.doRedirect (request, response, session, JSP_PATH + "menu.jsp");
2320                return;
2321            }
2322
2323            this.aclFilter = new ACLDataFilter ();
2324
2325            try {
2326
2327                String JavaDoc confirmRestore = request.getParameter ("confirmRestore");
2328
2329                String JavaDoc[] siteKeysArr = null;
2330                Vector JavaDoc selSiteKeys = null;
2331
2332                String JavaDoc jahiaExtractName = null;
2333
2334                if (confirmRestore == null || !confirmRestore.equals ("yes")) {
2335
2336                    jahiaExtractName = request.getParameter ("name");
2337
2338                    if (jahiaExtractName == null) {
2339                        logger.debug ("Missing extraction Name parameter");
2340
2341                        String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
2342                                jParams, jParams.getLocale ());
2343                        request.setAttribute ("jahiaDisplayMessage", dspMsg);
2344                        JahiaAdministration.doRedirect (request,
2345                                response,
2346                                session,
2347                                JSP_PATH + "menu.jsp");
2348                        return;
2349                    }
2350
2351                    siteKeysArr = request.getParameterValues ("sitesList");
2352                    selSiteKeys = new Vector JavaDoc ();
2353
2354                    if (siteKeysArr != null) {
2355                        for (int i = 0; i < siteKeysArr.length; i++) {
2356                            selSiteKeys.add (siteKeysArr[i]);
2357                        }
2358                    }
2359
2360                    session.setAttribute (CLASS_NAME + "selSiteKeys", selSiteKeys);
2361                    session.setAttribute (CLASS_NAME + "extractName", jahiaExtractName);
2362
2363                    if (selSiteKeys.size () == 0) {
2364                        String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.warningMsg.oneSiteMustSelected.label",
2365                                jParams, jParams.getLocale ());
2366                        session.setAttribute (CLASS_NAME + "jahiaDisplayMessage", dspMsg);
2367                        displayRestore (request, response, session);
2368                        return;
2369                    }
2370
2371                    if (Jahia.getCoreLicense () != null) {
2372                        int maxSite = Jahia.getSiteLimit ();
2373                        if (maxSite != -1) {
2374                            String JavaDoc s = "s";
2375                            if (maxSite == 1) {
2376                                s = "";
2377                            }
2378                            if (maxSite < selSiteKeys.size ()) {
2379                                String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.warningMsg.youCannotRestoreMoreThan.label",
2380                                        jParams, jParams.getLocale ());
2381                                dspMsg += " " + maxSite + " ";
2382                                dspMsg += JahiaResourceBundle.getAdminResource ("org.jahia.admin.warningMsg.sites.label",
2383                                        jParams, jParams.getLocale ());
2384                                dspMsg += " " + JahiaResourceBundle.getAdminResource ("org.jahia.admin.warningMsg.licenseLimitaion.label",
2385                                        jParams, jParams.getLocale ());
2386                                session.setAttribute (CLASS_NAME + "warningMsg", dspMsg);
2387                                displayRestore (request, response, session);
2388                                return;
2389                            }
2390                        }
2391                    }
2392
2393                    displayRestoreConfirmation (jahiaExtractName, request, response, session);
2394                    return;
2395
2396                }
2397
2398                // Got the confirmation so start restore
2399
// retrieve previous form values...
2400
selSiteKeys = (Vector JavaDoc)session.getAttribute (CLASS_NAME
2401                        + "selSiteKeys");
2402                jahiaExtractName = (String JavaDoc)session.getAttribute (CLASS_NAME
2403                        + "extractName");
2404
2405                if (selSiteKeys == null || jahiaExtractName == null) {
2406                    String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
2407                            jParams, jParams.getLocale ());
2408                    request.setAttribute ("jahiaDisplayMessage", dspMsg);
2409                    throw new JahiaException ("Error occured while processing your request",
2410                            CLASS_NAME + ": Data in session are not valid ",
2411                            JahiaException.ERROR_SEVERITY,
2412                            JahiaException.ERROR_SEVERITY);
2413                }
2414
2415                // init the extraction folder
2416
File JavaDoc extFolder = new File JavaDoc (composeExtractionFolder (jahiaExtractName));
2417                if (!extFolder.isDirectory ()) {
2418                    String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
2419                            jParams, jParams.getLocale ());
2420                    request.setAttribute ("jahiaDisplayMessage", dspMsg);
2421                    throw new JahiaException ("Error occured while processing your request",
2422                            CLASS_NAME + ": Cannot found extraction folder " + extFolder.getAbsolutePath (),
2423                            JahiaException.FILE_ERROR,
2424                            JahiaException.ERROR_SEVERITY);
2425                }
2426
2427                mSiteExtractionFolder = extFolder.getAbsolutePath ();
2428                extFolder = null;
2429
2430                boolean testBefore = ((request.getParameter ("testbefore")) != null);
2431                if (testBefore) {
2432                    // before any restore, perform a test on xml files
2433
boolean checkErr = false;
2434
2435                    try {
2436                        checkErr = !checkXmlData (jahiaExtractName, selSiteKeys);
2437                    } catch (Throwable JavaDoc t) {
2438                        checkErr = true;
2439                        t.printStackTrace ();
2440                    }
2441
2442                    if (checkErr) {
2443                        String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.warningMsg.restroreDataFailed.label",
2444                                jParams, jParams.getLocale ());
2445                        session.setAttribute (CLASS_NAME + "warningMsg", dspMsg);
2446                        displayRestoreConfirmation (jahiaExtractName, request, response, session);
2447                        return;
2448                    }
2449                }
2450
2451                // start restore here
2452
// start the chrono...
2453
long startTime = JahiaChrono.getInstance ().start ();
2454
2455                // change session time out to 1 hour ( the extraction can be very long !)
2456
int timeOut = session.getMaxInactiveInterval ();
2457                session.setMaxInactiveInterval (7200);
2458
2459                // empty db tables
2460
emptyJahiaDBTables ();
2461
2462                logger.debug ("start restore " + selSiteKeys.size () + " sites");
2463
2464
2465                // Restore the admin Info
2466
if (!restoreServerInfo (jahiaExtractName)) {
2467                    request.setAttribute ("siteExtDepMsg", "Restoring server information failed");
2468                    JahiaAdministration.doRedirect (request,
2469                            response,
2470                            session,
2471                            JSP_PATH + "extdep_restore_done.jsp");
2472                    return;
2473                }
2474
2475                try {
2476                    int size = selSiteKeys.size ();
2477
2478                    // FIRST RESTORE XML DATA TO DATABASE
2479
for (int i = 0; i < size; i++) {
2480                        String JavaDoc siteKey = (String JavaDoc)selSiteKeys.get (i);
2481                        if (!restoreSite (jahiaExtractName, siteKey)) {
2482                            String JavaDoc warningMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.siteExtDepMsg.restoringSite.label",
2483                                    jParams, jParams.getLocale ());
2484                            warningMsg += " " + siteKey + " ";
2485                            warningMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.siteExtDepMsg.failed.label",
2486                                    jParams, jParams.getLocale ());
2487                            request.setAttribute ("siteExtDepMsg", warningMsg);
2488                            JahiaAdministration.doRedirect (request,
2489                                    response,
2490                                    session,
2491                                    JSP_PATH + "extdep_restore_done.jsp");
2492                            return;
2493                        }
2494                    }
2495
2496                    // SECOND RESTORE EXTERNAL FILES
2497

2498                    boolean err = false;
2499                    for (int i = 0; i < size; i++) {
2500                        String JavaDoc siteKey = (String JavaDoc)selSiteKeys.get (i);
2501                        if (!restoreSiteExternalFile (jahiaExtractName, siteKey)) {
2502                            err = true;
2503                        }
2504                    }
2505
2506                    // SET THE DEFAULT SITE IN JAHIA PROPERTIES FILE
2507
// By default, get the first in the list
2508
setDefaultSite (selSiteKeys);
2509
2510
2511                    // NK, we do not free the lock.
2512
// Doing so, we force the admin to restart the server ! ugly isn't ?
2513
freeLock = false;
2514
2515
2516                    String JavaDoc warningMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.siteExtDepMsg.restoringExternalFilesDone.label",
2517                            jParams, jParams.getLocale ());
2518                    if (err) {
2519                        warningMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.siteExtDepMsg.restoringExternalFilesError.label",
2520                                jParams, jParams.getLocale ());
2521                    }
2522
2523                    request.setAttribute ("siteExtDepMsg", warningMsg);
2524                    JahiaAdministration.doRedirect (request,
2525                            response,
2526                            session,
2527                            JSP_PATH + "extdep_restore_done.jsp");
2528
2529                } catch (Throwable JavaDoc t) {
2530
2531                    logger.debug (" exception occured,\n");
2532                    //t.printStackTrace();
2533

2534                    String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource ("org.jahia.admin.warningMsg.extractingSitesError.label",
2535                            jParams, jParams.getLocale ());
2536                    session.setAttribute (CLASS_NAME + "warningMsg", dspMsg);
2537
2538                    displayChoice (request, response, session);
2539
2540                    // Restore at least Server Info
2541
// restoreServerInfo(jahiaExtractName);
2542
} finally {
2543                    // restore session time out
2544
session.setMaxInactiveInterval (timeOut);
2545                }
2546
2547                logger.debug ("restore time ["
2548                        + JahiaChrono.getInstance ().read (startTime) + "ms]");
2549
2550            } catch (Throwable JavaDoc t) {
2551                freeLock = true;
2552                t.printStackTrace ();
2553            } finally {
2554
2555                if (freeLock) {
2556                    Jahia.releaseLock (jahiaLock);
2557                }
2558            }
2559        }
2560    }
2561
2562
2563    /**
2564     * Try to read extracted xml data. On error, you should stop restoring anything
2565     *
2566     * @param extractName The extraction identifier.
2567     * @param siteKeys The vector of site keys identifying site to restore.
2568     * @return boolean true if xml data are read without error
2569     */

2570    private boolean checkXmlData (String JavaDoc extractName, Vector JavaDoc siteKeys)
2571            throws IOException JavaDoc, JahiaException {
2572
2573        logger.debug ("started");
2574
2575        /*
2576        // CHECK SERVER DATA
2577        StringBuffer path = new StringBuffer(mSiteExtractionFolder);
2578        path.append(File.separator);
2579        path.append(ExtDepSiteConstants.SERVER);
2580        path.append(File.separator);
2581        path.append(mXMLDOC);
2582        File f = new File(path.toString());
2583        if ( !f.isDirectory() ){
2584            return false;
2585        }
2586
2587        if ( !checkXmlData(f,ExtDepSiteConstants.getServerFiles()) ){
2588            return false;
2589        }
2590
2591        // CHECK SITE DATA
2592        int size = siteKeys.size();
2593        for ( int i=0 ; i<size ; i++ ){
2594            String siteKey = (String)siteKeys.get(i);
2595            path = new StringBuffer(mSiteExtractionFolder);
2596            path.append(File.separator);
2597            path.append(siteKey);
2598            path.append(File.separator);
2599            path.append(mXMLDOC);
2600            f = new File(path.toString());
2601            if ( !f.isDirectory() ){
2602                return false;
2603            }
2604            if ( !checkXmlData(f,ExtDepSiteConstants.getSiteFiles()) ){
2605                return false;
2606            }
2607        }
2608        */

2609        // FIXME : test each physical xml file because ExtDepSiteConstants.getSiteFiles() does not work with multiple users provider anymore
2610
return true;
2611    }
2612
2613
2614    /**
2615     * Try to read xml files.
2616     *
2617     * @param f the abstract file to the directory containing xml files
2618     * @param files the list of file names to read
2619     * @return boolean true if xml data are read without error
2620     */

2621    private boolean checkXmlData (File JavaDoc f, Enumeration JavaDoc files)
2622            throws IOException JavaDoc, JahiaException {
2623
2624        if (f == null || !f.isDirectory () || !f.canRead ()) {
2625            return false;
2626        }
2627
2628        String JavaDoc root = f.getAbsolutePath () + File.separator;
2629
2630        File JavaDoc fileItem = null;
2631        String JavaDoc fileName = "";
2632        DOM2DB dom2DB = null;
2633        while (files.hasMoreElements ()) {
2634            fileName = (String JavaDoc)files.nextElement ();
2635            fileItem = new File JavaDoc (root + fileName);
2636            if (!f.isFile () && !f.canRead ()) {
2637                logger.debug ("File " + fileItem.getAbsolutePath () + " not found");
2638                return false;
2639            }
2640            // the test consists to reading the xml file
2641
dom2DB = new DOM2DB (fileItem.getAbsolutePath ());
2642            dom2DB = null;
2643            logger.debug ("File " + fileItem.getAbsolutePath () + " read successfully");
2644
2645        }
2646        return true;
2647    }
2648
2649
2650    /**
2651     * Restore server info.
2652     *
2653     * @param extractName The extraction identifier.
2654     */

2655    private boolean restoreServerInfo (String JavaDoc extractName)
2656            throws IOException JavaDoc, JahiaException {
2657
2658        // RESTORE XML Documents
2659

2660        String JavaDoc tableName = null;
2661
2662        StringBuffer JavaDoc path = new StringBuffer JavaDoc (mSiteExtractionFolder);
2663        path.append (File.separator);
2664        path.append (ExtDepSiteConstants.SERVER);
2665        path.append (File.separator);
2666        path.append (mXMLDOC);
2667        File JavaDoc f = new File JavaDoc (path.toString ());
2668        if (!f.isDirectory ()) {
2669            return false;
2670        }
2671
2672        File JavaDoc[] files = f.listFiles ();
2673
2674        for (int i = 0; i < files.length; i++) {
2675            if (files[i].isFile ()) {
2676
2677                logger.debug ("found file"
2678                        + files[i].getAbsolutePath ());
2679
2680                if (files[i].getName ().endsWith (".xml")) {
2681                    DOM2DB dom2DB = new DOM2DB (files[i].getAbsolutePath ());
2682                    Enumeration JavaDoc tables = dom2DB.getTables ();
2683                    while (tables.hasMoreElements ()) {
2684                        Element JavaDoc table = (Element JavaDoc)tables.nextElement ();
2685
2686                        // clean the table before insert data
2687
tableName = XMLParser.getAttributeValue (table, "name");
2688
2689                        Connection JavaDoc dbConn = null;
2690                        Statement JavaDoc statement = null;
2691
2692                        try {
2693
2694                            dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
2695                            statement = dbConn.createStatement ();
2696                            if (statement != null) {
2697                                DOM2DB.sqlInsert (table, statement);
2698                            }
2699                        } catch (SQLException JavaDoc se) {
2700                            String JavaDoc errorMsg = "Error in "
2701                                    + CLASS_NAME + ".restoreServerInfo " + se.getMessage ();
2702                            logger.error (se);
2703                            throw new JahiaException ("Database Error",
2704                                    errorMsg, JahiaException.DATABASE_ERROR,
2705                                    JahiaException.CRITICAL_SEVERITY);
2706                        } finally {
2707
2708                            closeStatement (statement);
2709                        }
2710
2711                    }
2712                }
2713            }
2714        }
2715
2716        return true;
2717    }
2718
2719
2720    protected class ACLDataFilter implements DBRowDataFilter {
2721
2722        private Vector JavaDoc vals = new Vector JavaDoc ();
2723
2724        public boolean inValue (Hashtable JavaDoc vals) {
2725            StringBuffer JavaDoc val = new StringBuffer JavaDoc ((String JavaDoc)vals.get ("id_jahia_acl"));
2726            val.append ("_");
2727            val.append ((String JavaDoc)vals.get ("parent_id_jahia_acl"));
2728
2729            if (!this.vals.contains (val.toString ())) {
2730                this.vals.add (val.toString ());
2731                return true;
2732            }
2733            return false;
2734        }
2735
2736    }
2737
2738
2739    /**
2740     * Restore a site .
2741     * @param extractName The extraction identifier.
2742     * @param siteKey The site to extract.
2743     */

2744    private boolean restoreSite (String JavaDoc extractName, String JavaDoc siteKey)
2745            throws IOException JavaDoc, JahiaException {
2746
2747        // RESTORE XML Documents
2748

2749        String JavaDoc tableName = null;
2750        StringBuffer JavaDoc path = new StringBuffer JavaDoc (mSiteExtractionFolder);
2751        path.append (File.separator);
2752        path.append (siteKey);
2753        path.append (File.separator);
2754        path.append (mXMLDOC);
2755        File JavaDoc f = new File JavaDoc (path.toString ());
2756        if (!f.isDirectory ()) {
2757            return false;
2758        }
2759
2760        File JavaDoc[] files = f.listFiles ();
2761        for (int i = 0; i < files.length; i++) {
2762            if (files[i].isFile ()) {
2763
2764                /*
2765                JahiaConsole.println(CLASS_NAME+".restoreSite","found file"
2766                + files[i].getAbsolutePath());
2767                */

2768
2769                if (files[i].getName ().endsWith (".xml")) {
2770                    DOM2DB dom2DB = new DOM2DB (files[i].getAbsolutePath ());
2771                    Enumeration JavaDoc tables = dom2DB.getTables ();
2772                    while (tables.hasMoreElements ()) {
2773                        Element JavaDoc table = (Element JavaDoc)tables.nextElement ();
2774
2775                        tableName = XMLParser.getAttributeValue (table, "name");
2776
2777                        Connection JavaDoc dbConn = null;
2778                        Statement JavaDoc statement = null;
2779
2780                        try {
2781
2782                            dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
2783                            statement = dbConn.createStatement ();
2784                            if (statement != null) {
2785                                if (tableName.equals ("jahia_acl")) {
2786                                    DOM2DB.sqlInsert (table, statement, aclFilter);
2787                                } else {
2788                                    DOM2DB.sqlInsert (table, statement);
2789                                }
2790                            }
2791                        } catch (SQLException JavaDoc se) {
2792                            String JavaDoc errorMsg = "Error in "
2793                                    + CLASS_NAME + ".restoreSite " + se.getMessage ();
2794                            logger.error (se);
2795                            throw new JahiaException ("Database Error",
2796                                    errorMsg, JahiaException.DATABASE_ERROR,
2797                                    JahiaException.CRITICAL_SEVERITY);
2798                        } finally {
2799
2800                            closeStatement (statement);
2801                        }
2802                    }
2803                }
2804            }
2805        }
2806
2807        return true;
2808    }
2809
2810
2811    /**
2812     * Restore a site external files.
2813     *
2814     * @param extractName The extraction identifier.
2815     * @param siteKey The site to extract.
2816     */

2817    private boolean restoreSiteExternalFile (String JavaDoc extractName, String JavaDoc siteKey)
2818            throws IOException JavaDoc, JahiaException {
2819
2820        // RESTORE TEMPLATES
2821
if (!restoreTemplates (siteKey)) {
2822            return false;
2823        }
2824
2825        // RESTORE BIG TEXT
2826
if (!restoreBigText (siteKey)) {
2827            return false;
2828        }
2829
2830        // RESTORE SEARCH INDEX
2831
//restoreSearchIndex (siteKey);
2832

2833
2834        // RESTORE FILES
2835
if (!restoreFiles (siteKey)) {
2836            return false;
2837        }
2838
2839
2840        // RESTORE NEW WEBAPPS
2841
if (!restoreNewWebApps (siteKey)) {
2842            return false;
2843        }
2844
2845        // RESTORE NEW TEMPLATES
2846
if (!restoreNewTemplates (siteKey)) {
2847            return false;
2848        }
2849
2850        // RESTORE XML PORTLETS
2851
if (!restoreXmlPortletFiles (siteKey)) {
2852            return false;
2853        }
2854
2855        // RESTORE TOMCAT APPLICATION
2856
if (mServerType.startsWith (JahiaConstants.SERVER_TOMCAT)) {
2857            if (!restoreTomcatApplications (siteKey)) {
2858                throw new JahiaException ("Error occured while processing your request",
2859                        CLASS_NAME + ": Error restoring applications",
2860                        JahiaException.FILE_ERROR,
2861                        JahiaException.ERROR_SEVERITY);
2862            }
2863        }
2864
2865        return true;
2866    }
2867
2868
2869    /**
2870     * Restore Big Text for a gived Site
2871     *
2872     * @param siteKey the site identifier.
2873     * @return false on error
2874     */

2875    private boolean restoreBigText (String JavaDoc siteKey)
2876            throws JahiaException {
2877
2878        logger.debug ("For site " + siteKey);
2879
2880        JahiaTextFileService fileServ = sReg.getJahiaTextFileService ();
2881
2882        if (siteKey == null || siteKey.trim ().equals ("") || fileServ == null) {
2883            return false;
2884        }
2885
2886        // extracted data
2887
File JavaDoc src = new File JavaDoc (mSiteExtractionFolder
2888                + File.separator
2889                + siteKey
2890                + File.separator
2891                + mDATA);
2892
2893        // destination directory
2894
StringBuffer JavaDoc buff = new StringBuffer JavaDoc (
2895                properties.getProperty ("jahiaVarDiskPath").trim ());
2896        buff.append (File.separator);
2897        buff.append (mCONTENT);
2898        buff.append (File.separator);
2899        buff.append (mCONTENT_BIGTEXT);
2900
2901        File JavaDoc dest = new File JavaDoc (JahiaTools.convertContexted (buff.toString (), pathResolver));
2902        if (!dest.isDirectory ()) {
2903            if (!dest.mkdirs ()) {
2904                throw new JahiaException ("Error occured while processing your request",
2905                        CLASS_NAME + ": Error creating Big Text Folder",
2906                        JahiaException.FILE_ERROR,
2907                        JahiaException.ERROR_SEVERITY);
2908            }
2909        }
2910
2911        try {
2912            JahiaTools.copyFolderContent (src.getAbsolutePath (), dest.getAbsolutePath ());
2913        } catch (IOException JavaDoc ioe) {
2914            return false;
2915        }
2916
2917        return true;
2918    }
2919
2920    /**
2921     * Restore Search indexes for a gived Site
2922     *
2923     * @param siteKey the site identifier.
2924     * @return false on error
2925     */

2926    private boolean restoreSearchIndex (String JavaDoc siteKey)
2927            throws JahiaException {
2928
2929        logger.debug ("For site " + siteKey);
2930
2931        if (siteKey == null || siteKey.trim ().equals ("")) {
2932            return false;
2933        }
2934
2935        JahiaSearchService searchServ = ServicesRegistry.getInstance ().getJahiaSearchService ();
2936        if (searchServ == null) {
2937            return false;
2938        }
2939        String JavaDoc searchIndexRootDir = searchServ.getSearchIndexRootDir ();
2940        if (searchIndexRootDir == null) {
2941            return false;
2942        }
2943        File JavaDoc f = null;
2944        f = new File JavaDoc (searchIndexRootDir + File.separator + siteKey);
2945        f.mkdirs ();
2946
2947        if (!f.isDirectory () || !f.canWrite ()) {
2948            return false;
2949        }
2950
2951        JahiaTools.deleteFile (f);
2952
2953        StringBuffer JavaDoc buff = new StringBuffer JavaDoc (mSiteExtractionFolder);
2954        buff.append (File.separator);
2955        buff.append (siteKey);
2956        buff.append (File.separator);
2957        buff.append (mSEARCHINDEX);
2958        buff.append (File.separator);
2959        buff.append (siteKey);
2960
2961        try {
2962            JahiaTools.copyFolderContent (buff.toString (), f.getAbsolutePath ());
2963        } catch (IOException JavaDoc ioe) {
2964            throw new JahiaException ("Error occured while processing your request",
2965                    CLASS_NAME + ": Exception while copying files from "
2966                    + buff.toString () + " to " + f.getAbsolutePath (),
2967                    JahiaException.FILE_ERROR,
2968                    JahiaException.ERROR_SEVERITY);
2969        }
2970        f = null;
2971        return true;
2972    }
2973
2974    /**
2975     * Restore Files for a gived Site
2976     *
2977     * @param siteKey the site identifier.
2978     * @return false on error
2979     */

2980    private boolean restoreFiles (String JavaDoc siteKey)
2981            throws JahiaException {
2982
2983        logger.debug ("For site " + siteKey);
2984
2985        if (siteKey == null || siteKey.trim ().equals ("")) {
2986            return false;
2987        }
2988
2989        File JavaDoc f = null;
2990        f = new File JavaDoc (mFilemanagerFullPath + File.separator + siteKey);
2991        f.mkdirs ();
2992
2993        if (!f.isDirectory () || !f.canWrite ()) {
2994            return false;
2995        }
2996
2997        JahiaTools.deleteFile (f);
2998
2999        StringBuffer JavaDoc buff = new StringBuffer JavaDoc (mSiteExtractionFolder);
3000        buff.append (File.separator);
3001        buff.append (siteKey);
3002        buff.append (File.separator);
3003        buff.append (mFILEMANAGER);
3004
3005        try {
3006            JahiaTools.copyFolderContent (buff.toString (), mFilemanagerFullPath);
3007        } catch (IOException JavaDoc ioe) {
3008            throw new JahiaException ("Error occured while processing your request",
3009                    CLASS_NAME + ": Exception while copying files from "
3010                    + buff.toString () + " to " + f.getAbsolutePath (),
3011                    JahiaException.FILE_ERROR,
3012                    JahiaException.ERROR_SEVERITY);
3013        }
3014        f = null;
3015        return true;
3016    }
3017
3018
3019    /**
3020     * Restore a site's applications for Tomcat server.
3021     *
3022     * @param siteKey the site identifier.
3023     * @return false on error
3024     */

3025    private boolean restoreTomcatApplications (String JavaDoc siteKey)
3026            throws JahiaException {
3027
3028        logger.debug ("For site " + siteKey);
3029        JahiaApplicationsManagerService appServ =
3030                sReg.getJahiaApplicationsManagerService ();
3031
3032        if (siteKey == null || siteKey.trim ().equals ("") || appServ == null) {
3033            return false;
3034        }
3035
3036        String JavaDoc serverPath = properties.getProperty ("serverHomeDiskPath").trim ();
3037        if ((serverPath == null) || serverPath.equals ("")) {
3038            return false;
3039        }
3040
3041        File JavaDoc f = new File JavaDoc (serverPath + mTOMCATWEBAPPS);
3042        if (!f.isDirectory () || !f.canWrite ()) {
3043            return false;
3044        }
3045        f = null;
3046
3047        StringBuffer JavaDoc buff = new StringBuffer JavaDoc (mSiteExtractionFolder);
3048        buff.append (File.separator);
3049        buff.append (siteKey);
3050        buff.append (File.separator);
3051        buff.append (mAPPS);
3052
3053        String JavaDoc appsExtractFolder = buff.toString ();
3054        String JavaDoc tomcatWebAppsFolder = serverPath + mTOMCATWEBAPPS + File.separator;
3055
3056        f = new File JavaDoc (buff.toString ());
3057        if (!f.isDirectory ()) {
3058            return true; // nothing to restore
3059
}
3060
3061        try {
3062            // get the list of applications
3063
File JavaDoc[] files = f.listFiles ();
3064            File JavaDoc dest = null;
3065            for (int i = 0; i < files.length; i++) {
3066                if (files[i].isDirectory ()) {
3067                    // create the app context
3068
dest = new File JavaDoc (tomcatWebAppsFolder + files[i].getName ());
3069                    if (dest.isDirectory () && !dest.canWrite ()) {
3070                        return false;
3071                    }
3072                    if (dest.isDirectory ()) {
3073                        JahiaTools.deleteFile (dest);
3074                    }
3075                    dest.mkdirs ();
3076                    if (!dest.isDirectory ()) {
3077                        return false;
3078                    }
3079                    JahiaTools.copyFolderContent (files[i].getAbsolutePath (),
3080                            dest.getAbsolutePath ());
3081                }
3082            }
3083        } catch (IOException JavaDoc ioe) {
3084            logger.debug (" Exception occured while restoring the webapps " + ioe.toString ());
3085            return false;
3086        }
3087
3088        return true;
3089    }
3090
3091
3092    /**
3093     * Restore a site's JSP Template files.
3094     *
3095     * @param siteKey the site identifier.
3096     * @return false on error
3097     */

3098    private boolean restoreTemplates (String JavaDoc siteKey)
3099            throws JahiaException {
3100
3101        logger.debug ("For site " + siteKey);
3102        JahiaTemplatesDeployerService templateServ =
3103                sReg.getJahiaTemplatesDeployerService ();
3104
3105        if (siteKey == null || siteKey.trim ().equals ("") || templateServ == null) {
3106            return false;
3107        }
3108
3109        String JavaDoc templateRootPath = templateServ.getTemplateRootPath ();
3110        if (templateRootPath == null || templateRootPath.trim ().equals ("")) {
3111            return false;
3112        }
3113
3114        StringBuffer JavaDoc buff = new StringBuffer JavaDoc (mSiteExtractionFolder);
3115        buff.append (File.separator);
3116        buff.append (siteKey);
3117        buff.append (File.separator);
3118        buff.append (mTEMPLATES);
3119        String JavaDoc templatesExtractFolder = buff.toString ();
3120
3121
3122        try {
3123            JahiaTools.copyFolderContent (templatesExtractFolder,
3124                    templateRootPath);
3125        } catch (IOException JavaDoc ioe) {
3126            throw new JahiaException ("Error occured while processing your request",
3127                    CLASS_NAME + ": Exception while copying templates "
3128                    + templateRootPath + File.separator + siteKey,
3129                    JahiaException.FILE_ERROR,
3130                    JahiaException.ERROR_SEVERITY);
3131        }
3132
3133        return true;
3134    }
3135
3136
3137    /**
3138     * Restore a site's new webapps folder.
3139     *
3140     * @param siteKey the site identifier.
3141     * @return false on error
3142     */

3143    private boolean restoreNewWebApps (String JavaDoc siteKey)
3144            throws JahiaException {
3145
3146        logger.debug ("For site " + siteKey);
3147
3148        if (siteKey == null || siteKey.trim ().equals ("")) {
3149            return false;
3150        }
3151
3152        // get the new web apps folder for this site
3153
if (properties.getProperty ("jahiaNewWebAppsDiskPath") == null) {
3154            return false;
3155        }
3156        String JavaDoc destPath = JahiaTools.convertContexted (properties.getProperty ("jahiaNewWebAppsDiskPath").trim (), pathResolver);
3157        File JavaDoc dest = new File JavaDoc (destPath);
3158
3159        // get the src extraction folder for new web apps
3160
StringBuffer JavaDoc buff = new StringBuffer JavaDoc (mSiteExtractionFolder);
3161        buff.append (File.separator);
3162        buff.append (siteKey);
3163        buff.append (File.separator);
3164        buff.append (mNEW_WEBAPPS);
3165
3166        File JavaDoc src = null;
3167        try {
3168            src = new File JavaDoc (buff.toString ());
3169            JahiaTools.copyFolderContent (src.getAbsolutePath (),
3170                    dest.getAbsolutePath ());
3171
3172        } catch (IOException JavaDoc ioe) {
3173            throw new JahiaException ("Error occured while processing your request",
3174                    CLASS_NAME + ": Exception while restoring new webapps "
3175                    + src.getAbsolutePath (),
3176                    JahiaException.FILE_ERROR,
3177                    JahiaException.ERROR_SEVERITY);
3178        } finally {
3179            src = null;
3180            dest = null;
3181        }
3182
3183        return true;
3184    }
3185
3186
3187    /**
3188     * Restore a site's new template folder.
3189     *
3190     * @param siteKey the site identifier.
3191     * @return false on error
3192     */

3193    private boolean restoreNewTemplates (String JavaDoc siteKey)
3194            throws JahiaException {
3195
3196        logger.debug ("For site " + siteKey);
3197
3198        if (siteKey == null || siteKey.trim ().equals ("")) {
3199            return false;
3200        }
3201
3202        // get the new web apps folder for this site
3203
if (properties.getProperty ("jahiaNewTemplatesDiskPath") == null) {
3204            return false;
3205        }
3206        String JavaDoc destPath = JahiaTools.convertContexted (properties.getProperty ("jahiaNewTemplatesDiskPath").trim (), pathResolver);
3207        File JavaDoc dest = new File JavaDoc (destPath);
3208
3209        // get the src extraction folder for new web apps
3210
StringBuffer JavaDoc buff = new StringBuffer JavaDoc (mSiteExtractionFolder);
3211        buff.append (File.separator);
3212        buff.append (siteKey);
3213        buff.append (File.separator);
3214        buff.append (mNEW_TEMPLATES);
3215
3216        File JavaDoc src = null;
3217        try {
3218            src = new File JavaDoc (buff.toString ());
3219            JahiaTools.copyFolderContent (src.getAbsolutePath (),
3220                    dest.getAbsolutePath ());
3221
3222        } catch (IOException JavaDoc ioe) {
3223            throw new JahiaException ("Error occured while processing your request",
3224                    CLASS_NAME + ": Exception while restoring new templates "
3225                    + src.getAbsolutePath (),
3226                    JahiaException.FILE_ERROR,
3227                    JahiaException.ERROR_SEVERITY);
3228        } finally {
3229            src = null;
3230            dest = null;
3231        }
3232
3233        return true;
3234    }
3235
3236
3237    /**
3238     * Restore a site's XML Portlets files.
3239     *
3240     * @param siteKey the site identifier.
3241     * @return false on error
3242     */

3243    private boolean restoreXmlPortletFiles (String JavaDoc siteKey)
3244            throws JahiaException {
3245
3246        logger.debug ("For site " + siteKey);
3247
3248        if (siteKey == null || siteKey.trim ().equals ("")) {
3249            return false;
3250        }
3251
3252        StringBuffer JavaDoc buff =
3253                new StringBuffer JavaDoc (properties.getProperty ("jahiaVarDiskPath").trim ());
3254        buff.append (File.separator);
3255        buff.append ("templates");
3256        File JavaDoc f = new File JavaDoc (JahiaTools.convertContexted (buff.toString (), pathResolver));
3257        if (!f.isDirectory ()) {
3258            f.mkdirs ();
3259        }
3260        if (!f.isDirectory () || !f.canWrite ()) {
3261            return false;
3262        }
3263
3264        buff = new StringBuffer JavaDoc (mSiteExtractionFolder);
3265        buff.append (File.separator);
3266        buff.append (siteKey);
3267        buff.append (File.separator);
3268        buff.append (mXMLPORTLETS);
3269
3270        String JavaDoc templatesExtractFolder = buff.toString ();
3271
3272        try {
3273            JahiaTools.copyFolderContent (templatesExtractFolder,
3274                    f.getAbsolutePath ());
3275        } catch (IOException JavaDoc ioe) {
3276            throw new JahiaException ("Error occured while processing your request",
3277                    CLASS_NAME + ": Exception while copying xml portlets files "
3278                    + templatesExtractFolder,
3279                    JahiaException.FILE_ERROR,
3280                    JahiaException.ERROR_SEVERITY);
3281        }
3282
3283        return true;
3284    }
3285
3286    /**
3287     * Order a vector of extraction by date.
3288     *
3289     * @param vec the original vector.
3290     * @return Vector the ordered vector.
3291     */

3292    private Vector JavaDoc orderExtraction (Vector JavaDoc vec) {
3293
3294        if (vec.size () <= 1) {
3295            return vec;
3296        }
3297
3298        Vector JavaDoc ordered = new Vector JavaDoc ();
3299        SiteExtractionBean seBean = null;
3300        SiteExtractionBean seBean2 = null;
3301        int size = vec.size ();
3302        boolean greater = false;
3303        for (int i = 0; i < size; i++) {
3304            seBean = (SiteExtractionBean)vec.get (i);
3305            int size2 = ordered.size ();
3306            greater = false;
3307            for (int j = 0; j < size2; j++) {
3308                seBean2 = (SiteExtractionBean)ordered.get (j);
3309                if (seBean.getDate () > seBean2.getDate ()) {
3310                    ordered.insertElementAt (seBean, j);
3311                    greater = true;
3312                    break;
3313                }
3314            }
3315            if (!greater) {
3316                ordered.add (seBean);
3317            }
3318        }
3319        return ordered;
3320    }
3321
3322
3323    /**
3324     * Delete anything in a DB Table.
3325     *
3326     * @param tableName
3327     */

3328    private void flushDBTable (String JavaDoc tableName)
3329            throws JahiaException {
3330
3331        Connection JavaDoc dbConn = null;
3332        Statement JavaDoc statement = null;
3333
3334        try {
3335
3336            dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
3337            statement = dbConn.createStatement ();
3338            statement.executeUpdate ("DELETE FROM " + tableName);
3339            logger.debug (" delete from table " + tableName);
3340        } catch (SQLException JavaDoc se) {
3341            String JavaDoc errorMsg = "Error in " + CLASS_NAME + ".flushDBTable " + se.getMessage ();
3342            logger.error (se);
3343            throw new JahiaException ("Database Error",
3344                    errorMsg, JahiaException.DATABASE_ERROR,
3345                    JahiaException.CRITICAL_SEVERITY);
3346        } finally {
3347
3348            closeStatement (statement);
3349        }
3350    }
3351
3352    /**
3353     * empty Jahia db tables of contents.
3354     *
3355     * @exception Exception an exception occured during the process.
3356     */

3357    private void emptyJahiaDBTables ()
3358            throws JahiaException, Exception JavaDoc {
3359        File JavaDoc object = null;
3360        Enumeration JavaDoc runtime = null;
3361        String JavaDoc line = null;
3362
3363        // set the server type
3364
if (properties == null || properties.getProperty ("db_script") == null) {
3365            throw new JahiaException ("Error occured while processing your request",
3366                    CLASS_NAME + ": Cannot retrieve database script properties from jahia properties file",
3367                    JahiaException.CONFIG_ERROR,
3368                    JahiaException.ERROR_SEVERITY);
3369        }
3370
3371
3372        // construct script path...
3373
DatabaseScripts scripts = new DatabaseScripts ();
3374
3375        String JavaDoc dbScriptsPath = Jahia.jahiaDatabaseScriptsPath;
3376
3377        StringBuffer JavaDoc script = new StringBuffer JavaDoc (dbScriptsPath);
3378        script.append (File.separator);
3379        script.append ((properties.getProperty ("db_script")).trim ());
3380
3381        logger.debug (script.toString ());
3382        // get script runtime...
3383
try {
3384            object = new File JavaDoc (script.toString ());
3385            runtime = scripts.getDatabaseScriptsRuntime (object);
3386        } catch (Exception JavaDoc e) {
3387            throw new Exception JavaDoc ("Jahia can't read the appropriate database script.");
3388        }
3389
3390        // drop each tables (if present) and (re-)create it after...
3391
while (runtime.hasMoreElements ()) {
3392            line = (String JavaDoc)runtime.nextElement ();
3393            try {
3394                flushDBTable (line.substring (line.indexOf ("jahia_"), line.indexOf ("(")).trim ());
3395            } catch (Exception JavaDoc e) {
3396                // nothing to do...... i don't care if the drop doesn't work.
3397
}
3398        }
3399
3400        // force objects to garbage collector...
3401
object = null;
3402        script = null;
3403        runtime = null;
3404        line = null;
3405    }
3406
3407
3408    /**
3409     * Flush an extraction.
3410     *
3411     * @param request Servlet request.
3412     * @param response Servlet response.
3413     * @param session Servlet session for the current user.
3414     */

3415    private void processFlush (HttpServletRequest JavaDoc request,
3416                               HttpServletResponse JavaDoc response,
3417                               HttpSession JavaDoc session)
3418            throws IOException JavaDoc, ServletException JavaDoc {
3419
3420        synchronized (mLock) {
3421
3422            logger.debug ("started");
3423
3424            String JavaDoc extractName = request.getParameter ("name");
3425
3426            if (extractName == null || extractName.trim ().equals ("")) {
3427                displayManageExtractions (request, response, session);
3428                return;
3429            }
3430
3431
3432            String JavaDoc confirmflush = request.getParameter ("confirmflush");
3433            if (confirmflush != null && confirmflush.equals ("yes")) {
3434
3435                StringBuffer JavaDoc buff = new StringBuffer JavaDoc (mERFFullPath);
3436                buff.append (File.separator);
3437                buff.append (extractName);
3438                File JavaDoc f = new File JavaDoc (buff.toString ());
3439
3440                File JavaDoc descrFile = new File JavaDoc (f.getAbsolutePath () + File.separator + ExtDepSiteConstants.DESCRFILE);
3441                descrFile.delete ();
3442                descrFile = null;
3443                JahiaTools.deleteFile (f);
3444
3445                request.setAttribute ("flushDone", new Boolean JavaDoc (true));
3446                JahiaAdministration.doRedirect (request, response, session,
3447                        JSP_PATH + "extdep_site_flush.jsp");
3448                return;
3449
3450            } else {
3451
3452                StringBuffer JavaDoc buff = new StringBuffer JavaDoc (mERFFullPath);
3453                buff.append (File.separator);
3454                buff.append (extractName);
3455                buff.append (File.separator);
3456                buff.append (ExtDepSiteConstants.DESCRFILE);
3457                File JavaDoc f = new File JavaDoc (buff.toString ());
3458                if (!f.isFile ()) {
3459                    displayManageExtractions (request, response, session);
3460                    return;
3461                }
3462
3463                try {
3464                    SiteExtractionBean seBean = new SiteExtractionBean (f.getAbsolutePath ());
3465
3466                    f = null;
3467                    request.setAttribute ("flushDone", new Boolean JavaDoc (false));
3468                    request.setAttribute ("extractionProps", seBean);
3469                    // forward to JSP
3470
JahiaAdministration.doRedirect (request, response, session,
3471                            JSP_PATH + "extdep_site_flush.jsp");
3472                } catch (Throwable JavaDoc t) {
3473                    JahiaAdministration.doRedirect (request, response, session,
3474                            JSP_PATH + "extdep_site_manage.jsp");
3475                }
3476
3477            }
3478        }
3479    }
3480
3481
3482    /**
3483     * Returns the extraction folder for a gived Extract Name
3484     *
3485     * @param extractName the extraction folder.
3486     */

3487    private String JavaDoc composeExtractionFolder (String JavaDoc extractName) {
3488        logger.debug (" path ="
3489                + mERFFullPath + File.separator + extractName);
3490        return (mERFFullPath + File.separator + extractName);
3491    }
3492
3493
3494    /**
3495     * Check if the extraction name is already used or not.
3496     * The folder used to hold extracted data is the same as the extraction name
3497     * choosed by the user
3498     *
3499     * @param extractName
3500     */

3501    private boolean checkExtractionFolder (String JavaDoc extractName)
3502            throws IOException JavaDoc {
3503        File JavaDoc f = new File JavaDoc (composeExtractionFolder (extractName) + File.separator + ExtDepSiteConstants.DESCRFILE);
3504        logger.debug (" path ="
3505                + f.getAbsolutePath ());
3506        return (f.isFile ());
3507    }
3508
3509
3510    /**
3511     * Create the extraction folder for a site.
3512     *
3513     * @param extractName
3514     * @return File the extraction folder abstract File
3515     */

3516    private File JavaDoc createExtractionFolder (String JavaDoc extractName)
3517            throws IOException JavaDoc {
3518        File JavaDoc f = new File JavaDoc (composeExtractionFolder (extractName));
3519        f.mkdirs ();
3520        JahiaTools.deleteFile (f, true);
3521        return (f);
3522    }
3523
3524
3525    /**
3526     * Create a folder in the current sites extraction folder.
3527     *
3528     * @param subDir the sub directory name.
3529     * @return File the sub dir abstract File
3530     */

3531    private File JavaDoc createSubExtractionFolder (String JavaDoc subDir)
3532            throws IOException JavaDoc {
3533        File JavaDoc f = new File JavaDoc (mSiteExtractionFolder + File.separator + subDir);
3534        f.mkdirs ();
3535        return (f);
3536    }
3537
3538
3539    /**
3540     * If the current default site is not set or not found in the site keys list,
3541     * Change the default site to the first in the list
3542     *
3543     * @param siteKeys a vector of site keys
3544     */

3545    private void setDefaultSite (Vector JavaDoc siteKeys) {
3546
3547        if (siteKeys == null || siteKeys.size () == 0) {
3548            return;
3549        }
3550
3551        String JavaDoc siteKey = properties.getProperty ("defautSite");
3552
3553        if (siteKey == null || siteKey.trim ().equals ("")) {
3554            properties.setProperty ("defautSite", (String JavaDoc)siteKeys.get (0));
3555            properties.storeProperties ();
3556            return;
3557        }
3558
3559        int size = 0;
3560        String JavaDoc s = null;
3561        for (int i = 0; i < size; i++) {
3562            s = (String JavaDoc)siteKeys.get (i);
3563            if (s.equals (siteKey)) {
3564                // does not change the default site
3565
return;
3566            }
3567        }
3568
3569        properties.setProperty ("defautSite", (String JavaDoc)siteKeys.get (0));
3570        properties.storeProperties ();
3571        return;
3572
3573    }
3574
3575
3576    /**
3577     * Store a DOM Document in a file.
3578     *
3579     * @param dom the DOM Object.
3580     * @param destFolder the destination folder.
3581     * @param filename the filename.
3582     */

3583    private void saveDOMDocument (JahiaDOMObject dom,
3584                                  File JavaDoc destFolder,
3585                                  String JavaDoc filename)
3586            throws IOException JavaDoc, JahiaException {
3587        if (dom != null) {
3588            File JavaDoc f = new File JavaDoc (destFolder.getAbsolutePath ()
3589                    + File.separator
3590                    + filename);
3591            f.createNewFile ();
3592            dom.save (f.getAbsolutePath ());
3593            f = null;
3594        }
3595    }
3596
3597
3598    /**
3599     * Merge two vector of Integer. Add the ids from the second vector to the first vector
3600     * only if its value is not in the first Vector .
3601     *
3602     * @param result , the vector to add new Integer from the second vector
3603     * @param v
3604     */

3605    private void addNewIDs (Vector JavaDoc result, Vector JavaDoc v) {
3606
3607        int size = result.size ();
3608        int size2 = v.size ();
3609        Integer JavaDoc I = null;
3610        Integer JavaDoc J = null;
3611        boolean isNew = true;
3612        for (int i = 0; i < size2; i++) {
3613            isNew = true;
3614            I = (Integer JavaDoc)v.get (i);
3615            for (int j = 0; j < size; j++) {
3616                J = (Integer JavaDoc)result.get (j);
3617                if (I.intValue () == J.intValue ()) {
3618                    isNew = false;
3619                    break;
3620                }
3621            }
3622            if (isNew) {
3623                result.add (I);
3624                size = result.size ();
3625            }
3626        }
3627    }
3628
3629
3630    /**
3631     * Check if the String extract name is valid.
3632     */

3633    private static boolean isExtractNameValid (String JavaDoc name) {
3634
3635        if (name.startsWith (" ")) {
3636            return false;
3637        }
3638
3639        if (name == null) {
3640            return false;
3641        }
3642        if (name.length () == 0) {
3643            return false;
3644        }
3645
3646        String JavaDoc authorizedCharacters =
3647                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789";
3648        char[] chars = authorizedCharacters.toCharArray ();
3649        char[] nameBuffer = name.toCharArray ();
3650
3651        boolean badCharFound = false;
3652        int i = 0;
3653        while ((i < nameBuffer.length) && (!badCharFound)) {
3654            int j = 0;
3655            boolean ok = false;
3656            while ((j < chars.length) && (!ok)) {
3657                if (chars[j] == nameBuffer[i]) {
3658                    ok = true;
3659                }
3660                j++;
3661            }
3662            badCharFound = (!ok);
3663            if (badCharFound) {
3664                logger.debug ("--/ Bad character found in ["
3665                        + name + "] at position " + Integer.toString (i));
3666            }
3667            i++;
3668        }
3669        return (!badCharFound);
3670    }
3671
3672    private void closeStatement (Statement JavaDoc statement) {
3673        // Close the opened statement
3674
try {
3675            if (statement != null) {
3676                statement.close ();
3677            }
3678        } catch (SQLException JavaDoc sqlEx) {
3679            // just create an exception without raising it, just to notify it
3680
// in the logs.
3681
JahiaException je = new JahiaException ("Cannot close a statement",
3682                    "Cannot close a statement", JahiaException.DATABASE_ERROR,
3683                    JahiaException.WARNING_SEVERITY, sqlEx);
3684            logger.error ("Error:", je);
3685        }
3686    }
3687
3688
3689}
3690
Popular Tags