KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > views > engines > versioning > pages > actions > PagesVersioningAction


1 package org.jahia.views.engines.versioning.pages.actions;
2
3 import java.io.*;
4 import java.text.*;
5 import java.util.*;
6 import javax.servlet.*;
7 import javax.servlet.http.*;
8
9 import javax.swing.*;
10
11 import org.apache.log4j.Logger;
12 import org.apache.struts.action.*;
13 import org.jahia.bin.*;
14 import org.jahia.content.*;
15 import org.jahia.exceptions.*;
16 import org.jahia.params.*;
17 import org.jahia.registries.*;
18 import org.jahia.services.pages.*;
19 import org.jahia.services.usermanager.*;
20 import org.jahia.services.version.*;
21 import org.jahia.views.engines.*;
22 import org.jahia.views.engines.datepicker.*;
23 import org.jahia.views.engines.datepicker.actions.*;
24 import org.jahia.views.engines.versioning.pages.*;
25 import org.jahia.views.engines.versioning.revisionsdetail.actions.*;
26 import org.jahia.services.cache.HtmlCache;
27 import org.jahia.services.cache.CacheFactory;
28 import org.jahia.services.sitemap.JahiaSiteMapService;
29 import org.jahia.data.viewhelper.sitemap.SiteMapViewHelper;
30 import org.jahia.services.lock.LockService;
31 import org.jahia.services.lock.LockKey;
32
33
34 /**
35  *
36  * <p>Title: Page Versioning Dispatch Action</p>
37  * <p>Description: </p>
38  * <p>Copyright: Copyright (c) 2003</p>
39  * <p>Company: Jahia</p>
40  * @author Khue Nguyen
41  * @version 1.0
42  */

