KickJava   Java API By Example, From Geeks To Geeks.

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


1 // $Id: ManageSites.java 16441 2007-02-14 16:47:18Z 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
// ManageSites
15
//
16
// 02.04.2001 MJ added in jahia.
17
// 19.04.2001 AK multisite first steps.
18
// 20.04.2001 AK change selection way for re-use existant administrator.
19
// 21.04.2001 AK complete add a site capability.
20
// 22.04.2001 AK edit a site and delete a site capabilities.
21
// 27.04.2001 NK added default site handling.
22
// 02.05.2001 NK added templates, applications, users, files repository
23
// full deletion from disk and db storage when deleting a whole site
24
// 04.05.2001 NK Can delete all sites, no server site anymore
25
// 16.05.2001 NK Handle special case when the current site is deleted -> need session synchronisation.
26
// 16.05.2001 NK Integrate License Check.
27
// 23.05.2001 NK Add Site reminder previous data by storing temporaty new site in session allowing
28
// GO BACK to the previous screen.
29
// 27.09.2001 NK Add Site , added template set choice step
30
//
31

32 package org.jahia.admin.sites;
33
34 import java.io.File JavaDoc;
35 import java.io.IOException JavaDoc;
36 import java.util.ArrayList JavaDoc;
37 import java.util.Enumeration JavaDoc;
38 import java.util.HashMap JavaDoc;
39 import java.util.Locale JavaDoc;
40 import java.util.Properties JavaDoc;
41 import java.util.Vector JavaDoc;
42
43 import javax.servlet.ServletContext JavaDoc;
44 import javax.servlet.ServletException JavaDoc;
45 import javax.servlet.http.HttpServletRequest JavaDoc;
46 import javax.servlet.http.HttpServletResponse JavaDoc;
47 import javax.servlet.http.HttpSession JavaDoc;
48
49 import org.jahia.bin.Jahia;
50 import org.jahia.bin.JahiaAdministration;
51 import org.jahia.data.JahiaData;
52 import org.jahia.data.templates.JahiaTemplateDef;
53 import org.jahia.data.templates.JahiaTemplatesPackage;
54 import org.jahia.exceptions.JahiaException;
55 import org.jahia.params.ParamBean;
56 import org.jahia.registries.ServicesRegistry;
57 import org.jahia.registries.SharedTemplatePackagesRegistry;
58 import org.jahia.resourcebundle.JahiaResourceBundle;
59 import org.jahia.services.acl.JahiaACLEntry;
60 import org.jahia.services.acl.JahiaBaseACL;
61 import org.jahia.services.audit.JahiaAuditLogManagerService;
62 import org.jahia.services.filemanager.JahiaFilemanagerService;
63 import org.jahia.services.files.JahiaTextFileService;
64 import org.jahia.services.pages.ContentPage;
65 import org.jahia.services.pages.JahiaPage;
66 import org.jahia.services.pages.JahiaPageDefinition;
67 import org.jahia.services.pages.JahiaPageService;
68 import org.jahia.services.pages.JahiaPageTemplateService;
69 import org.jahia.services.pages.PageInfoInterface;
70 import org.jahia.services.search.JahiaSearchService;
71 import org.jahia.services.sites.JahiaSite;
72 import org.jahia.services.sites.JahiaSiteTools;
73 import org.jahia.services.sites.JahiaSitesService;
74 import org.jahia.services.sites.SiteLanguageSettings;
75 import org.jahia.services.sites.SiteLanguagesPersistance;
76 import org.jahia.services.templates_deployer.JahiaTemplatesDeployerService;
77 import org.jahia.services.usermanager.JahiaGroup;
78 import org.jahia.services.usermanager.JahiaGroupManagerService;
79 import org.jahia.services.usermanager.JahiaSiteGroupManagerService;
80 import org.jahia.services.usermanager.JahiaSiteUserManagerService;
81 import org.jahia.services.usermanager.JahiaUser;
82 import org.jahia.services.usermanager.JahiaUserManagerService;
83 import org.jahia.services.usermanager.UserManagerProviderBean;
84 import org.jahia.services.version.EntryLoadRequest;
85 import org.jahia.services.webapps_deployer.JahiaWebAppsDeployerService;
86 import org.jahia.utils.JahiaTools;
87 import org.jahia.utils.LanguageCodeConverters;
88 import org.jahia.utils.properties.PropertiesManager;
89 import org.jahia.security.license.License;
90 import org.jahia.services.cache.CacheFactory;
91 import java.util.Collections JavaDoc;
92
93 /**
94  * desc: This class provides the business methods for sites
95  * management, from the JahiaAdministration servlet.
96  * @author Khue Nguyen
97  *
98  * Copyright: Copyright (c) 2002
99  * Company: Jahia Ltd
100  *
101  * @version 1.0
102  */

103 public class ManageSites
104 {
105     private static org.apache.log4j.Logger logger =
106             org.apache.log4j.Logger.getLogger(ManageSites.class);
107
108     private static final String JavaDoc CLASS_NAME = JahiaAdministration.CLASS_NAME;
109     private static final String JavaDoc JSP_PATH = JahiaAdministration.JSP_PATH;
110
111     private static JahiaSitesService sMgr;
112
113     private License coreLicense;
114
115     private static ServletContext JavaDoc context;
116     private static HttpSession JavaDoc session;
117     private ParamBean jParams;
118
119     /**
120      * Default constructor.
121      *
122      * @param request Servlet request.
123      * @param response Servlet response.
124      * @param session Servlet session for the current user.
125      * @param context Servlet context.
126      */

127     public ManageSites( HttpServletRequest JavaDoc request,
128                         HttpServletResponse JavaDoc response,
129                         HttpSession JavaDoc session,
130                         ServletContext JavaDoc context )
131
132     throws Throwable JavaDoc
133     {
134
135         ManageSites.context = context;
136         ManageSites.session = session;
137
138         ServicesRegistry sReg = ServicesRegistry.getInstance();
139         if (sReg != null) {
140             sMgr = sReg.getJahiaSitesService();
141         }
142         JahiaData jData = (JahiaData) request.getAttribute("org.jahia.data.JahiaData");
143         this.jParams = jData.params();
144
145         coreLicense = Jahia.getCoreLicense();
146         if ( coreLicense == null ){
147             // set request attributes...
148
String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.invalidLicenseKey.label",
149                                                jParams, jParams.getLocale());
150             request.setAttribute("jahiaDisplayMessage", dspMsg);
151             // redirect...
152
JahiaAdministration.doRedirect( request, response, session, JSP_PATH + "menu.jsp" );
153             return;
154         }
155         userRequestDispatcher( request, response, session);
156     } // end constructor
157

158
159
160     /**
161      * This method serves as a dispatcher for user requests.
162      *
163      * @param req Servlet request.
164      * @param res Servlet response.
165      * @param sess Servlet session for the current user.
166      */

167     private void userRequestDispatcher( HttpServletRequest JavaDoc req,
168                                         HttpServletResponse JavaDoc res,
169                                         HttpSession JavaDoc sess )
170     throws IOException JavaDoc, ServletException JavaDoc
171     {
172
173         String JavaDoc op = req.getParameter("sub");
174
175         if(op.equals("list")) {
176             displayList( req, res, sess );
177         } else if(op.equals("add")) {
178             displayAdd( req, res, sess );
179         } else if(op.equals("processadd")) {
180             processAdd( req, res, sess );
181         } else if(op.equals("processcreateadmin")) {
182             processCreateAdmin( req, res, sess );
183         } else if(op.equals("processexistantadmin")) {
184             processExistantAdmin( req, res, sess );
185         } else if(op.equals("processadminselectsite")) {
186             processExistantAdminSelectSite( req, res, sess );
187         } else if(op.equals("processtemplatesetchoice")) {
188             processTemplateSetChoice( req, res, sess );
189         } else if(op.equals("edit")) {
190             displayEdit( req, res, sess );
191         } else if(op.equals("processedit")) {
192             processEdit( req, res, sess );
193         } else if(op.equals("delete")) {
194             displayDelete( req, res, sess );
195         } else if(op.equals("processdelete")) {
196             processDelete( req, res, sess);
197         }
198     } // userRequestDispatcher
199

200
201     /**
202      * Display the list of sites.
203      *
204      * @param request Servlet request.
205      * @param response Servlet response.
206      * @param session HttpSession object.
207      */

208     private void displayList( HttpServletRequest JavaDoc request,
209                                 HttpServletResponse JavaDoc response,
210                                 HttpSession JavaDoc session )
211     throws IOException JavaDoc, ServletException JavaDoc
212     {
213         logger.debug(" display sites list started ");
214
215         // retrieve previous form values...
216
String JavaDoc jahiaDisplayMessage = (String JavaDoc) request.getAttribute(CLASS_NAME + "jahiaDisplayMessage");
217
218         // set default values...
219
if(jahiaDisplayMessage == null) {
220             jahiaDisplayMessage =
221                 JahiaResourceBundle.getAdminResource("org.jahia.admin.copyright",
222                     jParams, jParams.getLocale());
223         }
224
225         try {
226             Enumeration JavaDoc siteEnum = sMgr.getSites();
227             Vector JavaDoc sortedSites = new Vector JavaDoc();
228             while (siteEnum.hasMoreElements()) {
229                 JahiaSite curSite = (JahiaSite) siteEnum.nextElement();
230                 sortedSites.add(curSite);
231             }
232             Locale JavaDoc defaultLocale = (Locale JavaDoc)session.getAttribute(ParamBean.SESSION_LOCALE);
233             if (defaultLocale != null) {
234                 Collections.sort(sortedSites, JahiaSite.getTitleComparator(defaultLocale));
235             } else {
236                 Collections.sort(sortedSites, JahiaSite.getTitleComparator());
237             }
238             request.setAttribute("sitesList", sortedSites.elements());
239         } catch (JahiaException ex) {
240             logger.error("Error while retrieving site list", ex);
241             jahiaDisplayMessage = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
242                                              jParams, jParams.getLocale());
243         }
244         // set request attributes...
245
request.setAttribute("jahiaDisplayMessage", jahiaDisplayMessage);
246
247         // redirect...
248
JahiaAdministration.doRedirect( request, response, session, JSP_PATH + "sites_management.jsp" );
249     } // end displayList
250

251
252
253     /**
254      * Display Add new site form
255      *
256      * @param request Servlet request.
257      * @param response Servlet response.
258      * @param session HttpSession object.
259      */

