KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > admin > templates > ManageTemplates


1 // $Id: ManageTemplates.java 10570 2005-09-13 09:35:40Z pvollenweider $
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
// ManageTemplates
15
//
16
// 01.04.2001 AK added in jahia.
17
// 17.05.2001 NK Integrate License Check.
18
//
19

20 package org.jahia.admin.templates;
21
22 import java.io.File JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.util.ArrayList JavaDoc;
25 import java.util.Enumeration JavaDoc;
26 import java.util.List JavaDoc;
27 import java.util.Vector JavaDoc;
28
29 import javax.servlet.ServletContext JavaDoc;
30 import javax.servlet.ServletException JavaDoc;
31 import javax.servlet.http.HttpServletRequest JavaDoc;
32 import javax.servlet.http.HttpServletResponse JavaDoc;
33 import javax.servlet.http.HttpSession JavaDoc;
34
35 import org.jahia.bin.Jahia;
36 import org.jahia.bin.JahiaAdministration;
37 import org.jahia.data.JahiaData;
38 import org.jahia.data.templates.JahiaTemplatesPackage;
39 import org.jahia.exceptions.JahiaException;
40 import org.jahia.params.ParamBean;
41 import org.jahia.registries.ServicesRegistry;
42 import org.jahia.resourcebundle.JahiaResourceBundle;
43 import org.jahia.services.pages.ContentPage;
44 import org.jahia.services.pages.JahiaPage;
45 import org.jahia.services.pages.JahiaPageBaseService;
46 import org.jahia.services.pages.JahiaPageDefinition;
47 import org.jahia.services.pages.JahiaPageService;
48 import org.jahia.services.pages.JahiaPageTemplateService;
49 import org.jahia.services.sites.JahiaSite;
50 import org.jahia.services.sites.JahiaSiteTools;
51 import org.jahia.services.sites.JahiaSitesService;
52 import org.jahia.services.templates_deployer.JahiaTemplatesDeployerService;
53 import org.jahia.services.usermanager.JahiaUser;
54 import org.jahia.utils.JahiaTools;
55 import org.jahia.utils.properties.PropertiesManager;
56 import org.jahia.security.license.License;
57
58
59 /**
60  * desc: This class is used by the administration to manage
61  * all the templates you've on your Jahia portal. You can add a
62  * template, edit, change the visibility of the template and edit
63  * its options. You can also view non-installed templates.
64  *
65  * Copyright: Copyright (c) 2002
66  * Company: Jahia Ltd
67  *
68  * @author Khue N'Guyen
69  * @author Alexandre Kraft
70  * @version 1.0
71  */

72 public class ManageTemplates
73 {
74     private static org.apache.log4j.Logger logger =
75             org.apache.log4j.Logger.getLogger(ManageTemplates.class);
76
77     private static final String JavaDoc CLASS_NAME = JahiaAdministration.CLASS_NAME;
78     private static final String JavaDoc JSP_PATH = JahiaAdministration.JSP_PATH;
79
80     private static ServletContext JavaDoc context;
81
82     private JahiaSite site;
83     private JahiaUser user;
84     private ServicesRegistry sReg;
85
86     private License coreLicense;
87
88
89     /**
90      * Default constructor.
91      * @author Alexandre Kraft
92      *
93      * @param request Servlet request.
94      * @param response Servlet response.
95      * @param session Servlet session for the current user.
96      * @param context Servlet context.
97      */

98     public ManageTemplates( HttpServletRequest JavaDoc request,
99                             HttpServletResponse JavaDoc response,
100                             HttpSession JavaDoc session,
101                             ServletContext JavaDoc context )
102     throws Throwable JavaDoc
103     {
104         ManageTemplates.context = context;
105         JahiaData jData = (JahiaData) request.getAttribute("org.jahia.data.JahiaData");
106         ParamBean jParams = null;
107         if (jData != null) {
108             jParams = jData.params();
109         }
110
111         coreLicense = Jahia.getCoreLicense();
112         if ( coreLicense == null ){
113             // set request attributes...
114
String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.invalidLicenseKey.label",
115                                                jParams, jParams.getLocale());
116             request.setAttribute("jahiaDisplayMessage", dspMsg);
117             // redirect...
118
JahiaAdministration.doRedirect( request, response, session, JSP_PATH + "menu.jsp" );
119             return;
120         }
121
122         userRequestDispatcher( request, response, session );
123     } // end constructor
124

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