43 public class PagesVersioningAction extends org.apache.struts.actions.DispatchAction {
44
45     private static Logger logger = Logger.getLogger(PagesVersioningAction.class);
46
47     private static final String JavaDoc ENGINE_TITLE = "Pages Versioning";
48
49     public static final String JavaDoc SESSION_VERSIONING_LOCK_LIST = "org.jahia.views.engines.versioning.pages.Locks";
50
51     /**
52      * Init Engine Data
53      *
54      * @param request
55      * @return
56      */

57     private void init(ActionMapping mapping, HttpServletRequest request)
58     throws JahiaException {
59
60         try {
61
62             // test whether the data already exists in session or should be created
63
String JavaDoc engineView = request.getParameter ("engineview");
64             String JavaDoc reloaded = request.getParameter("reloaded");
65
66             // engine view Helper
67
PagesVersioningViewHelper engineViewHelper = null;
68             if ( engineView != null && !"yes".equals(reloaded) ){
69                 // try to retrieve engine data from session
70
engineViewHelper =
71                         (PagesVersioningViewHelper)request.getSession()
72                         .getAttribute(JahiaEngineViewHelper.ENGINE_VIEW_HELPER);
73             }
74             // engine common data
75
JahiaEngineCommonData engineCommonData =
76                     new JahiaEngineCommonData(request);
77             engineCommonData.setEngineTitle(PagesVersioningAction.ENGINE_TITLE);
78
79             // Prepare engine buttons helper
80
JahiaEngineButtonsHelper jahiaEngineButtonsHelper =
81                     new JahiaEngineButtonsHelper();
82             jahiaEngineButtonsHelper.addCloseButton();
83
84             jahiaEngineButtonsHelper.addAuthoringButton();
85             if ( engineCommonData.getParamBean().getPage()
86                  .checkAdminAccess(engineCommonData.getParamBean().getUser()) ){
87                 jahiaEngineButtonsHelper.addRightsButton();
88             }
89             if ( engineCommonData.getParamBean().getPage()
90                  .checkAdminAccess(engineCommonData.getParamBean().getUser()) ||
91                  engineCommonData.getParamBean().getPage()
92                  .checkWriteAccess(engineCommonData.getParamBean().getUser()) ){
93                 jahiaEngineButtonsHelper.addVersioningButton();
94             }
95             if ( engineCommonData.getParamBean().getPage()
96                  .checkAdminAccess(engineCommonData.getParamBean().getUser()) ){
97                 jahiaEngineButtonsHelper.addLogsButton();
98             }
99             if ( engineCommonData.getParamBean().getPage()
100                     .checkAdminAccess(engineCommonData.getParamBean().getUser()) ||
101                     engineCommonData.getParamBean().getPage()
102                     .checkWriteAccess(engineCommonData.getParamBean().getUser()) ){
103                 jahiaEngineButtonsHelper.addCategoriesButton();
104             }
105             
106             request.setAttribute(JahiaEngineButtonsHelper.JAHIA_ENGINE_BUTTONS_HELPER,
107                                  jahiaEngineButtonsHelper);
108
109             if ( engineViewHelper == null ){
110                 // Prepage a new engine view helper
111
String JavaDoc pid = null;
112                 EntryLoadRequest loadRequest = EntryLoadRequest.VERSIONED;
113                 pid = request.getParameter("pageid");
114                 ContentPage page = ServicesRegistry.getInstance()
115                                  .getJahiaPageService()
116                                  .lookupContentPage(Integer.parseInt(pid),loadRequest,false);
117                 engineViewHelper =
118                         new PagesVersioningViewHelper(page);
119
120                 // store engine data in session
121
request.getSession().setAttribute(JahiaEngineViewHelper.ENGINE_VIEW_HELPER,
122                                      engineViewHelper);
123             }
124
125             // check permission
126
ContentPage page = engineViewHelper.getPage();
127             if ( !page.checkWriteAccess(engineCommonData.getParamBean().getUser())
128                  && !page.checkAdminAccess(engineCommonData.getParamBean().getUser()) ){
129                 throw new JahiaForbiddenAccessException();
130             }
131
132             request.setAttribute(JahiaEngineCommonData.JAHIA_ENGINE_COMMON_DATA,
133                                  engineCommonData);
134
135             request.setAttribute(JahiaEngineViewHelper.ENGINE_VIEW_HELPER,
136                                  engineViewHelper);
137
138             // JSP attributes
139
String JavaDoc pageTitle = engineViewHelper.getPage()
140                                  .getTitle(engineCommonData.getParamBean()
141                                  .getEntryLoadRequest());
142             if ( pageTitle == null ){
143                 pageTitle = "No title for page [" + engineViewHelper.getPage().getID() + "] in lang : " + engineCommonData.getParamBean()
144                                  .getEntryLoadRequest().getFirstLocale(true).getDisplayName();
145             }
146             request.setAttribute("pageproperties.pagetitle",
147                                  pageTitle);
148             request.setAttribute("pageproperties.pageid",
149                                  String.valueOf(engineViewHelper.getPage().getID()));
150
151             // Prepare the Action URL for this Action Dispatcher
152
String JavaDoc actionURL = composeActionURL(engineViewHelper.getPage(),
153                     engineCommonData.getParamBean(),mapping.getPath(),null,null);
154             request.setAttribute("PagesVersioning.ActionURL",actionURL);
155
156             // BACKWARD COMPATIBILITY WITH OLD ENGINE
157
// Shared engine map for keeping compatibility with old engine system
158
HashMap engineMap = (HashMap)request
159                               .getSession().getAttribute("jahia_session_engineMap");
160             if ( engineMap != null ){
161                 engineMap.put("screen","versioning");
162                 request.setAttribute("jahia_session_engineMap", engineMap);
163                 // use the engineURL to keep compatibility
164
engineCommonData.setEngineURL((String JavaDoc)engineMap.get("engineUrl"));
165             }
166
167         } catch ( Throwable JavaDoc t ){
168             logger.debug("Error occurred",t);
169             throw new JahiaException("Exception occured initializing engine's objects",
170                                      "Exception occured initializing engine's objects",
171                                      JahiaException.ENGINE_ERROR,
172                                      JahiaException.ENGINE_ERROR, t);
173         }
174     }
175
176     /**
177      * Display the operation choices view.
178      *
179      * @param mapping
180      * @param form
181      * @param request
182      * @param response
183      * @return
184      * @throws IOException
185      * @throws ServletException
186      */

187     public ActionForward showOperationChoices(ActionMapping mapping,
188                                               ActionForm form,
189                                               HttpServletRequest request,
190                                               HttpServletResponse response)
191     throws IOException, ServletException {
192
193         ActionForward forward = mapping.findForward("operationChoices");
194         ActionMessages errors = new ActionMessages();
195         JahiaEngineCommonData engineCommonData = null;
196         try {
197             init(mapping,request);
198             getRevisionsListFormData(mapping,form,request,response);
199             getSiteMapFormData(mapping,form,request,response);
200             engineCommonData = (JahiaEngineCommonData)
201                     request.getAttribute(JahiaEngineCommonData.JAHIA_ENGINE_COMMON_DATA);
202
203             // before we go any further, let's try to acquire all the locks
204
// on the page sub tree.
205
ActionMessages localMessages = new ActionMessages();
206             boolean lockingSuccessful = acquireTreeLocks(engineCommonData.getParamBean(), localMessages);
207             if (!lockingSuccessful) {
208                 forward = mapping.findForward("pageTreeLocked");
209                 saveMessages(request, localMessages);
210             }
211
212         } catch ( Throwable JavaDoc t ){
213             JahiaErrorDisplay.DisplayException(request, response,
214                     super.getServlet().getServletContext(), t);
215             errors.add(ActionMessages.GLOBAL_MESSAGE,
216                        new ActionMessage("Error preparing Operation Choices view"));
217         }
218         // set engine screen
219
request.setAttribute("engineView","operationChoices");
220         return continueForward(mapping,request,errors,forward);
221     }
222
223     /**
224      * Display the main screen containing the revisions list
225      *
226      * @param mapping
227      * @param form
228      * @param request
229      * @param response
230      * @return
231      * @throws IOException
232      * @throws ServletException
233      */

234     public ActionForward showRevisionsList(ActionMapping mapping,
235                                        ActionForm form,
236                                        HttpServletRequest request,
237                                        HttpServletResponse response)
238     throws IOException, ServletException {
239
240         ActionForward forward = mapping.getInputForward();
241         ActionMessages errors = new ActionMessages();
242         PagesVersioningViewHelper pagesVersViewHelper = null;
243         JahiaEngineCommonData engineCommonData = null;
244         try {
245             init(mapping,request);
246             getRevisionsListFormData(mapping,form,request,response);
247             pagesVersViewHelper = (PagesVersioningViewHelper)
248                     request.getAttribute(JahiaEngineViewHelper.ENGINE_VIEW_HELPER);
249             engineCommonData = (JahiaEngineCommonData)
250                     request.getAttribute(JahiaEngineCommonData.JAHIA_ENGINE_COMMON_DATA);
251
252             initRevisionsDateListener(pagesVersViewHelper,request);
253
254             // append full day
255
Calendar calendar = Calendar.getInstance();
256             calendar.setTime(new Date(pagesVersViewHelper.getToRevisionDate().longValue()));
257             calendar.set(Calendar.HOUR,23);
258             calendar.set(Calendar.MINUTE,59);
259             calendar.set(Calendar.SECOND,0);
260             long toDate = calendar.getTime().getTime();
261             EntryLoadRequest loadRequest =
262                     new EntryLoadRequest(EntryLoadRequest.VERSIONED_WORKFLOW_STATE,
263                     (int)(toDate/1000),
264                     engineCommonData.getParamBean().getEntryLoadRequest().getLocales());
265
266             // prepare Revisions List
267
int pageLevel = pagesVersViewHelper.getPageLevel().intValue();
268             if ( pageLevel>0 ){
269                 pageLevel -=1;
270             }
271             ContentTreeRevisionsVisitor revisionsVisitor =
272                     pagesVersViewHelper.getContentTreeRevisionsVisitor(
273                     engineCommonData.getParamBean().getUser(),
274                     loadRequest,ParamBean.EDIT);
275
276             revisionsVisitor.setWithDeletedContent(true);
277             revisionsVisitor.setDescendingPageLevel(pageLevel);
278
279             long fromDate = pagesVersViewHelper.getFromRevisionDate().longValue();
280             calendar.setTime(new Date(fromDate));
281             calendar.set(Calendar.HOUR,0);
282             calendar.set(Calendar.MINUTE,0);
283             calendar.set(Calendar.SECOND,1);
284             revisionsVisitor.setFromRevisionDate(calendar.getTime().getTime());
285             revisionsVisitor.setToRevisionDate(
286                     toDate);
287
288             revisionsVisitor.loadRevisions(false);
289             revisionsVisitor.sortRevisions(
290                     engineCommonData.getParamBean().getLocale().toString(),
291                     pagesVersViewHelper.getSortAttribute(),
292                     pagesVersViewHelper.getSortOrder(),false);
293
294             ArrayList revisions = revisionsVisitor.getRevisions();
295             ArrayList filteredRevisions = new ArrayList();
296             int size = revisions.size();
297             // remove deleted revisions, we don't want to restore at deleted revision
298
RevisionEntrySet revEntrySet = null;
299             for ( int i=0; i<size; i++ ){
300                 revEntrySet = (RevisionEntrySet)revisions.get(i);
301                 if ( (revEntrySet.getWorkflowState() !=
302                       EntryLoadRequest.DELETED_WORKFLOW_STATE) ){
303                     filteredRevisions.add(revEntrySet);
304                 }
305             }
306             request.setAttribute("revisions",filteredRevisions);
307
308         } catch ( Throwable JavaDoc t ){
309             JahiaErrorDisplay.DisplayException(request, response,
310                     super.getServlet().getServletContext(), t);
311             errors.add(ActionMessages.GLOBAL_MESSAGE,
312                        new ActionMessage("Exception occured when processing page pid["
313                        + pagesVersViewHelper.getPage().getID() + "]"));
314         }
315         // set engine screen
316
request.setAttribute("engineView","revisionsList");
317         return continueForward(mapping,request,errors,forward);
318     }
319
320     /**
321      * Display the site map with the selected page to restore.
322      *
323      * @param mapping
324      * @param form
325      * @param request
326      * @param response
327      * @return
328      * @throws IOException
329      * @throws ServletException
330      */

331     public ActionForward showSiteMap(ActionMapping mapping,
332                                      ActionForm form,
333                                      HttpServletRequest request,
334                                      HttpServletResponse response)
335     throws IOException, ServletException {
336
337         ActionForward forward = mapping.findForward("sitemap");
338         ActionMessages errors = new ActionMessages();
339         PagesVersioningViewHelper pagesVersViewHelper = null;
340         JahiaEngineCommonData engineCommonData = null;
341         try {
342             init(mapping,request);
343             getRevisionsListFormData(mapping,form,request,response);
344             getSiteMapFormData(mapping,form,request,response);
345             pagesVersViewHelper = (PagesVersioningViewHelper)
346                     request.getAttribute(JahiaEngineViewHelper.ENGINE_VIEW_HELPER);
347             engineCommonData = (JahiaEngineCommonData)
348                     request.getAttribute(JahiaEngineCommonData.JAHIA_ENGINE_COMMON_DATA);
349             initRestoreDateListener(pagesVersViewHelper,request);
350             pagesVersViewHelper.loadSiteMapViewHelper(
351                     engineCommonData.getParamBean().getUser(),request);
352
353             // retrieve the requested operation
354
String JavaDoc paramVal = request.getParameter("operationType");
355             if ( paramVal != null ){
356                 try {
357                     pagesVersViewHelper.setOperationType(Integer.parseInt(paramVal));
358                 }catch(Throwable JavaDoc t){
359                 }
360             }
361
362             // select the current page if none selected and operation type = restore archived
363
if ( pagesVersViewHelper.getSelectedPages().size()==0
364                  && pagesVersViewHelper.getOperationType() == PagesVersioningViewHelper.RESTORE_ARCHIVE_CONTENT_OPERATION ){
365                 pagesVersViewHelper.getSelectedPages().add(pagesVersViewHelper.getPage().getObjectKey());
366             }
367
368             String JavaDoc siteMapParam = request.getParameter("sitemap");
369             if (siteMapParam != null) {
370                 ServicesRegistry.getInstance().getJahiaSiteMapService()
371                         .invokeTreeSiteMapViewHelperMethod(engineCommonData.getParamBean().getUser(),
372                         pagesVersViewHelper.getPage(), engineCommonData.getParamBean().getSessionID(),
373                         ContentPage.ARCHIVED_PAGE_INFOS,
374                         null, siteMapParam);
375             }
376
377         } catch ( Throwable JavaDoc t ){
378             JahiaErrorDisplay.DisplayException(request, response,
379                     super.getServlet().getServletContext(), t);
380             errors.add(ActionMessages.GLOBAL_MESSAGE,
381                        new ActionMessage("Error preparing sitemap view"));
382         }
383         // set engine screen
384
request.setAttribute("engineView","sitemap");
385         return continueForward(mapping,request,errors,forward);
386     }
387
388     /**
389      * Display the confirm restore view.
390      *
391      * @param mapping
392      * @param form
393      * @param request
394      * @param response
395      * @return
396      * @throws IOException
397      * @throws ServletException
398      */

399     public ActionForward showConfirmRestore(ActionMapping mapping,
400                                      ActionForm form,
401                                      HttpServletRequest request,
402                                      HttpServletResponse response)
403     throws IOException, ServletException {
404
405         ActionForward forward = null;
406         ActionMessages errors = new ActionMessages();
407         PagesVersioningViewHelper pagesVersViewHelper = null;
408         JahiaEngineCommonData engineCommonData = null;
409         try {
410             init(mapping,request);
411             getSiteMapFormData(mapping,form,request,response);
412             pagesVersViewHelper = (PagesVersioningViewHelper)
413                     request.getAttribute(JahiaEngineViewHelper.ENGINE_VIEW_HELPER);
414             // store pages to restore
415
pagesVersViewHelper.setPagesToRestore(getPagesToRestore(request));
416
417             engineCommonData = (JahiaEngineCommonData)
418                     request.getAttribute(JahiaEngineCommonData.JAHIA_ENGINE_COMMON_DATA);
419
420             switch( pagesVersViewHelper.getOperationType() ){
421                 case PagesVersioningViewHelper.UNDO_STAGING_OPERATION :
422                 {
423                     forward = mapping.findForward("confirmUndoStaging");
424                     break;
425                 }
426                 case PagesVersioningViewHelper.RESTORE_ARCHIVE_CONTENT_OPERATION :
427                 {
428                     forward = mapping.findForward("confirmRestore");
429                     break;
430                 }
431                 case PagesVersioningViewHelper.RESTORE_DELETED_PAGES :
432                 {
433                     forward = mapping.findForward("confirmPageUndelete");
434                     break;
435                 }
436             }
437
438             if ( pagesVersViewHelper.getPagesToRestore().size()==0 ){
439                 forward = this.showSiteMap(mapping,form,request,response);
440                 // set engine screen
441
request.setAttribute("engineView","sitemap");
442                 return continueForward(mapping,request,errors,forward);
443             } else {
444
445                 // Prepare engine buttons helper
446
JahiaEngineButtonsHelper jahiaEngineButtonsHelper =
447                         new JahiaEngineButtonsHelper();
448
449                 jahiaEngineButtonsHelper.addOkButton();
450                 jahiaEngineButtonsHelper.addApplyButton();
451                 jahiaEngineButtonsHelper.addCloseButton();
452
453                 jahiaEngineButtonsHelper.addAuthoringButton();
454                 if ( engineCommonData.getParamBean().getPage()
455                      .checkAdminAccess(engineCommonData.getParamBean().getUser()) ){
456                     jahiaEngineButtonsHelper.addRightsButton();
457                     jahiaEngineButtonsHelper.addVersioningButton();
458                     jahiaEngineButtonsHelper.addLogsButton();
459                 }
460
461                 request.setAttribute(JahiaEngineButtonsHelper.JAHIA_ENGINE_BUTTONS_HELPER,
462                                      jahiaEngineButtonsHelper);
463
464                 // JSP output
465
Date d = new java.util.Date JavaDoc(
466                         pagesVersViewHelper.getSiteMapDisplayDate().longValue());
467                 request.setAttribute("pagesversioning.full_restore_date",
468                                      DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.MEDIUM,
469                                      engineCommonData.getParamBean().getLocale()).format(d));
470                 request.setAttribute("pagesversioning.nb_pages_to_restore",
471                                      new Integer JavaDoc(pagesVersViewHelper.getPagesToRestore().size()/2));
472                 request.setAttribute("pagesversioning.restore_exact",
473                                      pagesVersViewHelper.exactRestore()?"yes":"no");
474             }
475         } catch ( Throwable JavaDoc t ){
476             JahiaErrorDisplay.DisplayException(request, response,
477                     super.getServlet().getServletContext(), t);
478             errors.add(ActionMessages.GLOBAL_MESSAGE,
479                        new ActionMessage("Error preparing confirm restore view"));
480         }
481         // set engine screen
482
request.setAttribute("engineView","confirmRestore");
483         return continueForward(mapping,request,errors,forward);
484     }
485
486     /**
487      * Restore.
488      *
489      * @param mapping
490      * @param form
491      * @param request
492      * @param response
493      * @return
494      * @throws IOException
495      * @throws ServletException
496      */