260     private void displayAdd( HttpServletRequest JavaDoc request,
261                                 HttpServletResponse JavaDoc response,
262                                 HttpSession JavaDoc session )
263     throws IOException JavaDoc, ServletException JavaDoc
264     {
265         logger.debug(" display add site started ");
266
267         // retrieve previous form values...
268
String JavaDoc jahiaDisplayMessage = "";
269         String JavaDoc warningMsg = (String JavaDoc)request.getAttribute("warningMsg");
270         if ( warningMsg == null ){
271             warningMsg = "";
272         }
273
274         JahiaUser theUser = (JahiaUser) session.getAttribute( ParamBean.SESSION_USER );
275
276         // check it there is a temporary new site in session
277
JahiaSite newJahiaSite = (JahiaSite) session.getAttribute(CLASS_NAME + "newJahiaSite");
278
279         if ( newJahiaSite == null ){
280
281             logger.debug("site not found in session, assuming new site ");
282
283             // it's the first time this screen is displayed, so create an empty one
284

285             newJahiaSite = new JahiaSite( -1,
286                                         "", // site title
287
"", // site server name
288
"", // site key
289
true, // is active
290
-1, // default page (homepage id)
291
"", // description
292
null, // the acl
293
null );
294         }
295
296
297         Boolean JavaDoc defaultSite = (Boolean JavaDoc)session.getAttribute(CLASS_NAME + "defaultSite");
298         if ( defaultSite == null ){
299             defaultSite = new Boolean JavaDoc(true);
300         }
301
302         Boolean JavaDoc siteMemberShip = (Boolean JavaDoc)session.getAttribute(CLASS_NAME + "siteMemberShip");
303         if ( siteMemberShip == null ){
304             siteMemberShip = new Boolean JavaDoc(true);
305         }
306
307         Locale JavaDoc selectedLocale = (Locale JavaDoc)session.getAttribute(CLASS_NAME + "selectedLocale");
308         if ( selectedLocale == null ){
309             selectedLocale = LanguageCodeConverters.languageCodeToLocale(Jahia.getSettings().getDefaultLanguageCode());
310         }
311
312         // store in session
313
session.setAttribute(CLASS_NAME + "newJahiaSite",newJahiaSite);
314         session.setAttribute(CLASS_NAME + "defaultSite",defaultSite);
315         session.setAttribute(CLASS_NAME + "siteMemberShip",siteMemberShip);
316         session.setAttribute(CLASS_NAME + "selectedLocale",selectedLocale);
317
318         Vector JavaDoc grantedSites = new Vector JavaDoc();
319         if ( theUser != null ){
320             try {
321                 grantedSites = ServicesRegistry.getInstance()
322                                                         .getJahiaGroupManagerService()
323                                                         .getAdminGrantedSites( theUser );
324             } catch ( JahiaException je ){
325
326             }
327             if ( grantedSites == null ){
328                 grantedSites = new Vector JavaDoc();
329             } else {
330                 Locale JavaDoc defaultLocale = (Locale JavaDoc)session.getAttribute(ParamBean.SESSION_LOCALE);
331                 if (defaultLocale != null) {
332                     Collections.sort(grantedSites, JahiaSite.getTitleComparator(defaultLocale));
333                 } else {
334                     Collections.sort(grantedSites, JahiaSite.getTitleComparator());
335                 }
336             }
337         }
338
339         // set request attributes...
340
request.setAttribute("newJahiaSite", newJahiaSite);
341         request.setAttribute("jahiaDisplayMessage", jahiaDisplayMessage);
342         request.setAttribute("warningMsg", warningMsg);
343         request.setAttribute("defaultSite", defaultSite);
344         request.setAttribute("siteMemberShip", siteMemberShip);
345         request.setAttribute("selectedLocale", selectedLocale);
346         request.setAttribute("newAdminOnly", new Boolean JavaDoc(grantedSites.size()<=0) );
347
348         try {
349
350             // logger.debug(" license check ");
351

352             // get the number of sites in db
353
int nbSites = ServicesRegistry.getInstance().getJahiaSitesService(). getNbSites();
354
355             request.setAttribute("nbSites", new Integer JavaDoc(nbSites) );
356
357             // set license info
358
request.setAttribute("siteLimit", new Integer JavaDoc(Jahia.getSiteLimit()) );
359
360             //logger.debug(" let go in ");
361

362             // redirect...
363
JahiaAdministration.doRedirect( request, response, session, JSP_PATH + "site_add.jsp" );
364
365         } catch ( JahiaException je ) {
366             logger.error("Error while retrieving number of site in database", je);
367             // set request attributes...
368
jahiaDisplayMessage = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
369                                              jParams, jParams.getLocale());
370             request.setAttribute("jahiaDisplayMessage", jahiaDisplayMessage);
371             // redirect...
372
JahiaAdministration.doRedirect( request, response, session, JSP_PATH + "sites_management.jsp" );
373         }
374
375     } // end displayAdd
376

377
378
379     /**
380      * Process Add new site form
381      *
382      * @param request Servlet request.
383      * @param response Servlet response.
384      * @param session HttpSession object.
385      */

386     private void processAdd( HttpServletRequest JavaDoc request,
387                                 HttpServletResponse JavaDoc response,
388                                 HttpSession JavaDoc session )
389     throws IOException JavaDoc, ServletException JavaDoc
390     {
391         logger.debug("started");
392
393         boolean processError = true;
394         boolean siteMembershipRequested = false;
395
396         // get form values...
397
String JavaDoc siteTitle = JahiaTools.getStrParameter (request,"siteTitle","").trim();
398         String JavaDoc siteServerName = JahiaTools.getStrParameter (request,"siteServerName","").trim();
399         String JavaDoc siteKey = JahiaTools.getStrParameter (request,"siteKey","").toLowerCase().trim();
400         String JavaDoc siteDescr = JahiaTools.getStrParameter (request,"siteDescr","").trim();
401         Boolean JavaDoc siteMemberShip = Boolean.valueOf(request.getParameter("siteMemberShip") != null);
402         String JavaDoc siteAdmin = JahiaTools.getStrParameter (request,"siteAdmin","").trim();
403         Boolean JavaDoc defaultSite = Boolean.valueOf(request.getParameter ("defaultSite") != null);
404         String JavaDoc selectedLanguage = JahiaTools.getStrParameter (request,"languageList","").trim();
405
406         String JavaDoc warningMsg = "";
407
408         session.setAttribute( CLASS_NAME + "defaultSite", defaultSite );
409         session.setAttribute( CLASS_NAME + "siteMemberShip", siteMemberShip );
410
411         // check license limitation again
412
try {
413             // get the number of sites in db
414
int nbSites = ServicesRegistry.getInstance().getJahiaSitesService(). getNbSites();
415             if ( !Jahia.checkSiteLimit() ){
416                 // redirect...
417
JahiaAdministration.doRedirect( request, response, session, JSP_PATH + "sites_management.jsp" );
418                 return;
419             }
420         } catch ( JahiaException je ) {
421             // set request attributes...
422
String JavaDoc jahiaDisplayMessage = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
423                                              jParams, jParams.getLocale());
424             request.setAttribute("jahiaDisplayMessage", jahiaDisplayMessage);
425             // redirect...
426
JahiaAdministration.doRedirect( request, response, session, JSP_PATH + "sites_management.jsp" );
427             return;
428         }
429
430         // create jahia site object if checks are in green light...
431
try
432         {
433             // check validity...
434
if ( siteTitle != null && (siteTitle.length()>0)
435                  && siteServerName != null && (siteServerName.length()>0)
436                  && siteKey != null && (siteKey.length()>0)
437                  && !selectedLanguage.equals("") ) {
438
439                 if(!JahiaTools.isAlphaValid(siteKey)) {
440                   warningMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg.onlyLettersDigitsUnderscore.label",
441                                                    jParams, jParams.getLocale());
442                 } else if ( siteKey.equals("site") ){
443                   warningMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg.chooseAnotherSiteKey.label",
444                                                    jParams, jParams.getLocale());
445                 } else if ( siteServerName.equals("default") ){
446                   warningMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg.chooseAnotherServerName.label",
447                                                    jParams, jParams.getLocale());
448                 } else if ( siteServerName.equals("localhost") ){
449                   warningMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg.chooseAnotherServerName.label",
450                                                    jParams, jParams.getLocale());
451                 } else if ( sMgr.getSite(siteServerName) != null ){
452                   warningMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg.chooseAnotherServerName.label",
453                                                    jParams, jParams.getLocale());
454                 } else if( sMgr.getSiteByKey(siteKey) != null){
455                   warningMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg.chooseAnotherSiteKey.label",
456                                                    jParams, jParams.getLocale());
457                 } else if( siteKey.equals(ExtDepSiteConstants.SERVER) ){
458                   warningMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg.chooseAnotherSiteKey.label",
459                                                    jParams, jParams.getLocale());
460                 } else {
461                     processError = false;
462                 }
463             } else {
464               warningMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg.completeRequestInfo.label",
465                                                jParams, jParams.getLocale());
466             }
467
468             if(!processError)
469             {
470
471                 // create the ACL object...
472
JahiaBaseACL acl = null;
473                 acl = new JahiaBaseACL ();
474                 acl.create(0);
475
476                 // save new jahia site...
477
JahiaSite site = new JahiaSite( -1,
478                                                 siteTitle,
479                                                 siteServerName,
480                                                 siteKey,
481                                                 true, // is active
482
-1, // default page (homepage id)... subject to update in terminateAdd().
483
siteDescr,
484                                                 acl,
485                                                 null );
486
487                 site.setDefaultTemplateID(3); // FIXME_MULTISITE should not be hardcoded
488
site.setTemplatesAutoDeployMode(true);
489                 site.setWebAppsAutoDeployMode(true);
490
491                 // set in session...
492
session.setAttribute( CLASS_NAME + "newJahiaSite", site );
493                 if ( !selectedLanguage.equals("") ){
494                     session.setAttribute( CLASS_NAME + "selectedLocale",
495                             LanguageCodeConverters.languageCodeToLocale(selectedLanguage));
496                 }
497
498                 // all is okay, go to add admin or use existant admin...
499
if(siteAdmin.trim().equals("0")) {
500                     displayCreateAdmin( request, response, session );
501                 } else {
502                     displaySelectExistantAdmin( request, response, session );
503                 }
504
505                 acl = null;
506                 site = null;
507             } else {
508
509                 JahiaSite site = new JahiaSite( -1,
510                                         siteTitle,
511                                         siteServerName,
512                                         siteKey,
513                                         true,
514                                         -1,
515                                         siteDescr,
516                                         null,
517                                         null );
518
519
520                 session.setAttribute( CLASS_NAME + "newJahiaSite", site );
521                 request.setAttribute("selectedlanguage", selectedLanguage);
522                 request.setAttribute("newJahiaSite", site);
523                 request.setAttribute("warningMsg", warningMsg);
524                 displayAdd( request, response, session);
525             }
526         } catch (JahiaException ex) {
527             warningMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg.processingRequestError.label",
528                                            jParams, jParams.getLocale());
529             request.setAttribute("warningMsg", warningMsg);
530             displayAdd( request, response, session);
531         }
532         finally{
533             siteTitle = null;
534             siteServerName = null;
535             siteKey = null;
536             siteDescr = null;
537             siteMemberShip = null;
538             siteAdmin = null;
539             defaultSite = null;
540             warningMsg = null;
541
542         }
543     } // end processAdd
544