135     private void userRequestDispatcher( HttpServletRequest JavaDoc request,
136                                         HttpServletResponse JavaDoc response,
137                                         HttpSession JavaDoc session )
138     throws Throwable JavaDoc
139     {
140         String JavaDoc operation = request.getParameter("sub");
141
142         sReg = ServicesRegistry.getInstance();
143
144         // check if the user has really admin access to this site...
145
user = (JahiaUser) session.getAttribute( ParamBean.SESSION_USER );
146         site = (JahiaSite) session.getAttribute( ParamBean.SESSION_SITE );
147         JahiaData jData = (JahiaData) request.getAttribute("org.jahia.data.JahiaData");
148         ParamBean jParams = null;
149         if (jData != null) {
150             jParams = jData.params();
151         }
152
153         if ( site != null && user != null && sReg != null ){
154
155             if ( JahiaSiteTools.getAdminGroup(site).isMember(user) ){
156
157                 // set the new site id to administrate...
158
request.setAttribute( "site", site );
159
160                 if(operation.equals("display")) {
161                     displayTemplateList( request, response, session );
162                 } else if(operation.equals("displaynewlist")) {
163                     displayNewTemplateList( request, response, session );
164                 } else if(operation.equals("details")) {
165                     displayNewTemplateDetail( request, response, session );
166                 } else if(operation.equals("edit")) {
167                     editTemplate( request, response, session );
168                 } else if(operation.equals("options")) {
169                     editTemplateOption( request, response, session );
170                 } else if(operation.equals("add")) {
171                     addTemplate( request, response, session );
172                 } else if(operation.equals("swap")) {
173                     processSwap( request, response, session );
174                 }
175             } else {
176                 //System.out.println(" --> no admin access on this site <--");
177
String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
178                                                    jParams, jParams.getLocale());
179                 request.setAttribute("jahiaDisplayMessage", dspMsg);
180                 JahiaAdministration.doRedirect( request, response, session, JSP_PATH + "menu.jsp" );
181             }
182         } else {
183           String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
184                                              jParams, jParams.getLocale());
185           request.setAttribute("jahiaDisplayMessage", dspMsg);
186             JahiaAdministration.doRedirect( request, response, session, JSP_PATH + "menu.jsp" );
187         }
188
189     } // userRequestDispatcher
190

191
192
193     //-------------------------------------------------------------------------
194
/**
195      * Display a list of the templates.
196      *
197      * @author NK
198      * @param request Servlet request.
199      * @param response Servlet response.
200      * @param session HttpSession object.
201      */

202     private void displayTemplateList( HttpServletRequest JavaDoc request,
203                                       HttpServletResponse JavaDoc response,
204                                       HttpSession JavaDoc session )
205     throws Throwable JavaDoc
206
207     {
208
209       JahiaData jData = (JahiaData) request.getAttribute("org.jahia.data.JahiaData");
210       ParamBean jParams = null;
211       if (jData != null) {
212           jParams = jData.params();
213       }
214         try {
215
216             JahiaPageTemplateService pageTempServ =
217             sReg.getJahiaPageTemplateService();
218
219             if ( pageTempServ == null ){
220                 throw new JahiaException( "Unavailable Services",
221                                             "Unavailable Services",
222                                             JahiaException.SERVICE_ERROR,
223                                             JahiaException.ERROR_SEVERITY );
224             }
225
226             Enumeration JavaDoc enumeration = pageTempServ.getPageTemplates (site.getID(), false);
227             request.setAttribute("templList", enumeration);
228
229             JahiaAdministration.doRedirect( request,
230                                             response,
231                                             session,
232                                             JSP_PATH + "manage_templates.jsp" );
233
234         } catch ( JahiaException je ){
235           String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
236                                              jParams, jParams.getLocale());
237           request.setAttribute("jahiaDisplayMessage", dspMsg);
238             JahiaAdministration.doRedirect( request,
239                                             response,
240                                             session,
241                                             JSP_PATH + "menu.jsp" );
242         }
243
244
245     } // end displayTemplateList
246

247
248     //-------------------------------------------------------------------------
249
/**
250      * Display the edit form for a single template.
251      *
252      * @author NK
253      * @param request Servlet request.
254      * @param response Servlet response.
255      * @param session HttpSession object.
256      */