497     public ActionForward restoreSave(ActionMapping mapping,
498                                      ActionForm form,
499                                      HttpServletRequest request,
500                                      HttpServletResponse response)
501     throws IOException, ServletException {
502
503         ActionForward forward = mapping.findForward("sitemap");
504         ActionMessages errors = new ActionMessages();
505         PagesVersioningViewHelper pagesVersViewHelper = null;
506         JahiaEngineCommonData engineCommonData = null;
507         try {
508             init(mapping,request);
509             pagesVersViewHelper = (PagesVersioningViewHelper)
510                     request.getAttribute(JahiaEngineViewHelper.ENGINE_VIEW_HELPER);
511             if ( pagesVersViewHelper.getPagesToRestore().size()==0 ){
512                 forward = this.showSiteMap(mapping,form,request,response);
513             } else {
514                 engineCommonData = (JahiaEngineCommonData)
515                     request.getAttribute(JahiaEngineCommonData.JAHIA_ENGINE_COMMON_DATA);
516                 boolean activeRestoredPages =
517                         "yes".equals(request.getParameter("activate_pages_after_restore"));
518                 boolean applyPageMoveWhenRestore =
519                         "yes".equals(request.getParameter("apply_page_move_when_restore"));
520
521                 pagesVersViewHelper.setApplyPageMoveWhenRestore(applyPageMoveWhenRestore);
522
523                 ArrayList pagesToRestoreArray = pagesVersViewHelper.getPagesToRestore();
524                 HashMap pagesToRestore = new HashMap();
525                 int size = pagesToRestoreArray.size();
526                 for ( int i=0 ; i<size-1 ; i+=2){
527                     String JavaDoc lang = (String JavaDoc)pagesToRestoreArray.get(i);
528                     Integer JavaDoc pageID = (Integer JavaDoc)pagesToRestoreArray.get(i+1);
529                     ArrayList langs = (ArrayList)pagesToRestore.get(pageID);
530                     if ( langs == null ){
531                         langs = new ArrayList();
532                     }
533                     langs.add(lang);
534                     pagesToRestore.put(pageID,langs);
535                 }
536
537                 switch( pagesVersViewHelper.getOperationType() ){
538                     case PagesVersioningViewHelper.UNDO_STAGING_OPERATION :
539                     {
540                         this.undoStaging(engineCommonData.getParamBean(),
541                                          request, pagesToRestore);
542                         break;
543                     }
544                     case PagesVersioningViewHelper.RESTORE_ARCHIVE_CONTENT_OPERATION :
545                     {
546                         this.restorePages(engineCommonData.getParamBean(), request,
547                                           pagesToRestore,
548                                           engineCommonData.getParamBean().getUser(),
549                                           pagesVersViewHelper.getSiteMapDisplayDate().longValue(),
550                                           pagesVersViewHelper.exactRestore(),
551                                           activeRestoredPages);
552                         break;
553                     }
554                     case PagesVersioningViewHelper.RESTORE_DELETED_PAGES :
555                         this.restorePages(engineCommonData.getParamBean(), request,
556                                           pagesToRestore,
557                                           engineCommonData.getParamBean().getUser(),
558                                           pagesVersViewHelper.getSiteMapDisplayDate().longValue(),
559                                           pagesVersViewHelper.exactRestore(),
560                                           activeRestoredPages);
561                         break;
562
563                 }
564
565                 // reload revisions
566
if ( pagesVersViewHelper.getContentTreeRevisionsVisitor() != null ){
567                     pagesVersViewHelper.getContentTreeRevisionsVisitor().loadRevisions(true);
568                 }
569
570                 String JavaDoc method = request.getParameter(mapping.getParameter());
571                 if ( method.equals("restoreSave") ){
572                     releaseTreeLocks(engineCommonData.getParamBean());
573                     request.setAttribute("engines.close.refresh-opener","yes");
574                     request.setAttribute("engines.close.opener-url-params","&reloaded=yes");
575                     forward = mapping.findForward("EnginesCloseAnyPopup");
576                 } else if ( method.equals("restoreApply") ){
577                     Properties params = new Properties();
578                     params.put("method","showOperationChoices");
579                     params.put("engineview","restore");
580                     String JavaDoc requestURL = PagesVersioningAction.composeActionURL(pagesVersViewHelper.getPage(),
581                                       engineCommonData.getParamBean(),mapping.getPath(),params,null);
582                     request.setAttribute("engines.apply.new-url",requestURL);
583                     request.setAttribute("engines.apply.refresh-opener","yes");
584                     request.setAttribute("engines.apply.opener-url-params","&reloaded=yes");
585                     forward = mapping.findForward("EnginesApplyAnyPopup");
586                 } else {
587                     forward = this.showRevisionsList(mapping,form,request,response);
588                 }
589             }
590         } catch ( Throwable JavaDoc t ){
591             JahiaErrorDisplay.DisplayException(request, response,
592                     super.getServlet().getServletContext(), t);
593             errors.add(ActionMessages.GLOBAL_MESSAGE,
594                        new ActionMessage("Unable to retrieve pid or versionid"));
595         }
596         // set engine screen
597
request.setAttribute("engineView","sitemap");
598         return continueForward(mapping,request,errors,forward);
599     }
600
601     /**
602      * Restore .
603      *
604      * @param mapping
605      * @param form
606      * @param request
607      * @param response
608      * @return
609      * @throws IOException
610      * @throws ServletException
611      */

