KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > engines > addcontainer > AddContainer_Engine


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
// EV 10.01.2001
15
// NK 05.02.2002 Added Multiple fields (JahiaSimpleField) edit at once support
16
// NK 05.02.2002 Version 2.0 Multiple field edit + customisable field ( read/write permission check )
17
//
18

19 package org.jahia.engines.addcontainer;
20
21 import java.lang.reflect.Proxy JavaDoc;
22 import java.util.ArrayList JavaDoc;
23 import java.util.Collections JavaDoc;
24 import java.util.Enumeration JavaDoc;
25 import java.util.HashMap JavaDoc;
26 import java.util.HashSet JavaDoc;
27 import java.util.Hashtable JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.Locale JavaDoc;
30 import java.util.Map JavaDoc;
31 import java.util.Set JavaDoc;
32 import java.util.Vector JavaDoc;
33 import javax.servlet.http.HttpSession JavaDoc;
34
35 import org.apache.commons.validator.*;
36 import org.apache.struts.action.ActionMessages;
37 import org.apache.struts.validator.Resources;
38 import org.jahia.bin.Jahia;
39 import org.jahia.content.ContentContainerListsXRefManager;
40 import org.jahia.data.JahiaData;
41 import org.jahia.data.containers.ContainerEditView;
42 import org.jahia.data.containers.ContainerEditViewFieldGroup;
43 import org.jahia.data.containers.ContainerFacadeInterface;
44 import org.jahia.data.containers.ContainerValidatorBase;
45 import org.jahia.data.containers.JahiaContainer;
46 import org.jahia.data.containers.JahiaContainerDefinition;
47 import org.jahia.data.containers.JahiaContainerList;
48 import org.jahia.data.containers.JahiaContentContainerFacade;
49 import org.jahia.data.events.JahiaEvent;
50 import org.jahia.data.fields.JahiaContentFieldFacade;
51 import org.jahia.data.fields.JahiaField;
52 import org.jahia.data.fields.JahiaFieldDefinition;
53 import org.jahia.data.fields.JahiaSimpleField;
54 import org.jahia.data.fields.LoadFlags;
55 import org.jahia.engines.EngineToolBox;
56 import org.jahia.engines.JahiaEngine;
57 import org.jahia.engines.JahiaEngineTools;
58 import org.jahia.engines.validation.EngineValidationHelper;
59 import org.jahia.engines.validation.ValidationError;
60 import org.jahia.engines.validation.ValidationErrorSorter;
61 import org.jahia.engines.lock.LockEngine;
62 import org.jahia.engines.rights.ManageRights;
63 import org.jahia.exceptions.JahiaException;
64 import org.jahia.exceptions.JahiaForbiddenAccessException;
65 import org.jahia.exceptions.JahiaSessionExpirationException;
66 import org.jahia.params.ParamBean;
67 import org.jahia.registries.ServicesRegistry;
68 import org.jahia.services.acl.JahiaBaseACL;
69 import org.jahia.services.events.JahiaEventGeneratorService;
70 import org.jahia.services.fields.ContentField;
71 import org.jahia.services.lock.LockKey;
72 import org.jahia.services.lock.LockService;
73 import org.jahia.services.pages.JahiaPage;
74 import org.jahia.services.usermanager.JahiaUser;
75 import org.jahia.services.version.EntryLoadRequest;
76 import org.jahia.services.cache.HtmlCache;
77 import org.jahia.services.cache.CacheFactory;
78 import org.jahia.utils.LanguageCodeConverters;
79 import org.jahia.content.ContentContainerKey;
80 import org.jahia.engines.categories.ManageCategories;
81 /**
82  * Display the popup that let the user add a new container.
83  *
84  * @author EV
85  * @author NK
86  * @version 2.0
87  */