257     private void editTemplate( HttpServletRequest JavaDoc request,
258                                 HttpServletResponse JavaDoc response,
259                                 HttpSession JavaDoc session )
260     throws Throwable JavaDoc
261     {
262
263       JahiaData jData = (JahiaData) request.getAttribute("org.jahia.data.JahiaData");
264       ParamBean jParams = null;
265       if (jData != null) {
266           jParams = jData.params();
267       }
268         try {
269
270             JahiaPageTemplateService pageTempServ =
271             sReg.getJahiaPageTemplateService();
272
273             JahiaTemplatesDeployerService tempDepServ =
274             sReg.getJahiaTemplatesDeployerService();
275
276             JahiaSitesService sitesServ =
277             sReg.getJahiaSitesService();
278
279             JahiaPageService pageServ =
280             sReg.getJahiaPageService();
281
282             if ( pageTempServ == null
283                 || tempDepServ == null
284                 || sitesServ == null
285                 || pageServ == null ){
286                 throw new JahiaException( "Unavailable Services",
287                                             "Unavailable Services",
288                                             JahiaException.SERVICE_ERROR,
289                                             JahiaException.ERROR_SEVERITY );
290             }
291
292             // get paramater
293
String JavaDoc strVal = request.getParameter("templid");
294             if ( strVal != null ){
295                 int id = Integer.parseInt(strVal);
296                 JahiaPageDefinition templ = pageTempServ.lookupPageTemplate (id);
297
298                 // this is here so it doesn't overwrite the value set after critical pages check...
299
request.setAttribute("canDelete", Boolean.TRUE );
300
301                 if ( templ != null ){
302
303                     String JavaDoc subAction = (String JavaDoc) request.getParameter("subaction");
304
305                     // Override subAction if we are performing a template swap before
306
// template deletion
307
Integer JavaDoc processedSwap = (Integer JavaDoc)request.getAttribute("processedSwap");
308                     if ( processedSwap != null && processedSwap.intValue() == 1 ) {
309                         subAction = "confirmdelete";
310                     }
311
312                     if ( subAction == null ){
313                         subAction = "";
314                     }
315
316                     if ( subAction.equals("delete") ) {
317                         String JavaDoc undeploy = (String JavaDoc)request.getParameter("undeploy");
318
319                         if ( undeploy != null ){
320                             tempDepServ.undeploy(templ);
321                         }
322
323                         pageTempServ.deletePageTemplate(templ.getID());
324                         displayTemplateList(request,response,session);
325                         return;
326
327                     } else if ( subAction.equals("confirmdelete") ) {
328
329                         List JavaDoc criticalPages = new ArrayList JavaDoc();
330                         int mTemplID = templ.getID();
331                         Vector JavaDoc pageIDs = pageServ.getPageIDsWithTemplate(mTemplID);
332                         for (int i=0; i<pageIDs.size(); i++) {
333
334                             int pageID = ((Integer JavaDoc)pageIDs.get(i)).intValue();
335
336                             try {
337                                 ContentPage contentPage = ContentPage.getPage(pageID,false);
338                                 criticalPages.add(contentPage);
339                             } catch (Throwable JavaDoc t) {
340                                 logger.debug("Exception when loading pages using template[" + mTemplID + "]",t);
341                             }
342                         }
343                         if (!criticalPages.isEmpty()) {
344                             request.setAttribute("processedSwap", null);
345                             displaySwap (request, response, session, criticalPages, templ);
346                             return;
347                         }
348
349                         request.setAttribute("currAction", "confirmdelete");
350
351                     } else if ( subAction.equals("swap") ) {
352
353                         // process requested template swapping for a set of pages...
354
processSwap (request, response, session);
355
356                     } else if ( subAction.equals("save") ) {
357
358                         String JavaDoc templName = (String JavaDoc)request.getParameter("templName");
359                         String JavaDoc visible_status = (String JavaDoc)request.getParameter("visible_status");
360
361                         if (templName != null && (templName.trim().length()>0) ){
362                             templ.setName(templName);
363                         }
364                         if ( visible_status != null ){
365                             templ.setAvailable(true);
366                             String JavaDoc isDefault = (String JavaDoc)request.getParameter("isDefault");
367                             if ( isDefault != null ){
368                                 site.setDefaultTemplateID(templ.getID());
369                             } else {
370                                 site.setDefaultTemplateID(-1);
371                             }
372                         } else {
373                             templ.setAvailable(false);
374                         }
375
376                         templ.commitChanges();
377
378                         sitesServ.updateSite(site);
379
380                         templ = pageTempServ.lookupPageTemplate (id);
381                         String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.templateUpdated.label",
382                                                            jParams, jParams.getLocale());
383                         session.setAttribute(CLASS_NAME + "jahiaDisplayMessage", dspMsg);
384                     }
385
386                 } else {
387                   String JavaDoc errMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.errMsg.noTemplateDefinition.label",
388                                                      jParams, jParams.getLocale());
389                   request.setAttribute("errMsg", errMsg);
390                 }
391
392                 int pageid = site.getHomePageID();
393                 JahiaPage page = pageServ.lookupPage(pageid);
394
395                 if ( page != null && (page.getPageTemplateID() == templ.getID()) ){
396                     request.setAttribute("canDelete", Boolean.FALSE );
397                 }
398
399                 request.setAttribute("templ", templ);
400
401             }
402
403             request.setAttribute("templatesContext",getTemplatesContext(session));
404
405             JahiaAdministration.doRedirect( request,
406                                             response,
407                                             session,
408                                             JSP_PATH + "template_edit.jsp" );
409
410         } catch ( JahiaException je ){
411           String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
412                                              jParams, jParams.getLocale());
413           request.setAttribute("jahiaDisplayMessage", dspMsg);
414             JahiaAdministration.doRedirect( request,
415                                             response,
416                                             session,
417                                             JSP_PATH + "menu.jsp" );
418         }
419
420     }
421
422     //-------------------------------------------------------------------------
423
/**
424      * Handle Edit Templates options
425      *
426      * @author NK
427      * @param request Servlet request.
428      * @param response Servlet response.
429      * @param session HttpSession object.
430      */