612     public ActionForward restoreApply(ActionMapping mapping,
613                                      ActionForm form,
614                                      HttpServletRequest request,
615                                      HttpServletResponse response)
616     throws IOException, ServletException {
617         return restoreSave(mapping,form,request,response);
618     }
619
620     /**
621      * Forward to revision detail.
622      *
623      * @param mapping
624      * @param form
625      * @param request
626      * @param response
627      * @return
628      * @throws IOException
629      * @throws ServletException
630      */

631     public ActionForward revisionsDetail(ActionMapping mapping,
632                                      ActionForm form,
633                                      HttpServletRequest request,
634                                      HttpServletResponse response)
635     throws IOException, ServletException {
636
637         ActionForward forward = mapping.findForward("revisionsDetail");
638         ActionMessages errors = new ActionMessages();
639         PagesVersioningViewHelper pagesVersViewHelper = null;
640         try {
641             init(mapping,request);
642             pagesVersViewHelper = (PagesVersioningViewHelper)
643                     request.getAttribute(JahiaEngineViewHelper.ENGINE_VIEW_HELPER);
644             String JavaDoc revisionEntryParam = request.getParameter("revisionEntrySet");
645             RevisionEntrySet revisionEntrySet = getRevisionEntrySet(revisionEntryParam);
646
647             JTree tree = null;
648             ContentTreeRevisionsVisitor revisionsVisitor =
649                     pagesVersViewHelper.getContentTreeRevisionsVisitor();
650             ArrayList revisions = revisionsVisitor.getRevisions();
651             if ( revisions.size()>0 ){
652                 int index = revisions.indexOf(revisionEntrySet);
653                 if ( index != -1 ){
654                     revisionEntrySet = (RevisionEntrySet)revisions.get(index);
655                     tree = RevisionsTreeTools.getTreeOfPageRevisions(
656                             (PageRevisionEntrySet)revisionEntrySet,
657                             revisionsVisitor.getUser(),
658                             revisionsVisitor.getEntryLoadRequest(),
659                             revisionsVisitor.getOperationMode());
660                 }
661             }
662
663             // For forwarded action
664
request.setAttribute(RevisionEntrySetDetailAction.REVISIONS_TREE,
665                                  tree);
666             request.setAttribute(RevisionEntrySetDetailAction.REVISIONENTRYSET,
667                                  revisionEntrySet);
668
669         } catch ( Throwable JavaDoc t ){
670             JahiaErrorDisplay.DisplayException(request, response,
671                     super.getServlet().getServletContext(), t);
672             errors.add(ActionMessages.GLOBAL_MESSAGE,
673                        new ActionMessage("Exception processing show restore version test result"));
674         }
675         request.setAttribute("engineView","revisionsDetail");
676         return continueForward(mapping,request,errors,forward);
677     }
678
679     /**
680      * Closes the window, liberating all the locked resources.
681      * @param mapping ActionMapping
682      * @param form ActionForm
683      * @param request HttpServletRequest
684      * @param response HttpServletResponse
685      * @return ActionForward
686      * @throws IOException
687      * @throws ServletException
688      */

689     public ActionForward close(ActionMapping mapping,
690                                               ActionForm form,
691                                               HttpServletRequest request,
692                                               HttpServletResponse response)
693     throws IOException, ServletException {
694
695         ActionForward forward = mapping.findForward("close");
696         ActionMessages errors = new ActionMessages();
697         JahiaEngineCommonData engineCommonData = null;
698         try {
699             init(mapping,request);
700             getRevisionsListFormData(mapping,form,request,response);
701             getSiteMapFormData(mapping,form,request,response);
702             engineCommonData = (JahiaEngineCommonData)
703                     request.getAttribute(JahiaEngineCommonData.JAHIA_ENGINE_COMMON_DATA);
704
705             releaseTreeLocks(engineCommonData.getParamBean());
706
707             // this is required in the case that we never locked the tree
708
releaseActionLock(engineCommonData.getParamBean());
709
710         } catch ( Throwable JavaDoc t ){
711             JahiaErrorDisplay.DisplayException(request, response,
712                     super.getServlet().getServletContext(), t);
713             errors.add(ActionMessages.GLOBAL_MESSAGE,
714                        new ActionMessage("Error preparing Operation Choices view"));
715         }
716         // set engine screen
717
request.setAttribute("engineView","close");
718         return continueForward(mapping,request,errors,forward);
719     }
720
721     /**
722      *
723      * @param mapping
724      * @param form
725      * @param request
726      * @param response
727      * @throws IOException
728      * @throws ServletException
729      */