545
546
547     /**
548      * Terminate the creation of a new site. Create the site and dependancies.
549      *
550      * @param request Servlet request.
551      * @param response Servlet response.
552      * @param session HttpSession object.
553      */

554     private void terminateAdd( HttpServletRequest JavaDoc request,
555                                HttpServletResponse JavaDoc response,
556                                HttpSession JavaDoc session )
557     throws IOException JavaDoc, ServletException JavaDoc
558     {
559
560         logger.debug("started");
561
562         String JavaDoc warningMsg = "";
563
564         JahiaSite currentSite = (JahiaSite) session.getAttribute( ParamBean.SESSION_SITE );
565
566         // get objects temporary stocked in session...
567
JahiaSite site = (JahiaSite) session.getAttribute( CLASS_NAME + "newJahiaSite" );
568         Boolean JavaDoc membership = (Boolean JavaDoc) session.getAttribute( CLASS_NAME + "siteMemberShip" );
569         Boolean JavaDoc defaultSite = (Boolean JavaDoc) session.getAttribute( CLASS_NAME + "defaultSite" );
570         JahiaUser existantAdminUser = (JahiaUser) session.getAttribute( CLASS_NAME + "existantAdminUser" );
571         Locale JavaDoc selectedLocale = (Locale JavaDoc) session.getAttribute( CLASS_NAME + "selectedLocale" );
572
573         try
574         {
575             // get services...
576
JahiaUserManagerService jums = ServicesRegistry.getInstance().getJahiaUserManagerService();
577             JahiaGroupManagerService jgms = ServicesRegistry.getInstance().getJahiaGroupManagerService();
578             JahiaSiteGroupManagerService jsgms = ServicesRegistry.getInstance().getJahiaSiteGroupManagerService();
579             JahiaSiteUserManagerService jsums = ServicesRegistry.getInstance().getJahiaSiteUserManagerService();
580             JahiaSitesService jsms = ServicesRegistry.getInstance().getJahiaSitesService();
581             JahiaPageTemplateService jpts = ServicesRegistry.getInstance().getJahiaPageTemplateService();
582             JahiaSearchService searchServ = ServicesRegistry.getInstance().getJahiaSearchService();
583
584             JahiaUser currentUser = jums
585                     .lookupUser(0, (String JavaDoc) session.getAttribute(CLASS_NAME + "jahiaLoginUsername"));
586             JahiaUser adminSiteUser;
587
588             // add the site in siteManager...
589
sMgr.addSite(site);
590
591             // continue if the site is added correctly...
592
if(site.getID() != -1)
593             {
594                 // default value
595
site.setStaging(true);
596                 site.setVersioning(true);
597
598                 jsms.updateSite(site);
599
600                 // create site language
601
SiteLanguagesPersistance langSettingsSrv = SiteLanguagesPersistance.getInstance();
602                 SiteLanguageSettings newLanguage =
603                        new SiteLanguageSettings(site.getID(), selectedLocale.toString(), true, 1, false);
604                 langSettingsSrv.addSiteLanguageSettings(newLanguage);
605
606                 // settings default permissions
607
JahiaACLEntry adminAclEntry = new JahiaACLEntry(7,0);
608
609                 // root admin group
610
JahiaGroup adminGrp = jgms.getAdministratorGroup(0);
611                 site.getACL().setGroupEntry(adminGrp,adminAclEntry);
612
613                 // site admin group
614
adminGrp = jgms.getAdministratorGroup(site.getID());
615                 site.getACL().setGroupEntry(adminGrp,adminAclEntry);
616
617
618                 // create default groups...
619
JahiaGroup adminGroup = jgms.createGroup( site.getID(),
620                                                           JahiaGroupManagerService.ADMINISTRATORS_GROUPNAME, null );
621                 JahiaGroup usersGroup = jgms.createGroup( site.getID(),
622                                                           JahiaGroupManagerService.USERS_GROUPNAME, null );
623                 JahiaGroup guestGroup = jgms.createGroup( site.getID(),
624                                                           JahiaGroupManagerService.GUEST_GROUPNAME, null );
625
626                 // create groups memberships...
627
JahiaSiteTools.addGroup( adminGroup , site);
628                 JahiaSiteTools.addGroup( usersGroup , site);
629                 JahiaSiteTools.addGroup( guestGroup , site);
630
631                 // create the guest user
632
String JavaDoc uniqueKey = JahiaUserManagerService.GUEST_USERNAME + ":" + String.valueOf(site.getID());
633                 JahiaUser guestSiteUser = jums.createUser( JahiaUserManagerService.GUEST_USERNAME,
634                                                             JahiaUserManagerService.GUEST_USERNAME,
635                                                             uniqueKey,
636                                                             site.getID(),
637                                                             null );
638
639                 // attach superadmin user (current) to administrators group...
640
adminGroup.addMember( currentUser );
641
642                 // create creator user membership for this site...
643
if ( membership.booleanValue() ){
644                     JahiaSiteTools.addMember(currentUser,site);
645                 }
646
647                 // attach guest user to guest group...
648
guestGroup.addMember( guestSiteUser );
649
650                 // create guest user membership for this site...
651
JahiaSiteTools.addMember( guestSiteUser , site );
652
653                 JahiaPageDefinition pageDef = null;
654
655                 logger.debug( "createTemplateDir now");
656
657                 if ( JahiaSiteTools.createTemplateDir(site) ){
658
659                     pageDef = createDefaultTemplate(site);
660                 }
661
662                 logger.debug( "createTemplateDir done");
663
664                 JahiaData jData = (JahiaData)request.getAttribute("org.jahia.data.JahiaData");
665
666                 if ( pageDef != null ){
667
668                     // create the default homepage...
669
EntryLoadRequest saveRequest = EntryLoadRequest.STAGED;
670                     ArrayList JavaDoc locales = new ArrayList JavaDoc();
671                     locales.add(selectedLocale);
672                     saveRequest.setLocales(locales);
673                     jParams.setSubstituteEntryLoadRequest(saveRequest);
674
675                     JahiaPageService pageService = ServicesRegistry.getInstance().getJahiaPageService();
676                     JahiaPage page = pageService.createPage( site.getID(),
677                                                                          0,
678                                                                          PageInfoInterface.TYPE_DIRECT,
679                                                                          "Welcome to " + site.getServerName(),
680                                                                          pageDef.getID(),
681                                                                          "",
682                                                                          0,
683                                                                          "Jahia",
684                                                                          0,
685                                                                          jParams );
686                     jParams.resetSubstituteEntryLoadRequest();
687
688                     logger.debug( "Home Page created");
689
690                     // enable guest user to access the page
691
JahiaACLEntry guestAclEntry = new JahiaACLEntry(1,0);
692
693                     page.getACL().setUserEntry(guestSiteUser, guestAclEntry);
694                     page.getACL().setGroupEntry(guestGroup, guestAclEntry);
695
696                     // enable admin group to admin the page
697
adminAclEntry = new JahiaACLEntry(7,0);
698                     page.getACL().setGroupEntry(adminGroup, adminAclEntry);
699
700                     // set the site page by last action...
701
site.setHomePageID( page.getID() );
702
703                     // set the site default template
704
site.setDefaultTemplateID( pageDef.getID() );
705
706                     jsms.updateSite(site);
707
708                     logger.debug( "Site updated with Home Page");
709
710                 }
711
712                 // start and create the site's new templates folder
713
JahiaSiteTools.startTemplateObserver(site, jParams.settings());
714
715                 // start and create the site's new web apps folder
716
JahiaSiteTools.startWebAppsObserver(site, jParams.settings());
717
718                 // copy the default shared components
719
copySharedComponents(site.getSiteKey());
720
721                 // create the search index
722
searchServ.indexSite(site.getID(),jData.params(),true,true);
723
724                 // create administrator user if requested...
725
if(existantAdminUser == null)
726                 {
727                     // get session administrator properties...
728
String JavaDoc adminUsername = (String JavaDoc) session.getAttribute( CLASS_NAME + "adminUsername" );
729                     String JavaDoc adminPassword = (String JavaDoc) session.getAttribute( CLASS_NAME + "adminPassword" );
730                     Properties JavaDoc adminProps = (Properties JavaDoc) session.getAttribute( CLASS_NAME + "adminProps" );
731
732                     // create user...
733
uniqueKey = adminUsername + ":" + String.valueOf(site.getID());
734                     adminSiteUser = jums.createUser( adminUsername, adminPassword, uniqueKey, site.getID(), adminProps );
735                 } else {
736                     adminSiteUser = existantAdminUser; // the administrator already exists... use this.
737
}
738
739                 // attach admin to administrators group...
740
JahiaSiteTools.getAdminGroup(site).addMember( adminSiteUser );
741
742                 // create admin membership for this site...
743
JahiaSiteTools.addMember( adminSiteUser , site );
744
745                 // set as default site
746
if ( defaultSite.booleanValue() ){
747                     changeDefaultSite(site);
748                 }
749
750                 // set as current site if the session site is null
751
if ( session.getAttribute( ParamBean.SESSION_SITE ) == null ){
752                     session.setAttribute( ParamBean.SESSION_SITE, site );
753                     session.setAttribute( JahiaAdministration.CLASS_NAME + "manageSiteID", new Integer JavaDoc( site.getID() ) );
754
755                 }
756
757                 SharedTemplatePackagesRegistry tmplSetReg = SharedTemplatePackagesRegistry.getInstance();
758                 Integer JavaDoc siteID = new Integer JavaDoc(site.getID());
759
760                 // set new site in session
761
session.setAttribute( CLASS_NAME + "newJahiaSite" , site );
762
763             } else {
764                 sMgr.removeSite(site); // remove site because the process generate error(s)...
765
warningMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg.processingRequestError.label",
766                                                jParams, jParams.getLocale());
767                 request.setAttribute("warningMsg", warningMsg);
768                 displayAdd( request, response, session );
769             }
770         } catch (JahiaException ex) {
771
772             // clean site
773
try {
774                 sMgr.removeSite(site);
775             } catch ( Throwable JavaDoc t ) {
776             }
777
778             logger.error("Error while adding site", ex);
779
780             warningMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg.processingRequestError.label",
781                                            jParams, jParams.getLocale());
782             request.setAttribute("warningMsg", warningMsg);
783             displayAdd( request, response, session );
784         }
785
786     } // end terminateAdd
787

