KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > services > containers > JahiaContainersBaseService


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  * 26-DEC-2000, Xo3 SA, Eric Vassalli: Initial version
37  * 06-AUG-2003, Jahia Solutions Sarl, Fulco Houkes
38  *
39  * ----- END LICENSE BLOCK -----
40  */

41
42 package org.jahia.services.containers;
43
44 import java.io.IOException JavaDoc;
45 import java.util.*;
46
47 import org.jahia.content.ContentContainerKey;
48 import org.jahia.content.ContentFieldKey;
49 import org.jahia.content.ContentObject;
50 import org.jahia.data.JahiaDOMObject;
51 import org.jahia.data.JahiaData;
52 import org.jahia.data.containers.ContainersChangeEventListener;
53 import org.jahia.data.containers.JahiaContainer;
54 import org.jahia.data.containers.JahiaContainerDefinition;
55 import org.jahia.data.containers.JahiaContainerList;
56 import org.jahia.data.containers.JahiaContainerSet;
57 import org.jahia.data.containers.JahiaContainerStructure;
58 import org.jahia.data.events.JahiaEvent;
59 import org.jahia.data.fields.JahiaField;
60 import org.jahia.data.fields.JahiaFieldDefinition;
61 import org.jahia.data.fields.LoadFlags;
62 import org.jahia.engines.EngineMessage;
63 import org.jahia.exceptions.JahiaException;
64 import org.jahia.exceptions.JahiaInitializationException;
65 import org.jahia.params.ParamBean;
66 import org.jahia.registries.JahiaContainerDefinitionsRegistry;
67 import org.jahia.registries.ServicesRegistry;
68 import org.jahia.services.acl.ACLNotFoundException;
69 import org.jahia.services.acl.JahiaBaseACL;
70 import org.jahia.services.cache.Cache;
71 import org.jahia.services.cache.CacheFactory;
72 import org.jahia.services.fields.ContentField;
73 import org.jahia.services.pages.ContentPage;
74 import org.jahia.services.usermanager.JahiaUser;
75 import org.jahia.services.version.ActivationTestResults;
76 import org.jahia.services.version.ContentObjectEntryState;
77 import org.jahia.services.version.EntryLoadRequest;
78 import org.jahia.services.version.IsValidForActivationResults;
79 import org.jahia.services.version.JahiaSaveVersion;
80 import org.jahia.services.version.StateModificationContext;
81 import org.jahia.settings.SettingsBean;
82 import org.jahia.utils.LanguageCodeConverters;
83 import org.jahia.utils.xml.XMLSerializationOptions;
84 import org.jahia.utils.xml.XmlWriter;
85
86 public class JahiaContainersBaseService
87     extends JahiaContainersService {
88
89     /** logging */
90     private static final org.apache.log4j.Logger logger =
91         org.apache.log4j.Logger.getLogger(JahiaContainersBaseService.class);
92
93     /** the service unique instance */
94     private static JahiaContainersBaseService instance;
95
96 // private static SettingsBean jSettings;
97

98     private JahiaContainerUtilsDB c_utils;
99     private JahiaContainersDB c_containers;
100     private JahiaContainerPropDB c_containers_prop;
101     private JahiaContainerListsDB c_lists;
102     private JahiaContainerListPropDB c_lists_props;
103     private JahiaContainerDefinitionsDB c_defs;
104     private JahiaContainerDefPropDB c_defs_props;
105     private JahiaContainerStructuresDB c_struct;
106
107     // the Container cache name.
108
public static final String JavaDoc CONTAINER_CACHE = "ContainerCache";
109
110     // the Container List cache name.
111
public static final String JavaDoc CONTAINERLIST_CACHE = "ContainerListCache";
112
113     /* JahiaContainerInfo cache (active entry only)*/
114     private static Cache containerInfoCache;
115
116     /* JahiaContainerListInfo cache (active and stated entry only)*/
117     private static Cache containerListInfoCache;
118
119     /**
120      * Default constructor, creates a new <code>JahiaContainersBaseService</code> instance.
121      */

122     protected JahiaContainersBaseService() {
123         logger.debug("***** Starting up Containers Services *****");
124     }
125
126     /**
127      * inits the service cache and settings
128      *
129      * @param jSettings Settings to let the sevice where to save files, i.e.
130      */

131     public void init(SettingsBean jSettings) throws
132         JahiaInitializationException {
133 // jSettings = jSettings_;
134

135         c_utils = JahiaContainerUtilsDB.getInstance();
136         c_containers = new JahiaContainersDB();
137         c_containers_prop = new JahiaContainerPropDB();
138         c_lists = new JahiaContainerListsDB();
139         c_lists_props = new JahiaContainerListPropDB();
140         c_defs = new JahiaContainerDefinitionsDB();
141         c_defs_props = new JahiaContainerDefPropDB();
142         c_struct = new JahiaContainerStructuresDB();
143
144         //patchCtnDefs();
145

146         containerInfoCache = CacheFactory.createCache(CONTAINER_CACHE);
147
148         containerListInfoCache = CacheFactory.createCache(CONTAINERLIST_CACHE);
149     }
150
151     // Javadoc inherited from parent
152
public synchronized void shutdown() throws JahiaException {
153         super.shutdown();
154
155         // flush the caches
156
containerInfoCache.flush();
157         containerListInfoCache.flush();
158     }
159
160     /**
161      * Returns the unique instance of the Container Service.
162      *
163      * @return the unique instance of the Container Service
164      */

165     public static synchronized JahiaContainersBaseService getInstance() {
166         if (instance == null) {
167             instance = new JahiaContainersBaseService();
168         }
169         return instance;
170     }
171
172     /**
173      * Create a clone of the container list and all its contents (containers)
174      *
175      * @param cListID The containerList to clone
176      * @param newPageID The Id of the new page to which the cloned containerList must
177      * belong to.
178      */

179     public void cloneContainerList(int cListID, int newPageID,
180                                                 int parentAclID,
181                                                 boolean childrenCloned) throws
182         JahiaException {
183         cloneContainerList(cListID, newPageID, 0, parentAclID,
184             childrenCloned);
185     }
186
187     //-------------------------------------------------------------------------------
188
/**
189      * Create a clone of the container list and all its contents (containers)
190      *
191      * @param cListID The containerList to clone
192      * @param newPageID The Id of the new page to which the cloned containerList must
193      * belong to.
194      * @param parentEntryID The id of the container which contains this containerList
195      * egal 0, if the containerList is in a page.
196      */

197     public JahiaContainerList cloneContainerList(int cListID,
198         int newPageID,
199         int parentEntryID,
200         int parentAclID,
201         boolean childrenCloned) throws JahiaException {
202         //get list object
203
int loadFlag = LoadFlags.ALL;
204
205         JahiaContainerList theList = loadContainerList(cListID, loadFlag, null);
206         if (theList == null) {
207             throw new JahiaException("Could not clone container list.",
208                                      "Could not load the JahiaContainerList object.",
209                                      JahiaException.PAGE_ERROR,
210                                      JahiaException.CRITICAL_SEVERITY);
211         }
212
213         // All the ContainerList of the page are cloned
214
// the containerList in a container too
215
// set the parentEntryID of the clone to be not equal to 0
216
// if the containerList to clone has a parentEntryId !=0
217
// the parentEntryID of the clone will be set in
218
// cloneContainer method.
219
int parentEntryID2 = theList.getParentEntryID();
220         if (parentEntryID2 != 0 && parentEntryID == 0) {
221             parentEntryID = parentEntryID2;
222         }
223
224         // clone acl
225
int aclID = theList.getAclID();
226         JahiaBaseACL aclObj = new JahiaBaseACL(aclID);
227         if (aclObj == null) {
228             throw new JahiaException("Could not clone container list.",
229                                      "Could not get JahiaBaseACL object.",
230                                      JahiaException.PAGE_ERROR,
231                                      JahiaException.CRITICAL_SEVERITY);
232         }
233
234         JahiaBaseACL clonedACL = (JahiaBaseACL) aclObj.clone();
235         if (clonedACL == null) {
236             throw new JahiaException("Could not clone container list.",
237                                      "Could not clone acl.",
238                                      JahiaException.PAGE_ERROR,
239                                      JahiaException.CRITICAL_SEVERITY);
240         }
241         clonedACL.setParentID(parentAclID);
242         int cListAclID = clonedACL.getID();
243
244         //clone containerList
245
JahiaContainerList clonedList = new JahiaContainerList(0, parentEntryID,
246             newPageID,
247             theList.getctndefid(), clonedACL.getID());
248         if (clonedList == null) {
249             throw new JahiaException("Could not clone container list.",
250                                      "Could not instanciate a new JahiaContainerList object.",
251                                      JahiaException.PAGE_ERROR,
252                                      JahiaException.CRITICAL_SEVERITY);
253         }
254
255         // gets a new field id
256
int theListID = ServicesRegistry.getInstance().
257             getJahiaIncrementorsDBService().autoIncrement(
258             "jahia_ctn_lists");
259         if (theListID != 0) {
260             clonedList.setID(theListID);
261         }
262
263         // to get the JahiaSaveVersion, we need to load the page info at 1st, to know to what site the
264
// container list belongs to.
265
// throws a JahiaException if the page can't be found
266
ContentPage thePage = ServicesRegistry.getInstance().
267             getJahiaPageService().lookupContentPage(
268             theList.getPageID(), true);
269         JahiaSaveVersion saveVersion = ServicesRegistry.getInstance().
270             getJahiaVersionService().
271             getSiteSaveVersion(thePage.getJahiaID());
272         // save containerList in database
273
c_lists.db_create_container_list2(clonedList, saveVersion);
274
275         // clone containers into the containerList
276
JahiaContainer clonedContainer = null;
277         for (Enumeration e = theList.getContainers(); e.hasMoreElements(); ) {
278
279             clonedContainer = cloneContainer( (JahiaContainer) e.nextElement(),
280                                              clonedList.getID(), newPageID,
281                                              cListAclID, childrenCloned);
282             if (clonedContainer != null) {
283                 clonedList.addContainer(clonedContainer);
284             }
285
286         }
287
288         return clonedList;
289     }
290
291     //-------------------------------------------------------------------------------
292
/**
293      * Create a clone of the container and all its contents (fields and containerList)
294      *
295      * @param theContainer The container to clone
296      * @param newPageID The Id of the new page to which the cloned containerList must
297      * belong to.
298      * @param newCListID The id of the container list which contains this container.
299      */

300     public JahiaContainer cloneContainer(JahiaContainer
301         theContainer, int newCListID, int newPageID, int parentAclID,
302         boolean childrenCloned) throws JahiaException {
303         // get the container object
304
int loadFlag = LoadFlags.ALL;
305         theContainer = loadContainer(theContainer.getID(), loadFlag, null);
306         if (theContainer == null) {
307             throw new JahiaException("Could not clone container.",
308                                      "Could not load the JahiaContainer object.",
309                                      JahiaException.PAGE_ERROR,
310                                      JahiaException.CRITICAL_SEVERITY);
311         }
312
313         JahiaSaveVersion saveVersion = ServicesRegistry.getInstance().
314             getJahiaVersionService().
315             getSiteSaveVersion(theContainer.
316                                getJahiaID());
317
318         //cloneACl
319
int aclID = theContainer.getAclID();
320         JahiaBaseACL aclObj = new JahiaBaseACL(aclID);
321         if (aclObj == null) {
322             throw new JahiaException("Could not clone container.",
323                                      "Could not get JahiaBaseACL object.",
324                                      JahiaException.PAGE_ERROR,
325                                      JahiaException.CRITICAL_SEVERITY);
326         }
327
328         JahiaBaseACL clonedACL = (JahiaBaseACL) aclObj.clone();
329         if (clonedACL == null) {
330             throw new JahiaException("Could not clone container.",
331                                      "Could not clone acl.",
332                                      JahiaException.PAGE_ERROR,
333                                      JahiaException.CRITICAL_SEVERITY);
334         }
335         clonedACL.setParentID(parentAclID);
336         int containerAclID = clonedACL.getID();
337
338         //clone container
339
JahiaContainer clonedContainer = new JahiaContainer(0,
340             theContainer.getJahiaID(),
341             newPageID, newCListID, theContainer.getRank(),
342             clonedACL.getID(), theContainer.getctndefid(),
343             theContainer.getVersionID(),
344             theContainer.getWorkflowState());
345         clonedContainer.setLanguageCode(theContainer.getLanguageCode());
346         if (clonedContainer == null) {
347             throw new JahiaException("Could not clone container.",
348                                      "Could not instanciate a new JahiaContainer object.",
349                                      JahiaException.PAGE_ERROR,
350                                      JahiaException.CRITICAL_SEVERITY);
351         }
352
353         // gets the new container id
354
int newctnid = ServicesRegistry.getInstance().
355             getJahiaIncrementorsDBService().autoIncrement(
356             "jahia_ctn_entries");
357         if (newctnid != 0) {
358             clonedContainer.setID(newctnid);
359         }
360
361         //clone fields into container
362
JahiaField clonedField = null;
363         for (Enumeration e = theContainer.getFields(); e.hasMoreElements(); ) {
364
365             clonedField = ServicesRegistry.getInstance().getJahiaFieldService().
366                 cloneField(
367                 (JahiaField) e.nextElement(), clonedContainer.getID(),
368                 newPageID, containerAclID, childrenCloned);
369
370             if (clonedField == null) {
371                 throw new JahiaException("Could not clone container.",
372                                          "Could not clone a field.",
373                                          JahiaException.PAGE_ERROR,
374                                          JahiaException.CRITICAL_SEVERITY);
375             }
376
377             clonedContainer.addField(clonedField);
378         }
379
380         // clone container lists into container
381
// Already done, because all the container list of the page are cloned !
382
// set the parentEntryID of the containerList
383
int pageID = theContainer.getPageID();
384         ArrayList languageCodes = new ArrayList();
385         languageCodes.add(theContainer.getLanguageCode());
386         EntryLoadRequest entryLoadRequest = new EntryLoadRequest(theContainer.
387             getWorkflowState(), theContainer.getVersionID(), languageCodes);
388         ContentPage page = ServicesRegistry.getInstance().
389             getJahiaPageService().lookupContentPage(pageID,
390             entryLoadRequest, true);
391         if (page != null) {
392             Vector cListIDs = getContainerListIDsInPage(page, entryLoadRequest);
393
394             int cListID;
395             for (int i = 0; i < cListIDs.size(); i++) {
396                 cListID = ( (Integer JavaDoc) cListIDs.elementAt(i)).intValue();
397                 JahiaContainerList cList = loadContainerListInfo(cListID);
398                 if (cList != null) {
399                     // The cloned containerList is already associated with the clonedPage
400
// the cloned containerList has the same parentEntryID as the containerList to clone
401
// then set the parentEntryID.
402
if (cList.getParentEntryID() == theContainer.getID() &&
403                         cList.getPageID() == newPageID) {
404                         cList.setParentEntryID(newctnid);
405                         c_lists.db_update_container_list(cList, saveVersion);
406                     }
407                 }
408             }
409         }
410
411         //save container in DB
412
c_containers.db_create_container(clonedContainer, saveVersion);
413
414         return clonedContainer;
415     }
416
417     /**
418      * builds the complete container structure for a specific page
419      * builds the complete container structure
420      * (containerlists->containers->fields/containerlists)
421      * for a specific page
422      * DO NOT CACHE THIS METHOD (it depends on other caches values) !!
423      *
424      * @return a Vector of containerlist IDs
425      */

426     public JahiaContainerSet buildContainerStructureForPage(JahiaData jData,
427         EntryLoadRequest loadVersion) throws JahiaException {
428
429         /*
430                  // cache all Containers at the load of each page... it takes a little
431                  // time when the containers are already cached, but it's worth it
432                  // when they're not into cache!
433                  if (loadVersion.isCurrent()) {
434             Vector allContainers = c_containers.
435          db_load_all_active_containers_info_from_page(
436                 jData.params().getPageID());
437             for (int i = 0; i < allContainers.size(); i++) {
438          JahiaContainer cachedContainer = (JahiaContainer) allContainers.
439                                                  elementAt(i);
440                 cacheContainers.put(new Integer(cachedContainer.getID()),
441                                     cachedContainer.clone());
442             }
443                  }
444
445                  Hashtable cachedFieldsFromContainers = new Hashtable();
446                  // we only cache all fields from containers if we load the active version of the page
447                  if (loadVersion.isCurrent()) {
448             // actually this creates a Map of ctnIDs -> fieldIDs, the fields
449             // are not really loaded here.
450             cachedFieldsFromContainers = c_utils.
451          db_load_all_active_fields_from_container_from_page(jData.params().
452                 getPageID());
453                  }
454
455                  Vector ctnLists = new Vector();
456
457                  JahiaContainerList cList = null;
458          Vector definitions = getctndefidsInPage(jData.params().getContentPage(),
459                                                 loadVersion);
460                  for (int a = 0; a < definitions.size(); a++) {
461             JahiaContainerDefinition theDefinition =
462                 (JahiaContainerDefinition) definitions.elementAt(a);
463             // loads all container list ids corresponding to page id and def id
464             Vector listIDs = getContainerListIDs(
465                 jData.params().getPage().getID(),
466                 theDefinition.getID(), loadVersion);
467
468             // 05.05.2002 NK: Search,Sort,Filtering purpose
469             // Filtering must be evaluated before.
470             // Actually, filters are defined in template JSP files.
471             // that is why container list are loaded wihtout their containers here.
472
473             if (listIDs.size() > 0) {
474                 // if container lists found, loads them by their id
475                 for (int i = 0; i < listIDs.size(); i++) {
476                     int listID = ( (Integer) listIDs.elementAt(i)).intValue();
477                     cList = loadContainerListInfo(listID, loadVersion); // container list loaded wihtout its containers !!
478                     if (cList != null) {
479                         ctnLists.add(cList);
480                     }
481                 }
482             }
483                  }
484
485                  // loads all container definitions on the page
486                  JahiaContainerSet theSet = new JahiaContainerSet(jData,
487             cachedFieldsFromContainers, ctnLists);
488
489                  return theSet;
490          */

491
492         // cache all Containers at the load of each page... it takes a little
493
// time when the containers are already cached, but it's worth it
494
// when they're not into cache!
495
/*
496         if (loadVersion.isCurrent()) {
497             Vector allContainers = c_containers.
498                 db_load_all_active_containers_info_from_page(
499                 jData.params().getPageID());
500             for (int i = 0; i < allContainers.size(); i++) {
501                 JahiaContainer currentContainer = (JahiaContainer) allContainers
502                         .elementAt(i);
503                 Object entryKey = getCacheContainerOrContainerListActiveEntryKey(currentContainer
504                         .getID());
505                 JahiaContainer cachedContainer = (JahiaContainer) containerInfoCache
506                         .get(entryKey);
507                 if (cachedContainer == null
508                         || cachedContainer.getVersionID() != currentContainer
509                                 .getVersionID()) {
510                     containerInfoCache.put(entryKey, currentContainer);
511                 }
512             }
513         }
514 */

515         JahiaContainerSet theSet = new JahiaContainerSet(jData);
516         return theSet;
517
518     } // end buildContainerStructureForPage
519

520     /**
521      * gets all container definitions ids on a page
522      *
523      * @param contentPage the page object
524      *
525      * @return a Vector of container definition IDs
526      */

527     public Vector getctndefidsInPage(ContentPage contentPage,
528                                      EntryLoadRequest entryLoadRequest) throws
529         JahiaException {
530         return JahiaContainerDefinitionsRegistry.getInstance().
531             getDefinitionsInTemplate(contentPage.getPageTemplateID(
532             entryLoadRequest));
533     } // end getctndefidsInPage
534

535     /**
536      * gets all container list ids on a page, by their definition id
537      *
538      * @param pageID the page id
539      * @param defID the container definition id
540      *
541      * @return a Vector of containerlist IDs
542      */

543     public Vector getContainerListIDs(int pageID, int defID,
544                                       EntryLoadRequest loadVersion) throws
545         JahiaException {
546         return c_utils.db_get_container_list_ids(pageID, defID, loadVersion);
547     } // end getContainerListIDs
548

549     /**
550      * gets all container list ids on a page depending on the load request
551      * DO NOT CACHE THIS METHOD (it depends on other caches values) !!
552      *
553      * @return a Vector of containerlist IDs
554      */

555     public Vector getContainerListIDsInPage(ContentPage contentPage,
556                                             EntryLoadRequest entryLoadRequest) throws
557         JahiaException {
558         Vector listIDs = new Vector();
559         Vector definitions = getctndefidsInPage(contentPage,
560                                                 entryLoadRequest);
561         for (int i = 0; i < definitions.size(); i++) {
562             JahiaContainerDefinition theDefinition = (JahiaContainerDefinition)
563                 definitions.elementAt(i);
564             listIDs.addAll(getContainerListIDs(contentPage.getID(),
565                                                theDefinition.getID(),
566                                                entryLoadRequest));
567         }
568         return listIDs;
569     } // end getContainerListIDsInPage
570

571     /**
572      * gets all container ids in a container list. This list uses stored
573      * ranks to order its values
574      *
575      * @param listID the container list id
576      *
577      * @return a Vector of container IDs
578      *
579      * @todo we might want to cache these values in memory in order to
580      * improve performance.
581      * laisser encore un moment pour pol parske il le vaut bien
582      */

583     // laisser encore un moment pour pol parske il le vaut bien
584
public Vector getctnidsInList(int listID) throws JahiaException {
585         return getctnidsInList(listID, EntryLoadRequest.CURRENT);
586     } // end getctnidsInList
587

588     public Vector getctnidsInList(int listID, EntryLoadRequest loadVersion) throws
589         JahiaException {
590         return c_utils.db_get_container_ids_in_container_list(listID,
591             loadVersion, false);
592     } // end getctnidsInList
593

594     /**
595      * Gets all container ids in a container list with ordering on a given field.
596      * If the fieldName is null, not ordering applied
597      *
598      * @param listID the container list id
599      * @param fieldName the fieldname on which to filter
600      * @param asc Asc. or desc. ordering ( true = asc )
601      *
602      * @return a Vector of container IDs
603      *
604      * @todo we might want to cache these values in memory in order to
605      * improve performance.
606      */

607     public Vector getctnidsInList(int listID, String JavaDoc fieldName, boolean asc,
608                                   EntryLoadRequest loadVersion) throws
609         JahiaException {
610         if (fieldName == null || fieldName.trim().equals("")) {
611             return c_utils.db_get_container_ids_in_container_list(listID,
612                 loadVersion, false);
613         }
614         return c_utils.db_get_container_ids_in_container_list(listID, fieldName,
615             asc, loadVersion);
616     } // end getctnidsInList
617

618     /**
619      * gets all container ids for a given site. This list uses stored
620      * ranks to order its values
621      *
622      * @param siteID the given site id.
623      *
624      * @return Vector a vector of container IDs
625      */

626     public Vector getCtnIds(int siteID) throws JahiaException {
627         return c_utils.db_get_all_containers_id(siteID);
628     }
629
630     /**
631      * gets all container ids of the system.
632      *
633      * @return Vector a vector of container IDs
634      */

635     public Vector getCtnIds() throws JahiaException {
636         return getCtnIds(false);
637     }
638
639     /**
640     *
641     * @param orderByRanking if true, order by container ranking
642     * @return ordered container ids
643     * @throws JahiaException
644     */

645    public Vector getCtnIds(boolean orderByRanking) throws JahiaException {
646        return c_utils.db_get_all_containers_id(orderByRanking);
647    }
648     
649     /**
650      * gets all container ids for a given entryLoadRequest
651      *
652      * @param loadVersion
653      *
654      * @return container ids for a given entryLoadRequest
655      *
656      * @throws JahiaException
657      */

658     public Vector getCtnIds(EntryLoadRequest loadVersion) throws JahiaException {
659         return c_utils.db_get_container_ids_in_container_list( -1, loadVersion,
660             true);
661     }
662
663     /**
664      * gets all container list ids in a container.
665      *
666      * @param ctnID the container list id
667      *
668      * @return a Vector of container IDs
669      *
670      * @todo we might want to cache these values in memory in order to
671      * improve performance.
672      */

673     public Vector getCtnListIDsInContainer(int ctnID) throws JahiaException {
674         return c_utils.db_get_containerlist_ids_in_container(ctnID);
675     }
676
677     /**
678      * gets all field ids in a container
679      *
680      * @param ctnid the container id
681      *
682      * @return a Vector of field IDs
683      */

684     public Vector getFieldIDsInContainer(int ctnid) throws JahiaException {
685         return getFieldIDsInContainer(ctnid, null);
686     } // end getFieldIDsInContainer
687

688     public Vector getFieldIDsInContainer(int ctnid,
689                                          EntryLoadRequest loadVersion) throws
690         JahiaException {
691         //return c_utils.db_get_field_ids_in_container (ctnid, loadVersion);
692
return ContentContainerTools.getInstance()
693             .getFieldIDsByContainer(ctnid, loadVersion);
694     } // end getFieldIDsInContainer
695

696     public Map getFieldIDsAndDefsInContainer(int ctnid,
697             EntryLoadRequest loadVersion) throws JahiaException {
698         return ContentContainerTools.getInstance()
699                 .getFieldIDsAndDefsByContainer(ctnid, loadVersion, false);
700     } // end getFieldIDsAndDefsInContainer
701

702     /**
703      * gets a container list id by its container list name and page id
704      *
705      * @param containerName the container name
706      * @param pageID the page ID
707      *
708      * @return a container list id
709      */

710     public int getContainerListID(String JavaDoc containerName, int pageID) throws
711         JahiaException {
712         return c_utils.db_get_container_list_id(containerName, pageID);
713     } // end getContainerListID
714

715     /**
716      * gets all container definition ids in Jahia
717      *
718      * @return a Vector of container definition IDs
719      */

720     public Vector getAllContainerDefinitionIDs() throws JahiaException {
721         return c_utils.db_get_all_container_definition_ids();
722     } // end getAllContainerDefinitionIDs
723

724     /**
725      * loads a container info, by its container id
726      * NO RIGHTS CHECKS ! see loadContainer(ctnid,LoadFlags,jParams) for that.
727      *
728      * @param ctnid the container id
729      *
730      * @return a JahiaContainer object, without field values
731      *
732      * @see org.jahia.data.containers.JahiaContainer
733      */

734     public JahiaContainer loadContainerInfo(int ctnid) throws JahiaException {
735         return loadContainerInfo(ctnid, EntryLoadRequest.CURRENT);
736     }
737
738     public JahiaContainer loadContainerInfo(int ctnid,
739                                             EntryLoadRequest loadVersion) throws
740         JahiaException {
741         logger.debug("Attempting to load container " + ctnid +
742                      " , EntryLoadRequest=" + loadVersion);
743
744         JahiaContainer result = null;
745         // if we load the current version, we use the container cache
746
if (loadVersion.getWorkflowState() >=
747             EntryLoadRequest.ACTIVE_WORKFLOW_STATE) {
748             result = (JahiaContainer) containerInfoCache
749                 .get(getCacheContainerOrContainerListEntryKey(ctnid,
750                 loadVersion.getWorkflowState()));
751             if (result == null)
752             // load it
753
{
754                 result = c_containers.db_load_container(ctnid, loadVersion);
755                 if (result != null) {
756                     containerInfoCache.put(
757                         getCacheContainerOrContainerListEntryKey(ctnid,
758                         loadVersion.getWorkflowState()), result.clone());
759                 }
760             }
761             else {
762                 result = (JahiaContainer) (result.clone());
763             }
764         }
765         else
766         // else we load it from the database
767
{
768             result = c_containers.db_load_container(ctnid, loadVersion);
769         }
770
771         return result;
772
773     } // end loadContainerInfo
774

775     /**
776      * loads a container by its container id
777      * loads a container info and fields by its container id, but not dependant containerlists
778      * this method cannot load request-specific values (i.e. applications);
779      * see the loadContainer( ctnid, loadFlag, jParams) for that.
780      * NO RIGHTS CHECKS ! see loadContainer(ctnid,LoadFlags,jParams) for that.
781      * DO NOT CACHE THIS METHOD (it depends on other caches values) !!
782      *
783      * @param ctnid the container id
784      * @param loadFlag the loadFlag
785      *
786      * @see org.jahia.data.containers.JahiaContainer
787      * @see org.jahia.data.fields.LoadFlags
788      */

789     public JahiaContainer loadContainer(int ctnid, int loadFlag) throws
790         JahiaException {
791         return loadContainer(ctnid, loadFlag, null);
792     } // end loadContainer
793

794     public JahiaContainer loadContainer(int ctnid, int loadFlag,
795                                         ParamBean jParams) throws
796         JahiaException {
797         return loadContainer(ctnid, loadFlag, jParams,
798                              jParams.getEntryLoadRequest());
799     }
800
801     /**
802      * loads a container by its container id
803      * loads a container info and fields by its container id, but not dependant containerlists
804      * this method can load request-specific values (i.e. applications);
805      * DO NOT CACHE THIS METHOD (it depends on other caches values) !!
806      *
807      * @param ctnid the container id
808      * @param loadFlag the loadFlag
809      * @param jParams the ParamBean object, containing request and response
810      *
811      * @see org.jahia.data.containers.JahiaContainer
812      * @see org.jahia.data.fields.LoadFlags
813      * DJ 29.01.2001 - added ACL checks
814      * if there are no read rights -> return an empty container with -1 as ID.
815      */

816     // DJ 29.01.2001 - added ACL checks
817
// if there are no read rights -> return an empty container with -1 as ID.
818

819     public JahiaContainer loadContainer(int ctnid, int loadFlag,
820                                         ParamBean jParams,
821                                         EntryLoadRequest loadVersion) throws
822         JahiaException {
823         return loadContainer(ctnid, loadFlag, jParams, loadVersion,
824                              new Hashtable(), new Hashtable(), new Hashtable());
825     }
826
827     /**
828      *
829      * @param ctnid
830      * @param loadFlag
831      * @param jParams
832      * @param loadVersion
833      * @param cachedFieldsInContainer
834      * @return the loaded container
835      * @throws JahiaException
836      */

837     // the hashtable cachedFieldsInContainer is here if we already have a hashtable
838
// with containerID as key, and a Vector of fieldIDs in object, see buildContainerStructure.
839
public JahiaContainer loadContainer(int ctnid, int loadFlag,
840                                         ParamBean jParams,
841                                         EntryLoadRequest loadVersion,
842                                         Hashtable cachedFieldsInContainer,
843                                         Hashtable
844                                         cachedContainersFromContainerLists,
845                                         Hashtable
846                                         cachedContainerListsFromContainers) throws
847         JahiaException {
848         // loads container info
849
JahiaContainer theContainer = loadContainerInfo(ctnid, loadVersion);
850         if (theContainer == null) {
851             return theContainer;
852         }
853
854         ContainerFactoryProxy cFactory =
855             new ContainerFactoryProxy(loadFlag,
856                                       jParams,
857                                       loadVersion,
858                                       cachedFieldsInContainer,
859                                       cachedContainersFromContainerLists,
860                                       cachedContainerListsFromContainers);
861
862         theContainer.setFactoryProxy(cFactory);
863
864         // loads container fields
865
// check for correct rights on container
866
if (jParams != null) { // no jParams, can't check for rights
867
JahiaUser currentUser = jParams.getUser();
868             if (currentUser != null) {
869                 logger.debug("loadContainer(): checking rights...");
870                 // if the user has no read rights, return the container with no fields.
871
if (!theContainer.checkReadAccess(currentUser)) {
872                     logger.debug(
873                         "loadContainer(): NO read rights! -> returning null");
874                     theContainer.setID( -1); // special flag to say the container is not loaded
875
return theContainer;
876                 }
877                 logger.debug("loadContainer(): read rights OK");
878             }
879             else {
880                 throw new JahiaException("No user present !",
881                                          "No current user defined in the params in loadField() method.",
882                                          JahiaException.USER_ERROR,
883                                          JahiaException.ERROR_SEVERITY);
884             }
885         }
886         // end check rights on container
887

888         return theContainer;
889     } // end loadContainer
890

891     /**
892      * saves the container info
893      * if id=0, assigns a new id to container and creates it in datasource
894      * if listid=0, assigns a new listid to container and creates it in datasource
895      *
896      * @param theContainer a JahiaContainer object
897      * @param parentID parent container id
898      * @param parentAclID the Acl parent ID
899      *
900      * @param jParams the current ParamBean
901      * @see org.jahia.data.containers.JahiaContainer
902      */

903     // DJ 29.01.01 added ACL check
904
// Note : the new ACLs are created here and not in the engine.
905
// EV 26.02.2001 added parentAclID - acl is no more a dirty hack ;)
906
//
907
public void saveContainerInfo(JahiaContainer theContainer,
908                                                int parentID,
909                                                int parentAclID,
910                                                ParamBean jParams) throws
911         JahiaException {
912         // start check for correct rights.
913
if (jParams != null) { // no jParams, can't check for rights
914
JahiaUser currentUser = jParams.getUser();
915             if (currentUser != null) {
916                 logger.debug("saveContainerInfo(): checking rights...");
917                 // if the user has no write rights, exit method.
918
if (theContainer.getID() != 0 &&
919                     !theContainer.checkWriteAccess(currentUser)) {
920                     logger.debug(
921                         "saveContainerInfo(): NO write rights! -> don't save");
922                     return;
923                 }
924                 logger.debug("saveContainerInfo(): write rights OK");
925             }
926             else {
927                 throw new JahiaException("No user present !",
928                                          "No current user defined in the params in saveContainerInfo() method.",
929                                          JahiaException.USER_ERROR,
930                                          JahiaException.ERROR_SEVERITY);
931             }
932         }
933         // end check rights.
934

935         JahiaSaveVersion saveVersion = ServicesRegistry.getInstance().
936             getJahiaVersionService().
937             getSiteSaveVersion(theContainer.
938                                getJahiaID());
939
940         JahiaContainer tmpContainer = null;
941         if (theContainer.getID() == 0) {
942             // container not yet exists -> we have to give him an ID !
943
int listID = theContainer.getListID();
944
945             /** @todo this code was commented out because it caused problems
946              * with sub-containers lists that were always loading the first
947              * sub-container list.
948              */

949
950             /*
951                          if (listID == 0) {
952                 // try to load from db again
953                 listID = ServicesRegistry.getInstance()
954                            .getJahiaContainersService().getContainerListID(
955                            theContainer.getDefinition().getName(),
956                            theContainer.getPageID());
957                          }
958              */

959             if (listID <= 0) {
960                 // container is not yet in a list -> we have to create a list !
961
JahiaContainerList newList = new JahiaContainerList(0, parentID,
962                     theContainer.getPageID(),
963                     theContainer.getctndefid(), 0);
964                 saveContainerListInfo(newList, parentAclID);
965
966                 //create default acl for container list edit view field
967
JahiaField aField = null;
968                 Enumeration fList = theContainer.getFields();
969                 while (fList.hasMoreElements()) {
970                     aField = (JahiaField) fList.nextElement();
971                     /*
972                          aField = ServicesRegistry.getInstance().
973                      getJahiaFieldService().loadField( aField.getID(), LoadFlags.ALL, jParams );
974                      */

975                     JahiaFieldDefinition theDef = aField.getDefinition();
976                     if (theDef != null) {
977
978                         // create the ACL object...
979
JahiaBaseACL newAcl = new JahiaBaseACL();
980                         newAcl.create(newList.getAclID());
981                         newList.setProperty("view_field_acl_" + theDef.getName(),
982                                             String.valueOf(newAcl.getID()));
983                     }
984                 }
985                 listID = newList.getID();
986                 // FIXME : saved twice ????
987
/*
988                 saveContainerListInfo(newList, parentAclID);
989                  */

990             }
991             theContainer.setListID(listID);
992
993             // Start Create a new ACL object for the new container.
994
JahiaBaseACL acl = new JahiaBaseACL();
995             if (acl != null) {
996                 // let's load the parent ContainerList to get its ACL ID
997
JahiaContainerList tempList = loadContainerListInfo(
998                     theContainer.getListID());
999                 int clAclID = 0;
1000                if (tempList != null) {
1001                    clAclID = tempList.getAclID();
1002                    logger.debug(
1003                        ">Container herited ACL from the ContainerList, OK<");
1004                }
1005                tempList = null; // destroy the tempList.
1006
// create a new object by specifying the parent ACL ID (a containerList)
1007
if (!acl.create(clAclID)) {
1008                    String JavaDoc message =
1009                        "Could not create an ACL object for a new container.";
1010                    logger.debug(message + " -> Stop container creation!");
1011                    throw new JahiaException("JahiaContainersBaseService",
1012                                             message,
1013                                             JahiaException.ACL_ERROR,
1014                                             JahiaException.CRITICAL_SEVERITY);
1015                }
1016                else {
1017                    logger.debug("ACL [" + acl.getID() +
1018                                 "] has just been created! (Container)");
1019                }
1020            }
1021            else {
1022                throw new JahiaException("JahiaContainersBaseService",
1023                                         "Counld not instanciate the JahiaBaseACL class",
1024                                         JahiaException.ACL_ERROR,
1025                                         JahiaException.CRITICAL_SEVERITY);
1026            }
1027            // End Create ACL
1028
theContainer.setAclID(acl.getID());
1029
1030            // gets the new container id
1031
int thectnid = ServicesRegistry.getInstance().
1032                getJahiaIncrementorsDBService().autoIncrement(
1033                "jahia_ctn_entries");
1034            theContainer.setID(thectnid);
1035
1036            tmpContainer = (JahiaContainer) theContainer.clone();
1037            c_containers.db_create_container(tmpContainer, saveVersion);
1038        }
1039        else {
1040            // container already exists -> just need to update
1041
tmpContainer = (JahiaContainer) theContainer.clone();
1042
1043            c_containers.db_update_container(tmpContainer, saveVersion);
1044        }
1045
1046        // update cache
1047
if (theContainer != null) {
1048            synchronized (this) {
1049                if (!saveVersion.isStaging()) {
1050                    containerInfoCache.put(getCacheContainerOrContainerListEntryKey(
1051                            theContainer.getID(), saveVersion.getWorkflowState()), tmpContainer);
1052                }
1053                containerInfoCache.remove(getCacheContainerOrContainerListStagingEntryKey(theContainer.getID()));
1054                ContentContainer.invalidateContainerCache(theContainer.getID());
1055                c_utils.invalidateCtnIdsByCtnListCache(theContainer.getListID());
1056            }
1057        }
1058
1059    } // end saveContainerInfo
1060

1061    /**
1062     * saves the container info and fields saves the container info and fields,
1063     * but not the dependant container lists if id=0, assigns a new id to
1064     * container and creates it in datasource if listid=0, assigns a new listid
1065     * to container and creates it in datasource
1066     *
1067     * @param theContainer
1068     * a JahiaContainer object
1069     *
1070     * @see org.jahia.data.containers.JahiaContainer
1071     */

1072    public void saveContainer(JahiaContainer theContainer,
1073                              int containerParentID,
1074                              ParamBean jParams) throws JahiaException {
1075        // gets the parent acl ID
1076
int parentAclID = 0;
1077        int listID = theContainer.getListID();
1078        // if the container is included in an existing list,
1079
// just get the container list acl id
1080
if (listID != 0) {
1081            JahiaContainerList theList = this.loadContainerListInfo(listID);
1082            if (theList != null) {
1083                parentAclID = theList.getAclID();
1084            }
1085        }
1086        // if parent acl id is still 0, then if the container is included in
1087
// a parent container, just get the parent container acl id
1088
if (parentAclID == 0) {
1089            if (containerParentID != 0) {
1090                JahiaContainer parentContainer = this.loadContainerInfo(
1091                    containerParentID, EntryLoadRequest.CURRENT);
1092                if (parentContainer != null) {
1093                    parentAclID = parentContainer.getAclID();
1094                }
1095            }
1096        }
1097        // if parent acl id is still 0, then simply get the page acl id
1098
if (parentAclID == 0) {
1099            parentAclID = jParams.getPage().getAclID();
1100        }
1101        // end of getting parent acl id
1102

1103        // save the container list info
1104
ServicesRegistry.getInstance().getJahiaContainersService().
1105            saveContainerInfo(theContainer, containerParentID, parentAclID,
1106                              jParams);
1107
1108        // save fields, one by one
1109
Enumeration fields = theContainer.getFields();
1110        while (fields.hasMoreElements()) {
1111            // gets the field
1112
JahiaField containerField = (JahiaField) fields.nextElement();
1113            // ensures that the field points to its including container
1114
containerField.setctnid(theContainer.getID());
1115            // saves the field
1116
containerField.save(jParams);
1117        }
1118    } // end saveContainer
1119

1120    /**
1121     * deletes the container info, fields and sublists
1122     * deletes the container info, fields and sublists
1123     *
1124     * @param ctnid the container id
1125     * @param jParams the request parameters
1126     *
1127     * @see org.jahia.data.containers.JahiaContainer
1128     * DJ 29.01.01 - added ACL check
1129     */

1130    // DJ 29.01.01 - added ACL check
1131
public synchronized void deleteContainer(int ctnid, ParamBean jParams) throws
1132        JahiaException {
1133        // loads container info
1134
EntryLoadRequest loadRequest = new EntryLoadRequest(EntryLoadRequest.
1135            STAGING_WORKFLOW_STATE, 0, EntryLoadRequest.STAGED.getLocales(), true);
1136        JahiaContainer theContainer = loadContainer(ctnid, LoadFlags.NOTHING,
1137            jParams, loadRequest);
1138
1139        // get current site save version
1140
JahiaSaveVersion saveVersion = ServicesRegistry.getInstance().
1141            getJahiaVersionService().
1142            getSiteSaveVersion(theContainer.
1143                               getJahiaID());
1144
1145        // start check for correct rights.
1146
if (jParams != null) {
1147            JahiaUser currentUser = jParams.getUser();
1148            if (currentUser != null) {
1149                logger.debug("deleteContainer(): checking rights...");
1150                // if the user has no write rights, exit method.
1151
if (!theContainer.checkWriteAccess(currentUser)) {
1152                    logger.debug(
1153                        "deleteContainer(): NO write rights! -> don't delete");
1154                    return;
1155                }
1156                logger.debug("deleteContainer(): write rights OK");
1157            }
1158            else {
1159                throw new JahiaException("No user present !",
1160                                         "No current user defined in the params in deleteContainer() method.",
1161                                         JahiaException.USER_ERROR,
1162                                         JahiaException.ERROR_SEVERITY);
1163            }
1164        }
1165        // end check rights.
1166

1167        // deletes container fields - even if no write rights in the fields
1168
Enumeration theFields = theContainer.getFields();
1169
1170        while (theFields.hasMoreElements()) {
1171
1172            JahiaField theField = (JahiaField) theFields.nextElement();
1173            ContentField contentField = ContentField.getField(theField.getID());
1174            Map languages = contentField.getLanguagesStates();
1175            Iterator iterator = languages.keySet().iterator();
1176            while (iterator.hasNext()) {
1177                String JavaDoc curLanguageCode = (String JavaDoc) iterator.next();
1178                /**
1179                 * @todo FIXME normally we shouldn't create the activation
1180                 * context here but take it as a parameter in order to
1181                 * correctly detect loops, but this means that the
1182                 * deleteContainer signature would have to change.
1183                 */

1184                Set languageCodes = new HashSet();
1185                languageCodes.add(curLanguageCode);
1186                contentField.markLanguageForDeletion(jParams.getUser(),
1187                    curLanguageCode,
1188                    new StateModificationContext(new ContentFieldKey(theField.
1189                    getID()),
1190                                                 languageCodes, true));
1191            }
1192        }
1193
1194        //deletes sub container lists - even if no write rights in the lists
1195
Enumeration theLists = theContainer.getContainerLists();
1196        while (theLists.hasMoreElements()) {
1197            JahiaContainerList theContainerList = (JahiaContainerList) theLists.
1198                nextElement();
1199            //logger.debug( "Deleting container list id " + theContainerList.getID() );
1200
deleteContainerList(theContainerList.getID(), jParams);
1201        }
1202
1203        // deletes ACL
1204
/* try {
1205                    // temporary we don't remove the ACL anymore, because of versioning & staging
1206                    // JahiaBaseACL theACL = new JahiaBaseACL (theContainer.getAclID());
1207                    // theACL.delete ();
1208                }
1209                catch (ACLNotFoundException ex) {
1210                    JahiaException je = new JahiaException ("", "Could not find the ACL ["+Integer.toString (theContainer.getAclID())+
1211             "] while removing field ["+Integer.toString(ctnid)+"]",
1212             JahiaException.ACL_ERROR, JahiaException.WARNING);
1213                }*/

1214
1215        // deletes container info
1216
c_containers.db_delete_container(theContainer.getID(), saveVersion);
1217        
1218        // we only delete it from cache if it's not the staged version
1219
if (!saveVersion.isStaging()) {
1220            invalidateContainerFromCache(theContainer.getID());
1221            ContentContainer.invalidateContainerCache(theContainer.getID());
1222            c_utils.invalidateCtnIdsByCtnListCache(theContainer.getListID());
1223        }
1224    } // end deleteContainer
1225

1226    public ActivationTestResults isContainerValidForActivation(
1227        Set languageCodes,
1228        int id, JahiaUser user, JahiaSaveVersion saveVersion,
1229        ParamBean jParams, StateModificationContext stateModifContext) throws
1230        JahiaException {
1231        ActivationTestResults activationResults = new ActivationTestResults();
1232
1233        /* Never used
1234                 JahiaContainer theContainer = loadContainerInfo (id,
1235                EntryLoadRequest.STAGED);
1236         */

1237
1238        // we must now check to see if this container has fields that
1239
// don't exist in an active version.
1240

1241        // we might want to cache the next field id retrieval code ?
1242

1243        EntryLoadRequest loadRequest = new EntryLoadRequest(EntryLoadRequest.STAGED);
1244        loadRequest.setWithMarkedForDeletion(true);
1245
1246        Vector fieldIDs = getFieldIDsInContainer(id, loadRequest);
1247
1248        for (int j = 0; j < fieldIDs.size(); j++) {
1249            int fieldID = ( (Integer JavaDoc) fieldIDs.elementAt(j)).intValue();
1250            ContentField currentField = ContentField.getField(fieldID);
1251            activationResults.merge(currentField.isValidForActivation(
1252                languageCodes, jParams, stateModifContext));
1253        }
1254
1255        return activationResults;
1256    }
1257
1258    public ActivationTestResults activateStagedContainer(
1259        Set languageCodes,
1260        int id, JahiaUser user, JahiaSaveVersion saveVersion,
1261        ParamBean jParams, StateModificationContext stateModifContext) throws
1262        JahiaException {
1263
1264        ContentContainer contentContainer = ContentContainer.getContainer(id);
1265        boolean stateModified = false;
1266        if (contentContainer.willBeCompletelyDeleted(null, languageCodes)) {
1267            stateModified = true;
1268            stateModifContext.pushAllLanguages(true);
1269        }
1270
1271        Set activateLanguageCodes = new HashSet(languageCodes);
1272        if (stateModifContext.isAllLanguages()) {
1273            activateLanguageCodes.addAll(contentContainer.getStagingLanguages(true));
1274        }
1275
1276        ActivationTestResults activationResults =
1277            isContainerValidForActivation(
1278            activateLanguageCodes,
1279            id,
1280            user,
1281            saveVersion,
1282            jParams,
1283            stateModifContext);
1284
1285        // in the case of a container, if any field isn't activated we don't
1286
// activate the full container.
1287

1288        EntryLoadRequest entryLoadRequest = new EntryLoadRequest(
1289            EntryLoadRequest.STAGING_WORKFLOW_STATE,
1290            0, new ArrayList());
1291        entryLoadRequest.setWithMarkedForDeletion(true);
1292        entryLoadRequest.setWithDeleted(false);
1293        entryLoadRequest.getLocales().add(
1294            LanguageCodeConverters.languageCodeToLocale(ContentObject.
1295            SHARED_LANGUAGE));
1296        Vector fieldIDs = getFieldIDsInContainer(contentContainer.getID(),
1297                                                 entryLoadRequest);
1298        boolean hasStagingField = false;
1299        int size = fieldIDs.size();
1300        Integer JavaDoc fieldID = null;
1301        for (int i = 0; i < size; i++) {
1302            fieldID = (Integer JavaDoc) fieldIDs.get(i);
1303            ContentField contentField = ContentField.getField(fieldID.intValue());
1304            if (contentField.hasStagingEntries()) {
1305                hasStagingField = true;
1306                break;
1307            }
1308        }
1309
1310        // We only activate a container that is marked for delete if all its fields
1311
// are themselve deleted ( no staging fields left )
1312
if ( (hasStagingField && contentContainer.isMarkedForDelete())
1313            || (activationResults.getStatus() ==
1314                ActivationTestResults.FAILED_OPERATION_STATUS)) {
1315            activationResults.setStatus(ActivationTestResults.
1316                                        PARTIAL_OPERATION_STATUS);
1317            try {
1318                final EngineMessage msg = new EngineMessage(
1319                        "org.jahia.services.containers.JahiaContainersBaseService.invalidFieldsWarning");
1320                activationResults
1321                        .appendWarning(new IsValidForActivationResults(
1322                        ContentContainerKey.CONTAINER_TYPE, id, jParams
1323                        .getLocale().toString(), msg));
1324            }
1325            catch (ClassNotFoundException JavaDoc cnfe) {
1326                logger.debug("Error while creating activation test node result",
1327                             cnfe);
1328            }
1329            if (stateModified) {
1330                stateModifContext.popAllLanguages();
1331            }
1332            return activationResults;
1333        }
1334
1335        JahiaContainer theContainer = loadContainerInfo(id,
1336            EntryLoadRequest.STAGED);
1337
1338        /*
1339                if (activationResults.getStatus() != ActivationTestResults.COMPLETED_OPERATION_STATUS) {
1340                    return activationResults;
1341                }
1342         */

1343
1344        // we check if the VersionID = -1, which mean we should delete the container. to see if we have rights for
1345
// this container, we load the ACTIVE version, and if the guy has write&admin access on it, or if
1346
// the ACTIVE version doesn't even exist, it's ok.
1347
boolean isDeleteAllowed = false;
1348        if (theContainer.getVersionID() == -1) {
1349            JahiaContainer tempContainer = null;
1350            try {
1351                tempContainer = loadContainerInfo(id, EntryLoadRequest.CURRENT);
1352            }
1353            catch (JahiaException je) {
1354            }
1355            if (tempContainer == null) {
1356                isDeleteAllowed = true;
1357            }
1358            else if (tempContainer.checkAdminAccess(user) &&
1359                     tempContainer.checkWriteAccess(user)) {
1360                isDeleteAllowed = true;
1361            }
1362        }
1363        if ( (theContainer.checkAdminAccess(user) &&
1364              theContainer.checkWriteAccess(user)) || isDeleteAllowed) {
1365            // yes user has access, we can stage this field
1366

1367            // fire event
1368
JahiaEvent theEvent = new JahiaEvent(saveVersion, jParams,
1369                                                 contentContainer);
1370            ServicesRegistry.getInstance().getJahiaEventService()
1371                .fireBeforeContainerActivation(theEvent);
1372
1373            c_containers.db_validate_staged_container(id, saveVersion);
1374            logger.debug("Container " + id + " has just been validated.");
1375
1376            ContentContainer.notifyContainerUpdate(theContainer.getID(),
1377                ContainersChangeEventListener.CONTAINER_ACTIVATED);
1378
1379            // invalidate corresponding cache entry
1380
invalidateContainerFromCache(id);
1381            ContentContainer.invalidateContainerCache(theContainer.getID());
1382            c_utils.invalidateCtnIdsByCtnListCache(theContainer.getListID());
1383        }
1384
1385        if (stateModified) {
1386            stateModifContext.popAllLanguages();
1387        }
1388
1389        return activationResults;
1390
1391    }
1392
1393    /**
1394     * Validate the containers of the page to which the user has admin AND write access
1395     * i.e. now Staged containers are Active.
1396     *
1397     * @param saveVersion it must contain the right versionID and staging/versioning
1398     * info of the current site
1399     *
1400     * @return true if all the containers where successfully validated.
1401     */

1402    public ActivationTestResults activateStagedContainers(
1403        Set languageCodes,
1404        int pageID,
1405        JahiaUser user,
1406        JahiaSaveVersion saveVersion,
1407        ParamBean jParams,
1408        StateModificationContext stateModifContext) throws JahiaException {
1409        ActivationTestResults activationResults = new ActivationTestResults();
1410
1411        activationResults.merge(areContainersValidForActivation(languageCodes,
1412            pageID, user, saveVersion, jParams, stateModifContext));
1413        if (activationResults.getStatus() ==
1414            ActivationTestResults.FAILED_OPERATION_STATUS) {
1415            return activationResults;
1416        }
1417
1418        Vector ctnIDs = c_utils.db_get_only_staged_container_ids_in_page(pageID);
1419        // for each container, we check if the user has write+admin access to it,
1420
// if so we can validate it
1421
for (int i = 0; i < ctnIDs.size(); i++) {
1422            int id = ( (Integer JavaDoc) ctnIDs.elementAt(i)).intValue();
1423
1424            // Added this check here because of Page Move issue
1425
// If this container contains a page currently moved but not
1426
// activated, we won't to activate this container
1427
ActivationTestResults curTestResults =
1428                isContainerValidForActivation(
1429                languageCodes, id, user, saveVersion, jParams,
1430                stateModifContext);
1431
1432            if (curTestResults.getStatus() ==
1433                ActivationTestResults.FAILED_OPERATION_STATUS) {
1434                logger.debug("Container " + id +
1435                             " is not valid for activation. testResults="
1436                             + curTestResults.toString());
1437                continue;
1438            }
1439            activationResults.merge(activateStagedContainer(languageCodes, id,
1440                user, saveVersion, jParams, stateModifContext));
1441        }
1442        return activationResults;
1443    }
1444
1445    public ActivationTestResults areContainersValidForActivation(
1446        Set languageCodes,
1447        int pageID,
1448        JahiaUser user,
1449        JahiaSaveVersion saveVersion,
1450        ParamBean jParams,
1451        StateModificationContext stateModifContext) throws JahiaException {
1452        ActivationTestResults activationTestResults = new ActivationTestResults();
1453        Vector ctnIDs = c_utils.db_get_only_staged_container_ids_in_page(pageID);
1454        // for each container, we check if the user has write+admin access to it,
1455
// if so we can validate it
1456
for (int i = 0; i < ctnIDs.size(); i++) {
1457            int id = ( (Integer JavaDoc) ctnIDs.elementAt(i)).intValue();
1458
1459            ActivationTestResults curTestResults =
1460                isContainerValidForActivation(
1461                languageCodes, id, user, saveVersion, jParams,
1462                stateModifContext);
1463
1464            if (curTestResults.getStatus() !=
1465                ActivationTestResults.COMPLETED_OPERATION_STATUS) {
1466                logger.debug(
1467                    "Container " + id +
1468                    " is not valid for activation. testResults=" +
1469                    curTestResults.toString());
1470            }
1471
1472            if (curTestResults.getStatus() ==
1473                ActivationTestResults.FAILED_OPERATION_STATUS) {
1474                // a container may fail. It will simply not be validated, but the
1475
// total result for ALL the containers should be partial.
1476
curTestResults.setStatus(ActivationTestResults.
1477                                         PARTIAL_OPERATION_STATUS);
1478                curTestResults.moveErrorsToWarnings();
1479            }
1480
1481            activationTestResults.merge(curTestResults);
1482        }
1483        return activationTestResults;
1484
1485    }
1486
1487    public synchronized void serializePageContainerListsToXML(XmlWriter
1488        xmlWriter,
1489        XMLSerializationOptions xmlSerializationOptions,
1490        int pageID, ParamBean paramBean) throws IOException JavaDoc {
1491        try {
1492            Vector listIDs = c_utils.getPageTopLevelContainerListIDs(pageID,
1493                EntryLoadRequest.CURRENT);
1494            // for each container, we check if the user has write+admin access to it,
1495
// if so we can validate it
1496
for (int i = 0; i < listIDs.size(); i++) {
1497                int curContainerListID = ( (Integer JavaDoc) listIDs.elementAt(i)).
1498                    intValue();
1499                serializeContainerListToXML(xmlWriter, xmlSerializationOptions,
1500                                            curContainerListID, paramBean);
1501            }
1502        }
1503        catch (JahiaException je) {
1504            logger.debug("Error while serializing page " + pageID +
1505                         " container lists", je);
1506        }
1507    }
1508
1509    public synchronized void serializeContainerListToXML(XmlWriter xmlWriter,
1510        XMLSerializationOptions xmlSerializationOptions,
1511        int containerListID,
1512        ParamBean paramBean) throws IOException JavaDoc {
1513
1514        try {
1515
1516            JahiaContainerList containerList = loadContainerListInfo(
1517                containerListID, EntryLoadRequest.CURRENT);
1518            if (containerList == null) {
1519                logger.debug("Unable to load container list " + containerListID +
1520                             ", ignoring...");
1521                return;
1522            }
1523
1524            xmlWriter.writeEntity("contentContainerList").
1525                writeAttribute("name", containerList.getDefinition().getName());
1526
1527            Vector ctnIDs = c_utils.db_get_container_ids_in_container_list(
1528                containerListID, EntryLoadRequest.CURRENT, false);
1529            // for each container, we check if the user has write+admin access to it,
1530
// if so we can validate it
1531
for (int i = 0; i < ctnIDs.size(); i++) {
1532                int curContainerID = ( (Integer JavaDoc) ctnIDs.elementAt(i)).intValue();
1533
1534                serializeContainerToXML(xmlWriter, xmlSerializationOptions,
1535                                        curContainerID, paramBean);
1536
1537            }
1538
1539            xmlWriter.endEntity();
1540
1541        }
1542        catch (JahiaException je) {
1543            logger.debug("Error while exporting container list " +
1544                         containerListID + " to XML : ", je);
1545        }
1546
1547    }
1548
1549    public synchronized void serializeContainerToXML(XmlWriter xmlWriter,
1550        XMLSerializationOptions xmlSerializationOptions,
1551        int containerID, ParamBean paramBean) throws IOException JavaDoc {
1552
1553        /**
1554         * @todo FIXME : only handles serialization of active container data
1555         */

1556
1557        try {
1558
1559            // quick & dirty implementation that serializes the active and staging
1560
// entries.
1561
JahiaContainer theContainer = loadContainerInfo(containerID,
1562                EntryLoadRequest.CURRENT);
1563            if (theContainer == null) {
1564                logger.debug("Unable to load container " + containerID +
1565                             ", ignoring...");
1566                return;
1567            }
1568
1569            xmlWriter.writeEntity("contentContainer");
1570
1571            // we must now check to see if this container has fields that
1572
// don't exist in an active version.
1573

1574            // we might want to cache the next field id retrieval code ?
1575
Vector fieldIDs = getFieldIDsInContainer(containerID,
1576                EntryLoadRequest.CURRENT);
1577
1578            for (int j = 0; j < fieldIDs.size(); j++) {
1579                int fieldID = ( (Integer JavaDoc) fieldIDs.elementAt(j)).intValue();
1580                ContentField currentField = ContentField.getField(fieldID);
1581                currentField.serializeToXML(xmlWriter, xmlSerializationOptions,
1582                                            paramBean);
1583            }
1584
1585            // now we must load and display all the sub container lists.
1586
Vector subCtnListIDs = c_utils.getContainerSubContainerListIDs(
1587                containerID, EntryLoadRequest.CURRENT);
1588
1589            for (int i = 0; i < subCtnListIDs.size(); i++) {
1590                int curSubContainerListID = ( (Integer JavaDoc) subCtnListIDs.elementAt(
1591                    i)).intValue();
1592                serializeContainerListToXML(xmlWriter, xmlSerializationOptions,
1593                                            curSubContainerListID, paramBean);
1594            }
1595
1596            xmlWriter.endEntity();
1597
1598        }
1599        catch (JahiaException je) {
1600            logger.debug("Error while serializing container " + containerID +
1601                         " to XML : ", je);
1602        }
1603
1604    }
1605
1606    /**
1607     * loads a container list info without its containers
1608     * loads container list info, but not dependant fields and container lists
1609     * no rights check.
1610     *
1611     * @param containerListID the container list id
1612     *
1613     * @see org.jahia.data.containers.JahiaContainerList
1614     */

1615    public JahiaContainerList loadContainerListInfo(int containerListID) throws
1616        JahiaException {
1617        return loadContainerListInfo(containerListID, EntryLoadRequest.CURRENT);
1618    } // end loadContainerListInfo
1619

1620    public JahiaContainerList loadContainerListInfo(int
1621        containerListID,
1622        EntryLoadRequest loadVersion) throws JahiaException {
1623        
1624        if (logger.isDebugEnabled()) {
1625          logger.debug("Loading containerList " + containerListID + " version=" +
1626                     loadVersion);
1627        }
1628        Object JavaDoc key = getCacheContainerOrContainerListEntryKey(containerListID,
1629                loadVersion.getWorkflowState());
1630        JahiaContainerList result = (JahiaContainerList) containerListInfoCache
1631            .get(key);
1632
1633        if (result == null) {
1634            synchronized (this) {
1635                result = (JahiaContainerList) containerListInfoCache.get(key);
1636                if (result == null) {
1637                    result = c_lists.db_load_container_list(containerListID, loadVersion);
1638                    if (result != null) {
1639                        result.setProperties(c_lists_props.getProperties(result.getID()));
1640                        containerListInfoCache.put(key, result);
1641                    }
1642                }
1643            }
1644        }
1645
1646        if (result != null) {
1647            return (JahiaContainerList) result.clone();
1648        }
1649
1650        return result;
1651
1652    } // end loadContainerListInfo
1653

1654    /**
1655     * loads a container list
1656     * loads container list info and containers, but not dependant container lists
1657     * this method cannot load request-specific values (i.e. applications);
1658     * see the loadContainerList( containerListID, loadFlag, jParams) for that.
1659     * DO NOT CACHE THIS METHOD (it depends on other caches values) !!
1660     *
1661     * @param containerListID the container list id
1662     * @param loadFlag the loadFlag
1663     *
1664     * @see org.jahia.data.containers.JahiaContainerList
1665     * @see org.jahia.data.fields.LoadFlags
1666     */

1667    public JahiaContainerList loadContainerList(int containerListID,
1668                                                int loadFlag) throws
1669        JahiaException {
1670        return loadContainerList(containerListID, loadFlag, null);
1671    } // end loadContainerList
1672

1673    /**
1674     * loads a container list
1675     * loads container list info and containers, but not dependant container lists
1676     * this method can load request-specific values (i.e. applications).
1677     * DO NOT CACHE THIS METHOD (it depends on other caches values) !!
1678     *
1679     * @param containerListID the container list id
1680     * @param loadFlag the loadFlag
1681     * @param jParams the ParamBean object, containing request and response
1682     *
1683     * @see org.jahia.data.containers.JahiaContainerList
1684     * @see org.jahia.data.fields.LoadFlags
1685     * DJ 29.01.01 - added ACL rights
1686     * SH 19.01.02 - added Scrollable container support
1687     */

1688    // DJ 29.01.01 - added ACL rights
1689
// SH 19.01.02 - added Scrollable container support
1690
public JahiaContainerList loadContainerList(int containerListID,
1691                                                int loadFlag,
1692                                                ParamBean jParams) throws
1693        JahiaException {
1694        return loadContainerList(containerListID, loadFlag, jParams,
1695                                 jParams.getEntryLoadRequest(), new Hashtable(),
1696                                 new Hashtable(), new Hashtable());
1697    }
1698
1699    public JahiaContainerList loadContainerList(int containerListID,
1700                                                int loadFlag,
1701                                                ParamBean jParams,
1702                                                EntryLoadRequest loadVersion) throws
1703        JahiaException {
1704        return loadContainerList(containerListID, loadFlag, jParams,
1705                                 loadVersion, new Hashtable(), new Hashtable(),
1706                                 new Hashtable());
1707    }
1708
1709    public JahiaContainerList loadContainerList(int containerListID,
1710                                                int loadFlag,
1711                                                ParamBean jParams,
1712                                                EntryLoadRequest loadVersion,
1713                                                Hashtable
1714                                                cachedFieldsInContainer,
1715                                                Hashtable
1716        cachedContainersFromContainerLists,
1717                                                Hashtable
1718        cachedContainerListsFromContainers) throws JahiaException {
1719
1720        logger.debug("Starting...[" + containerListID + "]");
1721
1722        return loadContainerList(containerListID, null, loadFlag, jParams,
1723                                 loadVersion,
1724                                 cachedFieldsInContainer,
1725                                 cachedContainersFromContainerLists,
1726                                 cachedContainerListsFromContainers);
1727    }
1728
1729    /**
1730     * Loads a set of containers for a given container list
1731     * Loads container list info and containers, but not dependant container lists
1732     * this method can load request-specific values (i.e. applications).
1733     * DO NOT CACHE THIS METHOD (it depends on other caches values) !!
1734     *
1735     * @param containerListID the container list id
1736     * @param ctnids vector of container ids to load.
1737     * @param loadFlag the loadFlag
1738     * @param jParams the ParamBean object, containing request and response
1739     *
1740     * @see org.jahia.data.containers.JahiaContainerList
1741     * @see org.jahia.data.fields.LoadFlags
1742     */

1743    public JahiaContainerList loadContainerList(int containerListID,
1744                                                Vector ctnids,
1745                                                int loadFlag,
1746                                                ParamBean jParams,
1747                                                EntryLoadRequest loadVersion,
1748                                                Hashtable
1749                                                cachedFieldsInContainer,
1750                                                Hashtable
1751        cachedContainersFromContainerLists,
1752                                                Hashtable
1753        cachedContainerListsFromContainers) throws JahiaException {
1754        logger.debug("Starting for ctnlist [" + containerListID + "]");
1755
1756        // loads container list info
1757
JahiaContainerList theContainerList = loadContainerListInfo(
1758            containerListID, loadVersion);
1759
1760        if (theContainerList == null) {
1761            throw new JahiaException("Error while loading content",
1762                                     "JahiaContainersBaseService.loadContainerList> couldn't find container list ID " +
1763                                     Integer.toString(containerListID) +
1764                                     " in database",
1765                                     JahiaException.USER_ERROR,
1766                                     JahiaException.ERROR_SEVERITY);
1767        }
1768
1769        // start check for correct rights.
1770
if (jParams != null) { // no jParams, can't check for rights
1771
JahiaUser currentUser = jParams.getUser();
1772            if (currentUser != null) {
1773                logger.debug("loadContainerList(): checking rights...");
1774                // if the user has no read rights, return an empty list.
1775
if (!theContainerList.checkReadAccess(currentUser)) {
1776                    logger.debug(
1777                        "loadContainerList(): NO read rights! -> returning empty list");
1778                    theContainerList.setIsContainersLoaded(true);
1779                    return theContainerList;
1780                }
1781                logger.debug("loadContainerList(): read rights OK");
1782            }
1783            else {
1784                throw new JahiaException("No user present !",
1785                                         "No current user defined in the params in loadContainerList() method.",
1786                                         JahiaException.USER_ERROR,
1787                                         JahiaException.ERROR_SEVERITY);
1788            }
1789        }
1790        ContainerListFactoryProxy cListFactory =
1791            new ContainerListFactoryProxy(loadFlag,
1792                                          jParams,
1793                                          loadVersion,
1794                                          cachedFieldsInContainer,
1795                                          cachedContainersFromContainerLists,
1796                                          cachedContainerListsFromContainers);
1797
1798        theContainerList.setFactoryProxy(cListFactory);
1799
1800        return theContainerList;
1801
1802    } // end loadContainerList
1803

1804    /**
1805     * saves a container list info
1806     * saves container list info, but not dependant fields and container lists
1807     * if id=0, attributes a new id to container list and creates it in datasource
1808     *
1809     * @param theContainerList a JahiaContainerList object
1810     * @param parentAclID the Acl parent ID
1811     *
1812     * @see org.jahia.data.containers.JahiaContainerList
1813     * EV 26.02.2001 added parentAclID
1814     */

1815    // EV 26.02.2001 added parentAclID
1816
public void saveContainerListInfo(JahiaContainerList
1817        theContainerList, int parentAclID) throws JahiaException {
1818        if (theContainerList.getAclID() == 0) {
1819            // Start Create a new ACL object for the new container.
1820
JahiaBaseACL acl = new JahiaBaseACL();
1821            if (acl != null) {
1822                // create a new object by specifying the parent ACL ID (a containerList)
1823
if (!acl.create(parentAclID)) {
1824                    String JavaDoc message =
1825                        "Could not create an ACL object for a new container.";
1826                    logger.debug(message + " -> Stop container creation!");
1827                    throw new JahiaException("JahiaContainersBaseService",
1828                                             message,
1829                                             JahiaException.ACL_ERROR,
1830                                             JahiaException.CRITICAL_SEVERITY);
1831                }
1832                else {
1833                    logger.debug("ACL [" + acl.getID() +
1834                                 "] has just been created! (Container)");
1835                }
1836            }
1837            else {
1838                throw new JahiaException("JahiaContainersBaseService",
1839                                         "Counld not instanciate the JahiaBaseACL class",
1840                                         JahiaException.ACL_ERROR,
1841                                         JahiaException.CRITICAL_SEVERITY);
1842            }
1843            // End Create ACL
1844
theContainerList.setAclID(acl.getID());
1845        }
1846        // to get the JahiaSaveVersion, we need to load the page info at 1st, to know to what site the
1847
// container list belongs to.
1848
// throws a JahiaException if the page can't be found
1849
ContentPage thePage = ServicesRegistry.getInstance().
1850            getJahiaPageService().lookupContentPage(
1851            theContainerList.getPageID(), true);
1852        JahiaSaveVersion saveVersion = ServicesRegistry.getInstance().
1853            getJahiaVersionService().
1854            getSiteSaveVersion(thePage.getJahiaID());
1855        
1856        synchronized (this) {
1857            if (theContainerList.getID() == 0) {
1858                c_lists.db_create_container_list(theContainerList, saveVersion);
1859            } else {
1860                c_lists.db_update_container_list(theContainerList, saveVersion);
1861            }
1862            JahiaContainerDefinition cDef = JahiaContainerDefinitionsRegistry.getInstance().getDefinition(
1863                    theContainerList.getctndefid());
1864            if (cDef != null) {
1865                c_lists_props.setProperties(theContainerList.getID(), cDef.getJahiaID(), theContainerList
1866                        .getProperties());
1867            }
1868
1869            invalidateContainerListFromCache(theContainerList.getID());
1870
1871            c_utils.invalidateCtnIdsByCtnListCache(theContainerList.getID());
1872            c_utils.invalidateSubCtnListIDsByCtnCache(theContainerList.getParentEntryID());
1873        }
1874
1875    } // end saveContainerListInfo
1876

1877    /**
1878     * deletes a container list info
1879     * deletes a container list info, but not dependant containers
1880     * see deleteContainerList for that
1881     *
1882     * @param listID the container list id to delete
1883     */

1884    private synchronized void deleteContainerListInfo(int listID,
1885        JahiaSaveVersion saveVersion) throws JahiaException {
1886
1887        c_lists.db_delete_container_list(listID, saveVersion);
1888        c_lists_props.removeProperties(listID);
1889
1890        this.invalidateContainerListFromCache(listID);
1891    } // end deleteContainerListInfo
1892

1893    /**
1894     * deletes a container list info
1895     * deletes a container list info, including dependant containers
1896     * see deleteContainerList for that
1897     *
1898     * @param listID the container list id to delete
1899     */

1900    public synchronized void deleteContainerList(int listID, ParamBean jParams) throws
1901        JahiaException {
1902        // No ACL check implemented, because when you delete a page you want to
1903
// delete every containerlist / container it contains, even if you don't have
1904
// the specific rights to do so.
1905

1906        // gets list object
1907
JahiaContainerList theList = loadContainerListInfo(listID,
1908            EntryLoadRequest.STAGED);
1909
1910        // to get the JahiaSaveVersion, we need to load the page info at 1st, to know to what site the
1911
// container list belongs to.
1912
// throws a JahiaException if the page can't be found
1913
ContentPage thePage = ServicesRegistry.getInstance().
1914            getJahiaPageService().lookupContentPage(
1915            theList.getPageID(), true);
1916        JahiaSaveVersion saveVersion = ServicesRegistry.getInstance().
1917            getJahiaVersionService().
1918            getSiteSaveVersion(thePage.getJahiaID());
1919        EntryLoadRequest loadVersion = ServicesRegistry.getInstance().
1920            getJahiaVersionService().
1921            isStagingEnabled(thePage.getJahiaID()) ?
1922            EntryLoadRequest.STAGED :
1923            EntryLoadRequest.CURRENT;
1924
1925        // deletes list info
1926
deleteContainerListInfo(listID, saveVersion);
1927
1928        containerListInfoCache.remove(
1929            getCacheContainerOrContainerListStagingEntryKey(
1930            listID));
1931
1932        // deletes all containers of container list
1933
Vector cIDs = getctnidsInList(listID, loadVersion);
1934        for (int i = 0; i < cIDs.size(); i++) {
1935            int ctnid = ( (Integer JavaDoc) cIDs.elementAt(i)).intValue();
1936            deleteContainer(ctnid, jParams);
1937        }
1938
1939        c_utils.invalidateSubCtnListIDsByCtnCache(
1940            theList.getParentEntryID());
1941
1942        // deletes ACL (remporary removed because of versioning
1943
/* try {
1944                    if (theList != null) {
1945             JahiaBaseACL theACL = new JahiaBaseACL (theList.getAclID());
1946                        theACL.delete ();
1947                    }
1948                }
1949                catch (ACLNotFoundException ex) {
1950                    JahiaException je = new JahiaException ("", "Could not find the ACL ["+Integer.toString (theList.getAclID())+
1951             "] while removing field ["+Integer.toString(listID)+"]",
1952             JahiaException.ACL_ERROR, JahiaException.WARNING);
1953                }*/

1954    } // end deleteContainerList
1955

1956    /**
1957     * Validate the container lists of the page to which the user has admin AND write access
1958     * i.e. now Staged containers are Active.
1959     *
1960     * @param saveVersion it must contain the right versionID and staging/versioning
1961     * info of the current site
1962     */

1963    public ActivationTestResults activateStagedContainerLists(
1964        Set languageCodes,
1965        int pageID, JahiaUser user,
1966        JahiaSaveVersion saveVersion,
1967        StateModificationContext stateModifContext) throws JahiaException {
1968        ActivationTestResults activationResults = new ActivationTestResults();
1969
1970        activationResults.merge(areContainerListsValidForActivation(
1971            languageCodes, pageID, user, saveVersion, stateModifContext));
1972        if (activationResults.getStatus() ==
1973            ActivationTestResults.FAILED_OPERATION_STATUS) {
1974            return activationResults;
1975        }
1976
1977        Vector listIDs = c_utils.db_get_only_staged_container_list_ids_in_page(
1978            pageID);
1979        // for each container, we check if the user has write+admin access to it,
1980
// if so we can validate it
1981
for (int i = 0; i < listIDs.size(); i++) {
1982            int id = ( (Integer JavaDoc) listIDs.elementAt(i)).intValue();
1983            JahiaContainerList theContainerList = loadContainerListInfo(id,
1984                EntryLoadRequest.STAGED);
1985            if (theContainerList.checkAdminAccess(user) &&
1986                theContainerList.checkWriteAccess(user)) {
1987                // yes user has access, we can validate this containerlist
1988
c_lists.db_validate_staged_container_list(id, saveVersion);
1989
1990                // update cache
1991
containerListInfoCache.remove(
1992                    getCacheContainerOrContainerListStagingEntryKey(
1993                    id));
1994                c_utils.invalidateSubCtnListIDsByCtnCache(theContainerList.
1995                    getParentEntryID());
1996
1997                logger.debug("VALIDATION CONTAINER LIST #" + id);
1998            }
1999        }
2000        return activationResults;
2001    }
2002
2003    public ActivationTestResults areContainerListsValidForActivation(
2004        Set languageCodes,
2005        int pageID,
2006        JahiaUser user,
2007        JahiaSaveVersion saveVersion,
2008        StateModificationContext stateModifContext) throws JahiaException {
2009        // containers lists are for the moment always ready for activation
2010
return new ActivationTestResults();
2011    }
2012
2013    /**
2014     * loads a container definition by its id
2015     *
2016     * @param definitionID the container definition id
2017     *
2018     * @return a JahiaContainerDefinition object
2019     *
2020     * @see org.jahia.data.containers.JahiaContainerDefinition
2021     * @see org.jahia.data.containers.JahiaContainerStructure
2022     */

2023    public JahiaContainerDefinition loadContainerDefinition(int definitionID) throws
2024        JahiaException {
2025        JahiaContainerDefinition result = c_defs.db_load_container_definition(
2026            definitionID);
2027        if (result != null) {
2028            Properties defProps = c_defs_props.getProperties(result.getID());
2029            result.setProperties(defProps);
2030        }
2031        return result;
2032    } // end loadContainerDefinition
2033

2034    /**
2035     * Load a container definition by it's site ID and it's definition name
2036     *
2037     * @param siteID the site identifier on which to retrieve the definition
2038     * @param definitionName the unique name for the definition
2039     *
2040     * @return a JahiaContainerDefinition if found
2041     *
2042     * @throws JahiaException in case there was a problem communicating with
2043     * the database
2044     */

2045    public JahiaContainerDefinition loadContainerDefinition(int siteID,
2046        String JavaDoc definitionName) throws JahiaException {
2047        JahiaContainerDefinition result = c_defs.db_load_container_definition(
2048            siteID, definitionName);
2049        if (result != null) {
2050            Properties defProps = c_defs_props.getProperties(result.getID());
2051            result.setProperties(defProps);
2052        }
2053        return result;
2054    } // end loadContainerDefinition
2055

2056    /**
2057     * saves a container definition
2058     * if id=0, assigns a new id to the definition and creates it in the datasource
2059     *
2060     * @param theDefinition the JahiaContainerDefinition to save
2061     *
2062     * @see org.jahia.data.containers.JahiaContainerDefinition
2063     * @see org.jahia.data.containers.JahiaContainerStructure
2064     */

2065    public synchronized void saveContainerDefinition(JahiaContainerDefinition
2066        theDefinition) throws JahiaException {
2067        if (theDefinition.getID() == 0) {
2068            c_defs.db_create_container_definition(theDefinition);
2069        }
2070        else {
2071            c_defs.db_update_container_defprop(theDefinition);
2072        }
2073        c_defs_props.setProperties(theDefinition.getID(),
2074                                   theDefinition.getProperties());
2075    } // end saveContainerDefinition
2076

2077    /**
2078     * deletes a container definition
2079     *
2080     * @param definitionID the JahiaContainerDefinition to delete
2081     *
2082     * @see org.jahia.data.containers.JahiaContainerDefinition
2083     * @see org.jahia.data.containers.JahiaContainerStructure
2084     */

2085    public synchronized void deleteContainerDefinition(int definitionID) throws
2086        JahiaException {
2087        c_defs.db_delete_container_definition(definitionID);
2088        JahiaContainerDefinitionsRegistry.getInstance().
2089            removeContainerDefinition(definitionID);
2090
2091    } // end deleteContainerDefinition
2092

2093    //--------------------------------------------------------------------------
2094
/**
2095     * returns a DOM representation of all containers of a site
2096     *
2097     * @param siteID the site identification number
2098     */

2099    public JahiaDOMObject getContainersAsDOM(int siteID) throws JahiaException {
2100
2101        return c_containers.getContainersAsDOM(siteID);
2102
2103    }
2104
2105    //--------------------------------------------------------------------------
2106
/**
2107     * returns a DOM representation of all container lists of a site
2108     *
2109     * @param siteID
2110     */

2111    public JahiaDOMObject getContainerListsAsDOM(int siteID) throws
2112        JahiaException {
2113
2114        return c_lists.getContainerListsAsDOM(siteID);
2115
2116    }
2117
2118    //--------------------------------------------------------------------------
2119
/**
2120     * returns a DOM representation of all container lists props of a site
2121     *
2122     * @param siteID the site identification number
2123     */

2124    public JahiaDOMObject getContainerListPropsAsDOM(int siteID) throws
2125        JahiaException {
2126
2127        return c_lists_props.getPropertiesAsDOM(siteID);
2128
2129    }
2130
2131    //--------------------------------------------------------------------------
2132
/**
2133     * returns a DOM representation of all container def of a site
2134     *
2135     * @param siteID the site identification number
2136     */

2137    public JahiaDOMObject getContainerDefsAsDOM(int siteID) throws
2138        JahiaException {
2139
2140        return c_defs.getContainerDefsAsDOM(siteID);
2141
2142    }
2143
2144    //--------------------------------------------------------------------------
2145
/**
2146     * returns a DOM representation of all container def prop of a site
2147     *
2148     * @param siteID the site identification number
2149     */

2150    public JahiaDOMObject getContainerDefPropsAsDOM(int siteID) throws
2151        JahiaException {
2152
2153        return c_defs.getContainerDefPropsAsDOM(siteID);
2154
2155    }
2156
2157    //--------------------------------------------------------------------------
2158
/**
2159     * returns a DOM representation of all containers extented properties of a site
2160     *
2161     * @param siteID the site identification number
2162     */

2163    public JahiaDOMObject getContainerExtendedPropsAsDOM(int siteID) throws
2164        JahiaException {
2165        return c_defs_props.getPropertiesAsDOM(siteID);
2166    }
2167
2168    //--------------------------------------------------------------------------
2169
/**
2170     * returns a DOM representation of all container structure of a site
2171     *
2172     * @param siteID the site identification number
2173     */

2174    public JahiaDOMObject getContainerStructsAsDOM(int siteID) throws
2175        JahiaException {
2176
2177        return c_struct.getContainerStructsAsDOM(siteID);
2178
2179    }
2180
2181    //--------------------------------------------------------------------------
2182
/**
2183     * Returns a vector of all Acl ID used by container for a site
2184     * Used for site extraction
2185     *
2186     * @param siteID the site identification number
2187     */

2188    public Vector getAclIDs(int siteID) throws JahiaException {
2189
2190        return c_utils.db_get_all_acls_id(siteID);
2191
2192    }
2193
2194    //--------------------------------------------------------------------------
2195
/**
2196     * Returns a vector of all ctn lists fields ( field def ) Acl ID for a site
2197     * Used for site extraction
2198     *
2199     * @param siteID the site identification number
2200     */

2201    public Vector getCtnListFieldAclIDs(int siteID) throws JahiaException {
2202
2203        return c_lists_props.getCtnListFieldACLs(siteID);
2204
2205    }
2206
2207    public SortedSet getAllPageTopLevelContainerListIDs(int pageID,
2208        EntryLoadRequest loadRequest) throws JahiaException {
2209        return c_utils.getAllPageTopLevelContainerListIDs(pageID, loadRequest);
2210    }
2211
2212    public SortedSet getContainerListInPageEntryStates(int pageID) throws
2213        JahiaException {
2214        SortedSet entryStates = new TreeSet();
2215        Set containerListIDs = c_utils.getAllPageTopLevelContainerListIDs(
2216            pageID);
2217        Iterator containerListIDIter = containerListIDs.iterator();
2218        while (containerListIDIter.hasNext()) {
2219            Integer JavaDoc curContainerListID = (Integer JavaDoc) containerListIDIter.next();
2220            entryStates.addAll(getContainerListEntryStates(curContainerListID.
2221                intValue()));
2222        }
2223        return entryStates;
2224    }
2225
2226    private SortedSet getContainerListEntryStates(int listID) throws
2227        JahiaException {
2228        SortedSet entryStates = new TreeSet();
2229        /**
2230         * @todo FIXME the following will not work if we request a listID of
2231         * a versioned container list. We must make this work for any workflow
2232         * state.
2233         */

2234// JahiaContainerList theList = null;
2235
// EntryLoadRequest loadRequest = EntryLoadRequest.STAGED;
2236
// try {
2237
// theList = loadContainerListInfo(listID, loadRequest);
2238
// }
2239
// catch (JahiaException je) {
2240
// error while loading the container in staged mode, let's try to
2241
// load it from a deleted entry state.
2242
// loadRequest = EntryLoadRequest.DELETED;
2243
// try to load once again
2244
// theList = loadContainerListInfo(listID, loadRequest);
2245
// }
2246

2247        Set containerIDs = c_utils.getAllContainerIDsInList(listID);
2248        Iterator containerIDIter = containerIDs.iterator();
2249        while (containerIDIter.hasNext()) {
2250            int ctnid = ( (Integer JavaDoc) containerIDIter.next()).intValue();
2251            entryStates.addAll(getContainerEntryStates(ctnid));
2252        }
2253
2254        return entryStates;
2255    }
2256
2257    private SortedSet getContainerEntryStates(int id) throws JahiaException {
2258        SortedSet entryStates = new TreeSet();
2259
2260        /**
2261         * @todo FIXME the following will not work if we request a ID of
2262         * a versioned container. We must make this work for any workflow
2263         * state.
2264         */

2265        JahiaContainer theContainer = null;
2266        EntryLoadRequest loadRequest = EntryLoadRequest.STAGED;
2267        try {
2268            theContainer = loadContainerInfo(id, loadRequest);
2269        }
2270        catch (JahiaException je) {
2271            // error while loading the container in staged mode, let's try to
2272
// load it from a deleted entry state.
2273
loadRequest = EntryLoadRequest.DELETED;
2274            // try to load once again
2275
theContainer = loadContainerInfo(id, loadRequest);
2276        }
2277
2278        // we must now check to see if this container has fields that
2279
// don't exist in an active version.
2280

2281        // we might want to cache the next field id retrieval code ?
2282
Set fieldIDs = c_utils.getAllFieldIDsInContainer(id);
2283        Iterator fieldIDIter = fieldIDs.iterator();
2284        while (fieldIDIter.hasNext()) {
2285            int fieldID = ( (Integer JavaDoc) fieldIDIter.next()).intValue();
2286            ContentField currentField = ContentField.getField(fieldID);
2287            entryStates.addAll(currentField.getEntryStates());
2288        }
2289
2290        // now let's check that the case of subcontainer lists. If they cannot
2291
// be marked for deletion, neither can this container.
2292
Enumeration subContainerListsEnum = theContainer.getContainerLists();
2293        while (subContainerListsEnum.hasMoreElements()) {
2294            JahiaContainerList theContainerList = (JahiaContainerList)
2295                subContainerListsEnum.
2296                nextElement();
2297            entryStates.addAll(getContainerListEntryStates(theContainerList.
2298                getID()));
2299        }
2300
2301        return entryStates;
2302    }
2303
2304    public boolean markPageContainerListsLanguageForDeletion(int pageID,
2305        JahiaUser user,
2306        String JavaDoc languageCode,
2307        StateModificationContext stateModifContext) throws JahiaException {
2308
2309        ArrayList locales = new ArrayList();
2310        locales.add(LanguageCodeConverters.languageCodeToLocale(languageCode));
2311        EntryLoadRequest entryLoadRequest = new EntryLoadRequest(
2312            EntryLoadRequest.STAGING_WORKFLOW_STATE, 0, locales, true);
2313        ContentPage contentPage = ServicesRegistry.getInstance().
2314            getJahiaPageService().
2315            lookupContentPage(pageID, entryLoadRequest, false);
2316        Vector containerIDs = getContainerListIDsInPage(contentPage,
2317            entryLoadRequest);
2318
2319        boolean allDeleted = true;
2320        Enumeration containerIDEnum = containerIDs.elements();
2321        while (containerIDEnum.hasMoreElements()) {
2322            Integer JavaDoc curContainerListID = (Integer JavaDoc) containerIDEnum.nextElement();
2323            boolean succeeded = markContainerListLanguageForDeletion(
2324                curContainerListID.
2325                intValue(), user, languageCode, stateModifContext);
2326            if (!succeeded) {
2327                allDeleted = false;
2328            }
2329        }
2330        return allDeleted;
2331    }
2332
2333    public synchronized boolean markContainerListLanguageForDeletion(int listID,
2334        JahiaUser user,
2335        String JavaDoc languageCode,
2336        StateModificationContext
2337        stateModifContext) throws JahiaException {
2338
2339
2340        ContentContainerList contentContainerList = null;
2341        try {
2342            contentContainerList = ContentContainerList.
2343                getContainerList(
2344                listID);
2345        } catch ( Throwable JavaDoc t ){
2346            return false;
2347        }
2348
2349        /**
2350         * NK:
2351         * Testing if the container list will be completely deleted has no meaning,
2352         * because it is SHARED in nature.
2353         * Instead, we should state that :
2354         * a container list will be completely deleted only if its parent Page
2355         * is going to be completely deleted
2356         */

2357        boolean stateModified = false;
2358        if (contentContainerList.getParentContainerID() != 0) {
2359            if (contentContainerList.willBeCompletelyDeleted(languageCode, null)) {
2360                stateModified = true;
2361                stateModifContext.pushAllLanguages(true);
2362            }
2363        }
2364
2365        // mark all containers in this list for deletion if possible, otherwise
2366
// abort as soon as possible.
2367
boolean allDeleted = false;
2368        ArrayList locales = new ArrayList();
2369        locales.add(
2370            org.jahia.utils.LanguageCodeConverters.languageCodeToLocale(
2371            languageCode));
2372        EntryLoadRequest loadRequest = new EntryLoadRequest(EntryLoadRequest.
2373            STAGING_WORKFLOW_STATE, 0, locales, true);
2374        Vector cIDs = getctnidsInList(listID, loadRequest);
2375        for (int i = 0; i < cIDs.size(); i++) {
2376            int ctnid = ( (Integer JavaDoc) cIDs.elementAt(i)).intValue();
2377            boolean succeeded = markContainerLanguageForDeletion(ctnid, user,
2378                languageCode, stateModifContext);
2379            if (!succeeded) {
2380                allDeleted = false;
2381            }
2382        }
2383
2384        //if (allDeleted) {
2385
if (contentContainerList.getParentContainerID() != 0
2386            && contentContainerList.willAllChildsBeCompletelyDeleted(user,
2387            languageCode, null)) {
2388            JahiaSaveVersion saveVersion = new JahiaSaveVersion(true, true);
2389            c_lists.db_delete_container_list(listID, saveVersion);
2390            c_lists_props.removeProperties(listID);
2391            allDeleted = true;
2392        }
2393
2394        if (stateModified) {
2395            stateModifContext.popAllLanguages();
2396        }
2397
2398        invalidateContainerListFromCache(listID);
2399
2400        c_utils.invalidateCtnIdsByCtnListCache(listID);
2401        c_utils.invalidateSubCtnListIDsByCtnCache(
2402            contentContainerList.getParentContainerID());
2403
2404        return allDeleted;
2405    }
2406
2407    public boolean markContainerLanguageForDeletion(
2408        int id, JahiaUser user, String JavaDoc languageCode,
2409        StateModificationContext stateModifContext) throws JahiaException {
2410// ActivationTestResults activationResults = new ActivationTestResults();
2411

2412        ContentContainer contentContainer = ContentContainer.getContainer(id);
2413
2414        /**
2415         * NK:
2416         * Testing if the container will be completely deleted has no meaning,
2417         * because it is SHARED in nature.
2418         * Instead, we should state that :
2419         * a container will be completely deleted only if its container list
2420         * ( that is the parent page ) is going to be completely deleted
2421         */

2422        boolean stateModified = false;
2423        if (contentContainer.willBeCompletelyDeleted(languageCode, null)) {
2424            stateModified = true;
2425            stateModifContext.pushAllLanguages(true);
2426        }
2427
2428        // we must now check to see if this container has fields that
2429
// don't exist in an active version.
2430

2431        // we might want to cache the next field id retrieval code ?
2432
ArrayList locales = new ArrayList();
2433        locales.add(
2434            org.jahia.utils.LanguageCodeConverters.languageCodeToLocale(
2435            languageCode));
2436        EntryLoadRequest loadRequest = new EntryLoadRequest(EntryLoadRequest.
2437            STAGING_WORKFLOW_STATE, 0, locales, true);
2438
2439        // now let's check that the case of subcontainer lists. If they cannot
2440
// be marked for deletion, neither can this container.
2441
ArrayList children = contentContainer.getChilds(user, loadRequest);
2442        ListIterator childrenIter = children.listIterator();
2443        while (childrenIter.hasNext()) {
2444            ContentObject curChild = (ContentObject) childrenIter.next();
2445            if (curChild instanceof ContentContainerList) {
2446                ContentContainerList subContainerList = (ContentContainerList)
2447                    curChild;
2448                subContainerList.markLanguageForDeletion(user, languageCode,
2449                    stateModifContext);
2450            }
2451        }
2452
2453        // if we got here it means that the container is ready to be deleted
2454
// so we can mark it to be deleted.
2455

2456        // start check for correct rights.
2457
if (user != null) {
2458            JahiaUser currentUser = user;
2459            if (currentUser != null) {
2460                logger.debug("checking rights...");
2461                // if the user has no write rights, exit method.
2462
if (!contentContainer.checkWriteAccess(currentUser)) {
2463                    logger.debug("NO write rights! -> don't delete");
2464                    if (stateModified) {
2465                        stateModifContext.popAllLanguages();
2466                    }
2467                    return false;
2468                }
2469                logger.debug("write rights OK");
2470            }
2471            else {
2472                throw new JahiaException("No user present !",
2473                                         "No current user defined in the params in deleteContainer() method.",
2474                                         JahiaException.USER_ERROR,
2475                                         JahiaException.ERROR_SEVERITY);
2476            }
2477        }
2478        // end check rights.
2479

2480        Integer JavaDoc containerParam = new Integer JavaDoc(contentContainer.getID());
2481
2482// boolean canMarkForDeletion = true;
2483
ListIterator childrenFieldIter = children.listIterator();
2484        while (childrenFieldIter.hasNext()) {
2485            ContentObject curChild = (ContentObject) childrenFieldIter.next();
2486            if (curChild instanceof ContentField) {
2487                ContentField currentField = (ContentField) curChild;
2488                // this is done to set a new cache entry, which is manipulated
2489
// in the transaction just by the current thread
2490
ContentField newlyLoadedField = ContentField.getField(currentField.getID(), true);
2491                newlyLoadedField.markLanguageForDeletion(user, languageCode,
2492                    stateModifContext);
2493// if (!currentField.willBeCompletelyDeleted(null, null)) {
2494
// container fields still have active or staged entries, so
2495
// we cannot mark the container for deletion.
2496
// canMarkForDeletion = false;
2497
// }
2498
}
2499        }
2500
2501        // We only delete the container if all its lang are going to be deleted
2502
// and no childs exist
2503
if (stateModified && stateModifContext.isAllLanguages()
2504            && contentContainer.willAllChildsBeCompletelyDeleted(user,
2505            languageCode, null)) {
2506            JahiaSaveVersion saveVersion = new JahiaSaveVersion(true, true);
2507            c_containers.db_delete_container(contentContainer.getID(),
2508                                             saveVersion);
2509            
2510            invalidateContainerFromCache(containerParam.intValue());
2511            ContentContainer.invalidateContainerCache(contentContainer.getID());
2512            c_utils.invalidateCtnIdsByCtnListCache(contentContainer.
2513                getParentContainerListID());
2514        }
2515        else {
2516            // we have to create a staged entry to be able to active mark for deleted on this container's fields
2517
if (contentContainer.getStagingLanguages(false, true).isEmpty()) {
2518                // if no staging or nor marked for delete exists
2519
Iterator iterator = contentContainer
2520                    .getActiveAndStagingEntryStates().iterator();
2521                if (iterator.hasNext()) {
2522                    ContentObjectEntryState fromEntryState =
2523                        (ContentObjectEntryState) iterator.next();
2524                    ContentObjectEntryState toEntryState =
2525                        new ContentObjectEntryState(ContentObjectEntryState
2526                        .WORKFLOW_STATE_START_STAGING, 0,
2527                        ContentObject.SHARED_LANGUAGE);
2528                    contentContainer.copyEntry(fromEntryState, toEntryState);
2529
2530                    invalidateContainerFromCache(containerParam.intValue());
2531                    ContentContainer.invalidateContainerCache(contentContainer.
2532                        getID());
2533                    this.c_utils.invalidateCtnIdsByCtnListCache(
2534                        contentContainer.getParentContainerListID());
2535                }
2536            }
2537        }
2538        if (stateModified) {
2539            stateModifContext.popAllLanguages();
2540        }
2541
2542// ContentContainer.notifyContainerUpdate(id,
2543
// ContainersChangeEventListener.CONTAINER_MARKED_FOR_DELETION);
2544

2545        return true;
2546    }
2547
2548    public void purgeContainer(int id) throws JahiaException {
2549
2550        /**
2551         * @todo FIXME the following will not work if we request a ID of
2552         * a versioned container. We must make this work for any workflow
2553         * state.
2554         */

2555        JahiaContainer theContainer = null;
2556        EntryLoadRequest loadRequest = EntryLoadRequest.STAGED;
2557        try {
2558            theContainer = loadContainerInfo(id, loadRequest);
2559        }
2560        catch (JahiaException je) {
2561            // error while loading the container in staged mode, let's try to
2562
// load it from a deleted entry state.
2563
loadRequest = EntryLoadRequest.DELETED;
2564            // try to load once again
2565
theContainer = loadContainerInfo(id, loadRequest);
2566        }
2567
2568        // we must now check to see if this container has fields that
2569
// don't exist in an active version.
2570

2571        // we might want to cache the next field id retrieval code ?
2572
Set fieldIDs = c_utils.getAllFieldIDsInContainer(id);
2573        Iterator fieldIDIter = fieldIDs.iterator();
2574        while (fieldIDIter.hasNext()) {
2575            int fieldID = ( (Integer JavaDoc) fieldIDIter.next()).intValue();
2576            ContentField currentField = ContentField.getField(fieldID);
2577            currentField.purge();
2578        }
2579
2580        // now let's check that the case of subcontainer lists. If they cannot
2581
// be marked for deletion, neither can this container.
2582
Enumeration subContainerListsEnum = theContainer.getContainerLists();
2583        while (subContainerListsEnum.hasMoreElements()) {
2584            JahiaContainerList theContainerList = (JahiaContainerList)
2585                subContainerListsEnum.
2586                nextElement();
2587            purgeContainerList(theContainerList.getID());
2588        }
2589
2590        // if we got here it means that the container is ready to be deleted
2591
// so we can mark it to be deleted.
2592

2593        Integer JavaDoc containerIDInt = new Integer JavaDoc(theContainer.getID());
2594        // we should now mark the sub container lists too...
2595

2596        JahiaBaseACL acl = theContainer.getACL();
2597        acl.delete();
2598        acl = null;
2599
2600        c_containers.purgeContainer(theContainer.getID());
2601        // we only delete it from cache if it's not the staged version
2602
invalidateContainerFromCache(containerIDInt.intValue());
2603        ContentContainer.invalidateContainerCache(theContainer.getID());
2604        this.c_utils.invalidateCtnIdsByCtnListCache(theContainer.getListID());
2605    }
2606
2607    public void purgeContainerList(int listID) throws JahiaException {
2608        // gets list object
2609
/**
2610         * @todo FIXME the following will not work if we request a listID of
2611         * a versioned container list. We must make this work for any workflow
2612         * state.
2613         */

2614        JahiaContainerList theList = loadContainerListInfo(listID,
2615            EntryLoadRequest.STAGED);
2616
2617        // mark all containers in this list for deletion if possible, otherwise
2618
// abort as soon as possible.
2619
Set containerIDs = c_utils.getAllContainerIDsInList(listID);
2620        Iterator containerIDIter = containerIDs.iterator();
2621        while (containerIDIter.hasNext()) {
2622            int ctnid = ( (Integer JavaDoc) containerIDIter.next()).intValue();
2623            purgeContainer(ctnid);
2624        }
2625
2626        JahiaBaseACL acl = theList.getACL();
2627        acl.delete();
2628        acl = null;
2629
2630        // we must now remove all the field def ACL properties.
2631
ContentPage sourceContentPage = ServicesRegistry.getInstance().
2632            getJahiaPageService().
2633            lookupContentPage(theList.
2634                              getPageID(), true);
2635        if (sourceContentPage != null) {
2636            int pageDefID = sourceContentPage.getPageTemplateID(
2637                EntryLoadRequest.STAGED);
2638            Enumeration structure = theList.getDefinition().getStructure(
2639                "", pageDefID, JahiaContainerStructure.JAHIA_FIELD);
2640            while (structure.hasMoreElements()) {
2641                JahiaContainerStructure theStruct =
2642                    (JahiaContainerStructure) structure.nextElement();
2643                JahiaFieldDefinition theDef =
2644                    (JahiaFieldDefinition) theStruct.getObjectDef();
2645                String JavaDoc val = theList.getProperty("view_field_acl_" +
2646                                                 theDef.getName());
2647                if (val != null) {
2648                    try {
2649                        int aclID = Integer.parseInt(val);
2650                        JahiaBaseACL theACL = null;
2651                        try {
2652                            theACL = new JahiaBaseACL(aclID);
2653                            theACL.delete();
2654                        }
2655                        catch (ACLNotFoundException ex) {
2656                            logger.debug("Error loading ACL", ex);
2657                        }
2658                        catch (JahiaException ex) {
2659                            logger.debug("Error loading ACL", ex);
2660                        }
2661                    }
2662                    catch (Throwable JavaDoc t) {
2663                    }
2664                }
2665            }
2666        }
2667
2668        // now let's delete the database related data.
2669
c_lists.purgeContainerList(listID);
2670        c_lists_props.removeProperties(listID);
2671
2672        this.invalidateContainerListFromCache(listID);
2673    }
2674
2675    public void purgePageContainerLists(int pageID) throws JahiaException {
2676        Set containerListIDs = c_utils.getAllPageTopLevelContainerListIDs(
2677            pageID);
2678
2679        Iterator containerListIDIter = containerListIDs.iterator();
2680        while (containerListIDIter.hasNext()) {
2681            Integer JavaDoc curContainerListID = (Integer JavaDoc) containerListIDIter.next();
2682            purgeContainerList(curContainerListID.intValue());
2683        }
2684    }
2685
2686    /**
2687     * Returns a set of subContainerDefinitionIDs that contain the container
2688     * definition ID we are looking for.
2689     *
2690     * @param containerDefinitionID an integer specifying the container
2691     * definition for which to find the parent sub definitions.
2692     *
2693     * @return a SortedSet containing Integer that are subContainerDefinitionIDs
2694     * that contain the container definition we are looking for.
2695     *
2696     * @throws JahiaException if there was an error while communicating with the
2697     * database
2698     */

2699    public SortedSet getContainerDefinitionParents(int containerDefinitionID) throws
2700        JahiaException {
2701        return c_utils.getContainerDefinitionParents(containerDefinitionID);
2702    }
2703
2704    /**
2705     * Retrieves all the container list IDs in a site that correspond to the
2706     * passed name. Note that the structure of these lists may be different
2707     * because they may have originated in different templates !
2708     *
2709     * @param siteID the site for which to retrieve the container lists by name
2710     * @param name the name (definition name) for which to retrieve the
2711     * container lists in the site.
2712     * @param loadRequest the EntryLoadRequest for which to retrieve the
2713     * container list IDs. Maybe null if we want to get absolutely EVERY
2714     * container list regardless of status/version, etc...
2715     *
2716     * @return a SortedSet containing Integer that are subContainerDefinitionIDs
2717     * that contain the container definition we are looking for.
2718     *
2719     * @throws JahiaException if there was an error while communicating with the
2720     * database
2721     */

2722    public SortedSet getSiteTopLevelContainerListsIDsByName(int siteID,
2723        String JavaDoc name,
2724        EntryLoadRequest loadRequest) throws JahiaException {
2725        JahiaContainerDefinition jahiaContainerDefinition = c_defs.
2726            db_load_container_definition(siteID, name);
2727        if (jahiaContainerDefinition != null) {
2728            return c_utils.getTopLevelContainerListIDsByDefID(
2729                jahiaContainerDefinition.getID(), loadRequest);
2730        }
2731        else {
2732            return new TreeSet();
2733        }
2734    }
2735
2736    /**
2737     * Retrieves all the properties for a given container
2738     *
2739     * @param containerID the identifier of the container whose properties
2740     * we want to retrieve from the database
2741     *
2742     * @return a Properties object that contains all the properties that are
2743     * available for this container in the database
2744     *
2745     * @throws JahiaException generated if there were problems executing the
2746     * query or communicating with the database.
2747     */

2748    public Properties getContainerProperties(int containerID) throws
2749        JahiaException {
2750        return c_containers_prop.getProperties(containerID);
2751    }
2752    
2753    /**
2754     * Save a property in the database for the specified container.
2755     *
2756     * @param containerID the container whose properties we are serializing
2757     * in the database.
2758     * @param jahiaID the site id
2759     * @param propertyName name of the property to be set
2760     * @param propertyValue value of the property to be set
2761     *
2762     * @throws JahiaException generated if there were problems executing the
2763     * query or communicating with the database.
2764     */

2765    public void setContainerProperty (int containerID,
2766            int jahiaID,
2767            String JavaDoc propertyName,
2768            String JavaDoc propertyValue) throws
2769        JahiaException {
2770        c_containers_prop.setProperty(containerID, jahiaID,
2771                                        propertyName, propertyValue);
2772        invalidateContainerFromCache(containerID);
2773    }
2774
2775    /**
2776     * Saves a whole set of properties in the database for the specified
2777     * container.
2778     *
2779     * @param containerID the container whose properties we are serializing
2780     * in the database.
2781     * @param jahiaID the site id
2782     * @param containerProperties the Properties object that contains all
2783     * the properties to save in the database. Only what is passed here will
2784     * exist in the database. If the database contained properties that aren't
2785     * in this hashtable they will be deleted.
2786     *
2787     * @throws JahiaException generated if there were problems executing the
2788     * query or communicating with the database.
2789     */

2790    public void setContainerProperties(int containerID,
2791                                       int jahiaID,
2792                                       Properties containerProperties) throws
2793        JahiaException {
2794        c_containers_prop.setProperties(containerID, jahiaID,
2795                                        containerProperties);
2796        invalidateContainerFromCache(containerID);
2797    }
2798
2799    /**
2800     * Returns the staging workflow state of the containers for all the languages
2801     * on the specified page.
2802     * Normally as currently we only do state changes on a page basis these
2803     * should all be equal. This does not retrieve the state of absolute containers.
2804     *
2805     * @param pageID the page id on which to retrieve the containers workflow state
2806     *
2807     * @return a Map that contains all the states of the languages for the
2808     * containers on the page (for the moment we assume all the objects are in the
2809     * same state)
2810     *
2811     * @throws JahiaException in the case we couldn't load a field.
2812     */

2813    public Map getContainersLanguagesState(int pageID) throws JahiaException {
2814
2815        Vector containerIDs = c_utils.getActiveOrStagedContainerIDsInPage(
2816            pageID);
2817        // For performance reasons we might want to preload the containers on
2818
// a page by implementing such a method :
2819
// ContentField.preloadActiveOrStagedContainersByPageID (pageID);
2820

2821        Map result = new HashMap();
2822
2823        for (int i = 0; i < containerIDs.size(); i++) {
2824            int id = ( (Integer JavaDoc) containerIDs.elementAt(i)).intValue();
2825
2826            ContentContainer theContainer = ContentContainer.getContainer(id);
2827            Map containerLanguagesStates = theContainer.
2828                getLanguagesStatesWithoutChilds();
2829
2830            Iterator containerLanguagesStatesIter = containerLanguagesStates.
2831                keySet().iterator();
2832            while (containerLanguagesStatesIter.hasNext()) {
2833                String JavaDoc curLanguageCode = (String JavaDoc) containerLanguagesStatesIter.
2834                    next();
2835                Integer JavaDoc languageState = (Integer JavaDoc) containerLanguagesStates.get(
2836                    curLanguageCode);
2837                Integer JavaDoc resultState = (Integer JavaDoc) result.get(curLanguageCode);
2838                if (resultState != null) {
2839                    if (resultState.intValue() < languageState.intValue()) {
2840                        result.put(curLanguageCode, languageState);
2841                    }
2842                }
2843                else {
2844                    result.put(curLanguageCode, languageState);
2845                }
2846            }
2847
2848        }
2849        return result;
2850    }
2851
2852    private Object JavaDoc getCacheContainerOrContainerListActiveEntryKey(int id) {
2853        return getCacheContainerOrContainerListEntryKey(id,
2854            EntryLoadRequest.ACTIVE_WORKFLOW_STATE);
2855    }
2856
2857    private Object JavaDoc getCacheContainerOrContainerListStagingEntryKey(int id) {
2858        return getCacheContainerOrContainerListEntryKey(id,
2859            EntryLoadRequest.STAGING_WORKFLOW_STATE);
2860    }
2861
2862    private Object JavaDoc getCacheContainerOrContainerListEntryKey(int id,
2863        int workflowState) {
2864        Object JavaDoc key = null;
2865        if (workflowState > EntryLoadRequest.ACTIVE_WORKFLOW_STATE) {
2866            workflowState = EntryLoadRequest.STAGING_WORKFLOW_STATE;
2867        }
2868        if (CacheFactory.getInstance().isKeyHierarchyEnabled()){
2869            List keyList = new ArrayList(2);
2870            keyList.add(String.valueOf(id));
2871            keyList.add(Integer.toString(workflowState));
2872            key = keyList;
2873        } else {
2874            key = id + "_" + workflowState;
2875        }
2876        return key;
2877    }
2878
2879    /**
2880     * Removes all container infos from the cache if it was present in the cache. If not,
2881     * this does nothing.
2882     *
2883     * @param containerID the identifier for the container to try to remove from the
2884     * cache.
2885     */

2886    public void invalidateContainerFromCache(int containerID) {
2887        synchronized (containerInfoCache) {
2888            if (CacheFactory.getInstance().isKeyHierarchyEnabled()) {
2889                containerInfoCache.remove(String.valueOf(containerID));
2890            } else {
2891                containerInfoCache
2892                        .remove(getCacheContainerOrContainerListActiveEntryKey(containerID));
2893                containerInfoCache
2894                        .remove(getCacheContainerOrContainerListStagingEntryKey(containerID));
2895            }
2896        }
2897    }
2898
2899    /**
2900     * Removes all container list from the cache if it was present in the cache. If not,
2901     * this does nothing.
2902     *
2903     * @param containerListID the identifier for the container list to try to remove from the
2904     * cache.
2905     */

2906    public void invalidateContainerListFromCache(int containerListID) {
2907        synchronized (containerListInfoCache) {
2908            if (CacheFactory.getInstance().isKeyHierarchyEnabled()) {
2909                containerListInfoCache.remove(String.valueOf(containerListID));
2910            } else {
2911                containerListInfoCache
2912                        .remove(getCacheContainerOrContainerListActiveEntryKey(containerListID));
2913                containerListInfoCache
2914                        .remove(getCacheContainerOrContainerListStagingEntryKey(containerListID));
2915            }
2916        }
2917    }
2918
2919} // end JahiaContainersBaseService
2920
Popular Tags