730     private void getRevisionsListFormData(ActionMapping mapping,
731                                          ActionForm form,
732                                          HttpServletRequest request,
733                                          HttpServletResponse response)
734     throws IOException, ServletException, JahiaSessionExpirationException {
735
736         PagesVersioningViewHelper pagesVersViewHelper =
737                 (PagesVersioningViewHelper)
738                 request.getAttribute(JahiaEngineViewHelper.ENGINE_VIEW_HELPER);
739         JahiaEngineCommonData engineCommonData = (JahiaEngineCommonData)
740                 request.getAttribute(JahiaEngineCommonData.JAHIA_ENGINE_COMMON_DATA);
741
742         // Choosed Revision entry
743
String JavaDoc revisionEntryParam = request.getParameter("revisionEntrySet");
744         String JavaDoc useRevisionEntryParam = request.getParameter("useRevisionEntry");
745         RevisionEntrySet revisionEntrySet = getRevisionEntrySet(revisionEntryParam);
746
747         if ( revisionEntrySet != null ){
748             pagesVersViewHelper.setRevisionEntrySet(revisionEntrySet);
749             if ( useRevisionEntryParam.equals("yes") ){
750                 pagesVersViewHelper.setSiteMapDisplayDate(revisionEntrySet.getVersionID()*1000L);
751                 // reset restore Date listener
752
String JavaDoc restoreDateKey = "PagesVersioningAction_restoredate_" +
753                              engineCommonData.getParamBean().getSessionID();
754                 DatePicker.getInstance().removeListener(restoreDateKey);
755             }
756         }
757
758         // Choosed type of revision
759
String JavaDoc paramVal = request.getParameter("rev_type");
760         if ( paramVal != null ){
761             try {
762                 pagesVersViewHelper.setTypeOfRevisions(Integer.parseInt(paramVal));
763             }catch(Throwable JavaDoc t){
764             }
765         }
766
767         // Choosed page level
768
paramVal = request.getParameter("level");
769         if ( paramVal != null ){
770             try {
771                 pagesVersViewHelper.setPageLevel(Integer.parseInt(paramVal));
772             }catch(Throwable JavaDoc t){
773             }
774         }
775
776         // Choosed nb max of revisions
777
paramVal = request.getParameter("nbmax_rev");
778         if ( paramVal != null ){
779             try {
780                 pagesVersViewHelper.setNbMaxOfRevisions(Integer.parseInt(paramVal));
781             }catch(Throwable JavaDoc t){
782             }
783         }
784
785         // Choosed sortAttribute
786
paramVal = request.getParameter("sortAttribute");
787         if ( paramVal != null ){
788             try {
789                 pagesVersViewHelper.setSortAttribute(Integer.parseInt(paramVal));
790             }catch(Throwable JavaDoc t){
791             }
792         }
793
794         // Choosed sortOrder
795
paramVal = request.getParameter("sortOrder");
796         if ( paramVal != null ){
797             try {
798                 pagesVersViewHelper.setSortOrder(Integer.parseInt(paramVal));
799             }catch(Throwable JavaDoc t){
800             }
801         }
802
803     }
804
805     /**
806      *
807      * @param mapping
808      * @param form
809      * @param request
810      * @param response
811      * @throws IOException
812      * @throws ServletException
813      */

814     private void getSiteMapFormData(ActionMapping mapping,
815                                     ActionForm form,
816                                     HttpServletRequest request,
817                                     HttpServletResponse response)
818     throws IOException, ServletException {
819
820         try {
821             PagesVersioningViewHelper pagesVersViewHelper =
822                     (PagesVersioningViewHelper)
823                     request.getAttribute(JahiaEngineViewHelper.ENGINE_VIEW_HELPER);
824             JahiaEngineCommonData engineCommonData = (JahiaEngineCommonData)
825                     request.getAttribute(JahiaEngineCommonData.JAHIA_ENGINE_COMMON_DATA);
826             ParamBean jParams = engineCommonData.getParamBean();
827
828             String JavaDoc siteMapParam = request.getParameter("sitemap");
829             if (siteMapParam != null) {
830                 ServicesRegistry.getInstance().getJahiaSiteMapService()
831                         .invokeTreeSiteMapViewHelperMethod(jParams.getUser(),
832                         pagesVersViewHelper.getPage(), jParams.getSessionID(),
833                         ContentPage.ARCHIVED_PAGE_INFOS,
834                         null, siteMapParam);
835             }
836
837             // Choosed nb max of revisions
838
String JavaDoc paramVal = request.getParameter("exact_restore");
839             if ( paramVal != null ){
840                 pagesVersViewHelper.setExactRestore("yes".equals(paramVal));
841             }
842         } catch ( Throwable JavaDoc t ){
843             logger.debug("Error occurred",t);
844         }
845     }
846
847     /**
848      * Restore pages
849      *
850      * @param pagesToRestore, an array containing alternatively the language to restore
851      * following by the content page to restore
852      *
853      * @param jParams
854      * @param request
855      * @param pagesToRestore
856      * @param user
857      * @param restoreDate
858      * @param removeMoreRecentActive
859      * @param activeRestoredPages
860      * @throws JahiaException
861      */

862     private void restorePages(ParamBean jParams,
863                               HttpServletRequest request,
864                               HashMap pagesToRestore,
865                               JahiaUser user,
866                               long restoreDate,
867                               boolean removeMoreRecentActive,
868                               boolean activeRestoredPages) throws JahiaException{
869
870         PagesVersioningViewHelper pagesVersViewHelper =
871                 (PagesVersioningViewHelper)request
872                 .getAttribute(JahiaEngineViewHelper.ENGINE_VIEW_HELPER);
873
874         // Build the list of pages to restore ( both page attributes and content ).
875
ArrayList selectedPages = new ArrayList();
876         Iterator iterator = pagesToRestore.keySet().iterator();
877         while ( iterator.hasNext() ){
878             Integer JavaDoc pageID = (Integer JavaDoc)iterator.next();
879             if ( pageID != null ){
880                 selectedPages.add(pageID);
881             }
882         }
883
884         // sort pages to undo staging , childs first
885
Vector sortedPages = ServicesRegistry.getInstance().getJahiaPageService()
886             .sortPages(selectedPages,jParams.getEntryLoadRequest(),
887                        jParams.getUser(),jParams.getOperationMode());
888         Enumeration enumeration = sortedPages.elements();
889
890         // Before we first start restore a page, we need to check if its parent page
891
// should be restored too. It should be the case if at the archive date,
892
// its parent page is it child !! If we don't restore both of them,
893
// an infinite loop occurs.
894
/*
895         if ( (pagesVersViewHelper.getOperationType() ==
896                  PagesVersioningViewHelper.RESTORE_ARCHIVE_CONTENT_OPERATION) ){
897             checkPagesToRestore(pagesToRestore,jParams,restoreDate);
898         }*/

899
900         ArrayList processedPages = new ArrayList();
901         while ( enumeration.hasMoreElements() ){
902             Integer JavaDoc pageID = (Integer JavaDoc) enumeration.nextElement();
903             ArrayList langsToRestore = (ArrayList)pagesToRestore.get(pageID);
904             String JavaDoc lang = (String JavaDoc)langsToRestore.get(0);
905             if ( processedPages.contains(pageID) ){
906                 continue;
907             }
908             ContentPage contentPage = ContentPage.getPage(pageID.intValue());
909
910             Set langs = new HashSet();
911             langs.add(lang);
912             ContentObjectEntryState entryState =
913                     new ContentObjectEntryState(EntryLoadRequest.VERSIONED_WORKFLOW_STATE,
914                     (int)(restoreDate/1000),lang);
915
916             boolean undeletePage = false;
917
918             // Are we doing an undelete ?
919
if ( pagesVersViewHelper.getOperationType() ==
920                  PagesVersioningViewHelper.RESTORE_DELETED_PAGES ){
921                 // Check if we are restoring a currently deleted page.
922
// If so and if the restore date is more recent,
923
// use the date before the deletion of the page.
924

925                 // check if we are processing a deleted page
926
if ( contentPage.isStagedEntryMarkedForDeletion(lang) ){
927                     // undo staging
928
HashMap pages = new HashMap();
929                     langs.add(lang);
930                     pages.put(pageID,langs);
931                     this.undoStaging(jParams,request,pages);
932                     entryState = null; // to skip restore
933
} else {
934                     int deleteVersionID = contentPage.getDeleteVersionID();
935                     if ( deleteVersionID != -1 ){
936                         undeletePage = true;
937                         //a page deleted for real
938
//use the closest entry state before the delete date
939
//entryState = contentPage.getClosestVersionedEntryState(entryState,true);
940
entryState =
941                                 new ContentObjectEntryState(EntryLoadRequest.VERSIONED_WORKFLOW_STATE,
942                                 (deleteVersionID),lang);
943                         //use the closest entry state before the delete date
944
//entryState = contentPage.getClosestVersionedEntryState(entryState,true);
945
}
946                 }
947             }
948             if ( entryState != null ){
949                 RestoreVersionStateModificationContext stateModificationContext =
950                         new RestoreVersionStateModificationContext(contentPage.getObjectKey(),langs,entryState);
951                 stateModificationContext.setDescendingInSubPages(false);
952
953                 // 1. restore current page
954
contentPage.restoreVersion(user,ParamBean.EDIT,entryState,
955                                     (removeMoreRecentActive && !undeletePage),
956                                     selectedPages.contains(new Integer JavaDoc(contentPage.getID())),
957                                     stateModificationContext);
958
959                 // 2. apply restore on other languages
960
ArrayList langsArray = (ArrayList)pagesToRestore
961                     .get(new Integer JavaDoc(contentPage.getID()));
962                 langsArray.remove(lang);
963                 Iterator it = langsArray.iterator();
964                 while ( it.hasNext() ){
965                     String JavaDoc lng = (String JavaDoc)it.next();
966                     entryState = new ContentObjectEntryState(entryState.getWorkflowState(),
967                         entryState.getVersionID(),lng);
968                     stateModificationContext.getLanguageCodes().clear();
969                     stateModificationContext.getLanguageCodes().add(lng);
970
971                     contentPage.restoreVersion(user,ParamBean.EDIT,entryState,
972                                         (removeMoreRecentActive && !undeletePage),
973                                         selectedPages.contains(new Integer JavaDoc(contentPage.getID())),
974                                         stateModificationContext);
975                 }
976
977                 processedPages.add(pageID);
978
979                // 3. remove more recent page recursively on page childs
980
if ( removeMoreRecentActive ){
981                     this.removeMoreRecentActivePages(contentPage,user,ParamBean.EDIT,
982                             entryState,stateModificationContext,
983                             new RestoreVersionTestResults(),
984                             pagesToRestore, selectedPages, processedPages,
985                             jParams);
986                 }
987             }
988         }
989     }
990
991     /**
992      * Undo Staging pages
993      *
994      * @param jParams
995      * @param request
996      * @param pagesToRestore key = pageID, value = ArrayList of lang codes
997      * @throws JahiaException
998      */