788
789
790     /**
791      * Display page to create an administrator for the new site.
792      *
793      * @param request Servlet request.
794      * @param response Servlet response.
795      * @param session HttpSession object.
796      */

797     private void displayCreateAdmin( HttpServletRequest JavaDoc request,
798                                      HttpServletResponse JavaDoc response,
799                                      HttpSession JavaDoc session )
800     throws IOException JavaDoc, ServletException JavaDoc
801     {
802         //logger.debug(" display create administrator started ");
803

804         // retrieve previous form values...
805
String JavaDoc jahiaDisplayMessage = (String JavaDoc) request.getAttribute(CLASS_NAME + "jahiaDisplayMessage");
806         String JavaDoc adminUsername = (String JavaDoc) request.getAttribute("adminUsername");
807         String JavaDoc adminPassword = (String JavaDoc) request.getAttribute("adminPassword");
808         String JavaDoc adminConfirm = (String JavaDoc) request.getAttribute("adminConfirm");
809         String JavaDoc adminFirstName = (String JavaDoc) request.getAttribute("adminFirstName");
810         String JavaDoc adminLastName = (String JavaDoc) request.getAttribute("adminLastName");
811         String JavaDoc adminOrganization = (String JavaDoc) request.getAttribute("adminOrganization");
812         String JavaDoc adminEmail = (String JavaDoc) request.getAttribute("adminEmail");
813
814         // set default values...
815
if(jahiaDisplayMessage == null) {
816             jahiaDisplayMessage =
817                 JahiaResourceBundle.getAdminResource("org.jahia.admin.copyright",
818                     jParams, jParams.getLocale());
819         }
820         if(adminUsername == null) { adminUsername = ""; }
821         if(adminPassword == null) { adminPassword = ""; }
822         if(adminConfirm == null) { adminConfirm = ""; }
823         if(adminFirstName == null) { adminFirstName = ""; }
824         if(adminLastName == null) { adminLastName = ""; }
825         if(adminOrganization == null) { adminOrganization = ""; }
826         if(adminEmail == null) { adminEmail = ""; }
827
828         // set display message...
829
session.setAttribute(CLASS_NAME + "jahiaDisplayMessage", jahiaDisplayMessage);
830
831         // set request attributes...
832
request.setAttribute("adminUsername", adminUsername);
833         request.setAttribute("adminPassword", adminPassword);
834         request.setAttribute("adminConfirm", adminConfirm);
835         request.setAttribute("adminFirstName", adminFirstName);
836         request.setAttribute("adminLastName", adminLastName);
837         request.setAttribute("adminOrganization", adminOrganization);
838         request.setAttribute("adminEmail", adminEmail);
839
840         // redirect...
841
JahiaAdministration.doRedirect( request, response, session, JSP_PATH + "site_create_admin.jsp" );
842     } // end displayCreateAdmin
843

844
845
846     /**
847      * Process create new administrator for this new site.
848      *
849      * @param request Servlet request.
850      * @param response Servlet response.
851      * @param session HttpSession object.
852      */

853     private void processCreateAdmin( HttpServletRequest JavaDoc request,
854                                      HttpServletResponse JavaDoc response,
855                                      HttpSession JavaDoc session )
856     throws IOException JavaDoc, ServletException JavaDoc
857     {
858         //logger.debug(" process create administrator started ");
859
boolean processError = true;
860
861         // get form values...
862
String JavaDoc adminUsername = JahiaTools.getStrParameter(request,"adminUsername","").trim();
863         String JavaDoc adminPassword = JahiaTools.getStrParameter(request,"adminPassword","").trim();
864         String JavaDoc adminConfirm = JahiaTools.getStrParameter(request,"adminConfirm","").trim();
865         String JavaDoc adminFirstName = JahiaTools.getStrParameter(request,"adminFirstName","").trim();
866         String JavaDoc adminLastName = JahiaTools.getStrParameter(request,"adminLastName","").trim();
867         String JavaDoc adminOrganization = JahiaTools.getStrParameter(request,"adminOrganization","").trim();
868         String JavaDoc adminEmail = JahiaTools.getStrParameter(request,"adminEmail","").trim();
869         String JavaDoc jahiaDisplayMessage = "";
870
871         // set request attributes...
872
request.setAttribute("adminUsername", adminUsername);
873         request.setAttribute("adminPassword", adminPassword);
874         request.setAttribute("adminConfirm", adminConfirm);
875         request.setAttribute("adminFirstName", adminFirstName);
876         request.setAttribute("adminLastName", adminLastName);
877         request.setAttribute("adminOrganization", adminOrganization);
878         request.setAttribute("adminEmail", adminEmail);
879
880         // get current user...
881
JahiaUser currentUser = ServicesRegistry.getInstance().getJahiaUserManagerService().lookupUser( 0, (String JavaDoc) session.getAttribute(CLASS_NAME+"jahiaLoginUsername") );
882
883         // check validity...
884
if(adminUsername.equals(currentUser.getUsername())) {
885           jahiaDisplayMessage = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.usernameSameLogin.label",
886                                            jParams, jParams.getLocale());
887         } else if(adminUsername.length() == 0) {
888           jahiaDisplayMessage = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.usernameMustLeast4Chars.label",
889                                            jParams, jParams.getLocale());
890         } else if(adminUsername.length() < 4) {
891           jahiaDisplayMessage = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.usernameTooShort.label",
892                                            jParams, jParams.getLocale());
893         } else if(!adminPassword.equals(adminConfirm)) {
894           jahiaDisplayMessage = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.confirmPasswdBeSame.label",
895                                            jParams, jParams.getLocale());
896         } else if(adminPassword.length() == 0) {
897           jahiaDisplayMessage = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.passwdLeast4Chars.label",
898                                            jParams, jParams.getLocale());
899         } else if(adminPassword.length() < 4) {
900           jahiaDisplayMessage = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.passwdTooShort.label",
901                                            jParams, jParams.getLocale());
902         } else if(adminEmail.length() == 0) {
903           jahiaDisplayMessage = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.EmailMustset.label",
904                                            jParams, jParams.getLocale());
905         } else if(!JahiaTools.isAlphaValid( adminUsername )) {
906           jahiaDisplayMessage = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.onlyLettersDigitsUnderscoreWithUsername.label",
907                                            jParams, jParams.getLocale());
908         } else if(!JahiaTools.isAlphaValid( adminPassword )) {
909           jahiaDisplayMessage = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.onlyLettersDigitsUnderscoreWithPasswd.label",
910                                            jParams, jParams.getLocale());
911         } else {
912             processError = false;
913         }
914
915         if(!processError)
916         {
917             // compose user properties...
918
Properties JavaDoc userProps = new Properties JavaDoc();
919             userProps.setProperty("firstname", adminFirstName);
920             userProps.setProperty("lastname", adminLastName);
921             userProps.setProperty("email", adminEmail);
922             userProps.setProperty("organization", adminOrganization);
923
924             session.setAttribute( CLASS_NAME + "adminUsername", adminUsername );
925             session.setAttribute( CLASS_NAME + "adminPassword", adminPassword );
926             session.setAttribute( CLASS_NAME + "adminProps", userProps );
927             session.setAttribute( CLASS_NAME + "jahiaDisplayMessage",
928                 JahiaResourceBundle.getAdminResource("org.jahia.admin.copyright",
929                     jParams, jParams.getLocale()));
930
931             // reset session
932
session.setAttribute( CLASS_NAME + "existantAdminUser", null );
933
934             SharedTemplatePackagesRegistry tmplSetReg = SharedTemplatePackagesRegistry.getInstance();
935
936             if ( tmplSetReg != null && (tmplSetReg.getNbPackage()>0) ){
937                 displayTemplateSetChoice(request, response, session);
938             } else {
939                 // redirection to full sites list...
940
terminateAdd( request, response, session );
941                 displayList( request, response, session );
942             }
943
944         } else {
945             request.setAttribute(CLASS_NAME + "jahiaDisplayMessage", jahiaDisplayMessage);
946             displayCreateAdmin( request, response, session);
947         }
948     } // end processCreateAdmin
949

950
951
952     /**
953      * Display page to select an existant administrator for the new site.
954      *
955      * @param request Servlet request.
956      * @param response Servlet response.
957      * @param session HttpSession object.
958      */