88 public class AddContainer_Engine implements JahiaEngine {
89
90     /** The engine name */
91     public static final String JavaDoc ENGINE_NAME = "addcontainer";
92
93     private static final String JavaDoc TEMPLATE_JSP = "add_container";
94
95     /** Unique class instance */
96     private static AddContainer_Engine instance;
97
98     private EngineToolBox toolBox;
99
100     /** logging */
101     private static final org.apache.log4j.Logger logger =
102             org.apache.log4j.Logger.getLogger (AddContainer_Engine.class);
103
104     /**
105      * Default constructor, creates a new <code>AddContainer_Engine</code> instance.
106      */

107     private AddContainer_Engine () {
108         logger.debug (
109                 "***** Starting " + AddContainer_Engine.class.getName () + " engine *****");
110         toolBox = EngineToolBox.getInstance ();
111     }
112
113     /**
114      * Returns the unique instance of this class
115      *
116      * @return the unique instance of this class
117      */

118     public static synchronized AddContainer_Engine getInstance () {
119
120         if (instance == null) {
121             instance = new AddContainer_Engine ();
122         }
123         return instance;
124     }
125
126     /**
127      * authoriseRender
128      */

129     public boolean authoriseRender (ParamBean jParams) {
130         return toolBox.authoriseRender (jParams);
131     }
132
133     /**
134      * @param jParams
135      * @param theObj
136      *
137      * @return
138      *
139      * @throws JahiaException
140      * @todo add some javadoc description here
141      */

142     public String JavaDoc renderLink (ParamBean jParams, Object JavaDoc theObj)
143             throws JahiaException {
144         JahiaContainerList jahiaContainerList = (JahiaContainerList) theObj;
145         StringBuffer JavaDoc params = new StringBuffer JavaDoc ("?mode=display&clistid=");
146         params.append (jahiaContainerList.getID ());
147         params.append ("&cdefid=");
148         params.append (jahiaContainerList.getctndefid ());
149         params.append ("&cpid=");
150         params.append (jahiaContainerList.getPageID ());
151         params.append ("&cparentid=");
152         params.append (jahiaContainerList.getParentEntryID ());
153
154         String JavaDoc opEditMode = jParams.getOperationMode();
155         jParams.setOperationMode(ParamBean.EDIT);
156         String JavaDoc result = jParams.composeEngineUrl (ENGINE_NAME, params.toString ());
157         jParams.setOperationMode(opEditMode);
158         return result;
159     }
160
161     public boolean needsJahiaData (ParamBean jParams) {
162         return true;
163     } // end needsJahiaData
164

165     protected boolean hasWriteAccess(JahiaContainer theContainer,
166             JahiaUser theUser, Map JavaDoc engineMap, ParamBean jParams)
167             throws JahiaException {
168         boolean hasAdmin = false, hasWrite = false;
169         if (theContainer.getListID() != 0) {
170             JahiaContainerList theContainerList = ServicesRegistry.getInstance().getJahiaContainersService()
171                     .loadContainerListInfo(theContainer.getListID());
172             hasAdmin = theContainerList.checkAdminAccess(theUser);
173             hasWrite = hasAdmin || theContainerList.checkWriteAccess(theUser);
174         } else {
175             JahiaPage thePage = jParams.getPage();
176             hasAdmin = thePage.checkAdminAccess(theUser);
177             hasWrite = hasAdmin || thePage.checkWriteAccess(theUser);
178         }
179         if (hasAdmin)
180             engineMap.put("adminAccess", Boolean.TRUE);
181         if (hasWrite)
182             engineMap.put("writeAccess", Boolean.TRUE);
183         return hasWrite;
184     }
185     
186     /**
187      * handles the engine actions
188      *
189      * @param jParams
190      * a ParamBean object
191      * @param jData
192      * a JahiaData object (not mandatory)
193      */

194     public void handleActions (ParamBean jParams, JahiaData jData)
195             throws JahiaException,
196             JahiaSessionExpirationException,
197             JahiaForbiddenAccessException {
198         logger.debug ("Processing engine action...");
199
200         // initalizes the hashmap
201
HashMap JavaDoc engineMap = initEngineMap (jParams);
202
203         // init the flag
204
engineMap.put("org.jahia.engines.fieldEdit.flagStayOnSameField",Boolean.FALSE);
205
206         // checks if the user has the right to display the engine
207
JahiaUser theUser = jParams.getUser ();
208         JahiaContainer theContainer = (JahiaContainer) engineMap.get (
209                 "theContainer");
210         if (hasWriteAccess(theContainer, theUser, engineMap, jParams)) {
211
212             boolean allowedToProcess = true;
213             
214             String JavaDoc ignore_waiting_for_approval = (String JavaDoc) engineMap.get("ignore_waiting_for_approval");
215             
216             // #ifdef LOCK
217
LockService lockRegistry = ServicesRegistry.getInstance ().getLockService ();
218             if (Jahia.getSettings ().areLocksActivated ()) {
219                 LockKey lockKey = LockKey.composeLockKey (LockKey.
220                         ADD_CONTAINER_TYPE,
221                         theContainer.getListID (), theContainer.getPageID ());
222                 if (!lockRegistry.acquire (lockKey, jParams.getUser (),
223                         jParams.getSessionID (),
224                         jParams.getSession ().
225                         getMaxInactiveInterval ()) && (ignore_waiting_for_approval==null)) {
226                     // Prerequisites are NOT completed ! Damned ! Redirect the JSP
227
// output to lock informations.
228
if (ignore_waiting_for_approval==null)
229                     {
230                       LockEngine.getInstance ().redirect (jParams, engineMap,lockKey);
231                       allowedToProcess = false;
232                     } else flushPageCacheThatDisplayContainer (jParams, theContainer);
233                 } else {
234                     flushPageCacheThatDisplayContainer (jParams, theContainer);
235                 }
236             }
237             // #endif
238
if (allowedToProcess) {
239                 // fire event
240
JahiaEvent theEvent = new JahiaEvent (this, jParams,
241                         theContainer);
242                 ServicesRegistry.getInstance ().getJahiaEventService ()
243                         .fireAddContainerEngineAfterInit (theEvent);
244
245                 processLastScreen (jParams, engineMap);
246
247                 processCurrentScreen(jParams, engineMap);
248
249             }
250
251         } else {
252             throw new JahiaForbiddenAccessException ();
253         }
254
255         // do not forward to engine.jsp - only the data should be saved (for e.g. partnerregistration)
256
if (jParams.getRequest().getParameter("noEngineForward")==null)
257           // displays the screen
258
toolBox.displayScreen (jParams, engineMap);
259
260     } // end handleActions
261

262
263     /**
264      * Retrieve the engine name.
265      *
266      * @return the engine name.
267      */

268     public final String JavaDoc getName () {
269         return ENGINE_NAME;
270     }
271
272
273     /**
274      * processes the last screen sent by the user
275      *
276      * @param jParams a ParamBean object
277      */

278     public void processLastScreen (ParamBean jParams, HashMap JavaDoc engineMap)
279             throws JahiaException,
280             JahiaForbiddenAccessException {
281         logger.debug ("Processing last screen...");
282
283         // gets the last screen
284
// lastscreen = edit, rights, logs
285
String JavaDoc lastScreen = jParams.getRequest ().getParameter ("lastscreen");
286         if (lastScreen == null) {
287             lastScreen = "edit";
288             // reset session var
289
jParams.getSession ().removeAttribute ("UpdateContainer");
290         }
291
292         // indicates to sub engines that we are processing last screen
293
int mode = JahiaEngine.UPDATE_MODE;
294
295         String JavaDoc lastFieldIDStr = jParams.getRequest ().getParameter ("lastfid");
296
297         if (lastScreen.equals ("edit")) {
298             int lastFieldID = -1;
299             try {
300                 lastFieldID = Integer.parseInt (lastFieldIDStr);
301             } catch (NumberFormatException JavaDoc nfe) {
302                 String JavaDoc reload = jParams.getRequest ().getParameter ("reload");
303                 if ((reload != null) && reload.equals ("true")) {
304
305                     JahiaField lastField = (JahiaField) jParams.getRequest ().
306                             getAttribute ("lastField");
307                     if (lastField != null) {
308                         lastFieldID = lastField.getID ();
309                     }
310                 } else {
311                     return;
312                 }
313             }
314
315             Boolean JavaDoc flagStayOnSameField = (Boolean JavaDoc)
316                 engineMap.get("org.jahia.engines.fieldEdit.flagStayOnSameField");
317
318             processLastFields (lastFieldID, jParams, engineMap, mode, lastScreen,
319                     this.toolBox, (flagStayOnSameField != null && flagStayOnSameField.booleanValue()) );
320
321
322         } else if (lastScreen.equals ("rightsMgmt")) {
323             /** When adding a container, the acl doesn't exist yet
324              if (engineMap.get("adminAccess") != null) {
325              ManageRights.getInstance().handleActions( jParams, mode,engineMap, jahiaContentContainerFacade.getAclID() );
326              } else {
327              throw new JahiaForbiddenAccessException ();
328              }*/

329         } else if (lastScreen.equals ("categories")) {
330             JahiaContainer theContainer = (JahiaContainer) engineMap.get (
331                     "theContainer");
332             ManageCategories.getInstance ().handleActions (jParams, mode,
333                     engineMap, new ContentContainerKey (0),
334                     theContainer.getDefinition (), true);
335         }
336
337     } // end processLastScreen
338

339     /**
340      * prepares the screen requested by the user
341      *
342      * @param jParams a ParamBean object
343      */

344     public EngineValidationHelper processCurrentScreen (ParamBean jParams, HashMap JavaDoc engineMap)
345             throws JahiaException,
346             JahiaForbiddenAccessException {
347
348         logger.debug ("Processing current screen...");
349
350         JahiaContentContainerFacade jahiaContentContainerFacade
351                 = (JahiaContentContainerFacade) engineMap.get (
352                         "UpdateContainer_Engine.JahiaContentContainerFacade");
353
354         EntryLoadRequest entryLoadRequest
355                 = (EntryLoadRequest) engineMap.get ("entryLoadRequest");
356
357         HashSet JavaDoc updatedLanguageEntries = (HashSet JavaDoc) engineMap.get (
358                 "updatedLanguageEntries");
359         HashSet JavaDoc updatedFields = (HashSet JavaDoc) engineMap.get ("updated.fields");
360
361         JahiaContainer theContainer = jahiaContentContainerFacade.getContainer (
362                 entryLoadRequest, true);
363
364         engineMap.put ("theContainer", theContainer);
365
366         // gets the current screen
367
// screen = edit, rights, logs
368
String JavaDoc theScreen = (String JavaDoc) engineMap.get ("screen");
369
370         // indicates to sub engines that we are processing last screen
371
int mode = JahiaEngine.LOAD_MODE;
372
373         String JavaDoc fieldIDStr;
374
375         Boolean JavaDoc flagStayOnSameField = (Boolean JavaDoc)
376             engineMap.get("org.jahia.engines.fieldEdit.flagStayOnSameField");
377
378         if (flagStayOnSameField != null && flagStayOnSameField.booleanValue()) {
379             fieldIDStr = jParams.getRequest ().getParameter ("lastfid");
380         } else {
381             fieldIDStr = jParams.getRequest ().getParameter ("fid");
382         }
383
384         int fieldID = -1;
385
386         try {
387             fieldID = Integer.parseInt (fieldIDStr);
388         } catch (NumberFormatException JavaDoc nfe) {
389             try {
390                 fieldID = (((Integer JavaDoc) engineMap.get ("field_id"))).intValue ();
391             } catch (Exception JavaDoc e) {
392                 fieldID = -1;
393             }
394         }
395         // #ifdef LOCK
396
LockKey lockKey = LockKey.composeLockKey (LockKey.ADD_CONTAINER_TYPE,
397                 theContainer.getListID (),
398                 theContainer.getPageID ());
399         LockService lockRegistry = ServicesRegistry.getInstance ().
400                 getLockService ();
401         // #endif
402
if (theScreen.equals ("edit")) {
403             processCurrentFields (fieldID, jParams, engineMap, mode, theScreen,
404                     this.toolBox);
405             // This test should replace the above
406
} else if (theScreen.equals ("rightsMgmt")) {
407             /** When adding a container, the acl doesn't exist yet
408              if (engineMap.get("adminAccess") != null) {
409              ManageRights.getInstance().handleActions( jParams, mode, engineMap, jahiaContentContainerFacade.getAclID() );
410              } else {
411              throw new JahiaForbiddenAccessException();
412              }*/

413
414         } else if (theScreen.equals ("categories")) {
415             ManageCategories.getInstance ().handleActions (jParams, mode,
416                     engineMap,
417                     new ContentContainerKey (jahiaContentContainerFacade.getContainerID ()),
418                     theContainer.getDefinition (), true);
419         } else if (theScreen.equals ("save")) { //|| theScreen.equals("apply")) {
420

421             logger.debug(
422                 "processCurrentScreen > we are in validate Mode");
423             // before saving container, call validation on subengines.
424
// switch to validate mode
425
mode = JahiaEngine.VALIDATE_MODE;
426
427             final EngineValidationHelper evh =
428               validate(
429                 AddContainer_Engine.ENGINE_NAME,
430                 jahiaContentContainerFacade,
431                 jParams,
432                 engineMap);
433             
434             engineMap.put(JahiaEngine.ENGINE_VALIDATION_HELPER, evh);
435             final JahiaEvent validationEvent = new JahiaEvent (this, jParams, theContainer);
436             ServicesRegistry.getInstance ().getJahiaEventService ()
437                     .fireContainerValidation(validationEvent);
438
439             if (evh != null && evh.hasErrors()) {
440            
441                 final ContainerEditViewFieldGroup currentFieldGroup =
442                   getFieldGroup(
443                     fieldID,
444                     theContainer,
445                     (ContainerEditView)engineMap.get("ctnEditView"));
446
447                 Collections.sort(
448                     evh.getErrors(),
449                     new ValidationErrorSorter(currentFieldGroup));
450
451                 final ValidationError ve =
452                     (ValidationError)evh.getErrors().get(0);
453                 final JahiaField field = (JahiaField)ve.getSource();
454  
455                 processCurrentFields(
456                     field.getID(),
457                     jParams,
458                     engineMap,
459                     JahiaEngine.LOAD_MODE,
460                     "edit",
461                     this.toolBox);
462           
463                 // prepare view
464
engineMap.put(JahiaEngine.ENGINE_VALIDATION_HELPER, evh);
465                 engineMap.put("screen", "edit");
466                 engineMap.put("jspSource", TEMPLATE_JSP);
467                 return evh;
468             }
469
470             engineMap.remove(JahiaEngine.ENGINE_VALIDATION_HELPER);
471             logger.debug ("processCurrentScreen > we are in save Mode");
472
473             mode = JahiaEngine.SAVE_MODE;
474
475             // #ifdef LOCK
476
// Did somebody steal the lock ? Panpan cucul !
477
if (jParams.settings ().areLocksActivated () &&
478                     lockRegistry.isStealedInContext (lockKey, jParams.getUser (),
479                             jParams.getSessionID ())) {
480                 engineMap.put ("screen",
481                         jParams.getRequest ().getParameter ("lastscreen"));
482                 engineMap.put ("jspSource", "apply");
483                 return null;
484             }
485             // #endif
486

487             // fire event
488
JahiaEvent theEvent = new JahiaEvent (this, jParams, theContainer);
489             JahiaEventGeneratorService eventService = ServicesRegistry.getInstance ().getJahiaEventService ();
490             eventService.fireAddContainerEngineBeforeSave (theEvent);
491
492             // save the container info
493
int containerParentID = ((Integer JavaDoc) engineMap.get (
494                     "containerParentID")).intValue ();
495             int parentAclID = 0;
496             if (containerParentID != 0) {
497                 parentAclID = ServicesRegistry.getInstance ().
498                         getJahiaContainersService ().
499                         loadContainerInfo (containerParentID,
500                                 jParams.getEntryLoadRequest ()).
501                         getAclID ();
502             } else {
503                 parentAclID = jParams.getPage ().getAclID ();
504             }
505             ServicesRegistry.getInstance ().getJahiaContainersService ().
506                     saveContainerInfo(theContainer, containerParentID, parentAclID,
507                             jParams);
508
509             theEvent = new JahiaEvent (this, jParams, theContainer);
510             eventService.fireAddContainerEngineAfterSave(theEvent);
511                             
512             Enumeration JavaDoc enumeration = jahiaContentContainerFacade.getFields ();
513             while (enumeration.hasMoreElements ()) {
514                 JahiaContentFieldFacade contentFieldFacade = (
515                         JahiaContentFieldFacade) enumeration.nextElement ();
516                 Enumeration JavaDoc fields = contentFieldFacade.getFields ();
517                 EntryLoadRequest processingEntryLoadRequest = null;
518                 int newFieldID = 0;
519                 int newAclID = 0;
520                 while (fields.hasMoreElements ()) {
521                     JahiaField field = (JahiaField) fields.nextElement ();
522                     if (field.getLanguageCode ().equals (ContentField.
523                             SHARED_LANGUAGE)
524                             ||
525                             updatedLanguageEntries.contains (field.getLanguageCode ())
526                             || updatedFields.contains (new Integer JavaDoc (field.getID ()))) {
527                         field.setID (newFieldID);
528                         if (newAclID != 0) {
529                             field.setAclID (newAclID);
530                         }
531                         field.setctnid (theContainer.getID ());
532
533                         // save the active entry only if the staging doesn't exists.
534
processingEntryLoadRequest =
535                                 new EntryLoadRequest (field.getWorkflowState (),
536                                         field.getVersionID (),
537                                         new ArrayList JavaDoc ());
538                         processingEntryLoadRequest.getLocales ()
539                                 .add (LanguageCodeConverters.languageCodeToLocale (
540                                         field.getLanguageCode ()));
541
542                         jParams.setSubstituteEntryLoadRequest (
543                                 processingEntryLoadRequest);
544                         if (field.getID () == 0) {
545                             // create the field only once
546
ServicesRegistry.getInstance ().getJahiaFieldService ().
547                                     saveField (field, theContainer.getAclID (),
548                                             jParams);
549                         }
550                         engineMap.put ("theField", field);
551                         toolBox.processFieldTypes (jParams, mode, engineMap);
552                         jParams.resetSubstituteEntryLoadRequest ();
553                         if (newFieldID == 0) {
554                             newFieldID = field.getID ();
555                         }
556                         if (newAclID == 0) {
557                             newAclID = field.getAclID ();
558                         }
559                     }
560                 }
561             }
562
563             // save rights
564
if (engineMap.get ("adminAccess") != null) {
565                 ManageRights.getInstance ().handleActions (jParams, mode,
566                         engineMap, theContainer.getAclID ());
567             }
568
569             // save categories
570
ManageCategories.getInstance ().handleActions (jParams, mode,
571                     engineMap,
572                     new ContentContainerKey (theContainer.getID ()),
573                     theContainer.getDefinition (), true);
574
575             flushPageCacheThatDisplayContainer (jParams, theContainer);
576
577             // fire event
578
theEvent = new JahiaEvent (this, jParams, theContainer);
579             ServicesRegistry.getInstance ().getJahiaEventService ().
580                     fireAddContainer (theEvent);
581             // flag for subEngine: means that is a call from AddContainer, reset the flag
582
jParams.getSession ().setAttribute ("AddContainer", "false");
583             // #ifdef LOCK
584
if (jParams.settings ().areLocksActivated ()) {
585                 lockRegistry.release (lockKey, jParams.getUser (),
586                         jParams.getSessionID ());
587             }
588             // #endif
589
logger.debug ("Saving container !!");
590         } else if (theScreen.equals ("cancel")) {
591             // #ifdef LOCK
592
if (jParams.settings ().areLocksActivated ()) {
593                 lockRegistry.release (lockKey, jParams.getUser (),
594                         jParams.getSessionID ());
595                 flushPageCacheThatDisplayContainer (jParams, theContainer);
596             }
597             // #endif
598
// flag for subEngine: means that is a call from AddContainer, reset the flag
599
jParams.getSession ().setAttribute ("AddContainer", "false");
600         }
601         return null;
602     } // end processCurrentScreen
603

604     private void flushPageCacheThatDisplayContainer (ParamBean jParams,
605                                                      JahiaContainer theContainer)
606             throws JahiaException {
607         JahiaContainerList theList = ServicesRegistry.getInstance ().
608                 getJahiaContainersService ().
609                 loadContainerListInfo (theContainer.
610                 getListID ());
611
612         // Get the cache instance and invalidate the related page entries
613
HtmlCache htmlCache = CacheFactory.getHtmlCache ();
614         if (htmlCache == null) {
615             logger.warn ("Could not get the HTML cache instance!!");
616         }
617
618         // since we have made modifications concerning this page, let's flush
619
// the content cache for all the users and browsers as well as all
620
// pages that display this containerList...
621
if (theList != null) {
622             Set JavaDoc containerPageRefs = ContentContainerListsXRefManager.
623                     getInstance ().
624                     getAbsoluteContainerListPageIDs (theList.
625                     getID ());
626             if (containerPageRefs != null) {
627                 Iterator JavaDoc pageRefIDs = containerPageRefs.iterator ();
628                 while (pageRefIDs.hasNext ()) {
629                     Integer JavaDoc curPageID = (Integer JavaDoc) pageRefIDs.next ();
630                     if (htmlCache != null) {
631                         htmlCache.invalidatePageEntries (curPageID.toString (),jParams.getEntryLoadRequest().getWorkflowState());
632                     }
633                 }
634             } else {
635                 logger.debug ("Why is cross ref list empty ?");
636             }
637         } else {
638             logger.debug (
639                     "Couldn't retrieve parent containerList, why is that ?");
640         }
641         // this is still necessary in the case we are on the page itself
642
// and the containerList is not referenced in an absolute way.
643
if (htmlCache != null) {
644             htmlCache.invalidatePageEntries (
645                     Integer.toString (jParams.getPageID ()).toString (),jParams.getEntryLoadRequest().getWorkflowState());
646         }
647     }
648
649     /**
650      * inits the engine map
651      *
652      * @param jParams a ParamBean object (with request and response)
653      *
654      * @return a HashMap object containing all the basic values needed by an engine
655      */

656     private HashMap JavaDoc initEngineMap (ParamBean jParams)
657             throws JahiaException,
658             JahiaSessionExpirationException {
659
660         HashMap JavaDoc engineMap = new HashMap JavaDoc ();
661         JahiaContainer theContainer = null;
662         String JavaDoc theScreen = jParams.getRequest ().getParameter ("screen");
663         logger.debug ("Initializing engine map for screen [" + theScreen + "]");
664
665         // gets session values
666
//HttpSession theSession = jParams.getRequest().getSession( true );
667
HttpSession JavaDoc theSession = jParams.getSession ();
668
669         // flag for subEngine: means that is a call from AddContainer
670
theSession.setAttribute ("AddContainer", "true");
671
672         // gets parent container id
673
String JavaDoc parentIDStr = jParams.getRequest ().getParameter ("cparentid");
674         int parentID = 0;
675         try {
676             parentID = Integer.parseInt (parentIDStr);
677         } catch (NumberFormatException JavaDoc nfe) {
678             String JavaDoc errorMsg = "Error in parameters : parentid (" + parentIDStr +
679                     ") cannot be converted in int";
680             throw new JahiaException ("Error in parameters", errorMsg,
681                     JahiaException.DATA_ERROR,
682                     JahiaException.CRITICAL_SEVERITY);
683         }
684
685         // Resolve language code
686
String JavaDoc languageCode = jParams.getRequest ().getParameter ("engine_lang");
687         if (languageCode == null) {
688             Locale JavaDoc navLocale = (Locale JavaDoc) theSession.getAttribute (ParamBean.
689                     SESSION_LOCALE);
690             languageCode = navLocale.toString ();
691         }
692         if (languageCode == null) {
693             languageCode = jParams.settings ().getDefaultLanguageCode ();
694         }
695         String JavaDoc prevLanguageCode = jParams.getRequest ().getParameter (
696                 "prev_engine_lang");
697         if (prevLanguageCode == null) {
698             prevLanguageCode = languageCode;
699         }
700
701         ArrayList JavaDoc locales = new ArrayList JavaDoc ();
702         locales.add (LanguageCodeConverters.languageCodeToLocale (languageCode));
703         EntryLoadRequest entryLoadRequest =
704                 new EntryLoadRequest (EntryLoadRequest.STAGING_WORKFLOW_STATE,
705                         0,
706                         locales);
707
708         ArrayList JavaDoc prevLocales = new ArrayList JavaDoc ();
709         prevLocales.add (LanguageCodeConverters.languageCodeToLocale (
710                 prevLanguageCode));
711         EntryLoadRequest prevEntryLoadRequest =
712                 new EntryLoadRequest (EntryLoadRequest.STAGING_WORKFLOW_STATE,
713                         0,
714                         prevLocales);
715
716         JahiaContentContainerFacade jahiaContentContainerFacade = null;
717
718         if (theScreen != null) {
719             // if no, load the container value from the session
720
engineMap = (HashMap JavaDoc) theSession.getAttribute (
721                     "jahia_session_engineMap");
722
723             ///////////////////////////////////////////////////////////////////////////////////////
724
// FIXME -Fulco-
725
//
726
// This is a quick hack, engineMap should not be null if the session didn't
727
// expired. Maybe there are other cases where the engineMap can be null, I didn't
728
// checked them at all.
729
///////////////////////////////////////////////////////////////////////////////////////
730
if (engineMap == null) {
731                 throw new JahiaSessionExpirationException ();
732             }
733             jahiaContentContainerFacade = (JahiaContentContainerFacade)
734                     engineMap.get (
735                             "UpdateContainer_Engine.JahiaContentContainerFacade");
736         } else {
737             // init engine map
738
engineMap = new HashMap JavaDoc ();
739             org.jahia.engines.shared.Page_Field.resetPageBeanSession (jParams);
740             // retrieve the choice ID if the screen is reloaded. Otherwise it should be set
741
// to a default value, to avoid having it set to 3 (tree operation) if no source
742
// page has been selected
743
String JavaDoc reload = jParams.getRequest ().getParameter ("reload");
744             logger.debug (" reload = " + reload);
745             if (reload != null) {
746                 if (reload.equals ("true")) {
747                     HashMap JavaDoc previousEngineMap = (HashMap JavaDoc) theSession.
748                             getAttribute (
749                                     "jahia_session_engineMap");
750                     if (previousEngineMap != null) {
751                         logger.debug (" previous session is not null");
752                         JahiaField lastField = (JahiaField) previousEngineMap.
753                                 get ("theField");
754                         if (lastField != null) {
755                             jParams.getRequest ().setAttribute ("lastField",
756                                     lastField);
757                             logger.debug ("LastField is " + lastField.getID ());
758                         }
759                         theSession.removeAttribute ("jahia_session_engineMap");
760                     }
761                 }
762             }
763
764             jahiaContentContainerFacade = createJahiaContentContainerFacade (
765                     jParams, engineMap);
766
767             engineMap.put ("UpdateContainer_Engine.JahiaContentContainerFacade",
768                     jahiaContentContainerFacade);
769
770             theScreen = "edit";
771             engineMap.put ("containerParentID", new Integer JavaDoc (parentID));
772
773             // init container list field acls
774
// we get a staging version of a container to ensure it contains all fields.
775
Enumeration JavaDoc enumeration = jahiaContentContainerFacade.getContainers ();
776             while (enumeration.hasMoreElements ()) {
777                 theContainer = (JahiaContainer) enumeration.nextElement ();
778                 if (theContainer.getWorkflowState () >
779                         EntryLoadRequest.ACTIVE_WORKFLOW_STATE) {
780                     break;
781                 }
782             }
783             HashMap JavaDoc ctnListFieldAcls = AddContainer_Engine.
784                     getCtnListFieldAclMap (theContainer,
785                             jParams);
786             engineMap.put ("ctnListFieldAcls", ctnListFieldAcls);
787             Set JavaDoc visibleFields = AddContainer_Engine.getCtnListVisibleFields (
788                     theContainer, jParams.getUser (), ctnListFieldAcls);
789
790             // create the edit view
791
ContainerEditView editView = AddContainer_Engine.
792                     customizeContainerEditView (
793                             theContainer, jParams, visibleFields);
794             if (editView == null) {
795                 // create a default one
796
editView = AddContainer_Engine.buildContainerEditView (
797                         theContainer, jParams, visibleFields);
798             }
799             engineMap.put ("ctnEditView", editView);
800         }
801
802         engineMap.put ("entryLoadRequest", entryLoadRequest);
803         engineMap.put ("prevEntryLoadRequest", prevEntryLoadRequest);
804         engineMap.put ("prevLanguageCode", prevLanguageCode);
805         engineMap.put ("languageCode", languageCode);
806
807         // remember the requested language codes :
808
HashSet JavaDoc updatedLanguageEntries = (HashSet JavaDoc) engineMap.get (
809                 "updatedLanguageEntries");
810         if (updatedLanguageEntries == null) {
811             updatedLanguageEntries = new HashSet JavaDoc ();
812         }
813         if (!updatedLanguageEntries.contains (languageCode)) {
814             updatedLanguageEntries.add (languageCode);
815         }
816         engineMap.put ("updatedLanguageEntries", updatedLanguageEntries);
817
818         // remember the updated fields ( Apply Change to all lang options )
819
HashSet JavaDoc updatedFields = (HashSet JavaDoc) engineMap.get ("updated.fields");
820         if (updatedFields == null) {
821             updatedFields = new HashSet JavaDoc ();
822         }
823         engineMap.put ("updated.fields", updatedFields);
824
825         theContainer = jahiaContentContainerFacade.getContainer (
826                 entryLoadRequest, true);
827         engineMap.put ("theContainer", theContainer);
828
829         engineMap.put ("noApply", EMPTY_STRING);
830         engineMap.put (RENDER_TYPE_PARAM, new Integer JavaDoc (JahiaEngine.RENDERTYPE_FORWARD));
831         engineMap.put (ENGINE_NAME_PARAM, ENGINE_NAME);
832         engineMap.put (ENGINE_URL_PARAM, jParams.composeEngineUrl (ENGINE_NAME,
833                 "?clistid=" + theContainer.getListID () +
834                 "&cdefid=" + theContainer.getctndefid () +
835                 "&cpid=" + theContainer.getPageID () +
836                 "&cparentid=" + parentID));
837         theSession.setAttribute ("jahia_session_engineMap", engineMap);
838
839         // init map
840
engineMap.put ("screen", theScreen);
841         if (!theScreen.equals ("save") && !theScreen.equals ("cancel")) {
842             engineMap.put ("jspSource", TEMPLATE_JSP);
843
844             //} else if (theScreen.equals ("apply")) {
845
// engineMap.put( "jspSource", "apply" );
846

847         } else {
848             engineMap.put ("jspSource", "close");
849         }
850
851         engineMap.put ("enableCategories", new Boolean JavaDoc (true));
852
853         // sets engineMap for JSPs
854
engineMap.put ("fieldForms", new Hashtable JavaDoc ());
855         jParams.getRequest ().setAttribute ("engineTitle", "Add Container");
856         jParams.getRequest ().setAttribute ("org.jahia.engines.EngineHashMap",
857                 engineMap);
858
859         return engineMap;
860     } // end initEngineMap
861

862     private JahiaContentContainerFacade createJahiaContentContainerFacade
863             (ParamBean jParams, HashMap JavaDoc engineMap)
864             throws JahiaException {
865         JahiaContentContainerFacade contentContainerFacade = null;
866
867         String JavaDoc listIDStr = jParams.getRequest ().getParameter ("clistid");
868         int listID = 0;
869         String JavaDoc defIDStr = jParams.getRequest ().getParameter ("cdefid");
870         int defID = 0;
871         String JavaDoc pageIDStr = jParams.getRequest ().getParameter ("cpid");
872         int pageID = 0;
873
874         try {
875             listID = Integer.parseInt (listIDStr);
876             defID = Integer.parseInt (defIDStr);
877             pageID = Integer.parseInt (pageIDStr);
878         } catch (NumberFormatException JavaDoc nfe) {
879             String JavaDoc errorMsg = "Error in parameters : clistid (" + listIDStr
880                     + ") or cdefid (" + defIDStr +
881                     ") or cpid (" + pageIDStr + ") cannot be converted in int";
882             throw new JahiaException ("Error in parameters", errorMsg,
883                     JahiaException.DATA_ERROR,
884                     JahiaException.CRITICAL_SEVERITY);
885         }
886
887         // source page
888
JahiaPage sourcePage = ServicesRegistry.getInstance ()
889                 .getJahiaPageService ().lookupPage (pageID,
890                         jParams);
891         if (sourcePage == null) {
892             throw new JahiaException ("Page missing",
893                     "Trying to add a container on a non-existing page (" + pageID +
894                     ")",
895                     JahiaException.PAGE_ERROR, JahiaException.ERROR_SEVERITY);
896         }
897
898         contentContainerFacade =
899                 new JahiaContentContainerFacade (0,
900                         sourcePage.getJahiaID (),
901                         sourcePage.getID (),
902                         listID,
903                         defID,
904                         //sourcePage.getAclID(), why the page acl, it's the acl, not the parent acl
905
0,
906                         jParams,
907                         jParams.getSite ().
908                 getLanguageSettingsAsLocales (false));
909
910         return contentContainerFacade;
911     }
912
913     /**
914      * @param fieldID
915      * @param jParams
916      * @param engineMap
917      * @param mode
918      * @param screen
919      * @param toolBox
920      *
921      * @throws JahiaException
922      * @todo put in Tools class
923      */

924     static public void processCurrentFields (
925             int fieldID, ParamBean jParams, HashMap JavaDoc engineMap, int mode,
926             String JavaDoc screen, EngineToolBox toolBox)
927             throws JahiaException {
928
929         JahiaContentContainerFacade jahiaContentContainerFacade
930                 = (JahiaContentContainerFacade) engineMap.get (
931                         "UpdateContainer_Engine.JahiaContentContainerFacade");
932
933         EntryLoadRequest entryLoadRequest
934                 = (EntryLoadRequest) engineMap.get ("entryLoadRequest");
935
936         //HashSet updatedLanguageEntries = (HashSet)engineMap.get("updatedLanguageEntries");
937

938         JahiaContainer theContainer = jahiaContentContainerFacade.getContainer (
939                 entryLoadRequest, true);
940
941         engineMap.put ("theContainer", theContainer);
942
943         engineMap.put (JahiaEngine.PROCESSING_LANGUAGECODE,
944                 engineMap.get ("languageCode"));
945
946         ContainerEditView editView = (ContainerEditView) engineMap.get (
947                 "ctnEditView");
948         ContainerEditViewFieldGroup fieldGroup = null;
949
950         // get first visible field
951
JahiaField theField = theContainer.getField (fieldID);
952         if (theField != null) {
953             fieldGroup = editView.getFieldGroupByFieldName (theField.
954                     getDefinition ().getName ());
955         }
956         if (fieldGroup == null) {
957             Vector JavaDoc views = new Vector JavaDoc (editView.getViews ().values ());
958             if (views.size () > 0) {
959                 fieldGroup = (ContainerEditViewFieldGroup) views.get (0);
960                 theField = theContainer.getField ((String JavaDoc) fieldGroup.
961                         getFieldNames ().get (0));
962                 fieldID = theField.getID ();
963             } else {
964                 // no one field visible
965
theField = null;
966                 fieldID = 0;
967             }
968         }
969
970         JahiaField selectedField = theField;
971
972         engineMap.put ("field_id", new Integer JavaDoc (fieldID));
973
974         Vector JavaDoc fieldIDs = new Vector JavaDoc ();
975
976         if (theField != null) {
977             // at least one visible field
978

979             // get the lists of fields in the edit view
980
int size = fieldGroup.getFieldNames ().size ();
981             String JavaDoc fieldName = EMPTY_STRING;
982             EntryLoadRequest processingEntryLoadRequest = null;
983
984             for (int i = 0; i < size; i++) {
985                 fieldName = (String JavaDoc) fieldGroup.getFieldNames ().get (i);
986
987                 // dispatches to the appropriate sub engine
988
theField = theContainer.getField (fieldName);
989
990                 if (theField != null) {
991                     engineMap.put ("fieldForm", null); // reset field form
992
logger.debug ("The field value is now " + theField.getValue ());
993
994                     engineMap.put ("theField", theField);
995                     engineMap.put ("isSelectedField",
996                             new Boolean JavaDoc (theField.getID () == fieldID));
997                     engineMap.put ("fieldID", new Integer JavaDoc (theField.getID ()));
998
999                     processingEntryLoadRequest = new EntryLoadRequest (theField.
1000                            getWorkflowState (), theField.getVersionID (),
1001                            new ArrayList JavaDoc ());
1002                    processingEntryLoadRequest.getLocales ()
1003                            .add (LanguageCodeConverters
1004                            .languageCodeToLocale (theField.getLanguageCode ()));
1005                    jParams.setSubstituteEntryLoadRequest (
1006                            processingEntryLoadRequest);
1007                    if (toolBox.processFieldTypes (jParams, mode, engineMap)) {
1008
1009                        if (jParams.getRequest ().getParameter (
1010                                "apply_change_to_all_lang_" + theField.getID ()) != null) {
1011                            applyChangeToAllLang (theField,
1012                                    jahiaContentContainerFacade,
1013                                    engineMap, jParams);
1014                        }
1015                    }
1016                    jParams.resetSubstituteEntryLoadRequest ();
1017
1018                    if (engineMap.get ("fieldForm") != null) {
1019                        fieldIDs.add (new Integer JavaDoc (theField.getID ()));
1020                        Hashtable JavaDoc fieldForms = (Hashtable JavaDoc) engineMap.get (
1021                                "fieldForms");
1022                        fieldForms.put (new Integer JavaDoc (theField.getID ()),
1023                                engineMap.get ("fieldForm"));
1024                    }
1025                }
1026            }
1027        }
1028
1029        engineMap.put ("fieldID", new Integer JavaDoc (fieldID));
1030        engineMap.put ("theField", selectedField);
1031        engineMap.put ("fieldIDs", fieldIDs);
1032    }
1033
1034    /**
1035     * @param lastFieldID
1036     * @param jParams
1037     * @param engineMap
1038     * @param mode
1039     * @param lastScreen
1040     * @param toolBox
1041     * @param flagStayOnSameField
1042     *
1043     * @throws JahiaException
1044     * @todo put in Tools class
1045     */

1046    static public void processLastFields (int lastFieldID,
1047                                          ParamBean jParams,
1048                                          HashMap JavaDoc engineMap,
1049                                          int mode,
1050                                          String JavaDoc lastScreen,
1051                                          EngineToolBox toolBox,
1052                                          boolean flagStayOnSameField)
1053            throws JahiaException {
1054
1055        EntryLoadRequest prevEntryLoadRequest
1056                = (EntryLoadRequest) engineMap.get ("prevEntryLoadRequest");
1057
1058        JahiaContentContainerFacade jahiaContentContainerFacade
1059                = (JahiaContentContainerFacade) engineMap.get (
1060                        "UpdateContainer_Engine.JahiaContentContainerFacade");
1061
1062        engineMap.put (JahiaEngine.PROCESSING_LANGUAGECODE,
1063                engineMap.get ("prevLanguageCode"));
1064
1065        JahiaContainer theContainer = jahiaContentContainerFacade.getContainer (
1066                prevEntryLoadRequest, true);
1067        engineMap.put ("theContainer", theContainer);
1068
1069        JahiaField theField = theContainer.getField (lastFieldID);
1070
1071        ContainerEditView editView = (ContainerEditView) engineMap.get (
1072                "ctnEditView");
1073        if (theField == null)
1074            logger.error("theField is null! ID: " + lastFieldID);
1075        else if (theField.getDefinition() == null)
1076            logger.error("theField.getDefinition() is null! ID: " + theField.getFieldDefID() + " / " + lastFieldID);
1077        
1078        ContainerEditViewFieldGroup fieldGroup = editView.
1079                getFieldGroupByFieldName (
1080                        theField.getDefinition ().getName ());
1081
1082        // get the lists of fields in the edit view
1083
int size = fieldGroup.getFieldNames ().size ();
1084        String JavaDoc fieldName = EMPTY_STRING;
1085        for (int i = 0; i < size; i++) {
1086            fieldName = (String JavaDoc) fieldGroup.getFieldNames ().get (i);
1087
1088            // dispatches to the appropriate sub engine
1089
theField = theContainer.getField (fieldName);
1090            if (theField != null) {
1091
1092                int fieldType = theField.getType ();
1093
1094                logger.debug ("Update container field " +
1095                        theField.getDefinition ().getName () + "...");
1096                engineMap.put ("theField", theField);
1097                engineMap.put ("isSelectedField", new Boolean JavaDoc (false));
1098
1099                boolean doUpdate = false;
1100                if (theContainer.getListID () != 0) {
1101                    JahiaBaseACL acl = JahiaEngineTools.getCtnListFieldACL ((
1102                            HashMap JavaDoc) engineMap.get ("ctnListFieldAcls"),
1103                            theField.getID ());
1104                    if (acl != null) {
1105                        doUpdate = acl.getPermission (jParams.getUser (),
1106                                JahiaBaseACL.WRITE_RIGHTS, true);
1107                    }
1108                } else {
1109                    doUpdate = true;
1110                }
1111                jParams.setSubstituteEntryLoadRequest (prevEntryLoadRequest);
1112                if (doUpdate &&
1113                        !toolBox.processFieldTypes (jParams, mode, engineMap)) {
1114                    // if there was an error, come back to last screen
1115
engineMap.put ("screen", lastScreen);
1116                    engineMap.put ("jspSource", TEMPLATE_JSP);
1117                    // error on field, then stay on same field
1118
engineMap.put("org.jahia.engines.fieldEdit.flagStayOnSameField",Boolean.TRUE);
1119                    jParams.resetSubstituteEntryLoadRequest ();
1120                    break;
1121                } else {
1122
1123                    theField = (JahiaField) engineMap.get ("theField");
1124                    if (fieldType != theField.getType ()) {
1125                        // field type has changed
1126
jahiaContentContainerFacade.changeType (theField.getID (),
1127                                theField.getType (), jParams);
1128                        theField = jahiaContentContainerFacade.
1129                                getContentFieldFacade (theField.getID ()).
1130                                getField (prevEntryLoadRequest, true);
1131                        theContainer.setField (theField);
1132                        engineMap.put ("theField", theField);
1133                    }
1134
1135                    if (doUpdate &&
1136                            jParams.getRequest ().getParameter ("apply_change_to_all_lang_" +
1137                            theField.getID ()) != null) {
1138                        applyChangeToAllLang (theField,
1139                                jahiaContentContainerFacade,
1140                                engineMap, jParams);
1141                    }
1142                    engineMap.put("org.jahia.engines.fieldEdit.flagStayOnSameField",Boolean.FALSE);
1143                }
1144                jParams.resetSubstituteEntryLoadRequest ();
1145                logger.debug ("processLastScreen > the field value is now " +
1146                        theField.getValue ());
1147            }
1148        }
1149    }
1150
1151    /**
1152     * @param theField
1153     * @param jahiaContentContainerFacade
1154     *
1155     * @throws JahiaException
1156     * @todo : put in a Tool class
1157     */

1158    static public void applyChangeToAllLang (JahiaField theField,
1159                                             JahiaContentContainerFacade
1160            jahiaContentContainerFacade,
1161                                             HashMap JavaDoc engineMap,
1162                                             ParamBean jParams)
1163            throws JahiaException {
1164
1165        HashSet JavaDoc updatedFields = (HashSet JavaDoc) engineMap.get ("updated.fields");
1166
1167        JahiaContentFieldFacade contentFieldFacade =
1168                jahiaContentContainerFacade.getContentFieldFacade (theField.getID ());
1169        Enumeration JavaDoc enumeration = contentFieldFacade.getFields ();
1170        JahiaField field = null;
1171        while (enumeration.hasMoreElements ()) {
1172            field = (JahiaField) enumeration.nextElement ();
1173            theField.copyValueInAnotherLanguage (field, jParams);
1174
1175            // remember change
1176
if (!updatedFields.contains (new Integer JavaDoc (field.getID ()))) {
1177                updatedFields.add (new Integer JavaDoc (field.getID ()));
1178            }
1179        }
1180    }
1181
1182    // Khue Nguyen
1183
/**
1184     * Build a map that contains a pair of [fieldID (INTEGER),aclID (INTEGER)] for fields of a
1185     * given container list. The acl is the one set at container list level , not at field level
1186     * !!!
1187     *
1188     * @param theContainer the container instance
1189     * @param jParams the Jahia parameters
1190     *
1191     * @return HashMap the map containing the list of editable fields
1192     */

1193    static public HashMap JavaDoc getCtnListFieldAclMap (JahiaContainer theContainer,
1194                                                 ParamBean jParams) {
1195        logger.debug ("Started for container [" + theContainer.getID () + "]");
1196
1197        HashMap JavaDoc map = new HashMap JavaDoc ();
1198
1199        if (theContainer == null)
1200            return map;
1201
1202        if (theContainer.getListID () == 0) {
1203            return map;
1204        }
1205        JahiaContainerList cList = null;
1206        try {
1207            cList = ServicesRegistry.getInstance ().
1208                    getJahiaContainersService ().loadContainerListInfo (
1209                            theContainer.getListID ());
1210
1211            if (cList == null)
1212                return map;
1213
1214            String JavaDoc prop = null;
1215            JahiaField aField = null;
1216            JahiaFieldDefinition theDef = null;
1217
1218            Enumeration JavaDoc fList = theContainer.getFields ();
1219            while (fList.hasMoreElements ()) {
1220                aField = (JahiaField) fList.nextElement ();
1221                if (aField != null) {
1222                    logger.debug ("Field [" + aField.getID () + "]");
1223
1224                    /*
1225                         aField = ServicesRegistry.getInstance().
1226                         getJahiaFieldService().loadField( aField.getID(), LoadFlags.ALL, jParams );
1227                     */

1228                    logger.debug ("Field [" + aField.getID () + "]");
1229
1230                    theDef = aField.getDefinition ();
1231                    if (theDef != null) {
1232                        prop = cList.getProperty ("view_field_acl_" +
1233                                theDef.getName ());
1234                        if (prop != null) {
1235                            logger.debug ("ACL found = " + prop);
1236                            try {
1237                                int aclID = Integer.parseInt (prop);
1238                                map.put (new Integer JavaDoc (aField.getID ()),
1239                                        new Integer JavaDoc (aclID));
1240                                //logger.debug ("ACL added");
1241
} catch (Throwable JavaDoc t) {
1242                                logger.debug (" requested acl ( view_field_acl_" +
1243                                        theDef.getName () +
1244                                        "), exception :" + t.getMessage ());
1245                            }
1246                        } else {
1247                            // create the acl, because field declaration can change in template
1248
JahiaBaseACL newAcl = null;
1249                            newAcl = new JahiaBaseACL ();
1250                            newAcl.create (cList.getAclID ());
1251                            cList.setProperty ("view_field_acl_" +
1252                                    theDef.getName (),
1253                                    String.valueOf (newAcl.getID ()));
1254                            ServicesRegistry.getInstance ().
1255                                    getJahiaContainersService ().
1256                                    saveContainerListInfo (cList,
1257                                            jParams.getPage ().getAclID ());
1258
1259                            map.put (new Integer JavaDoc (aField.getID ()),
1260                                    new Integer JavaDoc (newAcl.getID ()));
1261                        }
1262                    }
1263                }
1264            }
1265        } catch (Throwable JavaDoc t) {
1266            t.printStackTrace ();
1267        }
1268
1269        return map;
1270    }
1271
1272    // @author Khue Nguyen
1273
/**
1274     * <p>Build a map which keys are field def ids of the container list fields, if they are
1275     * visible ( READ or WRITE or ADMIN RIGHT of the acl return true ).</p>
1276     * <p/>
1277     * <p>Note: <i>if the container's list id is 0 (that is, the list is not created yet, then
1278     * returned map contains all fields).</i></p>
1279     *
1280     * @param theContainer the container reference
1281     * @param user the user to check access
1282     * @param aclsMap the key is the fieldID and the value is the aclID.This map should be
1283     * the one returned by getCtnListFieldAclMap.
1284     *
1285     * @return Set the list of visible fields
1286     */

1287    static public Set JavaDoc getCtnListVisibleFields (JahiaContainer theContainer,
1288                                               JahiaUser user, HashMap JavaDoc aclsMap) {
1289        logger.debug ("Started for container [" + theContainer.getID () + "]");
1290
1291        Set JavaDoc visibleFields = new HashSet JavaDoc ();
1292
1293        if (theContainer == null)
1294            return visibleFields;
1295
1296        boolean cListExist = (theContainer.getListID () != 0);
1297
1298        Enumeration JavaDoc fields = theContainer.getFields ();
1299        JahiaBaseACL acl = null;
1300        JahiaField aField = null;
1301        while (fields.hasMoreElements ()) {
1302            aField = (JahiaField) fields.nextElement ();
1303            if (aField != null) {
1304                if (!cListExist) {
1305                    visibleFields.add (new Integer JavaDoc (aField.getID ()));
1306                } else {
1307                    acl = JahiaEngineTools.getCtnListFieldACL (aclsMap,
1308                            aField.getID ());
1309                    if (acl != null) {
1310                        try {
1311                            if (acl.getPermission (user,
1312                                    JahiaBaseACL.READ_RIGHTS)
1313                                    ||
1314                                    acl.getPermission (user, JahiaBaseACL.WRITE_RIGHTS)
1315                                    ||
1316                                    acl.getPermission (user, JahiaBaseACL.ADMIN_RIGHTS)) {
1317                                visibleFields.add (new Integer JavaDoc (aField.getID ()));
1318                            }
1319                        } catch (Throwable JavaDoc t) {
1320                            logger.error ("Exception : " + t.getMessage (), t);
1321                        }
1322                    }
1323                }
1324            }
1325        }
1326
1327        return visibleFields;
1328    }
1329
1330    /**
1331     * Build a Default Container Edit View for a given Container. It's based on how fields are
1332     * declared in the template.
1333     *
1334     * @param theContainer the container reference
1335     * @param jParams the param bean
1336     * @param visibleFields the list of visible fields
1337     */

1338    public static ContainerEditView buildContainerEditView (JahiaContainer
1339            theContainer,
1340                                                            ParamBean jParams,
1341                                                            Set JavaDoc visibleFields)
1342            throws JahiaException {
1343        logger.debug ("Started for container [" +
1344                theContainer.getDefinition ().getName () + "]");
1345
1346        ContainerEditView editView = new ContainerEditView ();
1347        ContainerEditViewFieldGroup fieldGroup = null;
1348
1349        Enumeration JavaDoc fieldsList = theContainer.getFields ();
1350        int pageDefID = jParams.getPage ().getPageTemplateID ();
1351        int nbFields = 0;
1352        String JavaDoc fieldTitle = EMPTY_STRING;
1353        while (fieldsList.hasMoreElements ()) {
1354            JahiaField theField = (JahiaField) fieldsList.nextElement ();
1355            if (visibleFields.contains (new Integer JavaDoc (theField.getID ()))) {
1356                if (theField instanceof JahiaSimpleField) {
1357                    if (nbFields == 0) {
1358                        // the first Field
1359
fieldTitle = theField.getDefinition ().getTitle (
1360                                pageDefID);
1361                        fieldGroup = new ContainerEditViewFieldGroup (theField.
1362                                getDefinition ().getName (), fieldTitle, EMPTY_STRING);
1363                    } else {
1364                        // a consecutive simple field
1365
fieldGroup.addField (theField.getDefinition ().getName (),
1366                                EMPTY_STRING);
1367                        if (!fieldGroup.getTitle ().endsWith (";...")) {
1368                            fieldGroup.setTitle (fieldGroup.getTitle () + ";...");
1369                        }
1370                    }
1371                    fieldGroup.addField (theField.getDefinition ().getName (), EMPTY_STRING);
1372                    nbFields += 1;
1373                } else {
1374                    if (nbFields > 0) {
1375                        // add the previous groups of simple fields in the edit view
1376
editView.addFieldGroup (fieldGroup);
1377                    }
1378                    // Create a new group with this single field
1379
fieldTitle = theField.getDefinition ().getTitle (pageDefID);
1380                    fieldGroup = new ContainerEditViewFieldGroup (theField.
1381                            getDefinition ().getName (), fieldTitle, EMPTY_STRING);
1382                    fieldGroup.addField (theField.getDefinition ().getName (), EMPTY_STRING);
1383                    editView.addFieldGroup (fieldGroup);
1384                    // reset nbFields
1385
nbFields = 0;
1386                }
1387            }
1388        }
1389        if (nbFields > 0) {
1390            editView.addFieldGroup (fieldGroup);
1391        }
1392        return editView;
1393    }
1394
1395    /**
1396     * Build a Customized Container Edit View for a given Container and a given User.
1397     *
1398     * @param theContainer the container on a
1399     * @param jParams the param bean
1400     * @param visibleFields the list of visible fields
1401     */

1402    public static ContainerEditView customizeContainerEditView (JahiaContainer
1403            theContainer,
1404                                                                ParamBean jParams,
1405                                                                Set JavaDoc visibleFields)
1406            throws JahiaException {
1407
1408        logger.debug ("Started for container [" +
1409                theContainer.getDefinition ().getName () + "]");
1410
1411        ContainerEditView editView = theContainer.getDefinition ().
1412                getContainerEditView ();
1413        if (editView == null) {
1414            return null;
1415        }
1416        ContainerEditView newEditView = new ContainerEditView ();
1417        ContainerEditViewFieldGroup fieldGroup = null;
1418
1419        Vector JavaDoc v = new Vector JavaDoc (editView.getViews ().values ());
1420        ContainerEditViewFieldGroup dummyFieldGroup = new
1421                ContainerEditViewFieldGroup (EMPTY_STRING, EMPTY_STRING, EMPTY_STRING);
1422        Collections.sort (v, dummyFieldGroup);
1423        JahiaField theField = null;
1424        int vSize = v.size ();
1425
1426        for (int i = 0; i < vSize; i++) {
1427            fieldGroup = (ContainerEditViewFieldGroup) v.get (i);
1428            Vector JavaDoc fieldNames = fieldGroup.getFieldNames ();
1429            int fieldNamesSize = fieldNames.size ();
1430            ContainerEditViewFieldGroup newFieldGroup =
1431                    new ContainerEditViewFieldGroup (fieldGroup.getName (),
1432                            fieldGroup.getTitle (),
1433                            fieldGroup.getDescr ());
1434            String JavaDoc fieldName = EMPTY_STRING;
1435            for (int j = 0; j < fieldNamesSize; j++) {
1436                fieldName = (String JavaDoc) fieldNames.get (j);
1437                theField = theContainer.getField (fieldName);
1438                if (visibleFields.contains (new Integer JavaDoc (theField.getID ()))) {
1439                    newFieldGroup.addField (fieldGroup.getField (fieldName));
1440                }
1441            }
1442            if (newFieldGroup.getFields ().size () > 0) {
1443                newEditView.addFieldGroup (newFieldGroup);
1444            }
1445        }
1446        return newEditView;
1447    }
1448
1449    /**
1450      * Check Fields validation
1451      *
1452      * @param engineName String
1453      * @param jahiaContentContainerFacade ContainerFacadeInterface
1454      * @param jParams ParamBean
1455      * @param engineMap HashMap
1456      * @throws JahiaException
1457      * @return EngineValidationHelper
1458      */

1459    public static EngineValidationHelper validate(
1460        final String JavaDoc engineName,
1461        final ContainerFacadeInterface jahiaContentContainerFacade,
1462        final ParamBean jParams,
1463        final HashMap JavaDoc engineMap)
1464        throws JahiaException {
1465
1466        final EngineValidationHelper evh = new EngineValidationHelper();
1467        final Enumeration JavaDoc enumeration = jahiaContentContainerFacade.getFields();
1468        final JahiaContainer theContainer =
1469            (JahiaContainer)engineMap.get("theContainer");
1470        final ContainerEditView editView =
1471            (ContainerEditView)engineMap.get("ctnEditView");
1472        JahiaContentFieldFacade cff = null;
1473        JahiaField field = null;
1474        final JahiaContainerDefinition definition = theContainer.getDefinition();
1475        final String JavaDoc containerBeanName = definition.getProperty("containerBeanName");
1476        final String JavaDoc validatorKey = definition.getProperty("validatorKey");
1477
1478        if (containerBeanName != null
1479            && containerBeanName.length() > 0
1480            && validatorKey != null
1481            && validatorKey.length() > 0) {
1482
1483            try {
1484                final Class JavaDoc theClass = Class.forName(containerBeanName);
1485                // define the types of the parameters
1486
final Class JavaDoc theParams[] = {
1487                        org.jahia.data.containers.ContainerFacadeInterface.class,
1488                        org.jahia.params.ParamBean.class};
1489
1490                final Object JavaDoc containerBean;
1491                if (!theClass.isInterface())
1492                    containerBean = theClass.getConstructor(theParams).newInstance(new Object JavaDoc[]{
1493                            jahiaContentContainerFacade,
1494                            jParams});
1495                else
1496                    containerBean = Proxy.newProxyInstance(theClass.getClassLoader(),
1497                            new Class JavaDoc[]{theClass}, new ContainerValidatorBase(jahiaContentContainerFacade, jParams));
1498
1499                final ActionMessages errors = new ActionMessages();
1500
1501                // Create a validator with the ValidateBean actions for the bean
1502
// we're interested in.
1503
final Validator validator =
1504                    Resources.initValidator(
1505                        validatorKey,
1506                        containerBean,
1507                        jParams.getContext(),
1508                        jParams.getRequest(),
1509                        errors,
1510                        1);
1511
1512                // Run the validation actions against the bean.
1513
final ValidatorResults results = validator.validate();
1514
1515                while (!results.isEmpty()
1516                    && enumeration.hasMoreElements()) {
1517                    cff = (JahiaContentFieldFacade)enumeration.nextElement();
1518                    field = (JahiaField)cff.getFields().nextElement();
1519                    final String JavaDoc name = field.getDefinition().getName();
1520                    if (editView.getFieldGroupByFieldName(name) != null) {
1521
1522                        // Get the result of validating the property.
1523
final ValidatorResult vr = results.getValidatorResult(name);
1524
1525                        // Get all the actions run against the property, and iterate over their names.
1526
if (vr != null) {
1527                            final Map JavaDoc actionMap = vr.getActionMap();
1528                            final Iterator JavaDoc keys =
1529                                actionMap.keySet().iterator();
1530                            while (keys.hasNext()) {
1531                                final String JavaDoc actName = (String JavaDoc)keys.next();
1532
1533                                // Get the Action for that name.
1534
final ValidatorAction action =
1535                                    Resources
1536                                        .getValidatorResources(
1537                                            jParams.getContext(),
1538                                            jParams.getRequest())
1539                                        .getValidatorAction(actName);
1540
1541                                //If the result failed, format the Action's message against the formatted field name
1542
if (!vr.isValid(actName)) {
1543                                    final String JavaDoc msg =
1544                                        Resources.getMessage(
1545                                            Resources
1546                                                .getMessageResources(
1547                                                jParams.getRequest()),
1548                                            jParams.getLocale(),
1549                                            action,
1550                                            vr.getField());
1551                                    
1552                                    final ValidationError ve =
1553                                        new ValidationError(
1554                                            field,
1555                                            msg);
1556                                    evh.addError(ve);
1557                                }
1558                            }
1559                        }
1560                    }
1561                }
1562            } catch (Throwable JavaDoc t) {
1563                logger.error("Error in validating :", t);
1564            }
1565        }
1566        return evh;
1567    }
1568
1569    public static ContainerEditViewFieldGroup getFieldGroup(
1570        int fieldID,
1571        JahiaContainer theContainer,
1572        ContainerEditView editView)
1573        throws JahiaException {
1574
1575        ContainerEditViewFieldGroup fieldGroup = null;
1576
1577        JahiaField theField = theContainer.getField(fieldID);
1578        if (theField != null) {
1579            fieldGroup =
1580                editView.getFieldGroupByFieldName(
1581                    theField.getDefinition().getName());
1582        }
1583        if (fieldGroup == null) {
1584            Vector JavaDoc views = new Vector JavaDoc(editView.getViews().values());
1585            if (views.size() > 0) {
1586                fieldGroup =
1587                    (ContainerEditViewFieldGroup)views.get(0);
1588            }
1589        }
1590        return fieldGroup;
1591    }
1592}
1593
Popular Tags