KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > services > fields > ContentPageField


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 package org.jahia.services.fields;
14
15 import java.util.*;
16
17 import org.jahia.content.ContentFieldKey;
18 import org.jahia.content.ContentObject;
19 import org.jahia.content.ContentPageKey;
20 import org.jahia.data.ConnectionTypes;
21 import org.jahia.data.fields.FieldTypes;
22 import org.jahia.engines.EngineMessage;
23 import org.jahia.exceptions.JahiaException;
24 import org.jahia.exceptions.JahiaPageNotFoundException;
25 import org.jahia.exceptions.JahiaTemplateNotFoundException;
26 import org.jahia.params.ParamBean;
27 import org.jahia.registries.ServicesRegistry;
28 import org.jahia.services.pages.ContentPage;
29 import org.jahia.services.pages.JahiaPage;
30 import org.jahia.services.usermanager.JahiaUser;
31 import org.jahia.services.version.ActivationTestResults;
32 import org.jahia.services.version.ContentObjectEntryState;
33 import org.jahia.services.version.EntryLoadRequest;
34 import org.jahia.services.version.EntrySaveRequest;
35 import org.jahia.services.version.EntryStateable;
36 import org.jahia.services.version.IsValidForActivationResults;
37 import org.jahia.services.version.JahiaSaveVersion;
38 import org.jahia.services.version.RestoreVersionNodeTestResult;
39 import org.jahia.services.version.RestoreVersionStateModificationContext;
40 import org.jahia.services.version.RestoreVersionTestResults;
41 import org.jahia.services.version.StateModificationContext;
42 import org.jahia.utils.xml.XMLSerializationOptions;
43 import org.jahia.utils.xml.XmlWriter;
44
45 /**
46  * <p>Title: The content field containing page related information. </p>
47  * <p>Description: This content element is associated with the JahiaPage
48  * object that describes a JahiaPage entry. These may be either hard or
49  * soft link, or remote URLs. By hard link we mean that if the link is created
50  * or disappears, so does the page it's related to, making this in fact an
51  * ownership relationship. We will probably change the model behing this for
52  * the next version of Jahia (4.0).</p>
53  * <p>Copyright: Copyright (c) 2002</p>
54  * <p>Company: </p>
55  *
56  * @author Serge Huber
57  * @version 1.0
58  */