959     private void displaySelectExistantAdmin( HttpServletRequest JavaDoc request,
960                                              HttpServletResponse JavaDoc response,
961                                              HttpSession JavaDoc session )
962     throws IOException JavaDoc, ServletException JavaDoc
963     {
964         //logger.debug("display select existant administrator started ");
965

966         // retrieve previous form values...
967
String JavaDoc jahiaDisplayMessage = (String JavaDoc) request.getAttribute(CLASS_NAME + "jahiaDisplayMessage");
968         String JavaDoc selectedSite = (String JavaDoc) request.getAttribute("selectedSite");
969
970         // set default values...
971
if(jahiaDisplayMessage == null) {
972             jahiaDisplayMessage =
973                 JahiaResourceBundle.getAdminResource("org.jahia.admin.copyright",
974                     jParams, jParams.getLocale());
975         }
976         if(selectedSite == null) {
977             if(request.getParameter("site") == null) {
978                 selectedSite = "0";
979             } else {
980                 selectedSite = request.getParameter("site");
981             }
982         }
983
984         try
985         {
986             // get admins list...
987
JahiaGroupManagerService groupManager = ServicesRegistry.getInstance().getJahiaGroupManagerService();
988             JahiaUserManagerService userManager = ServicesRegistry.getInstance().getJahiaUserManagerService();
989             Enumeration JavaDoc allSites = sMgr.getSites();
990             Vector JavaDoc sitesList = new Vector JavaDoc();
991             Integer JavaDoc siteIDInteger = new Integer JavaDoc( selectedSite );
992
993             // clean sites...
994
while(allSites.hasMoreElements()) {
995                 JahiaSite site = (JahiaSite) allSites.nextElement();
996                 if(site.getID() > 0) {
997                     sitesList.add( site );
998                 }
999             }
1000
1001            // set the enumeration to null if the vector is empty...
1002
if(sitesList.size() == 0) {
1003                allSites = null;
1004            } else {
1005                Locale JavaDoc defaultLocale = (Locale JavaDoc)session.getAttribute(ParamBean.SESSION_LOCALE);
1006                if (defaultLocale != null) {
1007                    Collections.sort(sitesList, JahiaSite.getTitleComparator(defaultLocale));
1008                } else {
1009                    Collections.sort(sitesList, JahiaSite.getTitleComparator());
1010                }
1011                allSites = sitesList.elements();
1012            }
1013
1014            // get users... only if allSites is not null...
1015
if((allSites != null) && (!selectedSite.equals("0")))
1016            {
1017                Vector JavaDoc allAdministrators = new Vector JavaDoc();
1018
1019                JahiaGroup adminGroup = groupManager.getAdministratorGroup( siteIDInteger.intValue() );
1020                Enumeration JavaDoc admins = adminGroup.members();
1021
1022                while(admins.hasMoreElements()) {
1023                    try {
1024                        JahiaUser user = (JahiaUser) admins.nextElement();
1025                        if(user.getSiteID() != 0)
1026                        {
1027                            HashMap JavaDoc adminHash = new HashMap JavaDoc();
1028                            adminHash.put( "key", user.getUserKey() );
1029                            adminHash.put( "username", user.getUsername() );
1030                            allAdministrators.add( adminHash );
1031                        }
1032                    } catch (Exception JavaDoc e) {
1033                        // do nothing...
1034
}
1035                }
1036
1037                request.setAttribute("adminsList", allAdministrators.elements());
1038            }
1039
1040            // set attributes...
1041
session.setAttribute(CLASS_NAME + "jahiaDisplayMessage", jahiaDisplayMessage);
1042            request.setAttribute("allSites", allSites);
1043            request.setAttribute("allSitesJS", sitesList.elements());
1044            request.setAttribute("selectedSite", new Integer JavaDoc(selectedSite));
1045
1046            // redirect...
1047
JahiaAdministration.doRedirect( request, response, session, JSP_PATH + "site_existant_admin.jsp" );
1048        } catch (JahiaException je) {
1049            displayList( request, response, session );
1050        }
1051
1052        // set default values...
1053
session.setAttribute(CLASS_NAME + "jahiaDisplayMessage",
1054            JahiaResourceBundle.getAdminResource("org.jahia.admin.copyright",
1055                jParams, jParams.getLocale()));
1056    } // end displaySelectExistantAdmin
1057

1058
1059
1060    /**
1061     * Process select existant administrator for this new site.
1062     *
1063     * @param request Servlet request.
1064     * @param response Servlet response.
1065     * @param session HttpSession object.
1066     */

1067    private void processExistantAdminSelectSite( HttpServletRequest JavaDoc request,
1068                                                 HttpServletResponse JavaDoc response,
1069                                                 HttpSession JavaDoc session )
1070    throws IOException JavaDoc, ServletException JavaDoc
1071    {
1072        //logger.debug(" process existant administrator change site started ");
1073
boolean processError = true;
1074
1075        request.setAttribute("selectedSite", request.getParameter("site"));
1076        displaySelectExistantAdmin( request, response, session );
1077    } // end processExistantAdminSelectSite
1078

1079
1080
1081    /**
1082     * Process select existant administrator for this new site.
1083     *
1084     * @param request Servlet request.
1085     * @param response Servlet response.
1086     * @param session HttpSession object.
1087     */

1088    private void processExistantAdmin( HttpServletRequest JavaDoc request,
1089                                       HttpServletResponse JavaDoc response,
1090                                       HttpSession JavaDoc session )
1091    throws IOException JavaDoc, ServletException JavaDoc
1092    {
1093        //logger.debug(" process existant administrator selected started ");
1094
boolean processError = true;
1095
1096        // get form values...
1097
String JavaDoc adminSelected = request.getParameter("adminSelected");
1098        String JavaDoc siteID = request.getParameter("site");
1099
1100        if(adminSelected == null) { // it's only the choice of site... display user list.
1101
request.setAttribute("selectedSite", siteID);
1102            String JavaDoc jahiaDisplayMessage = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.chooseUserInList.label",
1103                                             jParams, jParams.getLocale());
1104            request.setAttribute(CLASS_NAME + "jahiaDisplayMessage", jahiaDisplayMessage);
1105            displaySelectExistantAdmin( request, response, session );
1106        } else {
1107            // get the user...
1108
JahiaUserManagerService userManager = ServicesRegistry.getInstance().getJahiaUserManagerService();
1109            JahiaUser theUser = userManager.lookupUser( adminSelected );
1110
1111            session.setAttribute( CLASS_NAME + "existantAdminUser", theUser );
1112
1113            SharedTemplatePackagesRegistry tmplSetReg = SharedTemplatePackagesRegistry.getInstance();
1114
1115            if ( (tmplSetReg != null) && (tmplSetReg.getNbPackage()>0) ){
1116                displayTemplateSetChoice(request, response, session);
1117            } else {
1118                // redirection to full sites list...
1119
terminateAdd( request, response, session );
1120                // redirection to full sites list...
1121
displayList( request, response, session );
1122
1123            }
1124        }
1125    }
1126
1127    /**
1128     * Display page to let user choose a set of templates.
1129     *
1130     * @param request Servlet request.
1131     * @param response Servlet response.
1132     * @param session HttpSession object.
1133     */

1134    private void displayTemplateSetChoice( HttpServletRequest JavaDoc request,
1135                                            HttpServletResponse JavaDoc response,
1136                                            HttpSession JavaDoc session )
1137    throws IOException JavaDoc, ServletException JavaDoc
1138    {
1139        logger.debug("Display template set choice started ");
1140
1141        // retrieve previous form values...
1142
String JavaDoc jahiaDisplayMessage = (String JavaDoc) request.getAttribute(CLASS_NAME + "jahiaDisplayMessage");
1143        String JavaDoc selectedTmplSet = (String JavaDoc) request.getAttribute("selectedTmplSet");
1144        String JavaDoc thumbnail = null;
1145
1146        JahiaSite site = (JahiaSite) session.getAttribute( CLASS_NAME + "newJahiaSite" );
1147
1148        // get tmplPackage list...
1149
SharedTemplatePackagesRegistry tmplSetReg = SharedTemplatePackagesRegistry.getInstance();
1150
1151        // set default values...
1152
if(jahiaDisplayMessage == null) {
1153            jahiaDisplayMessage =
1154                JahiaResourceBundle.getAdminResource("org.jahia.admin.copyright",
1155                    jParams, jParams.getLocale());
1156        }
1157
1158        if(selectedTmplSet == null) {
1159            selectedTmplSet = "0";
1160            Enumeration JavaDoc enumeration = tmplSetReg.getAllTemplatePackages();
1161            if ( enumeration.hasMoreElements() ){
1162                JahiaTemplatesPackage tmplPack = (JahiaTemplatesPackage)enumeration.nextElement();
1163                if ( tmplPack != null ){
1164                    Integer JavaDoc I = new Integer JavaDoc(tmplPack.getID());
1165                    selectedTmplSet = I.toString();
1166                }
1167            }
1168        }
1169        try {
1170            JahiaTemplatesPackage tmplPack = tmplSetReg.getTemplatePackage(Integer.parseInt(selectedTmplSet));
1171            if ( tmplPack !=null ){
1172                logger.debug("Requested template set : " + tmplPack.getName());
1173                thumbnail = tmplSetReg.getTemplatePackageThumbnail(tmplPack.getFileName());
1174                logger.debug("Thumbnail found : " + thumbnail);
1175            }
1176        } catch ( JahiaException je ){
1177            logger.warn("Thumbnail lookup Exception : ", je);
1178            // no thumbnail
1179
}
1180
1181        Enumeration JavaDoc tmplSets = tmplSetReg.getAllTemplatePackages();
1182
1183        // set attributes...
1184
session.setAttribute(CLASS_NAME + "jahiaDisplayMessage", jahiaDisplayMessage);
1185        request.setAttribute("tmplSets", tmplSets);
1186        request.setAttribute("selectedTmplSet", new Integer JavaDoc(selectedTmplSet));
1187        request.setAttribute("thumbnail", thumbnail);
1188
1189        logger.debug("Nb template set found " + tmplSetReg.getNbPackage());
1190
1191        // redirect...
1192
JahiaAdministration.doRedirect( request, response, session, JSP_PATH + "site_choose_template_set.jsp" );
1193
1194        // set default values...
1195
session.setAttribute(CLASS_NAME + "jahiaDisplayMessage",
1196            JahiaResourceBundle.getAdminResource("org.jahia.admin.copyright",
1197                jParams, jParams.getLocale()));
1198    }
1199
1200    /**
1201     * Process template set choice.
1202     *
1203     * @param request Servlet request.
1204     * @param response Servlet response.
1205     * @param session HttpSession object.
1206     */