431     private void editTemplateOption( HttpServletRequest JavaDoc request,
432                                         HttpServletResponse JavaDoc response,
433                                         HttpSession JavaDoc session )
434     throws IOException JavaDoc, ServletException JavaDoc
435     {
436
437       JahiaData jData = (JahiaData) request.getAttribute("org.jahia.data.JahiaData");
438       ParamBean jParams = null;
439       if (jData != null) {
440           jParams = jData.params();
441       }
442         try {
443
444             JahiaSitesService sitesServ =
445             sReg.getJahiaSitesService();
446
447
448             if ( sitesServ == null ){
449                 throw new JahiaException( "Unavailable Services",
450                                             "Unavailable Services",
451                                             JahiaException.SERVICE_ERROR,
452                                             JahiaException.ERROR_SEVERITY );
453             }
454
455             int autoDeploy = 0;
456
457             if ( site.getTemplatesAutoDeployMode() ){
458                 autoDeploy = 1;
459             }
460
461             request.setAttribute("autoDeploy", new Integer JavaDoc(autoDeploy));
462
463             // get paramater
464
String JavaDoc subAction =(String JavaDoc)request.getParameter("subaction");
465             if ( subAction != null && subAction.equals("save") ) {
466
467                 String JavaDoc strVal = (String JavaDoc)request.getParameter("autoDeploy");
468                 int intVal = 0;
469
470                 if ( strVal != null ){
471                     intVal = 1;
472                 }
473
474                 if ( intVal != autoDeploy ){
475                     try {
476                         site.setTemplatesAutoDeployMode(intVal==1);
477                         sitesServ.updateSite(site);
478
479                         session.setAttribute( ParamBean.SESSION_SITE , site );
480
481                         String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.changeUpdated.label",
482                                                            jParams, jParams.getLocale());
483                         session.setAttribute(CLASS_NAME + "jahiaDisplayMessage", dspMsg);
484
485                     } catch ( JahiaException je ) {
486                       String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.changeNotUpdated.label",
487                                                          jParams, jParams.getLocale());
488                       session.setAttribute(CLASS_NAME + "jahiaDisplayMessage", dspMsg);
489                     }
490
491                     request.setAttribute("autoDeploy", new Integer JavaDoc(intVal));
492                 }
493             }
494
495             JahiaAdministration.doRedirect( request,
496                                             response,
497                                             session,
498                                             JSP_PATH + "template_option.jsp" );
499         } catch ( JahiaException je ){
500           String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
501                                              jParams, jParams.getLocale());
502           request.setAttribute("jahiaDisplayMessage", dspMsg);
503             JahiaAdministration.doRedirect( request,
504                                             response,
505                                             session,
506                                             JSP_PATH + "menu.jsp" );
507         }
508
509
510     } // end editTemplateOption
511

512
513     //-------------------------------------------------------------------------
514
/**
515      * Display the list of new templates.
516      *
517      * @author NK
518      * @param request Servlet request.
519      * @param response Servlet response.
520      * @param session HttpSession object.
521      */

522     private void displayNewTemplateList( HttpServletRequest JavaDoc request,
523                                        HttpServletResponse JavaDoc response,
524                                        HttpSession JavaDoc session )
525     throws IOException JavaDoc, ServletException JavaDoc
526     {
527
528       JahiaData jData = (JahiaData) request.getAttribute("org.jahia.data.JahiaData");
529       ParamBean jParams = null;
530       if (jData != null) {
531           jParams = jData.params();
532       }
533         try {
534
535             JahiaTemplatesDeployerService tempDepServ =
536             sReg.getJahiaTemplatesDeployerService();
537
538
539             if ( tempDepServ == null ){
540                 throw new JahiaException( "Unavailable Services",
541                                             "Unavailable Services",
542                                             JahiaException.SERVICE_ERROR,
543                                             JahiaException.ERROR_SEVERITY );
544             }
545
546             // get the list of new web apps
547
Enumeration JavaDoc newTemplatesKeys = tempDepServ.getTemplatesPackageKeys(site.getSiteKey());
548             Enumeration JavaDoc enumeration = tempDepServ.getTemplatesPackages(site.getSiteKey());
549             Vector JavaDoc vec = new Vector JavaDoc();
550
551             JahiaTemplatesPackage aPackage = null;
552
553             while (enumeration.hasMoreElements()){
554
555                 aPackage = (JahiaTemplatesPackage)enumeration.nextElement();
556
557                 if ( aPackage != null ){
558                     vec.add(aPackage);
559                 } else {
560                     //System.out.println("displayNewTemplateList packages is null");
561
}
562             }
563
564             request.setAttribute("packagesList", vec.elements());
565             JahiaAdministration.doRedirect( request,
566                                             response,
567                                             session,
568                                             JSP_PATH + "new_templates.jsp" );
569         } catch ( JahiaException je ){
570           String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
571                                              jParams, jParams.getLocale());
572           request.setAttribute("jahiaDisplayMessage", dspMsg);
573             JahiaAdministration.doRedirect( request,
574                                             response,
575                                             session,
576                                             JSP_PATH + "menu.jsp" );
577         }
578
579     }
580
581
582
583     //-------------------------------------------------------------------------
584
/**
585      * Display informations about a new template
586      *
587      * @author NK
588      * @param request Servlet request.
589      * @param response Servlet response.
590      * @param session HttpSession object.
591      */