59
60 public class ContentPageField extends ContentField {
61
62     private static org.apache.log4j.Logger logger
63             = org.apache.log4j.Logger.getLogger (ContentPageField.class);
64
65     int pageID = -1;
66
67     protected ContentPageField (Integer JavaDoc ID,
68                                 Integer JavaDoc jahiaID,
69                                 Integer JavaDoc pageID,
70                                 Integer JavaDoc ctnid,
71                                 Integer JavaDoc fieldDefID,
72                                 Integer JavaDoc fieldType,
73                                 Integer JavaDoc connectType,
74                                 Integer JavaDoc aclID,
75                                 Vector activeAndStagingEntryStates,
76                                 Hashtable activeAndStagedDBValues) {
77         super (ID.intValue (), jahiaID.intValue (), pageID.intValue (), ctnid.intValue (), fieldDefID.intValue (),
78                 fieldType.intValue (), connectType.intValue (), aclID.intValue (), activeAndStagingEntryStates,
79                 activeAndStagedDBValues);
80     }
81
82     private static synchronized ContentPageField create (int siteID,
83                                                          int pageID, int containerID,
84                                                          int fieldDefID, int parentAclID,
85                                                          int aclID,
86                                                          int pageType, String JavaDoc title,
87                                                          int pageDefID, String JavaDoc remoteURL,
88                                                          int pageLinkID, String JavaDoc creator,
89                                                          ParamBean jParams)
90             throws JahiaException {
91         JahiaPage thePage = ServicesRegistry.getInstance ().getJahiaPageService ().createPage (
92                 siteID,
93                 pageID, pageType, title, pageDefID, remoteURL, pageLinkID, creator, aclID,
94                 jParams);
95         ContentPageField result =
96                 (ContentPageField) ContentField.createField (siteID, pageID,
97                         containerID, fieldDefID,
98                         FieldTypes.PAGE,
99                         ConnectionTypes.LOCAL,
100                         parentAclID, aclID);
101         //EntrySaveRequest saveRequest = new EntrySaveRequest(jParams.getUser(), jParams.getLocale().toString());
102
EntrySaveRequest saveRequest = new EntrySaveRequest (jParams.getUser (),
103                 jParams.getEntryLoadRequest ().getFirstLocale (false).toString ());
104         result.preSet (Integer.toString (thePage.getID ()), saveRequest);
105         return result;
106     }
107
108     public static synchronized ContentPageField createNewPage (int siteID,
109                                                                int pageID, int containerID,
110                                                                int fieldDefID, int parentAclID,
111                                                                int aclID,
112                                                                String JavaDoc title, int pageDefID,
113                                                                String JavaDoc creator,
114                                                                ParamBean jParams)
115             throws JahiaException {
116         return create (siteID, pageID, containerID, fieldDefID, parentAclID,
117                 aclID, JahiaPage.TYPE_DIRECT, title, pageDefID, "", -1,
118                 creator, jParams);
119     }
120
121     public static synchronized ContentPageField createPageLink (int siteID,
122                                                                 int pageID, int containerID,
123                                                                 int fieldDefID,
124                                                                 int parentAclID, int aclID,
125                                                                 String JavaDoc title, int pageLinkID,
126                                                                 String JavaDoc creator,
127                                                                 ParamBean jParams)
128             throws JahiaException {
129         return create (siteID, pageID, containerID, fieldDefID, parentAclID,
130                 aclID, JahiaPage.TYPE_LINK, title, 0, "", pageLinkID,
131                 creator, jParams);
132     }
133
134     public static synchronized ContentPageField createRemoteURL (int siteID,
135                                                                  int pageID, int containerID,
136                                                                  int fieldDefID,
137                                                                  int parentAclID, int aclID,
138                                                                  String JavaDoc title,
139                                                                  String JavaDoc remoteURL,
140                                                                  String JavaDoc creator,
141                                                                  ParamBean jParams)
142             throws JahiaException {
143         return create (siteID, pageID, containerID, fieldDefID, parentAclID,
144                 aclID, JahiaPage.TYPE_URL, title, 0, remoteURL, -1,
145                 creator, jParams);
146     }
147
148     /**
149      * Set the page to the DB value field.
150      *
151      * @param pageID The page id in question.
152      * @param user The user actually logged on Jahia.
153      *
154      * @throws JahiaException
155      */

156     public void setPageID (int pageID, JahiaUser user)
157             throws JahiaException {
158         EntrySaveRequest entrySaveRequest = new EntrySaveRequest (user,
159                 ContentField.SHARED_LANGUAGE); // Page field are always in shared language.
160
ContentObjectEntryState verInfo = preSet (String.valueOf (pageID), entrySaveRequest);
161         logger.debug ("Saving page field..." + verInfo.toString ());
162     }
163
164     protected void copyEntry (EntryStateable fromEntryState, EntryStateable toEntryState)
165             throws JahiaException {
166         ContentPage contentPage = getContentPage (fromEntryState);
167         if (contentPage != null) {
168             EntryLoadRequest loadRequest = new EntryLoadRequest (fromEntryState);
169             if ((contentPage.getPageType (loadRequest) == JahiaPage.TYPE_URL) ||
170                     (contentPage.getPageType (loadRequest) == JahiaPage.TYPE_LINK)) {
171                 contentPage.copyEntry (fromEntryState, toEntryState);
172             }
173         }
174         super.copyEntry (fromEntryState, toEntryState);
175     }
176
177     protected ActivationTestResults changeEntryState (
178             ContentObjectEntryState fromEntryState,
179             ContentObjectEntryState toEntryState,
180             ParamBean jParams, StateModificationContext stateModifContext)
181             throws JahiaException {
182         ActivationTestResults activationResults = new ActivationTestResults ();
183         ContentPage contentPage = getContentPage (fromEntryState, false);
184         if (toEntryState.getWorkflowState () == -1) {
185             logger.debug ("Attempting to delete page field");
186         }
187
188         // this could happen if the database had a jahia_link_only value
189
// FIXME NK :
190
// In case of page field of link type, they can be created with a value = -1 ( meaning no link )
191
// that is why the content page can be null and this case should not abort validating the page field
192
/*
193         if (contentPage == null) {
194             activationResults.setStatus(ActivationTestResults.FAILED_OPERATION_STATUS);
195             activationResults.appendError("Field " + getID() + " value is not correctly set. Current value=" + getDBValue(fromEntryState));
196             return activationResults;
197         }
198         */

199
200         if (contentPage == null) {
201             return activationResults;
202         }
203
204         if ((toEntryState.getWorkflowState () == EntryLoadRequest.ACTIVE_WORKFLOW_STATE) ||
205                 (toEntryState.getWorkflowState () == EntryLoadRequest.DELETED_WORKFLOW_STATE)) {
206             boolean versioningActive = ServicesRegistry.getInstance ().getJahiaVersionService ()
207                     .isVersioningEnabled (this.getSiteID ());
208             JahiaSaveVersion saveVersion = new JahiaSaveVersion (true, versioningActive,
209                     toEntryState.getVersionID ());
210             EntryLoadRequest loadRequest = new EntryLoadRequest (fromEntryState);
211             if ((contentPage.getPageType (loadRequest) == JahiaPage.TYPE_URL) ||
212                     (contentPage.getPageType (loadRequest) == JahiaPage.TYPE_LINK)) {
213                 activationResults =
214                         contentPage.activeStagingEntries (
215                                 stateModifContext.getLanguageCodes (),
216                                 versioningActive, saveVersion, jParams.getUser (), jParams,
217                                 stateModifContext);
218             } else {
219                 if (stateModifContext.isDescendingInSubPages ()) {
220                     activationResults =
221                             contentPage.activeStagingEntries (
222                                     stateModifContext.getLanguageCodes (), versioningActive,
223                                     saveVersion, jParams.getUser (), jParams,
224                                     stateModifContext);
225                 }
226             }
227         } else {
228             EntryLoadRequest loadRequest = new EntryLoadRequest (fromEntryState);
229             if ((contentPage.getPageType (loadRequest) == JahiaPage.TYPE_URL) ||
230                     (contentPage.getPageType (loadRequest) == JahiaPage.TYPE_LINK)) {
231                 contentPage.changeStagingStatus (stateModifContext.getLanguageCodes (),
232                         toEntryState.getWorkflowState (), jParams, stateModifContext);
233             } else {
234                 if (stateModifContext.isDescendingInSubPages ()) {
235                     contentPage.changeStagingStatus (stateModifContext.getLanguageCodes (),
236                             toEntryState.getWorkflowState (), jParams, stateModifContext);
237                 }
238             }
239         }
240         return activationResults;
241     }
242
243     protected ActivationTestResults isContentValidForActivation (
244             Set languageCodes,
245             ParamBean jParams,
246             StateModificationContext stateModifContext)
247             throws JahiaException {
248         ActivationTestResults activationTestResults = new ActivationTestResults ();
249
250         ContentPage contentPage = null;
251
252         //1 ) Try with staged value
253
ContentObjectEntryState entryState = null;
254         ContentObjectEntryState activeEntryState = null;
255         ContentObjectEntryState stagedEntryState = null;
256
257         Set entrySets = this.getActiveAndStagingEntryStates();
258         Iterator iterator = entrySets.iterator();
259         while ( iterator.hasNext() ){
260             entryState = (ContentObjectEntryState)iterator.next();
261             if ( entryState.getWorkflowState()>ContentObjectEntryState.WORKFLOW_STATE_ACTIVE ){
262                 stagedEntryState = entryState;
263             } else {
264                 activeEntryState = entryState;
265             }
266         }
267
268         boolean movedPage = false;
269         if ( stagedEntryState != null ){
270             try {
271                 String JavaDoc value = this.getValue(stagedEntryState);
272                 if ( value != null && Integer.parseInt(value)>0 ){
273                     try {
274                         contentPage = ContentPage.getPage(Integer.parseInt(
275                             value));
276                         if (contentPage != null) {
277                             // check if page not currently moved
278
if (ServicesRegistry.getInstance().
279                                 getJahiaPageService()
280                                 .getStagingAndActivePageFieldIDs(contentPage.
281                                 getID()).size() > 1) {
282                                 // two different page fields are pointing the same page
283
// It's a moved page !
284
movedPage = true;
285                             }
286                         }
287                     } catch (JahiaPageNotFoundException pnfe) {
288                         logger.debug("Page not found." + value);
289                         // this is not considered an error
290
}
291                 }
292             } catch (NumberFormatException JavaDoc nfe) {
293                 logger.debug ("Page link seems to have an invalid value.");
294                 // this is not considered an error because we must be able to
295
// validate containers that have "unfilled" values.
296
}
297         }
298
299         if ( !movedPage && activeEntryState != null ){
300             try {
301                 String JavaDoc value = this.getValue(activeEntryState);
302                 if ( value != null && Integer.parseInt(value)>0 ){
303                     try {
304                         contentPage = ContentPage.getPage(Integer.parseInt(
305                             value));
306                         if (contentPage != null) {
307                             // check if page not currently moved
308
if (ServicesRegistry.getInstance().
309                                 getJahiaPageService()
310                                 .getStagingAndActivePageFieldIDs(contentPage.
311                                 getID()).size() > 1) {
312                                 // two different page fields are pointing the same page
313
// It's a moved page !
314
movedPage = true;
315                             }
316                         }
317                     }
318                     catch (JahiaPageNotFoundException pnfe) {
319                         logger.debug("Page not found." + value);
320                         // this is not considered an error
321
}
322                 }
323             } catch (NumberFormatException JavaDoc nfe) {
324                 logger.debug ("Page link seems to have an invalid value.");
325                 // this is not considered an error because we must be able to
326
// validate containers that have "unfilled" values.
327
}
328         }
329
330         /*
331         if ( movedPage ){
332             // the page is currently in a move state, but not activated
333             if ( !stateModifContext.getStartObject().equals(contentPage.getObjectKey()) ){
334                 activationTestResults.setStatus(ActivationTestResults.
335                                                 FAILED_OPERATION_STATUS);
336                 try {
337                     final EngineMessage msg = new EngineMessage(
338                             "org.jahia.services.fields.ContentPageField.referedToMovedPageError",
339                             Integer.toString(getID()));
340                     final IsValidForActivationResults activationResults = new IsValidForActivationResults(
341                             ContentFieldKey.FIELD_TYPE, getID(), jParams.getLocale()
342                             .toString(), msg);
343                     activationTestResults.appendError(activationResults);
344                 } catch (ClassNotFoundException cnfe) {
345                     logger.error(cnfe);
346                 }
347                 return activationTestResults;
348             }
349         }*/

350
351         if (contentPage == null) {
352             // this could happen if the database had a jahia_link_only value
353
activationTestResults.setStatus (ActivationTestResults.PARTIAL_OPERATION_STATUS);
354             try {
355                 final EngineMessage msg = new EngineMessage(
356                         "org.jahia.services.fields.ContentPageField.valueNotSetWarning",
357                         Integer.toString(getID()), getValue(jParams));
358                 IsValidForActivationResults activationResults = new
359                     IsValidForActivationResults (ContentFieldKey.FIELD_TYPE,
360                                                  getID (),
361                                                  jParams.getLocale ().toString (), msg);
362                 activationTestResults.appendWarning (activationResults);
363             } catch (ClassNotFoundException JavaDoc cnfe) {
364                 logger.error(cnfe);
365             }
366             return activationTestResults;
367         }
368         try {
369             // allow loading marked for delete page
370
EntryLoadRequest loadRequest =
371                     new EntryLoadRequest (jParams.getEntryLoadRequest ().getWorkflowState (),
372                             jParams.getEntryLoadRequest ().getVersionID (),
373                             jParams.getEntryLoadRequest ().getLocales (), true);
374             JahiaPage thePage = contentPage.getPage (loadRequest,
375                     ParamBean.EDIT, jParams.getUser ());
376
377             JahiaSaveVersion saveVersion = new JahiaSaveVersion (true,
378                     jParams.getSite ().isVersioningEnabled (),
379                     jParams.getEntryLoadRequest ().getVersionID ());
380
381             if (thePage == null) {
382                 activationTestResults.setStatus (ActivationTestResults.FAILED_OPERATION_STATUS);
383                 try {
384                     final EngineMessage msg = new EngineMessage(
385                             "org.jahia.services.fields.ContentPageField.pageLookupError",
386                             Integer.toString(pageID));
387                     IsValidForActivationResults activationResults = new
388                         IsValidForActivationResults (ContentFieldKey.FIELD_TYPE,
389                                                      getID (),
390                                                      jParams.getLocale ().toString (), msg);
391                     activationTestResults.appendError (activationResults);
392                 } catch (ClassNotFoundException JavaDoc cnfe) {
393                     logger.error(cnfe);
394                 }
395                 return activationTestResults;
396             }
397
398             if (!stateModifContext.isDescendingInSubPages ()) {
399                 // sub pages is not activated, let's check the page type to know
400
// if we must validate or not.
401
int pageType = thePage.getPageType ();
402                 switch (pageType) {
403                     case JahiaPage.TYPE_DIRECT :
404                         if (thePage.hasActiveEntries()) {
405                             activationTestResults.setStatus(ActivationTestResults.COMPLETED_OPERATION_STATUS);
406                         } else if (!contentPage.hasStagingEntries()) {
407                             // this page is either active or deleted
408
activationTestResults.setStatus(ActivationTestResults.COMPLETED_OPERATION_STATUS);
409                         } else {
410                             activationTestResults.setStatus (ActivationTestResults.FAILED_OPERATION_STATUS);
411                             try {
412                                 final EngineMessage msg = new EngineMessage(
413                                         "org.jahia.services.fields.ContentPageField.pageOnlyInStagingWarning",
414                                         Integer.toString(thePage.getID()));
415                                 IsValidForActivationResults activationResults = new
416                                     IsValidForActivationResults (ContentFieldKey.FIELD_TYPE,
417                                                                  getID (),
418                                                                  jParams.getLocale ().toString (), msg);
419                                 activationTestResults.appendWarning (activationResults);
420                             } catch (ClassNotFoundException JavaDoc cnfe) {
421                                 logger.error(cnfe);
422                             }
423                         }
424                         break;
425                     case JahiaPage.TYPE_LINK:
426                         JahiaPage linkPage = null;
427                         try {
428                             linkPage = ServicesRegistry.getInstance().
429                                        getJahiaPageService().
430                                        lookupPage(thePage.
431                                                   getPageLinkID(),
432                                                   jParams);
433                         } catch (JahiaPageNotFoundException jpnfe) {
434                             linkPage = null;
435                         }
436                         if (linkPage != null) {
437                             if (linkPage.hasActiveEntries ()) {
438                                 activationTestResults.setStatus (
439                                         ActivationTestResults.
440                                         COMPLETED_OPERATION_STATUS);
441                             } else {
442                                 activationTestResults.setStatus (ActivationTestResults.PARTIAL_OPERATION_STATUS);
443                                 try {
444                                     final EngineMessage msg = new EngineMessage(
445                                             "org.jahia.services.fields.ContentPageField.pageOnlyInStagingWarning",
446                                             Integer.toString(pageID));
447                                     IsValidForActivationResults activationResults = new
448                                         IsValidForActivationResults ( ContentFieldKey.FIELD_TYPE,
449                                                                       getID (),
450                                                                       jParams.getLocale ().toString (), msg);
451                                     activationTestResults.appendWarning (activationResults);
452                                 } catch (ClassNotFoundException JavaDoc cnfe) {
453                                     logger.error(cnfe);
454                                 }
455                             }
456                         } else {
457                             activationTestResults.setStatus (
458                                     ActivationTestResults.
459                                     PARTIAL_OPERATION_STATUS);
460                             try {
461                                 final EngineMessage msg = new EngineMessage(
462                                         "org.jahia.services.fields.ContentPageField.pageLinkNotFoundWarning",
463                                         Integer.toString(pageID), Integer.toString(thePage.getPageLinkID()));
464                                 IsValidForActivationResults activationResults = new
465                                     IsValidForActivationResults ( ContentFieldKey.FIELD_TYPE,
466                                                                   getID (),
467                                                                   jParams.getLocale ().toString (), msg);
468                             activationTestResults.appendWarning (activationResults);
469                         } catch (ClassNotFoundException JavaDoc cnfe) {
470                             logger.error(cnfe);
471                         }
472
473                         }
474                         break;
475                     case JahiaPage.TYPE_URL:
476                         activationTestResults =
477                                 thePage.isValidForActivation (languageCodes, saveVersion,
478                                         jParams.getUser (), jParams, stateModifContext);
479                         break;
480                 }
481
482             } else {
483                 // we do the activation all the time since we go down in the
484
// sub pages.
485
activationTestResults =
486                         thePage.isValidForActivation (languageCodes, saveVersion,
487                                 jParams.getUser (), jParams, stateModifContext);
488             }
489         } catch (NumberFormatException JavaDoc nfe) {
490             logger.error (nfe);
491         }
492
493         return activationTestResults;
494     }
495
496     public boolean isShared () {
497         return true;
498     }
499
500     public String JavaDoc getValue (ParamBean jParams, ContentObjectEntryState entryState)
501             throws JahiaException {
502         return getDBValue (entryState);
503     }
504
505     public void setValue (int value, ParamBean jParams)
506             throws JahiaException {
507         EntrySaveRequest entrySaveRequest = new EntrySaveRequest (jParams.getUser (),
508                 ContentField.SHARED_LANGUAGE); // Page field are always in shared language.
509
preSet (String.valueOf (value), entrySaveRequest);
510     }
511
512     public JahiaPage getPage (ParamBean jParams)
513             throws JahiaTemplateNotFoundException, JahiaException {
514         return getPage (jParams, true);
515     }
516
517     public JahiaPage getPage (ParamBean jParams, boolean withTemplate)
518             throws JahiaTemplateNotFoundException, JahiaException {
519         ContentPage contentPage = getContentPage (jParams, withTemplate);
520         if (contentPage == null) {
521             return null;
522         }
523         JahiaPage thePage = contentPage.getPage (jParams);
524         // now we must check whether this page has been moved or not.
525
int movedFrom = contentPage.hasSameParentID ();
526         if (movedFrom != ContentPage.SAME_PARENT) {
527             // page has been moved.
528
if (!ParamBean.NORMAL.equals (jParams.getOperationMode ())
529                     && !ParamBean.COMPARE.equals (jParams.getOperationMode ())) {
530                 // we are in preview or edit mode, let's check where we are
531
// before returning the page, because the page "exists" still
532
// at two locations, but only one should be returned.
533
if (getPageID () == movedFrom) {
534                     // we are at the old location, let's return null for
535
// the page.
536
return null;
537                 }
538             }
539         }
540
541         return thePage;
542     }
543
544     public String JavaDoc getValueForSearch (ParamBean jParams,
545                                      ContentObjectEntryState entryState)
546             throws JahiaException {
547         ContentPage contentPage = getContentPage (entryState);
548         if (contentPage == null) {
549             // this could happen if the database had a jahia_link_only value
550
return getDBValue (entryState);
551         }
552         return contentPage.getTitle (jParams);
553     }
554
555     /**
556      * This method is called when an entry should be deleted for real.
557      * It is called when a field is deleted, and versioning is disabled, or
558      * when staging values are undone.
559      * For a bigtext for instance, this method should delete the text file
560      * corresponding to this field entry
561      *
562      * @param State the entry state to delete
563      *
564      * @throws JahiaException in case we cannot lookup the page content or
565      * while deleting the entry (and the whole page in the case that it's the
566      * last entry)
567      */

568     public void deleteEntry (EntryStateable deleteEntryState) throws JahiaException {
569         ContentPage contentPage = getContentPage (deleteEntryState);
570
571         /**
572          * FIXME NK :
573          * When markfordeletion is called, the contentPage could be deleted at this point,
574          * so why couln't the process continue if the contentpage is null ?
575          *
576          if (contentPage == null) {
577          // this could happen if the database had a jahia_link_only value
578          logger.debug("Cannot delete page from jahia_pages_data table because it is a uninitialized page value=" + getDBValue(deleteEntryState));
579          return;
580          }*/

581         if (contentPage != null) {
582             contentPage.deleteEntry (deleteEntryState);
583         }
584         super.deleteEntry (deleteEntryState);
585     }
586
587     /**
588      * This is called on all content fields to have them serialized only their
589      * specific part. The actual field metadata seriliazing is handled by the
590      * ContentField class. This method is called multiple times per field
591      * according to the workflow state, languages and versioning entries we
592      * want to serialize.
593      *
594      * @param xmlWriter the XML writer object in which to write the XML output
595      * @param xmlSerializationOptions options used to activate/bypass certain
596      * output of elements.
597      * @param entryState the ContentFieldEntryState for which to generate the
598      * XML export.
599      * @param paramBean specifies context of serialization, such as current
600      * user, current request parameters, entry load request, URL generation
601      * information such as ServerName, ServerPort, ContextPath, etc... URL
602      * generation is an important part of XML serialization and this is why
603      * we pass this parameter down, as well as user rights checking.
604      *
605      * @throws IOException in case there was an error writing to the Writer
606      * output object.
607      */

608     protected void serializeContentToXML (XmlWriter xmlWriter,
609                                           XMLSerializationOptions xmlSerializationOptions,
610                                           ContentObjectEntryState entryState,
611                                           ParamBean paramBean) throws java.io.IOException JavaDoc {
612
613         try {
614             ContentPage contentPage = getContentPage (entryState);
615             if (contentPage == null) {
616                 // this could happen if the database had a jahia_link_only value
617
logger.debug (
618                         "Cannot delete page from jahia_pages_data table because it is a uninitialized page value=" + getDBValue (
619                                 entryState));
620                 xmlWriter.writeText ("Error while serializing page " + getID () +
621                         " to XML : Cannot delete page from jahia_pages_data table because it is a uninitialized page value=" +
622                         getDBValue (entryState));
623                 return;
624             }
625             contentPage.serializeToXML (xmlWriter, xmlSerializationOptions, paramBean);
626         } catch (JahiaException je) {
627             logger.debug ("Error while serializing page " + getID () + " to XML", je);
628             xmlWriter.writeText ("Error while serializing page " + getID () + " to XML");
629         } catch (NumberFormatException JavaDoc nfe) {
630             logger.debug ("Error while serializing page " + getID () + " to XML", nfe);
631             xmlWriter.writeText ("Error while serializing page " + getID () + " to XML");
632         }
633     }
634
635     protected Map getContentLanguageStates (ContentObjectEntryState entryState) {
636         Map result = new HashMap ();
637         try {
638             EntryLoadRequest loadRequest = new EntryLoadRequest (entryState);
639             ContentPage contentPage = getContentPage (entryState, false);
640             if (contentPage != null) {
641                 int pageType = contentPage.getPageType (loadRequest);
642                 if (contentPage != null && pageType != JahiaPage.TYPE_DIRECT
643                         && pageType != -1) {
644                     result = contentPage.getLanguagesStates (false);
645                 }
646             }
647         } catch (Exception JavaDoc e) {
648             logger.debug (
649                     "Error while retrieving page content object, pagefieldid=" + this.getID (),
650                     e);
651         }
652         return result;
653     }
654
655     protected void markContentLanguageForDeletion (JahiaUser user,
656                                                    String JavaDoc languageCode,
657                                                    StateModificationContext stateModifContext)
658             throws JahiaException {
659
660         ContentObjectEntryState entryState =
661                 new ContentObjectEntryState (
662                         ContentObjectEntryState.WORKFLOW_STATE_START_STAGING, 0,
663                         ContentObject.SHARED_LANGUAGE);
664
665         // we use entry load request resolving to have the active returned if the staging doesn't exist
666
entryState = this.getEntryState (new EntryLoadRequest (entryState));
667         if (entryState == null) {
668             return;
669         }
670
671         ContentPage contentPage = getContentPage (entryState, false);
672         if (contentPage == null) {
673             return;
674         }
675
676         EntryLoadRequest loadRequest = new EntryLoadRequest (entryState);
677         if ((contentPage.getPageType (loadRequest) == JahiaPage.TYPE_URL) ||
678                 (contentPage.getPageType (loadRequest) == JahiaPage.TYPE_LINK)) {
679             contentPage.markLanguageForDeletion (user, languageCode, stateModifContext);
680         } else {
681             if (stateModifContext.isDescendingInSubPages ()) {
682                 // We have to check here that the start object is not the current content page child
683
// to avoid infinite loop.
684
if (!contentPage.getObjectKey ().equals (stateModifContext.getStartObject ())) {
685                     contentPage.markLanguageForDeletion (user, languageCode, stateModifContext);
686                 }
687             }
688
689             /*
690             // The code bellow try to address the issue bellow
691             // Issue :
692             // 1) Home page activated
693             // 2) add ->subpage A1 ( simple), add sub-sub A11, then active from home
694             // 3) move A11 to Home ( top menu ) , do not active
695             // 4) restore (exact) from home just before move ( last active date ), select only home page !!!
696             // --> A1 is not deleted but not attached anywhere, because it's staged parent page field is marked for delete here
697             //
698             */

699
700             // check for page move and restore version
701
if ( stateModifContext instanceof RestoreVersionStateModificationContext ){
702                 if ( !stateModifContext.getStartObject().equals(contentPage.getObjectKey()) ){
703                     RestoreVersionStateModificationContext rvsmc =
704                         new RestoreVersionStateModificationContext(contentPage.
705                         getObjectKey(),
706                         stateModifContext.getLanguageCodes(),
707                         ( (RestoreVersionStateModificationContext)
708                          stateModifContext).getEntryState());
709                     // we actually perform a restore version
710
contentPage.restoreVersion(user, ParamBean.EDIT,
711                                                rvsmc.getEntryState(),
712                                                false, false, rvsmc);
713                 }
714             }
715
716         }
717
718         return;
719     }
720
721
722     protected void purgeContent ()
723             throws JahiaException {
724
725         // first let's retrieve all the different page IDs for this field.
726
Map dbValues = getAllDBValues ();
727         Iterator dbValuesEntryIter = dbValues.entrySet ().iterator ();
728         Set pageSet = new HashSet ();
729         while (dbValuesEntryIter.hasNext ()) {
730             Map.Entry curMapEntry = (Map.Entry) dbValuesEntryIter.next ();
731             ContentObjectEntryState curEntryState = (ContentObjectEntryState) curMapEntry.getKey ();
732             String JavaDoc curDBValue = (String JavaDoc) curMapEntry.getValue ();
733             if (curDBValue != null) {
734                 int pageID = -1;
735                 try {
736                     pageID = Integer.parseInt (curDBValue);
737                 } catch (NumberFormatException JavaDoc nfe) {
738                     pageID = -1;
739                 }
740                 if (pageID != -1) {
741                     pageSet.add (new Integer JavaDoc (pageID));
742                 }
743             }
744         }
745
746         // now let's remove the related pages. Some of these pages might have
747
// already been removed since we are removing pages in active and
748
// staging mode. Notably this could occur after a page has been moved.
749
Iterator pageSetIter = pageSet.iterator ();
750         while (pageSetIter.hasNext ()) {
751             Integer JavaDoc curPageID = (Integer JavaDoc) pageSetIter.next ();
752             ContentPage contentPage = null;
753             try {
754                 contentPage = ServicesRegistry.getInstance ().getJahiaPageService ().
755                         lookupContentPage (curPageID.intValue (), EntryLoadRequest.CURRENT,
756                                 true);
757             } catch (JahiaPageNotFoundException jpnfe) {
758                 try {
759                     contentPage = ServicesRegistry.getInstance ().
760                             getJahiaPageService ().
761                             lookupContentPage (curPageID.intValue (),
762                                     EntryLoadRequest.DELETED, true);
763                 } catch (JahiaPageNotFoundException jpnfe2) {
764                     contentPage = null;
765                 }
766             }
767             if (contentPage != null) {
768                 contentPage.purge (EntryLoadRequest.CURRENT);
769             }
770         }
771     }
772
773     // The two following methods are necessary because we cannot keep a
774
// reference to a ContentPage object as this field is a singleton
775
// but ContentPage is not ! Do not optimize by making a reference
776
// ContentPage object until ContentPage becomes a "singleton" for
777
// a single page instance.
778

779     private ContentPage getContentPage (EntryStateable entryState)
780             throws NumberFormatException JavaDoc, JahiaException {
781         return getContentPage (entryState, true);
782     }
783
784     // The two following methods are necessary because we cannot keep a
785
// reference to a ContentPage object as this field is a singleton
786
// but ContentPage is not ! Do not optimize by making a reference
787
// ContentPage object until ContentPage becomes a "singleton" for
788
// a single page instance.
789

790     private ContentPage getContentPage (EntryStateable entryState, boolean withTemplate)
791             throws NumberFormatException JavaDoc, JahiaException {
792
793         String JavaDoc dbValue = getDBValue (entryState).toLowerCase ();
794         if (dbValue.indexOf ("jahia_linkonly") != -1 ||
795                 dbValue.indexOf ("empty") != -1) {
796             // possible if using an old database format that still had
797
// jahia_linkonly values in it's database.
798
return null;
799         }
800         pageID = Integer.parseInt (dbValue);
801         if (pageID < 0) {
802             return null;
803         }
804         if (entryState == null) {
805             return null;
806         }
807         ContentPage contentPage = null;
808         try {
809             contentPage =
810                     ServicesRegistry.getInstance ().getJahiaPageService ().
811                     lookupContentPage (pageID, new EntryLoadRequest (entryState), withTemplate);
812         } catch (JahiaPageNotFoundException jpnfe) {
813             contentPage = null;
814         }
815         return contentPage;
816     }
817
818     public ContentPage getContentPage (ParamBean jParams)
819             throws NumberFormatException JavaDoc, JahiaException {
820         return getContentPage (jParams, true);
821     }
822
823     public ContentPage getContentPage (ParamBean jParams, boolean withTemplate)
824             throws NumberFormatException JavaDoc, JahiaException {
825
826         String JavaDoc dbValue = getValue (jParams);
827         if (dbValue == null) {
828             dbValue = "-1";
829         } else {
830             dbValue = dbValue.toLowerCase ();
831         }
832         if (dbValue.indexOf ("jahia_linkonly") != -1 ||
833                 dbValue.indexOf ("empty") != -1) {
834             // possible if using an old database format that still had
835
// jahia_link_only values in it's database.
836
return null;
837         }
838         pageID = Integer.parseInt (dbValue);
839         if (pageID < 0) {
840             return null;
841         }
842         ContentPage contentPage = null;
843         try {
844             contentPage = ServicesRegistry.getInstance ().getJahiaPageService ().
845                     lookupContentPage (pageID, withTemplate);
846         } catch (JahiaTemplateNotFoundException tnf) {
847             try {
848                 logger.debug ("Template not found for page :" + pageID);
849                 logger.debug ("Try to request page without template :");
850                 contentPage = ServicesRegistry.getInstance ().getJahiaPageService ().
851                         lookupContentPage (pageID, false);
852             } catch (JahiaPageNotFoundException jpnfe) {
853                 contentPage = null;
854             }
855         } catch (JahiaPageNotFoundException jpnfe) {
856             contentPage = null;
857         }
858         return contentPage;
859     }
860
861     public ArrayList getChilds (JahiaUser user,
862                                 EntryLoadRequest loadRequest)
863             throws JahiaException {
864         ArrayList resultList = new ArrayList ();
865         ContentPage contentPage = null;
866         try {
867             if (loadRequest != null) {
868                 ContentObjectEntryState entryState = getEntryState(loadRequest);
869                 if (entryState.getWorkflowState()
870                     !=
871                     ContentObjectEntryState.WORKFLOW_STATE_VERSIONING_DELETED) {
872                     // we don't want to return the child page if the current page field
873
// is marked for delete indicating the page was moved
874
contentPage = getContentPage(entryState, false);
875                 } else {
876                     // was the page deleted or not
877
contentPage = getContentPage(entryState, false);
878                     ContentObjectEntryState closestEntryState = contentPage.
879                             getClosestVersionedEntryState(
880                                     entryState);
881                     if (contentPage != null && closestEntryState != null &&
882                         closestEntryState.getWorkflowState() !=
883                         ContentObjectEntryState.
884                         WORKFLOW_STATE_VERSIONING_DELETED) {
885                         // the page wasn't deleted, check if it's parent field
886
// is different than this field
887
EntryLoadRequest lr = new EntryLoadRequest(
888                                 closestEntryState);
889                         int parentFieldID = contentPage.getParentID(lr);
890                         if (parentFieldID != this.getID()) {
891                             // the page was moved and wasn't the child of this current field
892
// so return empty array
893
return resultList;
894                         }
895                     }
896                 }
897             } else {
898                 contentPage = this.getPage();
899             }
900         } catch ( JahiaPageNotFoundException pnfe ){
901             // this exception can if the page doesn't exist in db
902
logger.debug("Page not found [" + this.getPageID(), pnfe);
903         }
904         if (contentPage != null) {
905             resultList.add (contentPage);
906         }
907         return resultList;
908     }
909
910     public RestoreVersionTestResults isValidForRestore (JahiaUser user,
911                                                         String JavaDoc operationMode,
912                                                         ContentObjectEntryState entryState,
913                                                         boolean removeMoreRecentActive,
914                                                         StateModificationContext stateModificationContext)
915             throws JahiaException {
916         // first let's check if we have entries that correspond for this
917
// page
918
RestoreVersionTestResults opResult = new RestoreVersionTestResults ();
919         opResult.merge (
920                 super.isValidForRestore (user, operationMode, entryState,
921                         removeMoreRecentActive, stateModificationContext));
922         if (opResult.getStatus () == RestoreVersionTestResults.FAILED_OPERATION_STATUS) {
923             return opResult;
924         }
925         ContentPage contentPage = getContentPage (entryState, false);
926         if (contentPage != null) {
927             opResult.merge (
928                     contentPage.isValidForRestore (user, operationMode, entryState,
929                             removeMoreRecentActive, stateModificationContext));
930         } else {
931             /** This test has no meaning because a page field can be created without assigned content page
932              opResult.setStatus(RestoreVersionTestResults.FAILED_OPERATION_STATUS);
933              opResult.appendError(new RestoreVersionNodeTestResult(getObjectKey(),
934              entryState.getLanguageCode(),
935              "Couldn't find ContentPage associated with this ContentPageField"));
936              */

937             opResult.setStatus (RestoreVersionTestResults.PARTIAL_OPERATION_STATUS);
938             opResult.appendWarning (new RestoreVersionNodeTestResult (getObjectKey (),
939                     entryState.getLanguageCode (),
940                     "Couldn't find ContentPage associated with this ContentPageField"));
941         }
942         return opResult;
943     }
944
945     public RestoreVersionTestResults restoreVersion (JahiaUser user,
946                                                      String JavaDoc operationMode,
947                                                      ContentObjectEntryState entryState,
948                                                      boolean removeMoreRecentActive,
949                                                      RestoreVersionStateModificationContext stateModificationContext)
950             throws JahiaException {
951
952         RestoreVersionTestResults opResult = new RestoreVersionTestResults ();
953
954         ContentObjectEntryState resultEntryState = getClosestVersionedEntryState (entryState);
955
956         ContentPage contentPage = null;
957         try {
958             contentPage = getContentPage (entryState, false);
959             if ( contentPage != null
960                  && contentPage.hasArchiveEntryState(entryState.getVersionID()) ){
961                 ContentObjectEntryState closestEntryState =
962                     contentPage.getClosestVersionedEntryState (entryState);
963                 if (closestEntryState != null && closestEntryState.getWorkflowState ()
964                         != ContentObjectEntryState.WORKFLOW_STATE_VERSIONING_DELETED) {
965                     EntryLoadRequest loadRequest = new EntryLoadRequest (entryState);
966                     if ((contentPage.getPageType (loadRequest) == JahiaPage.TYPE_URL) ||
967                             (contentPage.getPageType (loadRequest) == JahiaPage.TYPE_LINK)) {
968                         if (!stateModificationContext.isObjectIDInPath (
969                                 new ContentPageKey (contentPage.getID ()))) {
970                             opResult.merge (
971                                     contentPage.restoreVersion (user, operationMode,
972                                             entryState, removeMoreRecentActive,
973                                             stateModificationContext));
974                         }
975                     } else {
976                         if (stateModificationContext.isDescendingInSubPages()) {
977                             opResult.merge(contentPage.restoreVersion(user, operationMode,
978                                     entryState, removeMoreRecentActive, stateModificationContext));
979                         }
980                         if (!stateModificationContext.getStartObject()
981                                 .equals(contentPage.getObjectKey())){
982                             // we don't restore this page field if are not restoring from the page it reffered.
983
return opResult;
984                         }
985                     }
986                 }
987             }
988         } catch (Throwable JavaDoc t) {
989             logger.debug ("Content page not found for field [" + getID () + "]");
990         }
991
992         opResult.merge (super.restoreVersion (user, operationMode, entryState,
993                 removeMoreRecentActive, stateModificationContext));
994     /*
995         if ( !(this.isMarkedForDelete() || this.isDeletedOrDoesNotExist((new Long(System.currentTimeMillis()/1000L).intValue())))
996              && (this.hasActiveEntries()||this.hasStagingEntries()) ){
997             // if this page reffers to an internal page link or a direct page and if
998             // this page doesn't exist in staging or live, we set this page field to -1
999             // to avoid page 404 exception.
1000            EntryLoadRequest loadRequest = EntryLoadRequest.STAGED;
1001            loadRequest.setWithDeleted(false);
1002            loadRequest.setWithMarkedForDeletion(false);
1003            Vector v = new Vector(this.getActiveAndStagingEntryStates());
1004            ContentObjectEntryState resolvedEntryState =
1005                (ContentObjectEntryState) ServicesRegistry.getInstance()
1006                .getJahiaVersionService().resolveEntry(v, loadRequest);
1007            if (resolvedEntryState == null) {
1008                this.setValue( -1, Jahia.getThreadParamBean());
1009            }
1010        }*/

1011
1012        return opResult;
1013    }
1014
1015    protected boolean isEntryInitialized (ContentObjectEntryState curEntryState)
1016        throws JahiaException {
1017        String JavaDoc entryValue = getDBValue(curEntryState);
1018        if (entryValue == null) {
1019            return false;
1020        }
1021        if (!entryValue.equals("") &&
1022            !entryValue.equals("<empty>") &&
1023            !entryValue.equals("-1")) {
1024            return true;
1025        }
1026        return false;
1027    }
1028
1029}
1030
Popular Tags