1207    private void processTemplateSetChoice( HttpServletRequest JavaDoc request,
1208                                            HttpServletResponse JavaDoc response,
1209                                            HttpSession JavaDoc session )
1210    throws IOException JavaDoc, ServletException JavaDoc
1211    {
1212        logger.debug("Process template set choice started ");
1213        boolean processError = true;
1214
1215        // get form values...
1216
String JavaDoc operation = request.getParameter("operation");
1217        String JavaDoc selectTmplSet = request.getParameter("selectTmplSet");
1218        if ( selectTmplSet == null || selectTmplSet.trim().equals("")){
1219            selectTmplSet = "0";
1220        }
1221
1222        logger.debug("operation = " + operation );
1223        logger.debug("selected template = " + selectTmplSet );
1224
1225        request.setAttribute("selectedTmplSet", selectTmplSet);
1226
1227        if ( operation == null || !operation.trim().equals("save")
1228            || selectTmplSet.equals("0") ){
1229            displayTemplateSetChoice( request, response, session );
1230        } else {
1231
1232            terminateAdd(request,response,session);
1233
1234            JahiaSite site = (JahiaSite) session.getAttribute( CLASS_NAME + "newJahiaSite" );
1235
1236            logger.debug("Site = " + site.getID());
1237
1238            try {
1239                if ( site != null ){
1240                    JahiaTemplatesPackage tmplPack =
1241                    SharedTemplatePackagesRegistry.getInstance()
1242                    .getTemplatePackage(Integer.parseInt(selectTmplSet));
1243                    if ( tmplPack != null ){
1244                        logger.debug("Process template set choice, choosed template set is "
1245                        + tmplPack.getName() );
1246                        // deploy template
1247
JahiaTemplatesDeployerService tmplDepServ =
1248                                    ServicesRegistry.getInstance().getJahiaTemplatesDeployerService();
1249                        if ( !tmplDepServ.deploy(site,tmplPack.getRootFolder(),tmplPack.getFilePath(),false) ){
1250                          String JavaDoc jahiaDisplayMessage = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.deployingTemplatesError.label",
1251                                                           jParams, jParams.getLocale());
1252                          session.setAttribute(CLASS_NAME + "jahiaDisplayMessage", jahiaDisplayMessage);
1253                            displayList( request, response, session );
1254                            return;
1255                        }
1256
1257                        tmplDepServ.registerTemplates(site,tmplPack);
1258                        // Change the home page template
1259
JahiaPageTemplateService jpts = ServicesRegistry.getInstance()
1260                                                                .getJahiaPageTemplateService();
1261
1262                        JahiaTemplateDef homePageTemplate = tmplPack.getHomePageTemplate();
1263
1264                        /*
1265                        if ( homePageTemplate != null ){
1266                            logger.debug ("Home page template found in package :" + homePageTemplate.getName());
1267                            logger.debug ("Home page template found in package :" + homePageTemplate.getFileName());
1268                        } else {
1269                            logger.debug ("Home page template not found in package :");
1270                        }
1271                        */

1272                        Enumeration JavaDoc declaredTemplates = null;
1273                        JahiaPageDefinition newPageDef = null;
1274                        JahiaPageDefinition currentPageDef = null;
1275
1276
1277                        declaredTemplates = jpts.getPageTemplates(site.getID(),true);
1278
1279                        // Check if the template is registered in Jahia
1280
String JavaDoc templateFilename ="";
1281
1282                        try {
1283                            while ( declaredTemplates.hasMoreElements() ){
1284                                newPageDef = (JahiaPageDefinition)declaredTemplates.nextElement();
1285
1286                                templateFilename = newPageDef.getSourcePath();
1287
1288                                logger.debug("Declared template = " + templateFilename );
1289
1290                                if ( templateFilename != null ){
1291                                    templateFilename = templateFilename.toLowerCase();
1292                                } else {
1293                                    templateFilename = "";
1294                                }
1295                                if ( (homePageTemplate == null)
1296                                    && ( (templateFilename.indexOf((tmplPack.getRootFolder()+ "/" +"home").toLowerCase()) != -1)
1297                                         || (templateFilename.indexOf((tmplPack.getRootFolder()+ "/" +"index").toLowerCase()) != -1) ) ){
1298                                    logger.debug("Template used as home (a) = " + templateFilename + " id=" + newPageDef.getID() );
1299                                    break;
1300                                } else {
1301                                    String JavaDoc s = tmplPack.getRootFolder()+ "/" + homePageTemplate.getFileName();
1302                                    //logger.debug ("s = " + s );
1303
if ( templateFilename.toLowerCase().indexOf(s.toLowerCase()) != -1) {
1304                                        logger.debug("Template used as home (b) = " + templateFilename + " id=" + newPageDef.getID() );
1305                                        break;
1306                                    }
1307                                }
1308                                newPageDef = null;
1309                            }
1310                        } catch (Throwable JavaDoc t ){
1311                            t.printStackTrace();
1312                        }
1313                        //site.setDefaultTemplateID(newPageDef.getID());
1314
Locale JavaDoc selectedLocale =
1315                                (Locale JavaDoc) session.getAttribute( CLASS_NAME + "selectedLocale" );
1316                        EntryLoadRequest loadRequest = EntryLoadRequest.STAGED;
1317                        ArrayList JavaDoc locales = new ArrayList JavaDoc();
1318                        locales.add(selectedLocale);
1319                        loadRequest.setLocales(locales);
1320
1321                        ContentPage page = site.getHomeContentPage();
1322                        currentPageDef = page.getPageTemplate(loadRequest);
1323                        if ( page != null ){
1324                            if ( newPageDef != null ){
1325                                page.setPageTemplateID(newPageDef.getID(),loadRequest);
1326                                page.commitChanges(true);
1327                                sMgr.updateSite(site);
1328
1329                                // remove the default home template which is only
1330
// used when no other home templates are available.
1331
jpts.deletePageTemplate(currentPageDef.getID());
1332                                // In this change the default template ID to the next one.
1333
site.setDefaultTemplateID(currentPageDef.getID() + 1);
1334                                sMgr.updateSite(site);
1335                            }
1336                        }
1337                    }
1338
1339                    // reset session
1340
session.setAttribute( CLASS_NAME + "newJahiaSite" , null );
1341
1342                    displayList( request, response, session );
1343                } else {
1344                    JahiaAdministration.doRedirect( request, response, session, JSP_PATH + "menu.jsp" );
1345                }
1346            }catch ( JahiaException je ){
1347                logger.error("Exception ", je );
1348                String JavaDoc jahiaDisplayMessage = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.processingError.label",
1349                                                 jParams, jParams.getLocale());
1350                session.setAttribute(CLASS_NAME + "jahiaDisplayMessage", jahiaDisplayMessage);
1351                JahiaAdministration.doRedirect( request, response, session, JSP_PATH + "menu.jsp" );
1352                return;
1353            }
1354        }
1355    }
1356
1357
1358
1359    /**
1360     * Display Edit Site form
1361     *
1362     * @param request Servlet request.
1363     * @param response Servlet response.
1364     * @param session HttpSession object.
1365     */

1366    private void displayEdit( HttpServletRequest JavaDoc request,
1367                                HttpServletResponse JavaDoc response,
1368                                HttpSession JavaDoc session )
1369    throws IOException JavaDoc, ServletException JavaDoc
1370    {
1371        //logger.debug(" display edit site started ");
1372

1373        try
1374        {
1375            // get site...
1376
String JavaDoc site_id = JahiaTools.getStrParameter(request,"siteid","").trim();
1377            Integer JavaDoc siteID = new Integer JavaDoc( site_id );
1378            JahiaSite site = sMgr.getSite( siteID.intValue() );
1379
1380            // retrieve previous form values...
1381
String JavaDoc jahiaDisplayMessage = (String JavaDoc) request.getAttribute(CLASS_NAME + "jahiaDisplayMessage");
1382            String JavaDoc siteTitle = (String JavaDoc) request.getAttribute("siteTitle");
1383            String JavaDoc siteServerName = (String JavaDoc) request.getAttribute("siteServerName");
1384            String JavaDoc siteKey = (String JavaDoc) request.getAttribute("siteKey");
1385            String JavaDoc siteDescr = (String JavaDoc) request.getAttribute("siteDescr");
1386            String JavaDoc warningMsg = (String JavaDoc) request.getAttribute("warningMsg");
1387
1388            Boolean JavaDoc defaultSite = Boolean.FALSE;
1389            Boolean JavaDoc versioningEnabled = Boolean.valueOf(site.isVersioningEnabled());
1390            Boolean JavaDoc stagingEnabled = Boolean.valueOf(site.isStagingEnabled());
1391
1392            if ( request.getAttribute("defaultSite") == null ){
1393                JahiaSite defSite = getDefaultSite();
1394                if (defSite != null && defSite.getSiteKey().equals(site.getSiteKey())) {
1395                    defaultSite = Boolean.TRUE;
1396                }
1397            } else {
1398                defaultSite = (Boolean JavaDoc)request.getAttribute("defaultSite");
1399            }
1400
1401            if ( request.getAttribute("versioningEnabled") != null ){
1402                versioningEnabled = (Boolean JavaDoc)request.getAttribute("versioningEnabled");
1403            }
1404            if ( request.getAttribute("stagingEnabled") != null ){
1405                stagingEnabled = (Boolean JavaDoc)request.getAttribute("stagingEnabled");
1406            }
1407            // set default values...
1408
if(jahiaDisplayMessage == null) {
1409                jahiaDisplayMessage =
1410                    JahiaResourceBundle.getAdminResource("org.jahia.admin.copyright",
1411                        jParams, jParams.getLocale());
1412            }
1413            if(siteTitle == null) { siteTitle = site.getTitle(); }
1414            if(siteServerName == null) { siteServerName = site.getServerName(); }
1415            if(siteKey == null) { siteKey = site.getSiteKey(); }
1416            if(siteDescr == null) { siteDescr = site.getDescr(); }
1417            if(warningMsg == null) { warningMsg = ""; }
1418
1419            // set request attributes...
1420
request.setAttribute("jahiaDisplayMessage", jahiaDisplayMessage);
1421            request.setAttribute("siteTitle", siteTitle);
1422            request.setAttribute("siteServerName", siteServerName);
1423            request.setAttribute("siteKey", siteKey);
1424            request.setAttribute("siteDescr", siteDescr);
1425            request.setAttribute("warningMsg", warningMsg);
1426            request.setAttribute("siteID", siteID);
1427            request.setAttribute("defaultSite", defaultSite);
1428            request.setAttribute("versioningEnabled", versioningEnabled);
1429            request.setAttribute("stagingEnabled", stagingEnabled);
1430
1431            // redirect...
1432
JahiaAdministration.doRedirect( request, response, session, JSP_PATH + "site_edit.jsp" );
1433        } catch (Exception JavaDoc e) {
1434            // redirect to list...
1435
String JavaDoc jahiaDisplayMessage = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.processingError.label",
1436                                             jParams, jParams.getLocale());
1437            session.setAttribute(CLASS_NAME + "jahiaDisplayMessage", jahiaDisplayMessage);
1438            displayList( request, response, session );
1439
1440            // reset display message...
1441
session.setAttribute(CLASS_NAME + "jahiaDisplayMessage",
1442                JahiaResourceBundle.getAdminResource("org.jahia.admin.copyright",
1443                    jParams, jParams.getLocale()));
1444        }
1445    } // end displayEdit
1446

1447
1448
1449    /**
1450     * Process Edit Site form
1451     *
1452     * @param request Servlet request.
1453     * @param response Servlet response.
1454     * @param session HttpSession object.
1455     */

