KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > engines > workflow > WorkflowEngine


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

41
42
43 package org.jahia.engines.workflow;
44
45 import java.io.File JavaDoc;
46 import java.text.MessageFormat JavaDoc;
47 import java.util.ArrayList JavaDoc;
48 import java.util.Enumeration JavaDoc;
49 import java.util.HashMap JavaDoc;
50 import java.util.HashSet JavaDoc;
51 import java.util.Hashtable JavaDoc;
52 import java.util.Iterator JavaDoc;
53 import java.util.Locale JavaDoc;
54 import java.util.Map JavaDoc;
55 import java.util.Set JavaDoc;
56 import java.util.StringTokenizer JavaDoc;
57 import java.util.Vector JavaDoc;
58
59 import org.jahia.bin.Jahia;
60 import org.jahia.content.ContentPageKey;
61 import org.jahia.data.JahiaData;
62 import org.jahia.data.viewhelper.sitemap.PagesFilter;
63 import org.jahia.data.viewhelper.sitemap.SiteMapViewHelper;
64 import org.jahia.engines.EngineToolBox;
65 import org.jahia.engines.JahiaEngine;
66 import org.jahia.exceptions.JahiaException;
67 import org.jahia.exceptions.JahiaForbiddenAccessException;
68 import org.jahia.params.ParamBean;
69 import org.jahia.registries.ServicesRegistry;
70 import org.jahia.resourcebundle.JahiaResourceBundle;
71 import org.jahia.services.acl.JahiaACLException;
72 import org.jahia.services.acl.JahiaBaseACL;
73 import org.jahia.services.cache.CacheFactory;
74 import org.jahia.services.cache.HtmlCache;
75 import org.jahia.services.database.ConnectionDispenser;
76 import org.jahia.services.lock.LockKey;
77 import org.jahia.services.lock.LockService;
78 import org.jahia.services.pages.ContentPage;
79 import org.jahia.services.sitemap.JahiaSiteMapService;
80 import org.jahia.services.sites.JahiaSite;
81 import org.jahia.services.usermanager.JahiaUser;
82 import org.jahia.services.version.ActivationTestResults;
83 import org.jahia.services.version.EntryLoadRequest;
84 import org.jahia.services.version.IsValidForActivationResults;
85 import org.jahia.services.version.JahiaSaveVersion;
86 import org.jahia.services.version.StateModificationContext;
87
88 /**
89  * <p>Title: Jahia Workflow Engine</p> <p>Description: This engine displays all necessary forms
90  * to permit the user (who has write and/or admin access) to change a Jahia page workflow state.
91  * </p> <p>Copyright: Copyright (c) 2002</p> <p>Company: Jahia SA</p>
92  *
93  * @author MAP
94  * @version 1.0
95  */