592     private void displayNewTemplateDetail( HttpServletRequest JavaDoc request,
593                                             HttpServletResponse JavaDoc response,
594                                             HttpSession JavaDoc session )
595     throws IOException JavaDoc, ServletException JavaDoc
596     {
597
598       JahiaData jData = (JahiaData) request.getAttribute("org.jahia.data.JahiaData");
599       ParamBean jParams = null;
600       if (jData != null) {
601           jParams = jData.params();
602       }
603         try {
604
605             JahiaTemplatesDeployerService tempDepServ =
606             sReg.getJahiaTemplatesDeployerService();
607
608             JahiaPageTemplateService pageTempServ =
609             sReg.getJahiaPageTemplateService();
610
611
612             if ( tempDepServ == null || pageTempServ == null ){
613                 throw new JahiaException( "Unavailable Services",
614                                             "Unavailable Services",
615                                             JahiaException.SERVICE_ERROR,
616                                             JahiaException.ERROR_SEVERITY );
617             }
618
619             // get the new template package
620
String JavaDoc packageName = (String JavaDoc)request.getParameter("package_name");
621             JahiaTemplatesPackage aPackage =
622             (JahiaTemplatesPackage)tempDepServ.getTemplatesPackage(site.getSiteKey()
623                                                                     + "_"
624                                                                     + packageName);
625
626             // check for license limitation
627
int nbTemplates = pageTempServ.getNbPageTemplates(site.getID());
628
629             boolean canDeploy = ( ( Jahia.getTemplateLimit() == -1 )
630                                     || !(nbTemplates + aPackage.getTemplates().size() > Jahia.getTemplateLimit()) );
631
632             request.setAttribute("templateLimit", new Integer JavaDoc(Jahia.getTemplateLimit()) );
633             request.setAttribute("canDeploy", new Boolean JavaDoc(canDeploy) );
634
635
636             String JavaDoc subAction =(String JavaDoc)request.getParameter("subaction");
637             if ( subAction == null ){
638                 request.setAttribute("aPackage", aPackage);
639             } else if ( subAction.equals("deploy") && canDeploy){
640                 try {
641                     if (tempDepServ.deploy( site,
642                                             aPackage.getRootFolder(),
643                                             aPackage.getFilePath(),true)){
644
645                         // Register package in Jahia
646
tempDepServ.registerTemplates(site, aPackage);
647
648                         // delete the package
649
tempDepServ.deletePackage(site,aPackage.getFilePath());
650
651                         displayNewTemplateList(request,response,session);
652                         return;
653                     } else {
654                       String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.deployingPackageError.label",
655                                                          jParams, jParams.getLocale());
656                       session.setAttribute(CLASS_NAME + "jahiaDisplayMessage", dspMsg);
657                         request.setAttribute("aPackage", aPackage);
658                     }
659                 } catch ( JahiaException je ){
660                     request.setAttribute("aPackage", aPackage);
661                     String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.deployingPackageError.label",
662                                                        jParams, jParams.getLocale());
663                     session.setAttribute(CLASS_NAME + "jahiaDisplayMessage", dspMsg);
664                 }
665             } else if ( subAction.equals("delete") ){
666
667                 try {
668                     if (tempDepServ.deletePackage(site,aPackage.getFilePath())){
669                         displayNewTemplateList(request,response,session);
670                         return;
671                     } else {
672                         request.setAttribute("aPackage", aPackage);
673                         String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.deletingPackageError.label",
674                                                            jParams, jParams.getLocale());
675                         session.setAttribute(CLASS_NAME + "jahiaDisplayMessage", dspMsg);
676                     }
677                 } catch ( IOException JavaDoc ioe ){
678                   String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.deletingPackageError.label",
679                                                      jParams, jParams.getLocale());
680                   session.setAttribute(CLASS_NAME + "jahiaDisplayMessage", dspMsg);
681                 }
682             }
683
684              JahiaAdministration.doRedirect( request,
685                                              response,
686                                              session,
687                                              JSP_PATH + "new_template_detail.jsp" );
688         } catch ( JahiaException je ){
689           String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
690                                              jParams, jParams.getLocale());
691           request.setAttribute("jahiaDisplayMessage", dspMsg);
692             JahiaAdministration.doRedirect( request,
693                                             response,
694                                             session,
695                                             JSP_PATH + "menu.jsp" );
696         }
697
698     }
699
700
701     //-------------------------------------------------------------------------
702
/**
703      * Handle all the process of manually adding a new template
704      *
705      * @author NK
706      * @param request Servlet request.
707      * @param response Servlet response.
708      * @param session HttpSession object.
709      */