999     private void undoStaging(ParamBean jParams,
1000                             HttpServletRequest request,
1001                             HashMap pagesToRestore) throws JahiaException{
1002
1003        PagesVersioningViewHelper pagesVersViewHelper =
1004                (PagesVersioningViewHelper)request
1005                .getAttribute(JahiaEngineViewHelper.ENGINE_VIEW_HELPER);
1006
1007        ArrayList processedPages = new ArrayList();
1008        EntryLoadRequest loadRequest =
1009                (EntryLoadRequest)jParams.getEntryLoadRequest().clone();
1010        loadRequest.setWithMarkedForDeletion(true);
1011        Iterator iterator = pagesToRestore.keySet().iterator();
1012
1013        // sort pages to undo staging , childs first
1014
ArrayList pageIDs = new ArrayList();
1015        while ( iterator.hasNext() ){
1016            try {
1017                Integer JavaDoc pageID = (Integer JavaDoc) iterator.next();
1018                if ( pageID != null ){
1019                    pageIDs.add(pageID);
1020                }
1021            } catch ( Throwable JavaDoc t ){
1022                logger.debug(t);
1023            }
1024        }
1025        Vector sortedPages = ServicesRegistry.getInstance().getJahiaPageService()
1026            .sortPages(pageIDs,jParams.getEntryLoadRequest(),
1027                       jParams.getUser(),jParams.getOperationMode());
1028        Enumeration enumeration = sortedPages.elements();
1029
1030        while ( enumeration.hasMoreElements() ){
1031            Integer JavaDoc pageID = (Integer JavaDoc)enumeration.nextElement();
1032            if ( !processedPages.contains(pageID) ){
1033                ContentPage contentPage = ContentPage.getPage(pageID.intValue());
1034                UndoStagingContentTreeVisitor visitor =
1035                        new UndoStagingContentTreeVisitor(contentPage,jParams.getUser(),
1036                        loadRequest,jParams.getOperationMode(),jParams);
1037                visitor.undoStaging();
1038                processedPages.add(new Integer JavaDoc(pageID.intValue()));
1039                // reset page cache
1040
contentPage.commitChanges(true,jParams);
1041            }
1042        }
1043        // reset site map cache
1044
ServicesRegistry.getInstance().getJahiaSiteMapService().resetSiteMap();
1045        pagesVersViewHelper.loadSiteMapViewHelper(jParams.getUser(),request);
1046    }
1047
1048    /**
1049     * Forward to errors if any or to continueForward
1050     *
1051     * @param mapping
1052     * @param request
1053     * @param errors
1054     * @param continueForward
1055     * @return
1056     */

1057    private ActionForward continueForward(
1058            ActionMapping mapping,
1059            HttpServletRequest request,
1060            ActionMessages errors,
1061            ActionForward continueForward){
1062
1063        if(errors != null && !errors.isEmpty()){
1064            saveErrors(request,errors);
1065            return mapping.findForward("EnginesErrors");
1066        }
1067        return continueForward;
1068    }
1069
1070    /**
1071     *
1072     * @param engineViewHelper
1073     * @param request
1074     * @throws JahiaSessionExpirationException
1075     */

1076    private void initRevisionsDateListener(PagesVersioningViewHelper engineViewHelper,
1077            HttpServletRequest request)
1078    throws JahiaSessionExpirationException {
1079
1080        JahiaEngineCommonData engineCommonData = (JahiaEngineCommonData)
1081                request.getAttribute(JahiaEngineCommonData.JAHIA_ENGINE_COMMON_DATA);
1082
1083        // init the From date picker
1084
String JavaDoc fromDateKey = "PagesVersioningAction_fromdate_" +
1085                     request.getSession().getId();
1086        DatePickerEventListener fromDateListener = DatePicker.getInstance()
1087                     .getListener(fromDateKey);
1088        long dateLong = new Date().getTime();
1089        if ( fromDateListener == null ){
1090            DateValidator validator = new DateValidator(dateLong,
1091                    DateValidator.NO_COMP);
1092            fromDateListener = new DatePickerEventListener(fromDateKey,dateLong,validator);
1093            DatePicker.getInstance().addListener(fromDateKey,fromDateListener);
1094        }
1095        request.setAttribute("pagesversioning.startdate",
1096                             DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.MEDIUM,
1097        engineCommonData.getParamBean().getLocale()).format(new Date(fromDateListener.getDate())));
1098        request.setAttribute("from_" + DatePickerAction.DATE_EVENT_PARAM,fromDateKey);
1099        engineViewHelper.setFromRevisionDate(fromDateListener.getDate());
1100
1101        // init the To date picker
1102
String JavaDoc toDateKey = "PagesVersioningAction_todate_" +
1103                     request.getSession().getId();
1104        DatePickerEventListener toDateListener = DatePicker.getInstance()
1105                     .getListener(toDateKey);
1106
1107        DateValidator validator =
1108                new DateValidator(fromDateListener.getDate(),
1109                DateValidator.COMP_BIGGER_EQUAL);
1110        if ( toDateListener == null ){
1111            toDateListener =
1112                    new DatePickerEventListener(toDateKey,fromDateListener.getDate(),validator);
1113        } else {
1114            toDateListener.setValidator(validator);
1115            if ( toDateListener.getDate() < fromDateListener.getDate() ){
1116                toDateListener.setDate(fromDateListener.getDate());
1117            }
1118        }
1119
1120        DatePicker.getInstance().addListener(toDateKey,toDateListener);
1121
1122        request.setAttribute("pagesversioning.stopdate",
1123                             DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.MEDIUM,
1124        engineCommonData.getParamBean().getLocale()).format(new Date(toDateListener.getDate())));
1125        request.setAttribute("to_" + DatePickerAction.DATE_EVENT_PARAM,toDateKey);
1126        engineViewHelper.setToRevisionDate(toDateListener.getDate());
1127
1128    }
1129
1130    /**
1131     *
1132     * @param engineViewHelper
1133     * @param request
1134     */