96 public class WorkflowEngine implements JahiaEngine {
97
98     private static final String JavaDoc TEMPLATE_JSP = "workflow";
99     private final static String JavaDoc[] _tabOptions = {"notifyCompletedPages", "approvePendingPages"};
100     // private HashMap _lastDisplay = new HashMap ();
101
private static final String JavaDoc LAST_DISPLAY_SESSION_ATTRNAME = "org.jahia.engines.workflow.lastDisplay";
102
103
104     private EngineToolBox toolBox;
105
106     private static final org.apache.log4j.Logger logger =
107             org.apache.log4j.Logger.getLogger (WorkflowEngine.class);
108
109     /** the unique instance of this class */
110     private static WorkflowEngine instance = null;
111
112     private static final String JavaDoc WORKFLOW_MAIL_NOTIF_JSP = "workflow_mailnotif.jsp";
113     private static final String JavaDoc DEFAULT_PATH_TO_JSP =
114             "/jsp/jahia/engines/workflow/workflow_mailnotif.jsp";
115
116     public static final String JavaDoc WAITINGFORAPPROVAL_OPNAME = "waitingForApproval";
117     public static final String JavaDoc APPROVAL_OPNAME = "approval";
118     public static final String JavaDoc REFUSAL_OPNAME = "refusal";
119
120     public static final String JavaDoc ENGINE_NAME = "workflow";
121     
122     /**
123      * Default constructor, creates a new <code>WorkflowEngine</code> instance.
124      */

125     private WorkflowEngine () {
126         logger.debug ("***** Starting " + WorkflowEngine.class.getName () + " engine *****");
127         toolBox = EngineToolBox.getInstance ();
128     }
129
130     /**
131      * @return The instance of this engine
132      */

133     public static synchronized WorkflowEngine getInstance () {
134         if (instance == null) {
135             instance = new WorkflowEngine ();
136         }
137         return instance;
138     }
139
140     /**
141      * @param jParams ;)
142      *
143      * @return Always true
144      */

145     public boolean authoriseRender (ParamBean jParams) {
146         // Always allowed to render workflow. In other hand the button is displayed
147
// only if the logged user has write or admin access.
148
return true;
149     }
150
151     /**
152      * @param jParams ;)
153      *
154      * @return Always false
155      */

156     public boolean needsJahiaData (ParamBean jParams) {
157         return false;
158     }
159
160     /**
161      * Compose a valid workflow engine URL.
162      *
163      * @param jParams ;)
164      * @param theObj not used
165      *
166      * @return The composed URL; on s'en serait doute...
167      *
168      * @throws JahiaException
169      */

170     public String JavaDoc renderLink (ParamBean jParams, Object JavaDoc theObj)
171             throws JahiaException {
172         JahiaUser user = jParams.getUser ();
173         String JavaDoc params = EMPTY_STRING;
174         // Per default set the engine to the notification completed pages if the
175
// user has admin accesses.
176
if (jParams.getPage ().checkAdminAccess (user)) {
177             jParams.getSession().setAttribute(LAST_DISPLAY_SESSION_ATTRNAME, _tabOptions[1]);
178             // _lastDisplay.put (jParams.getSessionID (), _tabOptions[1]);
179
params = "?screen=display&display=" + _tabOptions[1];
180         } else if (jParams.getPage ().checkWriteAccess (user)) {
181             jParams.getSession().setAttribute(LAST_DISPLAY_SESSION_ATTRNAME, _tabOptions[0]);
182             // _lastDisplay.put (jParams.getSessionID (), _tabOptions[0]);
183
params = "?screen=display&display=" + _tabOptions[0];
184         }
185         
186         String JavaDoc pagesFilter = jParams.getParameter(JahiaSiteMapService.PAGES_FILTER);
187         if (pagesFilter != null)
188         {
189           if (params.indexOf('?') != -1)
190           {
191             params = params + "&";
192           }
193           else
194           {
195             params = params + "?";
196           }
197           params = params + JahiaSiteMapService.PAGES_FILTER + "=" + pagesFilter;
198         }
199                 
200         return jParams.composeEngineUrl ("workflow", params);
201     }
202
203     /**
204      * Process the engine action triggered on the displayed form. The actions can be decomposed
205      * as follow : screen ::= "display" | "apply" | "save" | "cancel"
206      * <p/>
207      * If the screen == "display" | "apply" the display should have the following values :
208      * display ::= "notifyCompletedPage" | "approvePendingPages"
209      *
210      * @param jParams ;)
211      * @param jData not used
212      *
213      * @throws JahiaException
214      */

215     public void handleActions (ParamBean jParams, JahiaData jData)
216             throws JahiaException {
217
218         JahiaUser user = jParams.getUser ();
219         if (!(jParams.getPage ().checkWriteAccess (user) ||
220                 jParams.getPage ().checkAdminAccess (user))) {
221             throw new JahiaForbiddenAccessException ();
222         }
223         int pageInfosFlag = ContentPage.ACTIVE_PAGE_INFOS | ContentPage.STAGING_PAGE_INFOS;
224         HashMap JavaDoc engineMap = new HashMap JavaDoc ();
225         String JavaDoc actionScreen = jParams.getParameter ("screen");
226         // screen = display
227
if ("display".equals (actionScreen)) {
228             initEngineMap (jParams, engineMap);
229             ContentPage contentPage = ServicesRegistry.getInstance ().
230                     getJahiaPageService ().lookupContentPage (jParams.getPageID (), false);
231
232             PagesFilter pagesFilter = JahiaSiteMapService.getCurrentPagesFilter(null, jParams);
233             JahiaSiteMapService siteMapService = ServicesRegistry.getInstance ().
234                     getJahiaSiteMapService ();
235             SiteMapViewHelper treeSiteMapViewHelper = siteMapService.
236                     getTreeSiteMapViewHelper (jParams.getUser (), contentPage,
237                             jParams.getSessionID (), pageInfosFlag, null,
238                             SiteMapViewHelper.DEFAULT_LEVEL, pagesFilter, jParams);
239             engineMap.put ("treeJahiaSiteMap", treeSiteMapViewHelper);
240
241             // Must expand first, to have all page displayed before getting locks on them !
242
// Has the user made a site map handling (collapse, expand...)...
243
String JavaDoc siteMapParam = jParams.getParameter ("sitemap");
244             if (siteMapParam != null) {
245                 siteMapService.invokeTreeSiteMapViewHelperMethod (jParams.getUser (),
246                         contentPage, jParams.getSessionID (), pageInfosFlag,
247                         null, siteMapParam, pagesFilter, jParams);
248             }
249
250             // #ifdef LOCK
251
if (jParams.settings ().areLocksActivated ()) {
252                 // Lock all page site if possible.
253
HtmlCache htmlCache = CacheFactory.getHtmlCache();
254 // HashMap lockInformationsMap = new HashMap ();
255
LockService lockRegistry = ServicesRegistry.getInstance ().getLockService ();
256                 for (int i = 0; i < treeSiteMapViewHelper.size (); i++) {
257                     ContentPage siteMapContentPage = treeSiteMapViewHelper.getContentPage (i);
258                     if (siteMapContentPage != null) {
259                         LockKey lockKey = LockKey.composeLockKey (LockKey.WORKFLOW_TYPE,
260                                 siteMapContentPage.getID (), siteMapContentPage.getID ());
261                         if (lockRegistry.acquire (lockKey, user, jParams.getSessionID (),
262                                 jParams.getSession ().getMaxInactiveInterval ())) {
263                             htmlCache.invalidatePageEntries(Integer.toString(siteMapContentPage.getID()),jParams.getEntryLoadRequest().getWorkflowState());
264                             logger.debug (
265                                     "Lock acquired for page " +
266                                     siteMapContentPage.getTitles (true));
267                         } else {
268                             logger.debug (
269                                     "Cannot acquire lock for page " +
270                                     siteMapContentPage.getTitles (true));
271                         }
272                     }
273                     else {
274                       // FIX: invisible page should be unlocked
275
int pageId = treeSiteMapViewHelper.getPageID(i);
276                       
277                       try {
278                         siteMapContentPage = ServicesRegistry.getInstance ().
279                                                 getJahiaPageService ().lookupContentPage(pageId, false);
280                         
281                         if(siteMapContentPage!=null)
282                         {
283                           LockKey lockKey = LockKey.composeLockKey (LockKey.WORKFLOW_TYPE,
284                             siteMapContentPage.getID (), siteMapContentPage.getID ());
285                           
286                           lockRegistry.release (lockKey, jParams.getUser (), jParams.getSessionID ());
287                           htmlCache.invalidatePageEntries(Integer.toString(siteMapContentPage.getID()),jParams.getEntryLoadRequest().getWorkflowState());
288                         }
289                       }
290                       catch(JahiaException exc) {
291                         // do nothing
292
}
293                     }
294                 }
295             }
296             // #endif
297

298             // If tab selected, which one ?
299
String JavaDoc display = jParams.getParameter ("display");
300             if ("notifyCompletedPages".equals (display)) {
301                 jParams.getSession().setAttribute(LAST_DISPLAY_SESSION_ATTRNAME, _tabOptions[0]);
302                 // _lastDisplay.put (jParams.getSessionID (), _tabOptions[0]);
303
engineMap.put ("activeTabOption", new Integer JavaDoc (0));
304             } else if ("approvePendingPages".equals (display)) {
305                 jParams.getSession().setAttribute(LAST_DISPLAY_SESSION_ATTRNAME, _tabOptions[1]);
306                 // _lastDisplay.put (jParams.getSessionID (), _tabOptions[1]);
307
engineMap.put ("activeTabOption", new Integer JavaDoc (1));
308             }
309             // screen = apply
310
} else if ("apply".equals (actionScreen)) {
311             applyModifications (jParams);
312             initEngineMap (jParams, engineMap);
313             ContentPage contentPage = ServicesRegistry.getInstance ().
314                     getJahiaPageService ().lookupContentPage (jParams.getPageID (), false);
315
316             PagesFilter pagesFilter = JahiaSiteMapService.getCurrentPagesFilter(null, jParams);
317             engineMap.put ("treeJahiaSiteMap",
318                     ServicesRegistry.getInstance ().getJahiaSiteMapService ().
319                     getTreeSiteMapViewHelper (jParams.getUser (), contentPage,
320                             jParams.getSessionID (), pageInfosFlag, null,
321                             SiteMapViewHelper.DEFAULT_LEVEL, pagesFilter, jParams));
322             engineMap.put ("screen", EMPTY_STRING); // Screen is defined bellow
323
//engineMap.put (ENGINE_URL_PARAM,
324
// jParams.composeEngineUrl (ENGINE_NAME,
325
// "?screen=display&display=" +
326
// _lastDisplay.get (jParams.getSessionID ())));
327
engineMap.put(ENGINE_URL_PARAM, jParams.composeEngineUrl(ENGINE_NAME, "?screen=display&display=" + jParams.getSession().getAttribute(LAST_DISPLAY_SESSION_ATTRNAME)));
328             engineMap.put ("jspSource", "apply");
329             // screen = save
330
} else if ("save".equals (actionScreen)) {
331             applyModifications (jParams);
332             engineMap.put ("jspSource", "close");
333             // #ifdef LOCK
334
releaseAllLock (jParams);
335             // #endif
336
// FIX: session site map should be removed
337
JahiaSiteMapService siteMapService = ServicesRegistry.getInstance().getJahiaSiteMapService();
338             ContentPage contentPage = ServicesRegistry.getInstance ().
339                                             getJahiaPageService ().lookupContentPage(jParams.getPageID(), false);
340             
341             siteMapService.removeSessionPageSiteMap(jParams.getUser(), contentPage, jParams.getSessionID());
342             // screen = cancel
343
} else if ("cancel".equals (actionScreen)) {
344             // #ifdef LOCK
345
releaseAllLock (jParams);
346             // #endif
347
// FIX: session site map should be removed
348
JahiaSiteMapService siteMapService = ServicesRegistry.getInstance().getJahiaSiteMapService();
349             ContentPage contentPage = ServicesRegistry.getInstance ().
350                                             getJahiaPageService ().lookupContentPage(jParams.getPageID(), false);
351             
352             siteMapService.removeSessionPageSiteMap(jParams.getUser(), contentPage, jParams.getSessionID());
353             engineMap.put ("jspSource", "close");
354         }
355         engineMap.put (RENDER_TYPE_PARAM, new Integer JavaDoc (JahiaEngine.RENDERTYPE_FORWARD));
356         toolBox.displayScreen (jParams, engineMap);
357     }
358
359     /**
360      * Retrieve the engine name.
361      *
362      * @return the engine name.
363      */

364     public final String JavaDoc getName () {
365         return ENGINE_NAME;
366     }
367
368     /**
369      * Prepare the datas to display in the engine.
370      *
371      * @param jParams ;)
372      *
373      * @throws JahiaException
374      */

375     private void initEngineMap (ParamBean jParams, HashMap JavaDoc engineMap)
376             throws JahiaException {
377         engineMap.clear ();
378         engineMap.put ("jspSource", TEMPLATE_JSP);
379         engineMap.put ("tabOptions", _tabOptions);
380         jParams.getRequest ().setAttribute ("engineTitle", "Workflow"); // Displayed in 'engine.jsp'
381
}
382
383     /**
384      * Apply modification made in to form submited. 1) Check all tokenized parameters. 2)
385      * Checkbox/Input tags 2.1) look at the checkbox and parse its name. The following format
386      * were choosen : 2.1.1) For notify completed pages : checkboxName ::= "checkobx"
387      * iso639LanguageCode pageID 2.1.2) Look up corresponding Jahia page and change it to
388      * WAITING state 2.2.1) For approve pending pages : checkboxName ::= "checkbox"
389      * iso639LanguageCode pageID ("accept" | "refuse") 2.2.2) If checkbox == "refuse" then
390      * lookup to corresponding Jahia page and change its state back to STAGED mode otherwise (if
391      * checkbox == "accept") the Jahia page is change to the ACTIVE state. 2.2) Look at the
392      * input box (not implemented yet)
393      *
394      * @param jParams ;)
395      */

396     private void applyModifications (ParamBean jParams)
397             throws JahiaException {
398
399         // Get the cache instance BEFORE applying any modification in case the cache cannot
400
// be found for any mysterious reason ;o) THIS SHOULD STAY THE FIRST ACTION TO
401
// PREVENT THE NECESSITY OF ROLLLING BACK PREVIOUS OPERATIONS IN CASE THE CACHE
402
// IN NOT AVAILABLE!!
403
//Cache pageChildCache = CacheFactory.getInstance().getCache (JahiaPageService.PAGE_CHILD_CACHE);
404
//if (pageChildCache == null)
405
// throw new JahiaException ("Internal Cache error", "Could not get the cache [" +
406
// JahiaPageService.PAGE_CHILD_CACHE + "] instance.",
407
// JahiaException.CACHE_ERROR, JahiaException.CRITICAL_SEVERITY);
408

409         // PAP: Get connection in order to start a JTA transaction for this thread
410
ConnectionDispenser.getTxConnection ();
411         
412         JahiaSaveVersion saveVersion = ServicesRegistry.getInstance ().getJahiaVersionService ().
413                 getSiteSaveVersion (jParams.getSiteID ());
414         Enumeration JavaDoc paramNames = jParams.getRequest ().getParameterNames ();
415         WorkflowMap workflowForm = new WorkflowMap ();
416         
417         boolean areLocksActivated = Jahia.getSettings().areLocksActivated();
418         LockService lockRegistry = ServicesRegistry.getInstance ().getLockService ();
419         
420         while (paramNames.hasMoreElements ()) {
421             String JavaDoc paramName = (String JavaDoc) paramNames.nextElement ();
422             String JavaDoc[] paramValues = jParams.getRequest ().getParameterValues (paramName);
423             for (int i = 0; i < paramValues.length; i++) {
424                 StringTokenizer JavaDoc paramToken = new StringTokenizer JavaDoc (paramName, "|");
425                 if (paramToken.hasMoreTokens ()) {
426                     String JavaDoc nextParam = paramToken.nextToken ();
427                     // Look for the checkboxes
428
if ("checkbox".equals (nextParam)) {
429                         String JavaDoc languageCode = paramToken.nextToken ();
430                         String JavaDoc pageIDStr = paramToken.nextToken ();
431                         // #ifdef LOCK
432
if (areLocksActivated) {
433                             // Ensure that the lock is always our's.
434
int pageID = Integer.parseInt (pageIDStr);
435                             LockKey lockKey = LockKey.composeLockKey (LockKey.WORKFLOW_TYPE,
436                                     pageID, pageID);
437                             if (!lockRegistry.isAlreadyAcquiredInContext (lockKey,
438                                     jParams.getUser (), jParams.getSessionID ())) {
439                                 continue;
440                             }
441                         }
442                         // #endif
443
// The last token (acceptRefuse) exists only if the form is
444
// comming from 'approvepending' JSP file. In this case the
445
// appropriate change status should be called.
446
String JavaDoc acceptRefuse = paramToken.hasMoreTokens () ?
447                                 paramToken.nextToken () : null;
448                         if (acceptRefuse == null) { // Notify completion page scase
449
workflowForm.setLanguage (WorkflowMap.FOR_NOTIFY_COMPLETION,
450                                     languageCode, pageIDStr);
451                         } else { // Approve pending pages case
452
if ("refuse".equals (acceptRefuse)) {
453                                 workflowForm.setLanguage (WorkflowMap.FOR_REFUSE_PENDING,
454                                         languageCode, pageIDStr);
455                             } else { // accept !
456
workflowForm.setLanguage (WorkflowMap.FOR_ACCEPT_PENDING,
457                                         languageCode, pageIDStr);
458                             }
459                         }
460                     }
461                     // Look for notification messages
462
if ("input".equals (nextParam)) {
463                         String JavaDoc pageIDStr = paramToken.nextToken ();
464                         if (!EMPTY_STRING.equals (paramValues[i])) {
465                             workflowForm.setComment (pageIDStr, paramValues[i]);
466                         }
467                     }
468                 }
469             }
470         }
471
472
473         Map JavaDoc userNotifData = new HashMap JavaDoc ();
474         ArrayList JavaDoc recipients;
475
476         for (int workflowOperation = 0; workflowOperation < 3; workflowOperation++) {
477             //String recipientList = null;
478
boolean shouldSendMessage = false;
479             HashMap JavaDoc languageMapForNotifyCompletion = workflowForm.
480                 getLanguageMap(
481                 workflowOperation);
482             Iterator JavaDoc languageMapIt = languageMapForNotifyCompletion.keySet().
483                 iterator();
484             ArrayList JavaDoc pageIDs = new ArrayList JavaDoc();
485             while (languageMapIt.hasNext ()) {
486                 String JavaDoc pageIDStr = (String JavaDoc) languageMapIt.next();
487                 try {
488                     Integer JavaDoc I = new Integer JavaDoc(Integer.parseInt(pageIDStr));
489                     pageIDs.add(I);
490                 } catch ( Throwable JavaDoc t ){
491                     logger.debug(t);
492                 }
493             }
494
495             // sort pages to activate childs first
496
Vector JavaDoc sortedPages = ServicesRegistry.getInstance().getJahiaPageService()
497                 .sortPages(pageIDs,jParams.getEntryLoadRequest(),
498                            jParams.getUser(),jParams.getOperationMode());
499             Enumeration JavaDoc enumeration = sortedPages.elements();
500             try {
501                 while (enumeration.hasMoreElements()) {
502                     Integer JavaDoc I = (Integer JavaDoc) enumeration.nextElement();
503                     int pageID = I.intValue();
504                     String JavaDoc pageIDStr = String.valueOf(pageID);
505                     HashSet JavaDoc languageCodes = (HashSet JavaDoc) workflowForm.getLanguages(workflowOperation, pageIDStr);
506                     StateModificationContext stateModifContext = new StateModificationContext(
507                             new ContentPageKey(pageID), languageCodes);
508                     stateModifContext.setDescendingInSubPages(false);
509                     try {
510                         // PAP: Create new object and don't get the one from
511
// cache, which is
512
// also used by other users, so they won't get
513
// uncommited modifications.
514
ContentPage contentPage = ContentPage.getPage(pageID, true, true);
515
516                         switch (workflowOperation) {
517                         case 0: // Notify complete
518
contentPage.changeStagingStatus(languageCodes, EntryLoadRequest.WAITING_WORKFLOW_STATE,
519                                     jParams, stateModifContext);
520
521                             // PAP: commit after each page and before adding page to mail notification
522
commitAndFlushCaches(contentPage);
523
524                             // we need to check if
525
shouldSendMessage = true;
526                             //recipientList = getRecipientsString(contentPage, jParams.getSiteID(), 0x2);
527

528                             // new system, per user messaging
529
recipients = getRecipients(contentPage, jParams.getSiteID(), 0x2);
530                             for (int i = 0; i < recipients.size(); i++) {
531                                 String JavaDoc curEmail = (String JavaDoc) recipients.get(i);
532                                 Map JavaDoc operationMap = (Map JavaDoc) userNotifData.get(curEmail);
533                                 if (operationMap == null) {
534                                     operationMap = new HashMap JavaDoc();
535                                 }
536                                 Set JavaDoc pageList = (Set JavaDoc) operationMap.get(WAITINGFORAPPROVAL_OPNAME);
537                                 if (pageList == null) {
538                                     pageList = new HashSet JavaDoc();
539                                 }
540                                 PageNotifData pageNotifData = new PageNotifData(
541                                     jParams.getSiteURL(pageID, false, false),
542                                     workflowForm.getComment(pageIDStr, jParams
543                                         .getLocale()), contentPage,
544                                     languageCodes, true, null, null);
545                                 pageList.add(pageNotifData);
546                                 operationMap.put(WAITINGFORAPPROVAL_OPNAME, pageList);
547                                 userNotifData.put(curEmail, operationMap);
548                             }
549                             break;
550                         case 1: // Refuse
551
contentPage.changeStagingStatus(languageCodes, EntryLoadRequest.STAGING_WORKFLOW_STATE,
552                                     jParams, stateModifContext);
553                             LockKey lockKey = LockKey.composeLockKey(LockKey.WAITING_FOR_APPROVAL_TYPE, contentPage
554                                     .getID(), contentPage.getID());
555                             lockRegistry.release(lockKey, jParams.getUser(), jParams.getSessionID());
556
557                             // PAP: commit after each page and before adding page to mail notification
558
commitAndFlushCaches(contentPage);
559                             
560                             shouldSendMessage = true;
561                             //recipientList = getRecipientsString(contentPage, jParams.getSiteID(), 0x1);
562

563                             // new system, per user messaging
564
recipients = getRecipients(contentPage, jParams.getSiteID(), 0x1);
565                             for (int i = 0; i < recipients.size(); i++) {
566                                 String JavaDoc curEmail = (String JavaDoc) recipients.get(i);
567                                 Map JavaDoc operationMap = (Map JavaDoc) userNotifData.get(curEmail);
568                                 if (operationMap == null) {
569                                     operationMap = new HashMap JavaDoc();
570                                 }
571                                 Set JavaDoc pageList = (Set JavaDoc) operationMap.get(REFUSAL_OPNAME);
572                                 if (pageList == null) {
573                                     pageList = new HashSet JavaDoc();
574                                 }
575                                 PageNotifData pageNotifData = new PageNotifData(
576                                     jParams.getSiteURL(pageID, false, false),
577                                     workflowForm.getComment(pageIDStr, jParams
578                                         .getLocale()), contentPage,
579                                     languageCodes, true, null, null);
580                                 pageList.add(pageNotifData);
581                                 operationMap.put(REFUSAL_OPNAME, pageList);
582                                 userNotifData.put(curEmail, operationMap);
583                             }
584                             break;
585                             
586                         case 2: // Accept
587
logger.debug("Start activating page: " + pageID);
588                             
589                             // to avoid creating twice a same version ID, we must check that
590
// this page has not been already versioned at this saveVersion Id
591
int activeVersionId = contentPage.getActiveVersionID();
592                             int deletedVersionId = contentPage.getDeleteVersionID();
593                             if (activeVersionId == saveVersion.getVersionID()
594                                     || deletedVersionId == saveVersion.getVersionID()) {
595                                 // has been already activated! Do not activate again
596
// because we will create a same save version date ( a corrupted situation )
597
logger.debug("Either active version ID: "
598                                         + activeVersionId
599                                         + " or deleted version ID: "
600                                         + deletedVersionId
601                                         + " is the same as saved version ID: "
602                                         + saveVersion.getVersionID());
603                                 continue;
604                             }
605
606                             // First verify if the page has the same parent. In
607
// this case remove the old moved parent page from cache and
608
// invalidate the site map. The new moved parent page
609
// does not need to be flushed !!
610
int parentPageIDToFlushFromCache = contentPage.hasSameParentID();
611                             if (parentPageIDToFlushFromCache > 0) {
612                                 //pageChildCache.remove(Integer.toString(parentPageIDToFlushFromCache));
613
/**
614                                  * @todo FIXME site map is entirely flushed in
615                                  * this case
616                                  */

617                                 ServicesRegistry.getInstance().getJahiaSiteMapService().resetSiteMap();
618                             }
619                             // Make the validation.
620
JahiaSite jahiaSite = ServicesRegistry.getInstance().getJahiaSitesService().getSite(
621                                     jParams.getSiteID());
622
623                             // Pages move issue, check if this page is involved
624
// in a page move. If this is the case check if we should
625
// activate the old parent page to avoid cyclic situation
626
// ( active only one page involved in a parent/child inversion )
627
boolean shouldActivateStagedParentPage = false;
628                             boolean shouldActivateCurrentParentPage = false;
629                             ContentPage stagedParentPage = null;
630                             ContentPage currentParentPage = null;
631                             if (contentPage.hasSameParentID() != ContentPage.SAME_PARENT) {
632                                 try {
633                                     // should active staged parent page ?
634
int stagedParentID = contentPage.getParentID(EntryLoadRequest.STAGED);
635                                     if (stagedParentID > 0) {
636                                         stagedParentPage = ContentPage.getPage(stagedParentID);
637                                         if (stagedParentPage.hasSameParentID() != ContentPage.SAME_PARENT) {
638                                             if (stagedParentPage.getParentID(EntryLoadRequest.CURRENT) == contentPage
639                                                     .getID()) {
640                                                 // page parent/child inversion
641
// we must activate both of them
642
shouldActivateStagedParentPage = true;
643                                             }
644                                         }
645                                     }
646                                 } catch (Throwable JavaDoc t) {
647                                     logger.debug("Exception when activate staged parent page of page "
648                                             + contentPage.getID(), t);
649                                 }
650                                 try {
651
652                                     // should active current parent page ?
653
int currentParentID = contentPage.getParentID(EntryLoadRequest.CURRENT);
654                                     if (currentParentID > 0) {
655                                         currentParentPage = ContentPage.getPage(currentParentID);
656                                         if (currentParentPage.hasSameParentID() != ContentPage.SAME_PARENT) {
657                                             if (currentParentPage.getParentID(EntryLoadRequest.STAGED) == contentPage
658                                                     .getID()) {
659                                                 // page parent/child inversion
660
// we must activate both of them
661
shouldActivateCurrentParentPage = true;
662                                             }
663                                         }
664                                     }
665                                 } catch (Throwable JavaDoc t) {
666                                     logger.debug("Exception when activate current parent page of page "
667                                             + contentPage.getID(), t);
668                                 }
669                             }
670
671                             if (shouldActivateStagedParentPage) {
672                                 logger.debug("Should activate staged parent page");
673                                 activatePage(stagedParentPage, languageCodes, saveVersion, jParams);
674                             }
675                             if (shouldActivateCurrentParentPage) {
676                                 logger.debug("Should activate current parent page");
677                                 activatePage(currentParentPage, languageCodes, saveVersion, jParams);
678                             }
679
680                             // now let's change the staging status of the
681
// content that was not activated back to the
682
// basic staging status.
683
logger.debug("start change staging status");
684                             contentPage.changeStagingStatus(languageCodes, EntryLoadRequest.STAGING_WORKFLOW_STATE,
685                                     jParams, stateModifContext);
686                             ActivationTestResults activationTestResults = contentPage.activeStagingEntries(
687                                     languageCodes, jahiaSite.isVersioningEnabled(), saveVersion, jParams.getUser(),
688                                     jParams, stateModifContext);
689
690                             boolean workflowSuccessful = (activationTestResults.getStatus() != ActivationTestResults.FAILED_OPERATION_STATUS);
691
692                             /**
693                              * @todo : FIXME catch the problems if any and put
694                              * them to the CMS event logger to implement.
695                              */

696                             logger.debug("ActivationTestResult=" + activationTestResults);
697                             /*
698                             if (activationTestResults.getStatus() ==
699                                 ActivationTestResults.FAILED_OPERATION_STATUS) {
700                                 logger.error("Error in activation : ",
701                                              new
702                                              JahiaException("Error in activation " +
703                                     activationTestResults.toString(),
704                                     "Error in activation " +
705                                     activationTestResults.toString(),
706                                     JahiaException.DATA_ERROR,
707                                     JahiaException.ERROR_SEVERITY));
708                             }
709                              */

710                             lockKey = LockKey.composeLockKey(LockKey.WAITING_FOR_APPROVAL_TYPE, contentPage.getID(),
711                                     contentPage.getID());
712                             lockRegistry.release(lockKey, jParams.getUser(), jParams.getSessionID());
713                             
714                             // PAP: commit after each page and before adding page to mail notification
715
commitAndFlushCaches(contentPage);
716                             
717                             shouldSendMessage = true;
718                             //recipientList = getRecipientsString(contentPage, jParams.getSiteID(), 0x3);
719

720                             // new system, per user messaging
721
recipients = getRecipients(contentPage, jParams.getSiteID(), 0x3);
722                             for (int i = 0; i < recipients.size(); i++) {
723                                 String JavaDoc curEmail = (String JavaDoc) recipients.get(i);
724                                 Map JavaDoc operationMap = (Map JavaDoc) userNotifData.get(curEmail);
725                                 if (operationMap == null) {
726                                     operationMap = new HashMap JavaDoc();
727                                 }
728                                 Set JavaDoc pageList = (Set JavaDoc) operationMap.get(APPROVAL_OPNAME);
729                                 if (pageList == null) {
730                                     pageList = new HashSet JavaDoc();
731                                 }
732                                 PageNotifData pageNotifData = new PageNotifData(
733                                     jParams.getSiteURL(pageID, false, false),
734                                     workflowForm.getComment(pageIDStr, jParams
735                                         .getLocale()), contentPage,
736                                     languageCodes, workflowSuccessful,
737                                     activationTestResults.getErrors(),
738                                     activationTestResults.getWarnings());
739                                 pageList.add(pageNotifData);
740                                 operationMap.put(APPROVAL_OPNAME, pageList);
741                                 userNotifData.put(curEmail, operationMap);
742                             }
743
744                             break;
745                         }
746                     } catch (JahiaException je) {
747                         logger.error("Cannot change Jahia Page staging status", je);
748                         throw je;
749                     }
750                 }
751             } finally {
752                 if (shouldSendMessage) {
753                     // ServicesRegistry.getInstance().getMailService().sendMessage(recipientList, message.toString());
754
String JavaDoc jspMailNotifFileName = jParams.getPage ().getPageTemplate ().getSourcePath ();
755                     jspMailNotifFileName = jspMailNotifFileName.substring (0,
756                             jspMailNotifFileName.lastIndexOf ("/") + 1) +
757                             WORKFLOW_MAIL_NOTIF_JSP;
758                     File JavaDoc jspFile = new File JavaDoc (jParams.getContext ().getRealPath (jspMailNotifFileName));
759                     if (!jspFile.exists ()) {
760                         jspMailNotifFileName = DEFAULT_PATH_TO_JSP;
761                     }
762                     jspFile = new File JavaDoc (jParams.getContext ().getRealPath (jspMailNotifFileName));
763                     if (jspFile.exists ()) {
764                         Iterator JavaDoc userIter = userNotifData.keySet ().iterator ();
765                         while (userIter.hasNext ()) {
766                             String JavaDoc curEmail = (String JavaDoc) userIter.next ();
767                             Map JavaDoc operationMap = (Map JavaDoc) userNotifData.get (curEmail);
768                             logger.debug ("Sending custom notification data to email " +
769                                     curEmail);
770                             jParams.getRequest ().setAttribute ("org.jahia.engines.workflow.paramBean",
771                                     jParams);
772                             jParams.getRequest ().setAttribute (
773                                     "org.jahia.engines.workflow.notifyOperationMap", operationMap);
774                             // warning, must check that nothing is written in the response
775
// in terms of content type attributes, etc...
776
String JavaDoc mailBody = ServicesRegistry.getInstance ().getJahiaFetcherService ().
777                                     fetchServlet (jParams, jspMailNotifFileName);
778                             jParams.getRequest ().removeAttribute (
779                                     "org.jahia.engines.workflow.notifyOperationMap");
780                             jParams.getRequest ().removeAttribute ("org.jahia.engines.workflow.paramBean");
781                             String JavaDoc from = (String JavaDoc) jParams.getRequest ().getAttribute (
782                                     "org.jahia.engines.workflow.notify.from");
783                             String JavaDoc cc = (String JavaDoc) jParams.getRequest ().getAttribute (
784                                     "org.jahia.engines.workflow.notify.cc");
785                             String JavaDoc bcc = (String JavaDoc) jParams.getRequest ().getAttribute (
786                                     "org.jahia.engines.workflow.notify.bcc");
787                             String JavaDoc subject = (String JavaDoc) jParams.getRequest ().getAttribute (
788                                     "org.jahia.engines.workflow.notify.subject");
789                             jParams.getRequest ().removeAttribute (
790                                     "org.jahia.engines.workflow.notify.from");
791                             jParams.getRequest ().removeAttribute ("org.jahia.engines.workflow.notify.cc");
792                             jParams.getRequest ().removeAttribute ("org.jahia.engines.workflow.notify.bcc");
793                             jParams.getRequest ().removeAttribute (
794                                     "org.jahia.engines.workflow.notify.subject");
795                             ServicesRegistry.getInstance ().getMailService ().sendMessage (from, curEmail,
796                                     cc, bcc, subject, mailBody, false);
797                         }
798                     }
799                 }
800             }
801         }
802         workflowForm = null; // Let's activate the garbage collector.
803
}
804
805     // #ifdef LOCK
806
private void releaseAllLock (ParamBean jParams)
807             throws JahiaException {
808         if (jParams.settings ().areLocksActivated ()) {
809             HtmlCache htmlCache = CacheFactory.getHtmlCache();
810             ContentPage contentPage = ServicesRegistry.getInstance ().
811                     getJahiaPageService ().lookupContentPage (jParams.getPageID (), false);
812             JahiaSiteMapService siteMapService = ServicesRegistry.getInstance ().
813                     getJahiaSiteMapService ();
814             // let's make sure the whole tree is expanded before we start
815
// liberating page locks.
816
int pageInfosFlag = ContentPage.ACTIVE_PAGE_INFOS | ContentPage.STAGING_PAGE_INFOS;
817             PagesFilter pagesFilter = JahiaSiteMapService.getCurrentPagesFilter(null, jParams);
818             siteMapService.invokeTreeSiteMapViewHelperMethod (jParams.getUser (),
819                     contentPage, jParams.getSessionID (), pageInfosFlag,
820                     null, "expandall|0", pagesFilter, jParams);
821
822             // here below we set the page level to maximum because we want
823
// to free all the sub pages locks.
824
SiteMapViewHelper treeSiteMapViewHelper = siteMapService.
825                     getTreeSiteMapViewHelper (jParams.getUser (), contentPage,
826                             jParams.getSessionID (), ContentPage.ACTIVE_PAGE_INFOS |
827                     ContentPage.STAGING_PAGE_INFOS,
828                     null, Integer.MAX_VALUE, pagesFilter, jParams);
829
830             // Lock all page site if possible.
831
LockService lockRegistry = ServicesRegistry.getInstance ().getLockService ();
832             for (int i = 0; i < treeSiteMapViewHelper.size (); i++) {
833                 ContentPage siteMapContentPage = treeSiteMapViewHelper.getContentPage (i);
834                 if (siteMapContentPage != null) {
835                     LockKey lockKey = LockKey.composeLockKey (LockKey.WORKFLOW_TYPE,
836                             siteMapContentPage.getID (), siteMapContentPage.getID ());
837                     lockRegistry.release (lockKey, jParams.getUser (), jParams.getSessionID ());
838                     htmlCache.invalidatePageEntries(Integer.toString(siteMapContentPage.getID()),jParams.getEntryLoadRequest().getWorkflowState());
839                 }
840             }
841         }
842     }
843     // #endif
844

845 // private String getRecipientsString (ContentPage contentPage, int siteID, int access) {
846
//
847
// ArrayList recipientList = getRecipients (contentPage, siteID, access);
848
// StringBuffer emailListBuf = new StringBuffer ();
849
// for (int i = 0; i < recipientList.size (); i++) {
850
// String email = (String) recipientList.get (i);
851
// if (email != null && !EMPTY_STRING.equals (email)) {
852
// /** @todo : @localhost address generates problems with Windows */
853
// if (email.indexOf ("@localhost") != -1) {
854
// continue;
855
// }
856
// if (emailListBuf.length () > 0) {
857
// emailListBuf.append (",");
858
// }
859
// emailListBuf.append (email);
860
// }
861
// }
862
// logger.debug ("Using email recipient list :" + emailListBuf);
863
// return emailListBuf.toString ();
864
// }
865

866     private ArrayList JavaDoc getRecipients (ContentPage contentPage, int siteID, int access) {
867         ArrayList JavaDoc result = new ArrayList JavaDoc ();
868         result.add (ServicesRegistry.getInstance ().getMailService ().defaultRecipient ());
869         //StringBuffer emailListBuf = new StringBuffer ();
870
/**
871          * @todo we could optimize this if we retrieved really only the list
872          * of using that have write and admin accesses instead of retrieving
873          * all users in the ACL.
874          */

875         JahiaBaseACL pageACL = contentPage.getACL ();
876         try {
877             Vector JavaDoc users = pageACL.getUsernameListAlsoGroupUsers (null);
878             for (int i = 0; i < users.size (); i++) {
879                 JahiaUser user = ServicesRegistry.getInstance ().
880                         getJahiaUserManagerService ().lookupUser ((String JavaDoc) users.get (
881                                 i));
882                 if (user == null)
883                     continue;
884                 String JavaDoc email = user.getProperty ("email");
885                 if (email != null && !EMPTY_STRING.equals (email)) {
886                     /** @todo : @localhost address generates problems with Windows */
887                     if (email.indexOf ("@localhost") != -1) {
888                         continue;
889                     }
890                     boolean shouldCheckWriteAccess = (access & 0x01) != 0;
891                     boolean shouldCheckAdminAccess = (access & 0x02) != 0;
892                     if (shouldCheckWriteAccess &&
893                             contentPage.checkWriteAccess (user) ||
894                             shouldCheckAdminAccess &&
895                             contentPage.checkAdminAccess (user)) {
896                         result.add (email);
897                     }
898                 }
899             }
900         } catch (JahiaACLException jae) {
901             logger.error ("Error while retrieving users from ACL", jae);
902         }
903         logger.debug ("Using email recipient list :" + result);
904         return result;
905     }
906
907
908
909
910
911     public class PageNotifData implements Comparable JavaDoc {
912         private String JavaDoc pageURL;
913         private String JavaDoc pageComment;
914         private ContentPage contentPage;
915         private Set JavaDoc languageCodes;
916         private boolean workflowSuccessful;
917         private ArrayList JavaDoc errors;
918         private ArrayList JavaDoc warnings;
919
920         public PageNotifData(String JavaDoc thePageURL, String JavaDoc thePageComment, ContentPage theContentPage, HashSet JavaDoc langCodes,
921                 boolean isWorkflowSuccessful, ArrayList JavaDoc errorList, ArrayList JavaDoc warningList) {
922             this.pageURL = thePageURL;
923             this.pageComment = thePageComment;
924             this.contentPage = theContentPage;
925             this.languageCodes = langCodes;
926             this.workflowSuccessful = isWorkflowSuccessful;
927             if (errorList != null) {
928                 this.errors = errorList;
929             } else {
930                 this.errors = new ArrayList JavaDoc();
931             }
932             if (warningList != null) {
933                 this.warnings = warningList;
934             } else {
935                 this.warnings = new ArrayList JavaDoc();
936             }
937         }
938
939         public String JavaDoc getPageURL () {
940             return pageURL;
941         }
942
943         public String JavaDoc getPageComment () {
944             return pageComment;
945         }
946
947         public ContentPage getContentPage () {
948             return contentPage;
949         }
950
951         public Set JavaDoc getLanguageCodes() {
952             return languageCodes;
953         }
954
955         public Map JavaDoc getTitles() {
956             Hashtable JavaDoc allTitles = contentPage.getTitles(true);
957             Map JavaDoc workflowTitles = new HashMap JavaDoc();
958             Iterator JavaDoc languageIter = languageCodes.iterator();
959             while (languageIter.hasNext()) {
960                 String JavaDoc curLanguageCode = (String JavaDoc) languageIter.next();
961                 String JavaDoc curLanguageTitle = (String JavaDoc) allTitles.get(curLanguageCode);
962                 workflowTitles.put(curLanguageCode, curLanguageTitle);
963             }
964             return workflowTitles;
965         }
966
967         public String JavaDoc getDisplayTitle() {
968             Map JavaDoc titles = getTitles();
969             StringBuffer JavaDoc result = new StringBuffer JavaDoc();
970             Iterator JavaDoc entryIter = titles.entrySet().iterator();
971             while (entryIter.hasNext()) {
972                 Map.Entry JavaDoc curEntry = (Map.Entry JavaDoc) entryIter.next();
973                 result.append(curEntry.getValue());
974                 if (entryIter.hasNext()) {
975                     result.append(", ");
976                 }
977             }
978             return result.toString();
979         }
980         
981         public String JavaDoc getDisplayTitles() {
982             Map JavaDoc titles = getTitles();
983             StringBuffer JavaDoc result = new StringBuffer JavaDoc();
984             Iterator JavaDoc entryIter = titles.entrySet().iterator();
985             while (entryIter.hasNext()) {
986                 Map.Entry JavaDoc curEntry = (Map.Entry JavaDoc) entryIter.next();
987                 result.append(curEntry.getKey());
988                 result.append("=");
989                 result.append(curEntry.getValue());
990                 if (entryIter.hasNext()) {
991                     result.append(", ");
992                 }
993             }
994             return result.toString();
995         }
996
997         public boolean isWorkflowSuccessful() {
998             return workflowSuccessful;
999         }
1000
1001        public ArrayList JavaDoc getErrors() {
1002            return errors;
1003        }
1004
1005        public ArrayList JavaDoc getWarnings() {
1006            return warnings;
1007        }
1008
1009        public String JavaDoc getDisplayErrors(Locale JavaDoc locale, String JavaDoc separator) {
1010            return getDisplayActivationResults(getErrors(), locale, separator);
1011        }
1012
1013        private String JavaDoc getDisplayActivationResults(ArrayList JavaDoc activationResults, Locale JavaDoc locale, String JavaDoc separator) {
1014            StringBuffer JavaDoc result = new StringBuffer JavaDoc();
1015            Iterator JavaDoc activationIter = activationResults.iterator();
1016            while (activationIter.hasNext()) {
1017                Object JavaDoc curActivationResultObj = activationIter.next();
1018                if (!(curActivationResultObj instanceof IsValidForActivationResults)) {
1019                    result.append(curActivationResultObj.toString());
1020                } else {
1021                    IsValidForActivationResults validationResult = (
1022                        IsValidForActivationResults) curActivationResultObj;
1023                    String JavaDoc resultFormat = JahiaResourceBundle.
1024                                          getMessageResource(
1025                        "org.jahia.engines.workflow.activationResultMessage",
1026                        locale);
1027                    Object JavaDoc[] arguments = {
1028                                         validationResult.getComment(),
1029                                         validationResult.getObjectType(),
1030                                         new Integer JavaDoc(validationResult.
1031                        getObjectID()),
1032                                         validationResult.getLanguageCode()
1033                    };
1034
1035                    result.append(MessageFormat.format(resultFormat, arguments));
1036                }
1037                 if (activationIter.hasNext()) {
1038                     result.append(separator);
1039                 }
1040            }
1041            return result.toString();
1042        }
1043
1044        public boolean equals (Object JavaDoc o) {
1045            if (!(o instanceof PageNotifData)) {
1046                return false;
1047            }
1048            PageNotifData right = (PageNotifData) o;
1049            return ((pageURL.equals (right.pageURL)) && (pageComment.equals (right.pageComment)));
1050        }
1051
1052        public int hashCode () {
1053            return (pageURL + pageComment).hashCode ();
1054        }
1055
1056        public int compareTo (Object JavaDoc o) throws ClassCastException JavaDoc {
1057            PageNotifData right = (PageNotifData) o;
1058            int pageURLComp = pageURL.compareTo (right.pageURL);
1059            if (pageURLComp != 0) {
1060                return pageURLComp;
1061            }
1062            return pageComment.compareTo (right.pageComment);
1063        }
1064    }
1065
1066    /**
1067     * <p>Title: </p> Workflow Map <p>Description: This class store all datas given by the
1068     * formular defined in the wokflow JSP view. The reason is to give a 'Set' of language codes
1069     * in one time for a given page ID to the 'changeStagingStatus' and 'activationTestResults'
1070     * methods insteed to apply these methods each time we catch something from the formular.
1071     * </p> <p>Copyright: MAP (Jahia Solutions S�rl 2002)</p> <p>Company: Jahia Solutions
1072     * S�rl</p>
1073     *
1074     * @author MAP
1075     * @version 1.0
1076     */

1077    protected class WorkflowMap {
1078
1079        public static final int FOR_NOTIFY_COMPLETION = 0;
1080        public static final int FOR_REFUSE_PENDING = 1;
1081        public static final int FOR_ACCEPT_PENDING = 2;
1082
1083        public void setLanguage (int whatFor, String JavaDoc languageCode, String JavaDoc pageID) {
1084            Set JavaDoc languages = (HashSet JavaDoc) languageMap[whatFor].get (pageID);
1085            if (languages == null) {
1086                Set JavaDoc _languages = new HashSet JavaDoc ();
1087                _languages.add (languageCode);
1088                languageMap[whatFor].put (pageID, _languages);
1089            } else {
1090                languages.add (languageCode);
1091            }
1092        }
1093
1094        public Set JavaDoc getLanguages (int whatFor, String JavaDoc pageID) {
1095            return (HashSet JavaDoc) languageMap[whatFor].get (pageID);
1096        }
1097
1098        public void setComment (String JavaDoc pageID, String JavaDoc comment) {
1099            commentMap.put (pageID, comment);
1100        }
1101
1102        public String JavaDoc getComment (String JavaDoc pageID, Locale JavaDoc userLocale) {
1103            String JavaDoc comment = (String JavaDoc) commentMap.get (pageID);
1104            if (comment == null) {
1105                comment = JahiaResourceBundle.getMessageResource(
1106                        "org.jahia.engines.workflow.noComment",
1107                        userLocale);
1108            }
1109            return comment;
1110        }
1111
1112        public HashMap JavaDoc getLanguageMap (int whatFor) {
1113            return languageMap[whatFor];
1114        }
1115
1116        private HashMap JavaDoc commentMap = new HashMap JavaDoc ();
1117        private HashMap JavaDoc languageMapForNotifyCompletion = new HashMap JavaDoc ();
1118        private HashMap JavaDoc languageMapForRefusePending = new HashMap JavaDoc ();
1119        private HashMap JavaDoc languageMapForAcceptPending = new HashMap JavaDoc ();
1120        private HashMap JavaDoc[] languageMap = {languageMapForNotifyCompletion,
1121                                         languageMapForRefusePending,
1122                                         languageMapForAcceptPending};
1123    }
1124
1125    private ActivationTestResults activatePage (ContentPage contentPage,
1126                                                HashSet JavaDoc languageCodes,
1127                                                JahiaSaveVersion saveVersion,
1128                                                ParamBean jParams)
1129        throws JahiaException {
1130
1131        StateModificationContext smc = new
1132                                       StateModificationContext(new
1133            ContentPageKey(contentPage.getID()), languageCodes);
1134        smc.setDescendingInSubPages(false);
1135
1136        // now let's change the staging status of the
1137
// content that was not activated back to the
1138
// basic staging status.
1139
contentPage.
1140            changeStagingStatus(languageCodes,
1141                                EntryLoadRequest.
1142                                STAGING_WORKFLOW_STATE,
1143                                jParams, smc);
1144
1145        return contentPage.activeStagingEntries(languageCodes,
1146                                                jParams.getSite().
1147                                                isVersioningEnabled(),
1148                                                saveVersion,
1149                                                jParams.getUser(), jParams,
1150                                                smc);
1151    }
1152    
1153    private void commitAndFlushCaches(ContentPage contentPage) throws JahiaException {
1154        ConnectionDispenser.terminateConnection();
1155        contentPage.invalidateHtmlCache();
1156        ServicesRegistry.getInstance().getJahiaPageService().invalidatePageCache(contentPage.getID());
1157        // begin new transaction
1158
ConnectionDispenser.getTxConnection();
1159    }
1160}
1161
Popular Tags