1456    private void processEdit( HttpServletRequest JavaDoc request,
1457                                 HttpServletResponse JavaDoc response,
1458                                 HttpSession JavaDoc session )
1459    throws IOException JavaDoc, ServletException JavaDoc
1460    {
1461        logger.debug(" process edit site started ");
1462
1463        boolean processError = false;
1464
1465        // get form values...
1466
String JavaDoc siteTitle = JahiaTools.getStrParameter(request,"siteTitle","").trim();
1467        String JavaDoc siteServerName = JahiaTools.getStrParameter(request,"siteServerName","").trim();
1468// String siteKey = JahiaTools.getStrParameter(request,"siteKey","").toLowerCase().trim();
1469
String JavaDoc siteDescr = JahiaTools.getStrParameter(request,"siteDescr","").trim();
1470        String JavaDoc warningMsg = "";
1471        boolean defaultSite = ( request.getParameter("defaultSite") != null );
1472        boolean versioningEnabled = ( request.getParameter("versioningEnabled") != null );
1473        boolean stagingEnabled = ( request.getParameter("stagingEnabled") != null );
1474
1475        // set request attributes...
1476
request.setAttribute("siteTitle", siteTitle);
1477        request.setAttribute("siteServerName", siteServerName);
1478        request.setAttribute("siteDescr", siteDescr);
1479        request.setAttribute("defaultSite", Boolean.valueOf(defaultSite) );
1480        request.setAttribute("versioningEnabled", Boolean.valueOf(versioningEnabled) );
1481        request.setAttribute("stagingEnabled", Boolean.valueOf(stagingEnabled) );
1482
1483        try
1484        {
1485            // get site...
1486
String JavaDoc site_id = JahiaTools.getStrParameter(request,"siteid","").trim();
1487            Integer JavaDoc siteID = new Integer JavaDoc( site_id );
1488            JahiaSite site = sMgr.getSite( siteID.intValue() );
1489
1490            // check validity...
1491
if ( siteTitle != null && (siteTitle.trim().length()>0)
1492                 && siteServerName != null && (siteServerName.trim().length()>0)
1493                ) {
1494
1495                if(!site.getServerName().equals(siteServerName)) {
1496                    if ( sMgr.getSite(siteServerName) != null ){
1497                      warningMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg.chooseAnotherServerName.label",
1498                                                       jParams, jParams.getLocale());
1499                        processError = true;
1500                    }
1501                }
1502
1503            } else {
1504              warningMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg.completeRequestInfo.label",
1505                                               jParams, jParams.getLocale());
1506            }
1507
1508            if(!processError)
1509            {
1510                // save modified informations...
1511
site.setTitle(siteTitle);
1512                site.setServerName(siteServerName);
1513                site.setDescr(siteDescr);
1514                site.setVersioning(versioningEnabled);
1515                site.setStaging(stagingEnabled);
1516                sMgr.updateSite( site );
1517
1518                JahiaSite defSite = getDefaultSite();
1519                if ( defaultSite ){
1520                    if ( defSite == null ){
1521                        changeDefaultSite(site);
1522                    } else if ( !defSite.getSiteKey().equals(site.getSiteKey()) ){
1523                        changeDefaultSite(site);
1524                    }
1525                } else {
1526                    if ( defSite != null && defSite.getSiteKey().equals(site.getSiteKey()) ){
1527                        changeDefaultSite(null);
1528                    }
1529                }
1530
1531                // set message default values...
1532
session.setAttribute(CLASS_NAME + "jahiaDisplayMessage",
1533                    JahiaResourceBundle.getAdminResource("org.jahia.admin.copyright",
1534                        jParams, jParams.getLocale()));
1535
1536                // redirect...
1537
displayList( request, response, session);
1538            } else {
1539                request.setAttribute("warningMsg", warningMsg);
1540                displayEdit( request, response, session);
1541            }
1542        } catch (JahiaException ex) {
1543          warningMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg.processingRequestError.label",
1544                                           jParams, jParams.getLocale());
1545            request.setAttribute("warningMsg", warningMsg);
1546            displayEdit( request, response, session);
1547        }
1548    }
1549
1550
1551    /**
1552     * Set the site as default site in storage, if site == null , set default site to undefined
1553     *
1554     * @param site the site
1555     */

1556    private void changeDefaultSite(JahiaSite site){
1557
1558        String JavaDoc siteKey = "";
1559
1560        if ( site != null ){
1561            siteKey = site.getSiteKey();
1562        }
1563        PropertiesManager pm = new PropertiesManager(Jahia.getJahiaPropertiesFileName());
1564
1565        if ( pm != null ){
1566            pm.setProperty("defautSite",siteKey);
1567            pm.storeProperties();
1568        }
1569        // we reload the settings because the default site has changed.
1570
Jahia.getSettings().load();
1571    }
1572
1573
1574    /**
1575     * Return the default site or null if not found or undefined
1576     *
1577     * @return JahiaSite the default site
1578     */

1579    private JahiaSite getDefaultSite(){
1580
1581
1582        JahiaSite site = null;
1583        String JavaDoc siteKey = null;
1584
1585        // try to load from storage
1586
PropertiesManager pm = new PropertiesManager(Jahia.getJahiaPropertiesFileName());
1587        if ( pm != null ){
1588            siteKey = pm.getProperty("defautSite");
1589            if ( siteKey == null || siteKey.trim().equals("") ){
1590                return null;
1591            }
1592        }
1593
1594        if ( siteKey != null ){
1595            try {
1596                site = ServicesRegistry.getInstance()
1597                            .getJahiaSitesService()
1598                            .getSiteByKey(siteKey);
1599            } catch ( JahiaException je ){
1600                return null;
1601            }
1602        }
1603        return site;
1604    }
1605
1606
1607    /**
1608     * Display Delete Site confirmation.
1609     *
1610     * @param request Servlet request.
1611     * @param response Servlet response.
1612     * @param session HttpSession object.
1613     */

1614    private void displayDelete( HttpServletRequest JavaDoc request,
1615                                  HttpServletResponse JavaDoc response,
1616                                  HttpSession JavaDoc session )
1617    throws IOException JavaDoc, ServletException JavaDoc
1618    {
1619
1620        //logger.debug(" display delete site started ");
1621

1622        // change session time out to 1 hour ( the extraction can be very long !)
1623
int timeOut = session.getMaxInactiveInterval();
1624
1625        try
1626        {
1627
1628            session.setMaxInactiveInterval(7200);
1629
1630            // get site...
1631
String JavaDoc site_id = JahiaTools.getStrParameter(request,"siteid","").trim();
1632            Integer JavaDoc siteID = new Integer JavaDoc( site_id );
1633
1634            JahiaSite site = sMgr.getSite( siteID.intValue() );
1635
1636            // retrieve previous form values...
1637
String JavaDoc jahiaDisplayMessage =
1638                JahiaResourceBundle.getAdminResource("org.jahia.admin.copyright",
1639                    jParams, jParams.getLocale());
1640            String JavaDoc siteTitle = (String JavaDoc) request.getAttribute("siteTitle");
1641            String JavaDoc siteServerName = (String JavaDoc) request.getAttribute("siteServerName");
1642            String JavaDoc siteKey = (String JavaDoc) request.getAttribute("siteKey");
1643            String JavaDoc siteDescr = (String JavaDoc) request.getAttribute("siteDescr");
1644
1645            // set default values...
1646
if(siteTitle == null) { siteTitle = site.getTitle(); }
1647            if(siteServerName == null) { siteServerName = site.getServerName(); }
1648            if(siteKey == null) { siteKey = site.getSiteKey(); }
1649            if(siteDescr == null) { siteDescr = site.getDescr(); }
1650
1651            // set request attributes...
1652
request.setAttribute("jahiaDisplayMessage", jahiaDisplayMessage);
1653            request.setAttribute("siteTitle", siteTitle);
1654            request.setAttribute("siteServerName", siteServerName);
1655            request.setAttribute("siteKey", siteKey);
1656            request.setAttribute("siteDescr", siteDescr);
1657            request.setAttribute("siteID", siteID);
1658
1659            // list of user providers
1660
UserManagerProviderBean usrProviderBean;
1661            JahiaUserManagerService userServ = ServicesRegistry.getInstance().getJahiaUserManagerService();
1662            Vector JavaDoc v = userServ.getProviderList();
1663            int size = v.size();
1664            Vector JavaDoc usrProviders = new Vector JavaDoc();
1665            for ( int i=0 ; i<size ; i++ ){
1666                usrProviderBean = (UserManagerProviderBean)v.get(i);
1667                if ( !usrProviderBean.getIsReadOnly() ){
1668                    usrProviders.add(usrProviderBean);
1669                }
1670            }
1671            request.setAttribute("usrProviders", usrProviders);
1672
1673            // redirect...
1674
JahiaAdministration.doRedirect( request, response, session, JSP_PATH + "site_delete.jsp" );
1675
1676        } catch (Exception JavaDoc e) {
1677            // redirect to list...
1678
String JavaDoc jahiaDisplayMessage = JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg..processingError.label",
1679                                             jParams, jParams.getLocale());
1680            session.setAttribute(CLASS_NAME + "jahiaDisplayMessage", jahiaDisplayMessage);
1681            displayList( request, response, session );
1682        } finally {
1683            // restore time out
1684
session.setMaxInactiveInterval(timeOut);
1685        }
1686
1687        // reset display message...
1688
session.setAttribute(CLASS_NAME + "jahiaDisplayMessage",
1689            JahiaResourceBundle.getAdminResource("org.jahia.admin.copyright",
1690                jParams, jParams.getLocale()));
1691    } // end displayEdit
1692

1693
1694
1695    /**
1696     * Process Delete Site.
1697     *
1698     * @param request Servlet request.
1699     * @param response Servlet response.
1700     * @param session HttpSession object.
1701     */