1135    private void initRestoreDateListener(PagesVersioningViewHelper engineViewHelper,
1136            HttpServletRequest request)
1137    throws JahiaSessionExpirationException {
1138
1139        JahiaEngineCommonData engineCommonData = (JahiaEngineCommonData)
1140                request.getAttribute(JahiaEngineCommonData.JAHIA_ENGINE_COMMON_DATA);
1141
1142        // init the Restore date picker
1143
String JavaDoc restoreDateKey = "PagesVersioningAction_restoredate_" +
1144                     request.getSession().getId();
1145        DatePickerEventListener restoreDateListener = DatePicker.getInstance()
1146                     .getListener(restoreDateKey);
1147
1148        java.util.Date JavaDoc d = new java.util.Date JavaDoc();
1149        long currentTime = d.getTime();
1150        DateValidator validator = new DateValidator(currentTime,
1151                DateValidator.COMP_SMALLER_EQUAL);
1152
1153        if (engineViewHelper.getSiteMapDisplayDate().longValue() == 0 ){
1154            engineViewHelper.setSiteMapDisplayDate(currentTime);
1155        }
1156        if ( restoreDateListener == null ){
1157            restoreDateListener =
1158                    new DatePickerEventListener(restoreDateKey,
1159                    engineViewHelper.getSiteMapDisplayDate().longValue(),validator);
1160        } else {
1161            restoreDateListener.setValidator(validator);
1162            engineViewHelper.setSiteMapDisplayDate(restoreDateListener.getDate());
1163        }
1164
1165        DatePicker.getInstance().addListener(restoreDateKey,restoreDateListener);
1166        request.setAttribute("pagesversioning.restoredate",
1167                             DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.MEDIUM,
1168                             engineCommonData.getParamBean().getLocale())
1169                             .format(new Date(restoreDateListener.getDate())));
1170        // For debugging
1171
d = new java.util.Date JavaDoc(restoreDateListener.getDate());
1172        request.setAttribute("pagesversioning.fullrestoredate",
1173                             DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.MEDIUM,
1174                                     engineCommonData.getParamBean().getLocale()).format(d));
1175
1176        request.setAttribute("restore_" + DatePickerAction.DATE_EVENT_PARAM,restoreDateKey);
1177    }
1178
1179    /**
1180     * Generate a valid url for this Struts Action
1181     *
1182     * @param contentPage
1183     * @param jParams
1184     * @param strutsAction
1185     * @param properties
1186     * @param params
1187     * @return
1188     * @throws JahiaException
1189     */

1190    public static String JavaDoc composeActionURL(ContentPage contentPage,
1191                                          ParamBean jParams,
1192                                          String JavaDoc strutsAction,
1193                                          Properties properties,
1194                                          String JavaDoc params)
1195    throws JahiaException {
1196        // Prepare this struts action Mapping url
1197
if ( properties == null ){
1198            properties = new Properties();
1199        }
1200        properties.put("pageid",String.valueOf(contentPage.getID()));
1201        String JavaDoc url = jParams.composeStrutsUrl(strutsAction,properties,params);
1202        return url;
1203    }
1204
1205    /**
1206     * Returns an array where a[0] is the language to restore and a[1] is
1207     * the page id of the page to restore.
1208     * @param pageParamStr
1209     * @return
1210     */

1211    private ArrayList getPageToRestore(String JavaDoc pageParamStr){
1212
1213        ArrayList array = new ArrayList();
1214
1215        try {
1216            StringTokenizer strToken = new StringTokenizer(pageParamStr, "_");
1217            String JavaDoc id = "";
1218            String JavaDoc type = "";
1219            String JavaDoc parentID = "";
1220            String JavaDoc lang = "";
1221
1222            if (strToken.countTokens()>4) {
1223                strToken.nextToken();
1224                type = strToken.nextToken();
1225                id = strToken.nextToken();
1226                parentID = strToken.nextToken();
1227                while ( strToken.hasMoreTokens() ){
1228                    lang += strToken.nextToken();
1229                    if ( strToken.hasMoreTokens() ) {
1230                        lang += "_";
1231                    }
1232                }
1233                array.add(lang);
1234                array.add(new Integer JavaDoc(id));
1235            }
1236        } catch ( Throwable JavaDoc t ){
1237            logger.debug("Error occurred",t);
1238        }
1239        return array;
1240    }
1241
1242    /**
1243     * Retrieve pages to restore
1244     * Returns an ArrayList containing alternatively the language followed by
1245     * the content page to restore.
1246     *
1247     * @param request
1248     * @return
1249     * @throws JahiaException
1250     */

1251    private ArrayList getPagesToRestore(HttpServletRequest request)
1252            throws JahiaException{
1253        ArrayList pages = new ArrayList();
1254        Enumeration paramNames = request.getParameterNames();
1255        String JavaDoc paramName = "";
1256        while ( paramNames.hasMoreElements() ){
1257            paramName = (String JavaDoc)paramNames.nextElement();
1258            if (paramName.startsWith("checkbox_ContentPage_") ){
1259                ArrayList array = getPageToRestore(paramName);
1260                pages.addAll(array);
1261            }
1262        }
1263        return pages;
1264    }
1265
1266    /**
1267     *
1268     * @param revisionEntrySetKey
1269     * @return
1270     */

1271    private RevisionEntrySet getRevisionEntrySet(String JavaDoc revisionEntrySetKey){
1272
1273        PageRevisionEntrySet revisionEntrySet = null;
1274        try {
1275            StringTokenizer strToken = new StringTokenizer(revisionEntrySetKey, "_");
1276            String JavaDoc objType = "";
1277            String JavaDoc objID = "";
1278            String JavaDoc w = "";
1279            String JavaDoc v = "";
1280
1281            if (strToken.countTokens()==4) {
1282                objType = strToken.nextToken();
1283                objID = strToken.nextToken();
1284                w = strToken.nextToken();
1285                v = strToken.nextToken();
1286                revisionEntrySet =
1287                        new PageRevisionEntrySet(Integer.parseInt(v),
1288                        ObjectKey.getInstance(objType + "_" + objID));
1289            }
1290        } catch ( Throwable JavaDoc t ){
1291            //t.printStackTrace();
1292
}
1293        return revisionEntrySet;
1294    }
1295
1296
1297    /**
1298     *
1299     * @param contentPage
1300     * @param user
1301     * @param operationMode
1302     * @param entryState
1303     * @param stateModificationContext
1304     * @param result
1305     * @throws JahiaException
1306     */

1307    private void removeMoreRecentActivePages(ContentPage contentPage,
1308            JahiaUser user,
1309            String JavaDoc operationMode,
1310            ContentObjectEntryState entryState,
1311            StateModificationContext stateModificationContext,
1312            RestoreVersionTestResults result,
1313            HashMap pagesToRestore,
1314            ArrayList selectedPages,
1315            ArrayList processedPages,
1316            ParamBean jParams ) throws JahiaException{
1317        Enumeration childs = contentPage.getChilds(jParams);
1318        while (childs.hasMoreElements()){
1319            JahiaPage child = (JahiaPage)childs.nextElement();
1320            ContentPage contentPageChild = ContentPage.getPage(child.getID());
1321            if ( processedPages.contains(new Integer JavaDoc(child.getID())) ){
1322                 continue;
1323            }
1324            if ( !contentPageChild.hasActiveEntries() &&
1325                 !contentPageChild.hasStagingEntries() ){
1326                // as this page is actually deleted, no need
1327
// to try to mark it for delete again.
1328
continue;
1329            }
1330
1331            // check if the page is not moved
1332
if ( contentPageChild.getParentID(EntryLoadRequest.STAGED)
1333                 != contentPage.getID() ){
1334                continue; // could be a moved page
1335
}
1336
1337            if ( child.getPageType()==ContentPage.TYPE_DIRECT
1338                 && contentPageChild.isDeletedOrDoesNotExist(entryState.getVersionID()) ){
1339                // the page was deleted or doesn't exist so remove
1340
// all languages ( delete the page )
1341

1342                // undo any page move
1343
/*
1344                contentPageChild =
1345                        this.undoPageMoveStagingState(contentPageChild,jParams);
1346                */

1347
1348                ContentObjectEntryState removeEntryState =
1349                        new ContentObjectEntryState(entryState.getWorkflowState(),
1350                        entryState.getVersionID(),
1351                        entryState.getLanguageCode());
1352                RestoreVersionStateModificationContext smc =
1353                        new RestoreVersionStateModificationContext(contentPageChild.getObjectKey(),
1354                        stateModificationContext.getLanguageCodes(),removeEntryState);
1355                result.merge(contentPageChild.restoreVersion(user,operationMode,
1356                        removeEntryState,true,
1357                        selectedPages.contains(new Integer JavaDoc(contentPageChild.getID())),
1358                        smc));
1359
1360                // apply restore on other languages
1361
ArrayList langsArray = (ArrayList)pagesToRestore
1362                    .get(new Integer JavaDoc(contentPage.getID()));
1363                if ( langsArray != null ){
1364                    langsArray.remove(entryState.getLanguageCode());
1365                    Iterator it = langsArray.iterator();
1366                    while (it.hasNext()) {
1367                        String JavaDoc lng = (String JavaDoc) it.next();
1368                        removeEntryState = new ContentObjectEntryState(
1369                            removeEntryState.getWorkflowState(),
1370                            removeEntryState.getVersionID(), lng);
1371                        smc.getLanguageCodes().clear();
1372                        smc.getLanguageCodes().add(lng);
1373                        result.merge(contentPageChild.restoreVersion(user,
1374                            operationMode,
1375                            removeEntryState, true,
1376                            selectedPages.contains(new Integer JavaDoc(contentPageChild.getID())),
1377                            smc));
1378                    }
1379                    pagesToRestore.put(new Integer JavaDoc(contentPageChild.getID()),
1380                                       langsArray.clone());
1381                }
1382
1383                processedPages.add(new Integer JavaDoc(contentPageChild.getID()));
1384                // recurse on childs
1385
removeMoreRecentActivePages(contentPageChild,user,
1386                        operationMode,entryState,stateModificationContext,result,
1387                        pagesToRestore, selectedPages, processedPages,
1388                        jParams);
1389            }
1390        }
1391    }
1392
1393    // #ifdef LOCK
1394