710     private void addTemplate( HttpServletRequest JavaDoc request,
711                                 HttpServletResponse JavaDoc response,
712                                 HttpSession JavaDoc session )
713
714     throws IOException JavaDoc, ServletException JavaDoc
715     {
716
717
718       JahiaData jData = (JahiaData) request.getAttribute("org.jahia.data.JahiaData");
719       ParamBean jParams = null;
720       if (jData != null) {
721           jParams = jData.params();
722       }
723         try {
724
725             JahiaTemplatesDeployerService tempDepServ =
726             sReg.getJahiaTemplatesDeployerService();
727
728             JahiaPageTemplateService pageTempServ =
729             sReg.getJahiaPageTemplateService();
730
731             if ( tempDepServ == null || pageTempServ == null ){
732                 throw new JahiaException( "Unavailable Services",
733                                             "Unavailable Services",
734                                             JahiaException.SERVICE_ERROR,
735                                             JahiaException.ERROR_SEVERITY );
736             }
737
738             // check for license limitation
739
int nbTemplates = pageTempServ.getNbPageTemplates(site.getID());
740
741             boolean canAddNew = ( (Jahia.getTemplateLimit() == -1)
742                                     || (nbTemplates < Jahia.getTemplateLimit()) );
743
744             request.setAttribute("templateLimit", new Integer JavaDoc(Jahia.getTemplateLimit()) );
745             request.setAttribute("canAddNew", new Boolean JavaDoc(canAddNew) );
746
747
748             PropertiesManager properties = new PropertiesManager( Jahia.getJahiaPropertiesFileName() );
749
750             request.setAttribute("warningMsg","");
751
752             JahiaSite site = (JahiaSite)request.getAttribute("site");
753
754             String JavaDoc subAction = (String JavaDoc)request.getParameter("subaction");
755             String JavaDoc templName = (String JavaDoc)request.getParameter("templName");
756             String JavaDoc rootFolder = (String JavaDoc)request.getParameter("rootFolder");
757             if ( rootFolder == null ){
758                 rootFolder = File.separator;
759             }
760
761             String JavaDoc fileName = (String JavaDoc)request.getParameter("fileName");
762             String JavaDoc isAvailable = (String JavaDoc)request.getParameter("isAvailable");
763
764             request.setAttribute("templName",JahiaTools.replaceNullString(templName,""));
765             request.setAttribute("rootFolder",JahiaTools.replaceNullString(rootFolder,""));
766             request.setAttribute("fileName",JahiaTools.replaceNullString(fileName,""));
767
768             if ( isAvailable != null ){
769                 request.setAttribute("isAvailable",new Integer JavaDoc(1));
770             } else {
771                 request.setAttribute("isAvailable",new Integer JavaDoc(0));
772             }
773
774             if ( subAction != null && subAction.equals("save") && canAddNew ){
775                 if ( templName == null || (templName.length()<=0)
776                      || fileName == null || (fileName.length()<=0) ) {
777                   String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg.completeRequestInfo.label",
778                                                      jParams, jParams.getLocale());
779                   request.setAttribute("warningMsg", dspMsg);
780                 } else {
781
782                     // save definition in db
783
String JavaDoc path = ManageTemplates.context.getRealPath(properties.getProperty("jahiaTemplatesDiskPath") );
784
785                     while ( rootFolder.startsWith("/")
786                             || rootFolder.startsWith("\\")
787                             || rootFolder.startsWith(".") ){
788                         rootFolder = rootFolder.substring(1,rootFolder.length());
789                     }
790
791                     while ( rootFolder.endsWith("/")
792                             || rootFolder.endsWith("\\") ){
793                         rootFolder = rootFolder.substring(0,rootFolder.length()-1);
794                     }
795
796                     // check if the file really exist
797
StringBuffer JavaDoc tempFullPath = new StringBuffer JavaDoc (1024);
798                     tempFullPath.append(path);
799                     tempFullPath.append(File.separator);
800                     tempFullPath.append(site.getSiteKey());
801                     tempFullPath.append(File.separator);
802                     tempFullPath.append(rootFolder);
803                     tempFullPath.append(File.separator) ;
804                     tempFullPath.append(fileName) ;
805
806                     if ( !JahiaTools.checkFileNameCaseSensitive(tempFullPath.toString()) ){
807                       String JavaDoc warningMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg.noFile.label",
808                                                          jParams, jParams.getLocale());
809                       warningMsg += " " + fileName + " ";
810                       warningMsg += JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg.inFolder.label",
811                                                          jParams, jParams.getLocale());
812                       warningMsg += " " + rootFolder;
813                       request.setAttribute("warningMsg", warningMsg);
814                     } else if ( rootFolder.startsWith(".") ){
815                       String JavaDoc warningMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg.invalidTemplateFolder.label",
816                                                          jParams, jParams.getLocale());
817                         request.setAttribute("warningMsg",warningMsg);
818                     } else {
819                         StringBuffer JavaDoc buff = new StringBuffer JavaDoc (1024);
820                         buff.append(properties.getProperty("jahiaTemplatesDiskPath"));
821                         buff.append(site.getSiteKey());
822                         buff.append("/") ;
823                         if ( !rootFolder.equals("") ){
824                             buff.append(rootFolder);
825                             buff.append("/") ;
826                         }
827                         buff.append(fileName) ;
828                         String JavaDoc sourcePath = JahiaTools.replacePattern(buff.toString(),"\\","/");
829
830                         JahiaPageDefinition def = pageTempServ.getPageTemplateBySourcePath(site.getID(),sourcePath);
831                         if ( def == null || !def.getSourcePath().equals(sourcePath) ){
832
833                             pageTempServ.createPageTemplate (
834
835                                         site.getID(),
836                                         templName,
837                                         sourcePath,
838                                         (isAvailable != null),
839                                         "", // no image
840
site.getAclID() );
841
842                             String JavaDoc warningMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg.template.label",
843                                 jParams, jParams.getLocale());
844                             warningMsg += " " + fileName + " ";
845                             warningMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.warningMsg.templateAdded.label",
846                                 jParams, jParams.getLocale());
847                             request.setAttribute("warningMsg",warningMsg);
848                         } else {
849                             request.setAttribute("warningMsg",
850                             "This template is already registered in Jahia");
851                         }
852                     }
853                 }
854
855             }
856
857             JahiaAdministration.doRedirect(request,response,session,JSP_PATH + "template_add.jsp");
858
859         } catch ( JahiaException je ){
860           String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.requestProcessingError.label",
861                                              jParams, jParams.getLocale());
862           request.setAttribute("jahiaDisplayMessage", dspMsg);
863             JahiaAdministration.doRedirect( request,
864                                             response,
865                                             session,
866                                             JSP_PATH + "menu.jsp" );
867         }
868
869
870     } // end addTemplate
871