1702    private void processDelete( HttpServletRequest JavaDoc request,
1703                                   HttpServletResponse JavaDoc response,
1704                                   HttpSession JavaDoc session)
1705    throws IOException JavaDoc, ServletException JavaDoc
1706    {
1707        //logger.debug(" process delete site started ");
1708

1709        JahiaUser theUser = (JahiaUser) session.getAttribute( ParamBean.SESSION_USER );
1710
1711        try
1712        {
1713            // get site...
1714
String JavaDoc site_id = JahiaTools.getStrParameter(request,"siteid","").trim();
1715            Integer JavaDoc siteID = new Integer JavaDoc( site_id );
1716            JahiaSite site = sMgr.getSite( siteID.intValue() );
1717
1718            // now let's check if this site is the default site, in which case
1719
// we need to change the default site to another one.
1720
JahiaSite defSite = getDefaultSite();
1721
1722            // first let's build a list of the all the sites except the
1723
// current one.
1724
Enumeration JavaDoc siteEnum = ServicesRegistry.getInstance().getJahiaSitesService().getSites();
1725            ArrayList JavaDoc otherSites = new ArrayList JavaDoc();
1726            while (siteEnum.hasMoreElements()) {
1727                JahiaSite curSite = (JahiaSite) siteEnum.nextElement();
1728                if (!curSite.getSiteKey().equals(site.getSiteKey())) {
1729                    otherSites.add(curSite);
1730                }
1731            }
1732            if ( defSite == null ){
1733                // no default site, let's assign once that isn't the current
1734
// one being deleted.
1735
if (otherSites.size() > 0) {
1736                    changeDefaultSite((JahiaSite)otherSites.get(0));
1737                }
1738            } else if ( defSite.getSiteKey().equals(site.getSiteKey()) ){
1739                // the default site IS the site being deleted, let's set
1740
// another site as a default site.
1741
if (otherSites.size() > 0) {
1742                    changeDefaultSite((JahiaSite)otherSites.get(0));
1743                }
1744            }
1745
1746            // get the search index
1747
String JavaDoc index = ServicesRegistry.getInstance().getJahiaSearchService().getSiteIndex(site.getID());
1748
1749            // switch staging and versioning to false.
1750
site.setStaging(false);
1751            site.setVersioning(false);
1752            sMgr.updateSite(site);
1753
1754            // indicate the site is going to be deleted
1755
sMgr.addSiteToDelete(site.getID());
1756
1757            //remove site definition
1758
sMgr.removeSite( site );
1759
1760            // delete the search index
1761
if ( index != null ){
1762                File JavaDoc f = new File JavaDoc(index);
1763                if ( f.exists() ){
1764                    logger.debug(" site[" + site.getID() + "] Process delete search index ");
1765                    JahiaTools.deleteFile(f);
1766                }
1767            }
1768
1769            // flush the content cache completely
1770
/** @todo find a way to flush only the cache of the pages of the
1771             * concerned site.
1772             */

1773            CacheFactory.getHtmlCache().flush();
1774
1775            /**
1776             * @todo realy delete all content.
1777             */

1778            ContentPage contentPage = site.getHomeContentPage();
1779            contentPage.purge(EntryLoadRequest.STAGED);
1780
1781            if ( request.getParameter("deleteApplications") != null ){
1782                //logger.debug(" process delete applications ");
1783
JahiaSiteTools.deleteApplications(theUser,site);
1784            }
1785
1786            // delete site's filemanager
1787
JahiaFilemanagerService fileManServ = ServicesRegistry.getInstance()
1788                                                    .getJahiaFilemanagerService();
1789
1790            //fileManServ.deleteFilemanager(theUser,site.getID());
1791

1792            if ( request.getParameter("deleteFileRepository") != null ){
1793                //logger.debug(" process delete filerepository ");
1794
JahiaSiteTools.deleteFileRepository(theUser,site);
1795            }
1796
1797            // purge options
1798
if ( request.getParameter("deleteTemplates") != null ){
1799                //logger.debug(" process delete templates ");
1800
JahiaSiteTools.deleteTemplates(theUser,site);
1801            }
1802
1803            // delete site's logs
1804
JahiaAuditLogManagerService logServ = ServicesRegistry.getInstance()
1805                                                    .getJahiaAuditLogManagerService();
1806
1807            logServ.flushSiteLogs(theUser,site.getSiteKey());
1808
1809            // delete big text
1810
JahiaTextFileService textFileServ = ServicesRegistry.getInstance()
1811                                                    .getJahiaTextFileService();
1812
1813
1814            String JavaDoc[] vals = request.getParameterValues("usrProviders");
1815            if ( vals != null && vals.length>0 )
1816            {
1817                // list of user providers
1818
JahiaUserManagerService userServ = ServicesRegistry.getInstance().getJahiaUserManagerService();
1819                Vector JavaDoc v = userServ.getProviderList();
1820                Vector JavaDoc usrProviders = new Vector JavaDoc();
1821                int size = v.size();
1822                for ( int i=0 ; i<size ; i++ ){
1823                    UserManagerProviderBean usrProviderBean = (UserManagerProviderBean)v.get(i);
1824                    if ( JahiaTools.inValues(usrProviderBean.getKey(),vals) ){
1825                        usrProviders.add(usrProviderBean);
1826                    }
1827                }
1828                JahiaSiteTools.deleteUsers(theUser,site,usrProviders);
1829            }
1830
1831            textFileServ.deleteSiteBigText(site.getID(),theUser);
1832
1833
1834            // reset session site
1835
JahiaSite sessSite = (JahiaSite) session.getAttribute( ParamBean.SESSION_SITE );
1836            if ( sessSite != null && sessSite.getSiteKey().equals(site.getSiteKey()) ){
1837                session.setAttribute( ParamBean.SESSION_SITE, null );
1838            }
1839
1840            // redirect...
1841
displayList( request, response, session );
1842        } catch (JahiaException ex) {
1843            ex.printStackTrace();
1844            String JavaDoc warningMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg.processingRequestError.label",
1845                                             jParams, jParams.getLocale());
1846            request.setAttribute("warningMsg", warningMsg);
1847            displayEdit( request, response, session);
1848        }
1849    }
1850
1851    //--------------------------------------------------------------------------
1852
/**
1853     * Sites' Templates Services
1854     *
1855     *
1856     *
1857     ***************************************************************************/

1858
1859    /**
1860     * Copy the default template in the site's template directory.
1861     * Register this template as a page definition for this site.
1862     * Return this page definition which can be used as the default template
1863     * for the site's home page when it's created.
1864     */

1865    private JahiaPageDefinition createDefaultTemplate(JahiaSite site) throws JahiaException {
1866
1867        if ( site == null || JahiaSiteTools.getSiteTemplateFolder(site) == null ){
1868            return null;
1869        }
1870
1871        File JavaDoc f = new File JavaDoc(JahiaSiteTools.getSiteTemplateFolder(site));
1872        if ( !f.isDirectory() ){
1873            return null;
1874        }
1875
1876        JahiaPageDefinition pageDef = null;
1877
1878        JahiaTemplatesDeployerService jtds =
1879                ServicesRegistry.getInstance()
1880                                .getJahiaTemplatesDeployerService();
1881        if ( jtds == null ) {
1882            return null;
1883        }
1884
1885        // get the root folder for all templates
1886
String JavaDoc templateRootPath = jtds.getTemplateRootPath();
1887
1888        // get the jsp template context
1889
String JavaDoc templateContext = jtds.getTemplatesContext();
1890
1891        if ( templateRootPath != null && (templateRootPath.trim().length()>0)){
1892
1893            File JavaDoc defaultTemplate = new File JavaDoc(templateRootPath + File.separator + "default");
1894
1895            if ( defaultTemplate.isDirectory() ){
1896
1897                try {
1898                    logger.debug("copying default templates" );
1899                    JahiaTools.copyFolderContent(defaultTemplate.getAbsolutePath(),
1900                                JahiaSiteTools.getSiteTemplateFolder(site) + File.separator + "default");
1901
1902                    // create template definitions for this site
1903
pageDef = ServicesRegistry.getInstance().getJahiaPageTemplateService().
1904                                createPageTemplate (
1905                                            site.getID(),
1906                                            "Default Home",
1907                                            templateContext + site.getSiteKey() + "/default/home.jsp",
1908                                            true,
1909                                            "", // no image
1910
site.getAclID() );
1911                    return pageDef;
1912                } catch (IOException JavaDoc ioe) {
1913                    logger.error(
1914                    "error copying default templates for default site", ioe);
1915                }
1916            }
1917        }
1918
1919        return null;
1920     }
1921
1922
1923    /**
1924     * copy all shared templates package (.jar) found in the
1925     * jahiafiles\shared_templates
1926     *
1927     * @param siteKey
1928     * @return boolean false on error
1929     */

1930    private boolean copySharedTemplates(String JavaDoc siteKey){
1931
1932
1933        JahiaTemplatesDeployerService tds = ServicesRegistry
1934                                            .getInstance()
1935                                            .getJahiaTemplatesDeployerService();
1936
1937        if ( tds == null ){
1938            return false;
1939        }
1940
1941
1942        File JavaDoc f = new File JavaDoc( tds.getSharedTemplatesPath() );
1943
1944        // get the new templates folder for the site, create it if not exists
1945
File JavaDoc newTemplate = new File JavaDoc(tds.getNewTemplatesPath() + File.separator + siteKey);
1946        newTemplate.mkdirs();
1947        logger.debug(" newtemplate is " + newTemplate.getAbsolutePath() );
1948
1949        try {
1950            // copy all shared package to the new templates folder for the site
1951
JahiaTools.copyFolderContent(f.getAbsolutePath(),
1952                        newTemplate.getAbsolutePath());
1953        } catch ( Exception JavaDoc e ){
1954            // msg..
1955
return false;
1956        }
1957        return true;
1958    }
1959
1960
1961
1962
1963
1964    /**
1965     * copy all shared components package (.jar) found in the
1966     * jahiafiles\shared_components
1967     *
1968     * @param siteKey
1969     * @return boolean false on error
1970     */

1971    private boolean copySharedComponents(String JavaDoc siteKey){
1972
1973
1974        JahiaWebAppsDeployerService wads = ServicesRegistry
1975                                            .getInstance()
1976                                            .getJahiaWebAppsDeployerService();
1977
1978        if ( wads == null ){
1979            return false;
1980        }
1981
1982
1983        File JavaDoc f = new File JavaDoc( JahiaWebAppsDeployerService.getSharedComponentsPath() );
1984
1985        // get the new components folder for the site, create it if not exists
1986
File JavaDoc newComponents = new File JavaDoc(JahiaWebAppsDeployerService.getNewWebAppsPath() + File.separator + siteKey);
1987        newComponents.mkdirs();
1988        logger.debug(" newcomponents is " + newComponents.getAbsolutePath() );
1989
1990        try {
1991            // copy all shared package to the new components folder for the site
1992
JahiaTools.copyFolderContent(f.getAbsolutePath(),
1993                        newComponents.getAbsolutePath());
1994        } catch ( Exception JavaDoc e ){
1995            // msg..
1996
return false;
1997        }
1998        return true;
1999    }
2000
2001
2002    /**
2003     * Deploy templates found in the new template folder of this site.
2004     *
2005     * @param site the site
2006     * @return boolean false on error
2007     */

2008    private boolean deployTemplates(JahiaSite site){
2009
2010        JahiaTemplatesDeployerService tds = ServicesRegistry
2011                                            .getInstance()
2012                                            .getJahiaTemplatesDeployerService();
2013
2014        if ( site == null || tds == null ){
2015            return false;
2016        }
2017
2018        // get the new templates folder for the site, create it if not exists
2019
File JavaDoc newTemplate = new File JavaDoc(tds.getNewTemplatesPath() + File.separator + site.getSiteKey());
2020        newTemplate.mkdirs();
2021        logger.debug(" newtemplate is " + newTemplate.getAbsolutePath() );
2022
2023        Vector JavaDoc v = new Vector JavaDoc();
2024
2025        File JavaDoc[] files = newTemplate.listFiles();
2026        for ( int i=0 ; i<files.length ; i++ ){
2027            logger.debug(" shared template package found " + files[i].getName() );
2028            if ( files[i].isFile() ){
2029                v.add(files[i]);
2030            }
2031        }
2032        return tds.deploy(site,v);
2033    }
2034
2035}
2036
Popular Tags