View Javadoc

1   /**
2    * This file Copyright (c) 2003-2011 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.cms.taglibs;
35  
36  import info.magnolia.cms.core.Content;
37  import info.magnolia.cms.core.ItemType;
38  import info.magnolia.cms.security.AccessDeniedException;
39  import org.apache.commons.lang.StringUtils;
40  import org.slf4j.Logger;
41  import org.slf4j.LoggerFactory;
42  
43  import javax.jcr.PathNotFoundException;
44  import javax.jcr.RepositoryException;
45  import javax.servlet.http.HttpServletRequest;
46  import javax.servlet.jsp.PageContext;
47  import javax.servlet.jsp.jstl.core.LoopTagStatus;
48  import java.io.Serializable;
49  import java.util.Collection;
50  import java.util.Collections;
51  import java.util.Iterator;
52  
53  
54  /**
55   * Iterate over contentNode collection. contentNodeIterator is used whenever you want to loop over content, typically paragraphs. A parameter
56          contentNodeCollectionName will contain the name of the contentNode you are looping over.
57          contentNodeCollectionName is created by providing a newBar with the corresponding name. This will result in
58          elements being created within that contentNode, and thus allow you to loop over these.
59  
60   * @jsp.tag name="contentNodeIterator" body-content="JSP"
61   * @jsp.tag-example
62   * <pre>
63   * &lt;cms:contentNodeIterator contentNodeCollectionName="mainColumnParagraphs"&gt;
64   *   &lt;cms:adminOnly&gt;
65   *     &lt;cms:editBar/&gt;
66   *   &lt;/cms:adminOnly&gt;
67   *   &lt;cms:includeTemplate/&gt;
68   * &lt;/cms:contentNodeIterator&gt;
69   *</pre>
70   * @author Sameer Charles
71   * @author Fabrizio Giustina
72   * @author David Smith
73   * @version $Revision: 41137 $ ($Author: gjoseph $)
74   */
75  public class ContentNodeIterator extends BaseContentTag {
76      private static final Logger log = LoggerFactory.getLogger(ContentNodeIterator.class);
77  
78      /**
79       * @deprecated
80       */
81      public static final String CONTENT_NODE_COLLECTION_NAME = "contentNodeCollectionName"; //$NON-NLS-1$
82  
83      /**
84       * @deprecated use the <code>varStatus</code> tag attribute to get a reference to a
85       * <code>javax.servlet.jsp.jstl.core.LoopTagStatus</code> instance.
86       */
87      protected static final String CURRENT_INDEX = "currentIndex"; //$NON-NLS-1$
88  
89      /**
90       * @deprecated use the <code>varStatus</code> tag attribute to get a reference to a
91       * <code>javax.servlet.jsp.jstl.core.LoopTagStatus</code> instance.
92       */
93      protected static final String SIZE = "size"; //$NON-NLS-1$
94  
95      /**
96       * Tag attribute.
97       */
98      protected int begin;
99  
100     /**
101      * Tag attribute.
102      */
103     protected Integer end;
104 
105     /**
106      * Tag attribute.
107      */
108     protected int step = 1;
109 
110     /**
111      * Tag attribute.
112      */
113     private String varStatus;
114 
115     /**
116      * Tag attribute.
117      */
118     private Collection items;
119 
120     protected int size;
121 
122     protected int count;
123     protected int index;
124 
125     protected Object current;
126 
127     private Iterator contentNodeIterator;
128 
129     private LoopTagStatus status;
130 
131     /** Size info from outer node iterator, if one exists. */
132     private Integer outerSize = null;
133 
134     /** Current index the outer node iterator is at. */
135     private Integer outerCurrIdx = null;
136 
137     /** Collection iterated over by the outer node iterator. */
138     private String outerCollName = null;
139 
140     /** Resource.getLocalContentNodeCollectionName() value set by outer node iterator. */
141     private String outerResCollName = null;
142 
143     /** Resource.getLocalContentNode set by the outer node iterator. */
144     private Content outerLocalContentNode = null;
145 
146     /** Flag indicating the previous node state should be restored. */
147     private boolean restorePreviousState = false;
148 
149     /**
150      * Zero-based index of first item to process, inclusive.
151      * @jsp.attribute required="false" rtexprvalue="true" type="int"
152      */
153     public void setBegin(int index) {
154         this.begin = index;
155     }
156 
157     /**
158      * Zero-based index of last item to process, inclusive.
159      * @jsp.attribute required="false" rtexprvalue="true" type="int"
160      */
161     public void setEnd(Integer index) {
162         this.end = index;
163     }
164 
165     /**
166      * Process every stepth element (e.g 2 = every second element).
167      * @jsp.attribute required="false" rtexprvalue="true" type="int"
168      */
169     public void setStep(int step) {
170         this.step = step;
171     }
172 
173     /**
174      * Name of variable to hold the loop status with the following properties: index: position of the current item;
175      *  count: number of times through the loop (starting with 1); first: boolean indicator if this is the first
176      *  iteration; last: boolean indicator if this is the last iteration.
177      *
178      * @jsp.attribute required="false" rtexprvalue="true"
179      */
180     public void setVarStatus(String varStatus) {
181         this.varStatus = varStatus;
182     }
183 
184     /**
185      * if this attribute is set, the tag will iterate on the collection directly passed here instead of fetching the
186      * collection named by contentNodeCollectionName. This collection must contains info.magnolia.cms.core.Content
187      * items.
188      * @jsp.attribute required="false" rtexprvalue="true" type="java.util.Collection"
189      */
190     public void setItems(Collection items) {
191         this.items = items;
192     }
193 
194     /**
195      * @jsp.attribute description="nodeDataName is not supported in this tag !" required="false" rtexprvalue="false"
196      */
197     public void setNodeDataName(String name) {
198         throw new UnsupportedOperationException("nodeDataName not supported in this tag");
199     }
200 
201     /**
202      * TODO : provide relevant doc for this attribute -- only overriden to do so.
203      */
204     public void setContentNodeName(String name) {
205         super.setContentNodeName(name);
206     }
207 
208     private Collection getCollection() throws RepositoryException {
209         if (this.items != null) {
210             return this.items;
211         }
212         // If this is a nested iterator, the collection should be from the local content node.
213         Content page = super.getFirstMatchingNode();
214         return page == null ? Collections.EMPTY_LIST : page.getChildren(ItemType.CONTENTNODE);
215     }
216 
217     protected LoopTagStatus getLoopStatus() {
218         /**
219          * Implementation class.
220          */
221         class Status implements LoopTagStatus, Serializable {
222 
223             public Object getCurrent() {
224                 return current;
225             }
226 
227             public int getIndex() {
228                 return count + begin - 1;
229             }
230 
231             public int getCount() {
232                 return count;
233             }
234 
235             public boolean isFirst() {
236                 return (count == 1); // count starts with 1
237             }
238 
239             public boolean isLast() {
240                 int lastItem = end != null ? end.intValue() : size;
241                 return count + begin == lastItem;
242             }
243 
244             public Integer getBegin() {
245                 return new Integer(begin);
246             }
247 
248             public Integer getEnd() {
249                 return end;
250             }
251 
252             public Integer getStep() {
253                 return new Integer(step);
254             }
255         }
256 
257         if (status == null) {
258             status = new Status();
259         }
260 
261         return status;
262     }
263 
264     public int doStartTag() {
265         index += begin;
266 
267         Collection children;
268         try {
269             children = getCollection();
270         }
271         catch (PathNotFoundException e) {
272             // ok, this is normal
273             return SKIP_BODY;
274         }
275         catch (AccessDeniedException e) {
276             log.debug(e.getMessage());
277             return SKIP_BODY;
278         }
279         catch (RepositoryException e) {
280             log.error(e.getMessage(), e);
281             return SKIP_BODY;
282         }
283 
284         this.size = children.size();
285 
286         this.savePrevState();
287 
288         pageContext.setAttribute(ContentNodeIterator.SIZE, new Integer(size), PageContext.REQUEST_SCOPE);
289 
290         pageContext.setAttribute(ContentNodeIterator.CURRENT_INDEX, new Integer(this.count), PageContext.REQUEST_SCOPE);
291 
292         pageContext.setAttribute(ContentNodeIterator.CONTENT_NODE_COLLECTION_NAME, getContentNodeCollectionName(), PageContext.REQUEST_SCOPE);
293 
294         Resource.setLocalContentNodeCollectionName(getContentNodeCollectionName());
295 
296         this.contentNodeIterator = children.iterator();
297         for (int i = 0; i < begin; i++) {
298             if (this.contentNodeIterator.hasNext()) {
299                 this.contentNodeIterator.next();
300             }
301         }
302 
303         return doIteration() ? EVAL_BODY_INCLUDE : SKIP_BODY;
304     }
305 
306     public int doAfterBody() {
307         return doIteration() ? EVAL_BODY_AGAIN : SKIP_BODY;
308     }
309 
310     private boolean doIteration() {
311         if (this.contentNodeIterator.hasNext()) {
312 
313             if (this.end != null && this.count > this.end.intValue()) {
314                 return false;
315             }
316 
317             pageContext.setAttribute(
318                 ContentNodeIterator.CURRENT_INDEX,
319                 new Integer(this.count),
320                 PageContext.REQUEST_SCOPE);
321 
322             if (StringUtils.isNotEmpty(varStatus)) {
323                 pageContext.setAttribute(varStatus, getLoopStatus());
324             }
325 
326             for (int j = 0; j < this.step; j++) {
327                 current = this.contentNodeIterator.next();
328                 Resource.setLocalContentNode((Content) current);
329             }
330 
331             this.count++;
332 
333             return true;
334         }
335         return false;
336     }
337 
338     public int doEndTag() {
339 
340         this.restorePrevState();
341         this.restorePreviousState = false;
342         this.size = 0;
343         this.count = 0;
344         this.current = null;
345 
346         if (varStatus != null) {
347             pageContext.removeAttribute(varStatus, PageContext.PAGE_SCOPE);
348         }
349 
350         reset();
351 
352         return EVAL_PAGE;
353     }
354 
355     public void reset() {
356         setContentNodeCollectionName(null); // TODO : is this correct - here ?
357         this.contentNodeIterator = null;
358         this.begin = 0;
359         this.end = null;
360         this.step = 1;
361         this.size = 0;
362         this.count = 0;
363         this.varStatus = null;
364         this.status = null;
365         this.items = null;
366 
367         this.outerCollName = null;
368         this.outerCurrIdx = null;
369         this.outerLocalContentNode = null;
370         this.outerResCollName = null;
371         this.outerSize = null;
372     }
373 
374     /** Checks if a content node iterator tag is already in operation and saves it's state. */
375     private void savePrevState() {
376         HttpServletRequest req = (HttpServletRequest) this.pageContext.getRequest();
377 
378         // savePrevState() was invoked. Enable restorePrevState()
379         this.restorePreviousState = true;
380 
381         if (req.getAttribute(ContentNodeIterator.SIZE) != null) {
382             this.outerSize = (Integer) pageContext.getAttribute(ContentNodeIterator.SIZE, PageContext.REQUEST_SCOPE);
383             this.outerCollName = (String) pageContext.getAttribute(
384                 ContentNodeIterator.CONTENT_NODE_COLLECTION_NAME,
385                 PageContext.REQUEST_SCOPE);
386             this.outerCurrIdx = (Integer) pageContext.getAttribute(
387                 ContentNodeIterator.CURRENT_INDEX,
388                 PageContext.REQUEST_SCOPE);
389             this.outerLocalContentNode = Resource.getLocalContentNode();
390             this.outerResCollName = Resource.getLocalContentNodeCollectionName();
391         }
392         else{
393             this.outerLocalContentNode = Resource.getLocalContentNode();
394         }
395 
396     }
397 
398     private void restorePrevState() {
399         if (this.restorePreviousState) {
400             HttpServletRequest req = (HttpServletRequest) this.pageContext.getRequest();
401             if (this.outerSize != null) {
402                 pageContext.setAttribute(ContentNodeIterator.SIZE, this.outerSize);
403                 pageContext.setAttribute(ContentNodeIterator.CURRENT_INDEX, this.outerCurrIdx);
404                 pageContext.setAttribute(ContentNodeIterator.CONTENT_NODE_COLLECTION_NAME, this.outerCollName);
405                 Resource.setLocalContentNode(this.outerLocalContentNode);
406                 Resource.setLocalContentNodeCollectionName(this.outerResCollName);
407             }
408             else {
409                 if(outerLocalContentNode != null){
410                     Resource.setLocalContentNode(this.outerLocalContentNode);
411                 }
412                 else{
413                     Resource.removeLocalContentNode();
414                 }
415                 Resource.removeLocalContentNodeCollectionName();
416                 pageContext.removeAttribute(ContentNodeIterator.CURRENT_INDEX);
417                 pageContext.removeAttribute(ContentNodeIterator.SIZE);
418                 pageContext.removeAttribute(ContentNodeIterator.CONTENT_NODE_COLLECTION_NAME);
419             }
420         }
421     }
422 
423 }