1395    /**
1396     * Tries to acquire all the locks for all the sub pages starting at the
1397     * current page
1398     * @param jParams ParamBean
1399     * @return boolean true if all the sub pages could be locked, false
1400     * otherwise.
1401     * @throws JahiaException
1402     */

1403    private boolean acquireTreeLocks (ParamBean jParams, ActionMessages actionMessages)
1404            throws JahiaException {
1405        ArrayList acquiredPageLocks = new ArrayList();
1406        if (Jahia.getSettings ().areLocksActivated ()) {
1407            JahiaUser user = jParams.getUser ();
1408            HtmlCache htmlCache = CacheFactory.getHtmlCache();
1409            ContentPage contentPage = ServicesRegistry.getInstance ().
1410                    getJahiaPageService ().lookupContentPage (jParams.getPageID (), false);
1411            JahiaSiteMapService siteMapService = ServicesRegistry.getInstance ().
1412                    getJahiaSiteMapService ();
1413            // let's make sure the whole tree is expanded before we start
1414
// liberating page locks.
1415
int pageInfosFlag = ContentPage.ACTIVE_PAGE_INFOS | ContentPage.STAGING_PAGE_INFOS;
1416            siteMapService.invokeTreeSiteMapViewHelperMethod (jParams.getUser (),
1417                    contentPage, jParams.getSessionID (), pageInfosFlag,
1418                    null, "expandall|0");
1419
1420            // here below we set the page level to maximum because we want
1421
// to free all the sub pages locks.
1422
SiteMapViewHelper treeSiteMapViewHelper = siteMapService.
1423                    getTreeSiteMapViewHelper (jParams.getUser (), contentPage,
1424                            jParams.getSessionID (), ContentPage.ACTIVE_PAGE_INFOS |
1425                    ContentPage.STAGING_PAGE_INFOS,
1426                            null, Integer.MAX_VALUE);
1427
1428            // Lock all page site if possible.
1429
LockService lockRegistry = ServicesRegistry.getInstance ().getLockService ();
1430
1431            // first let's test if we can acquire ALL the sub pages locks
1432
// before we start locking anything, otherwise we would end up
1433
// with half locked trees.
1434
for (int i = 0; i < treeSiteMapViewHelper.size (); i++) {
1435                ContentPage siteMapContentPage = treeSiteMapViewHelper.getContentPage (i);
1436                if (siteMapContentPage != null) {
1437                    LockKey lockKey = LockKey.composeLockKey (LockKey.UPDATE_PAGE_TYPE,
1438                            siteMapContentPage.getID (), siteMapContentPage.getID ());
1439                    if (!lockRegistry.isAcquireable (lockKey, user, jParams.getSessionID ())) {
1440                        // acquiring of all locks was not successfull, we
1441
// exit immediately.
1442
actionMessages.add(ActionMessages.GLOBAL_MESSAGE,
1443                                   new ActionMessage("message.org.jahia.views.engines.versioning.pages.cannotLockPage", new Integer JavaDoc(siteMapContentPage.getID())));
1444                        return false;
1445                    }
1446                }
1447            }
1448
1449            for (int i = 0; i < treeSiteMapViewHelper.size (); i++) {
1450                ContentPage siteMapContentPage = treeSiteMapViewHelper.getContentPage (i);
1451                if (siteMapContentPage != null) {
1452                    LockKey lockKey = LockKey.composeLockKey (LockKey.UPDATE_PAGE_TYPE,
1453                            siteMapContentPage.getID (), siteMapContentPage.getID ());
1454                    if (lockRegistry.acquire (lockKey, user, jParams.getSessionID (),
1455                            jParams.getSession ().getMaxInactiveInterval ())) {
1456                        htmlCache.invalidatePageEntries(Integer.toString(siteMapContentPage.getID()));
1457                        logger.debug (
1458                                "Lock acquired for page " +
1459                                siteMapContentPage.getTitles (true));
1460                        acquiredPageLocks.add(new Integer JavaDoc(siteMapContentPage.getID()));
1461                    } else {
1462                        // this case really shouldn't happen since we have
1463
// already previously tested lock availability, but
1464
// might happen under loads when the two operations
1465
// are not perfectly atomic.
1466
logger.warn ("Warning, page tree was partly locked for updating, you might want to clear the locks manually.");
1467                        return false;
1468                    }
1469                }
1470            }
1471        }
1472        jParams.getSession().setAttribute(SESSION_VERSIONING_LOCK_LIST, acquiredPageLocks);
1473        return true;
1474    }
1475
1476    private void releaseTreeLocks (ParamBean jParams)
1477            throws JahiaException {
1478        if (Jahia.getSettings ().areLocksActivated ()) {
1479            ArrayList acquiredPageLocks = (ArrayList) jParams.getSession().getAttribute(SESSION_VERSIONING_LOCK_LIST);
1480            if (acquiredPageLocks == null){
1481                return;
1482            }
1483            HtmlCache htmlCache = CacheFactory.getHtmlCache();
1484            ServicesRegistry.getInstance ().
1485                    getJahiaPageService ().lookupContentPage (jParams.getPageID (), false);
1486
1487            // Lock all page site if possible.
1488
LockService lockRegistry = ServicesRegistry.getInstance ().getLockService ();
1489            Iterator acquiredPageIter = acquiredPageLocks.iterator();
1490            while (acquiredPageIter.hasNext()) {
1491                int curPageID = ((Integer JavaDoc) acquiredPageIter.next()).intValue();
1492                LockKey lockKey = LockKey.composeLockKey (LockKey.UPDATE_PAGE_TYPE,
1493                                                          curPageID, curPageID);
1494                lockRegistry.release (lockKey, jParams.getUser (), jParams.getSessionID ());
1495                htmlCache.invalidatePageEntries(Integer.toString(curPageID));
1496            }
1497            jParams.getSession().removeAttribute(SESSION_VERSIONING_LOCK_LIST);
1498        }
1499    }
1500
1501    private void releaseActionLock(ParamBean jParams)
1502        throws JahiaException {
1503        if (jParams.settings ().areLocksActivated ()) {
1504            HtmlCache htmlCache = CacheFactory.getHtmlCache();
1505            LockService lockRegistry = ServicesRegistry.getInstance ().getLockService ();
1506            LockKey lockKey = LockKey.composeLockKey (LockKey.UPDATE_PAGE_TYPE,
1507                jParams.getPageID(), jParams.getPageID());
1508            lockRegistry.release (lockKey, jParams.getUser (), jParams.getSessionID ());
1509            htmlCache.invalidatePageEntries(Integer.toString(jParams.getPageID()));
1510        }
1511    }
1512    // #endif
1513

1514}
1515
Popular Tags