872
873
874
875
876     protected String JavaDoc getTemplatesContext(HttpSession JavaDoc session){
877
878         String JavaDoc templatesContext = null;
879
880         // try to get from session
881
templatesContext = (String JavaDoc)session.getAttribute(CLASS_NAME + "jahiaTemplatesDiskPath");
882         if ( templatesContext == null ){
883
884             PropertiesManager props = new PropertiesManager( Jahia.getJahiaPropertiesFileName() );
885
886             if ( props!= null ){
887
888                 templatesContext = (String JavaDoc)props.getProperty("jahiaTemplatesDiskPath");
889
890                 if ( templatesContext != null ){
891                     session.setAttribute(CLASS_NAME + "jahiaTemplatesDiskPath", templatesContext);
892                 }
893             }
894         }
895
896         return templatesContext;
897     }
898
899
900     /**
901      * Display a custom version of the pages settings view, using doRedirect().
902      * This form prompts the user to choose an alternative template for any pages
903      * currently referenced.
904      *
905      * @author Alexandre Kraft
906      * @author Mikha�l Janson
907      *
908      * @param request Servlet request.
909      * @param response Servlet response.
910      * @param session Servlet session for the current user.
911      * @param criticalPages an <code>List</code> of <code>JahiaPage</code> objects referencing the template we want to delete.
912      * @param templ a reference to the template we want to delete.
913      */

914     private void displaySwap( HttpServletRequest JavaDoc request,
915                               HttpServletResponse JavaDoc response,
916                               HttpSession JavaDoc session,
917                               List JavaDoc criticalPages,
918                               JahiaPageDefinition templ )
919     throws IOException JavaDoc, ServletException JavaDoc
920     {
921         try {
922
923             // get all pages id...
924
JahiaPageBaseService pageService = JahiaPageBaseService.getInstance();
925             boolean canDeleteTemplate = true;
926             int currentVersion = ServicesRegistry.getInstance()
927                     .getJahiaVersionService().getCurrentVersionID();
928
929             // get all pages infos...
930
Vector JavaDoc allPagesInfosVector = new Vector JavaDoc();
931             Vector JavaDoc allTemplatesVector = new Vector JavaDoc();
932             for (int i=0; i<criticalPages.size(); i++) {
933                 ContentPage contentPage = (ContentPage) criticalPages.get(i);
934                 if ( canDeleteTemplate
935                      && (contentPage.hasActiveEntries() ||
936                      contentPage.hasArchiveEntryState(currentVersion) ) ){
937                     canDeleteTemplate = false;
938                 }
939                 allPagesInfosVector.add (contentPage);
940             }
941
942             // get homepage id for the current site...
943
Integer JavaDoc homePageID = new Integer JavaDoc( site.getHomePageID() );
944
945             // retrieve previous form values...
946
Integer JavaDoc basePageID = (Integer JavaDoc) request.getAttribute(CLASS_NAME + "basePageID");
947             Integer JavaDoc baseTemplateID = (Integer JavaDoc) request.getAttribute(CLASS_NAME + "baseTemplateID");
948
949             // get only visible templates
950
Enumeration JavaDoc completeTemplatesEnumeration = ServicesRegistry.getInstance().getJahiaPageTemplateService().getPageTemplates (site.getID(), true);
951
952             // exclude the template we want to delete...
953
while (completeTemplatesEnumeration.hasMoreElements()) {
954                 JahiaPageDefinition template = (JahiaPageDefinition) completeTemplatesEnumeration.nextElement();
955                 if(template.getID() != templ.getID()) {
956                     allTemplatesVector.add (template);
957                 }
958             }
959             Enumeration JavaDoc allTemplatesEnumeration = allTemplatesVector.elements();
960
961             // set default values...
962
if(basePageID == null) { basePageID = new Integer JavaDoc(0); }
963             if(baseTemplateID == null) { baseTemplateID = new Integer JavaDoc(0); }
964             if(homePageID == null) { homePageID = new Integer JavaDoc(0); }
965
966             // set all pages infos into an enumeration and redirect...
967
request.setAttribute("canDeleteTemplate", new Boolean JavaDoc(canDeleteTemplate));
968             request.setAttribute("homePageID", homePageID);
969             request.setAttribute("basePageID", basePageID);
970             request.setAttribute("baseTemplateID", baseTemplateID);
971             request.setAttribute("allTemplatesEnumeration", allTemplatesEnumeration);
972             request.setAttribute("allPagesInfosEnumeration", allPagesInfosVector.elements());
973             request.setAttribute("totalCriticalPages", new Integer JavaDoc(criticalPages.size()));
974             request.setAttribute("templ", templ);
975
976             JahiaAdministration.doRedirect( request, response, session, JSP_PATH + "template_cleanpages.jsp" );
977
978             // reset message...
979
JahiaData jData = (JahiaData)request.getAttribute ("org.jahia.data.JahiaData");
980             ParamBean jParams = null;
981             if (jData != null) {
982                 jParams = jData.params ();
983             }
984             session.setAttribute(CLASS_NAME + "jahiaDisplayMessage",
985                 JahiaResourceBundle.getAdminResource("org.jahia.admin.copyright",
986                     jParams, jParams.getLocale()));
987         } catch (JahiaException je) {
988         }
989     } // end displaySwap
990

991
992     /**
993      * Process requested template swapping to remove references
994      * to a given template from a page before deleteing the template.
995      *
996      * @author Mikha�l Janson
997      *
998      * @param request Servlet request.
999      * @param response Servlet response.
1000     * @param session Servlet session for the current user.
1001     */

1002    protected void processSwap( HttpServletRequest JavaDoc request,
1003                                HttpServletResponse JavaDoc response,
1004                                HttpSession JavaDoc session )
1005    throws Throwable JavaDoc
1006    {
1007        int idPage = 0;
1008        int idTemplate = 0;
1009        String JavaDoc idPageString = "";
1010        String JavaDoc idTemplateString = (String JavaDoc) request.getParameter("templateid").trim();
1011        String JavaDoc[] pageIDs = request.getParameterValues( "pageids" );
1012        List JavaDoc errors = new ArrayList JavaDoc();
1013        JahiaPage page = null;
1014        JahiaData jData = (JahiaData) request.getAttribute("org.jahia.data.JahiaData");
1015        ParamBean jParams = null;
1016        if (jData != null) {
1017            jParams = jData.params();
1018        }
1019
1020        boolean valid = true;
1021
1022
1023        // check form validity...
1024
if ((pageIDs == null) || (pageIDs.length < 1)) {
1025            valid = false;
1026            errors.add("Please choose at least one page.");
1027        }
1028
1029        if (idTemplateString.equals("0")) {
1030            valid = false;
1031            errors.add("Please choose a template.");
1032        }
1033
1034        if (!valid) {
1035            request.setAttribute("manageTemplatesErrors", errors);
1036            idTemplate = 0;
1037
1038        } else {
1039
1040            try {
1041
1042                idTemplate = Integer.parseInt(idTemplateString);
1043
1044            } catch (NumberFormatException JavaDoc nfe) {
1045                // FIXME - Mik : TEMPORARY...
1046
String JavaDoc dspMsg = JahiaResourceBundle.getAdminResource("org.jahia.admin.JahiaDisplayMessage.invalidTemplateReference.label",
1047                                                   jParams, jParams.getLocale());
1048                session.setAttribute(CLASS_NAME + "jahiaDisplayMessage", dspMsg);
1049            }
1050
1051        }
1052
1053        // get form values...
1054
if (pageIDs != null) {
1055
1056            String JavaDoc titlePage = "";
1057
1058            for (int i = 0; i < pageIDs.length; i++) {
1059                idPageString = pageIDs[i];
1060
1061                try {
1062                    idPage = Integer.parseInt(idPageString);
1063
1064                    if (!swapTemplate(idPage, idTemplate)) {
1065
1066                        titlePage = sReg.getJahiaPageService().lookupPage(idPage).getTitle();
1067                        errors.add("Couldn't change templates for page "+ titlePage);
1068                    }
1069                } catch (Exception JavaDoc e) {
1070                    //
1071
}
1072            }
1073        }
1074        request.setAttribute("processedSwap", new Integer JavaDoc(1));
1075        editTemplate (request, response, session);
1076
1077
1078    } // end processSwap
1079

1080
1081
1082    /**
1083     * Perform a template swap on a page
1084     *
1085     * @author Mikhael Janson
1086     *
1087     * @param idPage the ID of the page we want to update
1088     * @param idTemplate the ID of the template we want to assign this page
1089     */

1090    private boolean swapTemplate( int idPage, int idTemplate )
1091    {
1092        boolean out = false;
1093        JahiaPage page = null;
1094        try {
1095
1096            JahiaPageService pageServ = ServicesRegistry.getInstance()
1097                                                        .getJahiaPageService();
1098
1099            if ( idPage != 0 && idTemplate != 0 ){
1100                page = pageServ.lookupPage(idPage);
1101
1102                if ( page != null ){
1103                    // set new settings for this JahiaPage...
1104
page.setPageTemplateID (idTemplate);
1105                    page.commitChanges (true);
1106                    // FIXME - mik : CHECK IF THE PAGE HAS CHANGED TEMPLATES, AND THE TEMPLATE IS VALID...
1107
out = true;
1108                }
1109
1110            }
1111
1112        } catch ( JahiaException je ){
1113            //
1114
}
1115
1116        return out;
1117
1118    } // end swapTemplate
1119

1120
1121
1122} // end ManageTemplates
Popular Tags