View Javadoc

1   /**
2    * This file Copyright (c) 2012-2013 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.templating.jsp.taglib;
35  
36  import info.magnolia.cms.core.Content;
37  import info.magnolia.cms.core.Content.ContentFilter;
38  import info.magnolia.cms.core.ItemType;
39  import info.magnolia.cms.core.NodeData;
40  import info.magnolia.cms.i18n.I18nContentSupportFactory;
41  import info.magnolia.context.MgnlContext;
42  
43  import java.io.IOException;
44  import java.util.ArrayList;
45  import java.util.Collection;
46  import java.util.Iterator;
47  import java.util.List;
48  
49  import javax.jcr.RepositoryException;
50  import javax.servlet.http.HttpServletRequest;
51  import javax.servlet.jsp.JspException;
52  import javax.servlet.jsp.JspWriter;
53  import javax.servlet.jsp.tagext.TagSupport;
54  
55  import org.apache.commons.lang.StringEscapeUtils;
56  import org.apache.commons.lang.StringUtils;
57  import org.apache.commons.lang.exception.NestableRuntimeException;
58  import org.slf4j.Logger;
59  import org.slf4j.LoggerFactory;
60  import org.tldgen.annotations.BodyContent;
61  import org.tldgen.annotations.Tag;
62  
63  /**
64   * Draws a simple, css based, navigation menu. The menu layout can then be customized using css, and the default menu
65   * should be enough for most uses. Two following page properties will also be used in the menu:
66   * <ul>
67   * <li><code>navTitle</code>: a title to use for the navigation menu, if different from the real page title</li>
68   * <li><code>accessKey</code>: an optional access key which will be added to the link</li>
69   * <li><code>wrappingElement</code>: an optional html element (div, span, p, etc) to go within the &lt;a&gt; tag wrapping the anchor text
70   * </ul>
71   * 
72   * @jsp.tag name="simpleNavigation" body-content="empty"
73   * @jsp.tag-example
74   * <pre>
75   * &lt;cmsu:simpleNavigation startLevel="3" style="mystyle"/&gt;
76   * 
77   * Will output the following:
78   * 
79   * &lt;ul class="level3 mystyle"&gt;
80   *     &lt;li&gt;&lt;a href="..."&gt;page 1 name &lt;/a&gt;&lt;/li&gt;
81   *     &lt;li&gt;&lt;a href="..."&gt;page 2 name &lt;/a&gt;&lt;/li&gt;
82   *     &lt;li class="trail"&gt;&lt;a href="..."&gt;page 3 name &lt;/a&gt;
83   *         &lt;ul class="level3"&gt;
84   *             &lt;li&gt;&lt;a href="..."&gt;subpage 1 name &lt;/a&gt;&lt;/li&gt;
85   *             &lt;li&gt;&lt;a href="..."&gt;subpage 2 name &lt;/a&gt;&lt;/li&gt;
86   *             &lt;li&gt;&lt;strong&gt;&lt;a href="..."&gt;selected page name &lt;/a&gt;&lt;/strong&gt;&lt;/li&gt;
87   *         &lt;/ul&gt;
88   *     &lt;/li&gt;
89   *     &lt;li&gt;&lt;a href="..."&gt;page 4 name &lt;/a&gt;&lt;/li&gt;
90   * &lt;/ul&gt;
91   * </pre>
92   * @author Fabrizio Giustina
93   * @version $Revision$ ($Author$)
94   */
95  @Tag(name = "simpleNavigation", bodyContent = BodyContent.EMPTY)
96  public class SimpleNavigationTag extends TagSupport {
97  
98      /**
99       * Css class added to active page.
100      */
101     private static final String CSS_LI_ACTIVE = "active";
102 
103     /**
104      * Css class added to ancestor of the active page.
105      */
106     private static final String CSS_LI_TRAIL = "trail";
107 
108     /**
109      * Css class added to leaf pages.
110      */
111     private static final String CSS_LI_LEAF = "leaf";
112 
113     /**
114      * Css class added to open trees.
115      */
116     private static final String CSS_LI_CLOSED = "closed";
117 
118     /**
119      * Css class added to closed trees.
120      */
121     private static final String CSS_LI_OPEN = "open";
122 
123     /**
124      * Css class added to first li in ul.
125      */
126     private static final String CSS_LI_FIRST = "first";
127 
128     /**
129      * Css class added to last li in ul.
130      */
131     private static final String CSS_LI_LAST = "last";
132 
133     /**
134      * Page property: navigation title.
135      */
136     private static final String NODEDATA_NAVIGATIONTITLE = "navTitle";
137 
138     /**
139      * Page property: access key.
140      */
141     public static final String NODEDATA_ACCESSKEY = "accessKey";
142 
143     /**
144      * Default name for "open menu" nodeData.
145      */
146     public static final String DEFAULT_OPENMENU_NODEDATA = "openMenu";
147 
148     /**
149      * Default name for "hide in nav" nodeData.
150      */
151     public static final String DEFAULT_HIDEINNAV_NODEDATA = "hideInNav";
152 
153     /**
154      * Default name for "wrapperElement" nodeData.
155      */
156     public static final String DEFAULT_WRAPPERELEMENT_NODEDATA = "";
157 
158     /**
159      * Expand all expand all the nodes.
160      */
161     public static final String EXPAND_ALL = "all";
162 
163     /**
164      * Expand all expand only page that should be displayed in navigation.
165      */
166     public static final String EXPAND_SHOW = "show";
167 
168     /**
169      * Do not use expand functions.
170      */
171     public static final String EXPAND_NONE = "none";
172 
173     /**
174      * Stable serialVersionUID.
175      */
176     private static final long serialVersionUID = 224L;
177 
178     /**
179      * Logger.
180      */
181     private static Logger log = LoggerFactory.getLogger(SimpleNavigationTag.class);
182 
183     /**
184      * Start level.
185      */
186     private int startLevel;
187 
188     /**
189      * End level.
190      */
191     private int endLevel;
192 
193     /**
194      * Name for the "hide in nav" nodeData.
195      */
196     private String hideInNav;
197 
198     /**
199      * Name for the "open menu" nodeData.
200      */
201     private String openMenu;
202 
203     /**
204      * Style to apply to the menu.
205      */
206     private String style;
207 
208     /**
209      * html element to wrap the anchortext. (i.e. &lt;a&gt;&lt;wrapper&gt;...&lt;/wrapper&gt;&lt;/a&gt;)
210      */
211     public String wrapperElement;
212 
213     /**
214      * Expand all the nodes. (sitemap mode)
215      */
216     private String expandAll = EXPAND_NONE;
217 
218     private boolean relativeLevels = false;
219 
220     /**
221      * Name for a page property which will be written to the css class attribute.
222      */
223     private String classProperty;
224 
225     /**
226      * Name for the "nofollow" hodeData (for link that must be ignored by search engines).
227      */
228     private String nofollow;
229 
230     /**
231      * Content Filter to use to evaluate if a page should be drawn.
232      */
233     private ContentFilter filter;
234 
235     private String contentFilter = "";
236 
237     /**
238      * Flag to set if the first and last li in each ul should be marked with a special css class.
239      */
240     private boolean markFirstAndLastElement = false;
241 
242     /**
243      * The start level for navigation, defaults to 0.
244      * 
245      * @jsp.attribute required="false" rtexprvalue="true" type="int"
246      */
247     public void setStartLevel(int startLevel) {
248         this.startLevel = startLevel;
249     }
250 
251     /**
252      * The end level for navigation, defaults to 0.
253      * 
254      * @jsp.attribute required="false" rtexprvalue="true" type="int"
255      */
256     public void setEndLevel(int endLevel) {
257         this.endLevel = endLevel;
258     }
259 
260     /**
261      * The css class to be applied to the first ul. Default is empty.
262      * 
263      * @jsp.attribute required="false" rtexprvalue="true"
264      */
265     public void setStyle(String style) {
266         this.style = style;
267     }
268 
269     /**
270      * Name for the "hide in nav" nodeData. If a page contains a boolean property with this name and
271      * it is set to true, the page is not shown in navigation. Defaults to "hideInNav".
272      * 
273      * @jsp.attribute required="false" rtexprvalue="true"
274      */
275     public void setHideInNav(String hideInNav) {
276         this.hideInNav = hideInNav;
277     }
278 
279     /**
280      * Name for the "open menu" nodeData. If a page contains a boolean property with this name and
281      * it is set to true, subpages are always shown also if the page is not selected.
282      * Defaults to "openMenu".
283      * 
284      * @jsp.attribute required="false" rtexprvalue="true"
285      */
286     public void setOpenMenu(String openMenu) {
287         this.openMenu = openMenu;
288     }
289 
290     /**
291      * Name for the "nofollow" nodeData. If a page contains a boolean property with this name
292      * and it is set to true, rel="nofollow" will be added to the generated link
293      * (for links the should be ignored by search engines).
294      * 
295      * @jsp.attribute required="false" rtexprvalue="true"
296      */
297     public void setNofollow(String nofollow) {
298         this.nofollow = nofollow;
299     }
300 
301     /**
302      * A variable in the pageContext that contains a content filter, determining if a given page should be drawn or not.
303      * 
304      * @jsp.attribute required="false" rtexprvalue="true"
305      */
306     public void setContentFilter(String contentFilter) {
307         this.contentFilter = contentFilter;
308     }
309 
310     /**
311      * Sitemap mode. Can be assigned the "show" value. Only showable pages will be displayed. Any other value will
312      * result in displaying all pages.
313      * 
314      * @jsp.attribute required="false" rtexprvalue="true"
315      */
316     public void setExpandAll(String expandAll) {
317         if (expandAll.equalsIgnoreCase(EXPAND_SHOW)) {
318             this.expandAll = expandAll;
319         }
320         else {
321             this.expandAll = EXPAND_ALL;
322         }
323     }
324 
325     /**
326      * If set to true, the startLevel and endLevel values are treated relatively to the current active page.
327      * The default value is false.
328      * 
329      * @jsp.attribute required="false" rtexprvalue="true" type="boolean"
330      */
331     public void setRelativeLevels(boolean relativeLevels) {
332         this.relativeLevels = relativeLevels;
333     }
334 
335     /**
336      * Name for a page property that will hold a css class name which will be added to the html class attribute.
337      * 
338      * @jsp.attribute required="false" rtexprvalue="true"
339      */
340     public void setClassProperty(String classProperty) {
341         this.classProperty = classProperty;
342     }
343 
344     /**
345      * When specified, all links will have the anchortext wrapped in the supplied element. (such as "span")
346      * 
347      * @param wrapperElement name of an html element that will be included in the anchor, wrapping the anchortext
348      * @jsp.attribute required="false" rtexprvalue="true"
349      */
350     public void setWrapperElement(String wrapperElement) {
351         this.wrapperElement = wrapperElement;
352     }
353 
354     /**
355      * If set to true, a "first" or "last" css class will be added to the list of css classes of the
356      * first and the last li in each ul.
357      * 
358      * @jsp.attribute required="false" rtexprvalue="true" type="boolean"
359      */
360     public void setMarkFirstAndLastElement(boolean flag) {
361         markFirstAndLastElement = flag;
362     }
363 
364     @Override
365     public int doEndTag() throws JspException {
366         Content activePage = getCurrentActivePage();
367         try {
368             while (!ItemType.PAGE.getSystemName().equals(activePage.getNodeTypeName()) && activePage.getLevel() != 0) {
369                 activePage = activePage.getParent();
370             }
371         } catch (RepositoryException e) {
372             log.error("Failed to obtain parent page for " + getCurrentActivePage().getHandle(), e);
373             activePage = getCurrentActivePage();
374         }
375         JspWriter out = this.pageContext.getOut();
376 
377         if (StringUtils.isNotEmpty(this.contentFilter)) {
378             try {
379                 filter = (ContentFilter) this.pageContext.getAttribute(this.contentFilter);
380             } catch (ClassCastException e) {
381                 log.error("contentFilter assigned was not a content filter", e);
382             }
383         } else {
384             filter = null;
385         }
386 
387         if (startLevel > endLevel) {
388             endLevel = 0;
389         }
390 
391         try {
392             final int activePageLevel = activePage.getLevel();
393             // if we are to treat the start and end level as relative
394             // to the active page, we adjust them here...
395             if (relativeLevels) {
396                 this.startLevel += activePageLevel;
397                 this.endLevel += activePageLevel;
398             }
399             if (this.startLevel <= activePageLevel) {
400                 Content startContent = activePage.getAncestor(this.startLevel);
401                 drawChildren(startContent, activePage, out);
402             }
403 
404         } catch (RepositoryException e) {
405             log.error("RepositoryException caught while drawing navigation: " + e.getMessage(), e);
406             return EVAL_PAGE;
407         } catch (IOException e) {
408             // should never happen
409             throw new NestableRuntimeException(e);
410         }
411 
412         return EVAL_PAGE;
413     }
414 
415     @Override
416     public void release() {
417         this.startLevel = 0;
418         this.endLevel = 0;
419         this.hideInNav = null;
420         this.openMenu = null;
421         this.style = null;
422         this.classProperty = null;
423         this.expandAll = EXPAND_NONE;
424         this.relativeLevels = false;
425         this.wrapperElement = "";
426         this.contentFilter = "";
427         this.filter = null;
428         this.nofollow = null;
429         this.markFirstAndLastElement = false;
430         super.release();
431     }
432 
433     /**
434      * Draws page children as an unordered list.
435      * 
436      * @param page current page
437      * @param activePage active page
438      * @param out jsp writer
439      * @throws IOException jspwriter exception
440      * @throws RepositoryException any exception thrown during repository reading
441      */
442     private void drawChildren(Content page, Content activePage, JspWriter out) throws IOException, RepositoryException {
443 
444         Collection<Content> children = new ArrayList<Content>(page.getChildren(ItemType.CONTENT));
445 
446         if (children.size() == 0) {
447             return;
448         }
449 
450         out.print("<ul class=\"level");
451         out.print(page.getLevel());
452         if (style != null && page.getLevel() == startLevel) {
453             out.print(" ");
454             out.print(style);
455         }
456         out.print("\">");
457 
458         Iterator<Content> iter = children.iterator();
459         // loop through all children and discard those we don't want to display
460         while (iter.hasNext()) {
461             final Content child = iter.next();
462 
463             if (expandAll.equalsIgnoreCase(EXPAND_NONE) || expandAll.equalsIgnoreCase(EXPAND_SHOW)) {
464                 if (child
465                         .getNodeData(StringUtils.defaultString(this.hideInNav, DEFAULT_HIDEINNAV_NODEDATA)).getBoolean()) {
466                     iter.remove();
467                     continue;
468                 }
469                 // use a filter
470                 if (filter != null) {
471                     if (!filter.accept(child)) {
472                         iter.remove();
473                         continue;
474                     }
475                 }
476             } else {
477                 if (child.getNodeData(StringUtils.defaultString(this.hideInNav, DEFAULT_HIDEINNAV_NODEDATA)).getBoolean()) {
478                     iter.remove();
479                     continue;
480                 }
481             }
482         }
483 
484         boolean isFirst = true;
485         Iterator<Content> visibleIt = children.iterator();
486         while (visibleIt.hasNext()) {
487             Content child = visibleIt.next();
488             List<String> cssClasses = new ArrayList<String>(4);
489 
490             NodeData nodeData = I18nContentSupportFactory.getI18nSupport().getNodeData(child, NODEDATA_NAVIGATIONTITLE);
491             String title = null;
492             if(nodeData != null){
493                 title = nodeData.getString(StringUtils.EMPTY);
494             }
495 
496             // if nav title is not set, the main title is taken
497             if (StringUtils.isEmpty(title)) {
498                 title = child.getTitle();
499             }
500 
501             // if main title is not set, the name of the page is taken
502             if (StringUtils.isEmpty(title)) {
503                 title = child.getName();
504             }
505 
506             boolean showChildren = false;
507             boolean self = false;
508 
509             if (!expandAll.equalsIgnoreCase(EXPAND_NONE)) {
510                 showChildren = true;
511             }
512 
513             if (activePage.getHandle().equals(child.getHandle())) {
514                 // self
515                 showChildren = true;
516                 self = true;
517                 cssClasses.add(CSS_LI_ACTIVE);
518             }
519             else if (!showChildren) {
520                 showChildren = child.getLevel() <= activePage.getAncestors().size() && StringUtils.equals(activePage.getAncestor(child.getLevel()).getHandle(), child.getHandle());
521             }
522 
523             if (!showChildren) {
524                 showChildren = child
525                         .getNodeData(StringUtils.defaultString(this.openMenu, DEFAULT_OPENMENU_NODEDATA))
526                         .getBoolean();
527             }
528 
529             if (endLevel > 0) {
530                 showChildren &= child.getLevel() < endLevel;
531             }
532 
533             cssClasses.add(hasVisibleChildren(child) ? showChildren ? CSS_LI_OPEN : CSS_LI_CLOSED : CSS_LI_LEAF);
534 
535             if (child.getLevel() < activePage.getLevel()
536                     && activePage.getAncestor(child.getLevel()).getHandle().equals(child.getHandle())) {
537                 cssClasses.add(CSS_LI_TRAIL);
538             }
539 
540             if (StringUtils.isNotEmpty(classProperty) && child.hasNodeData(classProperty)) {
541                 cssClasses.add(child.getNodeData(classProperty).getString(StringUtils.EMPTY));
542             }
543 
544             if (markFirstAndLastElement && isFirst) {
545                 cssClasses.add(CSS_LI_FIRST);
546                 isFirst = false;
547             }
548 
549             if (markFirstAndLastElement && !visibleIt.hasNext()) {
550                 cssClasses.add(CSS_LI_LAST);
551             }
552 
553             StringBuffer css = new StringBuffer(cssClasses.size() * 10);
554             Iterator<String> iterator = cssClasses.iterator();
555             while (iterator.hasNext()) {
556                 css.append(iterator.next());
557                 if (iterator.hasNext()) {
558                     css.append(" ");
559                 }
560             }
561 
562             out.print("<li class=\"");
563             out.print(css.toString());
564             out.print("\">");
565 
566             if (self) {
567                 out.println("<strong>");
568             }
569 
570             String accesskey = null;
571             if(child.getNodeData(NODEDATA_ACCESSKEY) != null){
572                 accesskey = child.getNodeData(NODEDATA_ACCESSKEY).getString(StringUtils.EMPTY);
573             }
574 
575             out.print("<a href=\"");
576             out.print(((HttpServletRequest) this.pageContext.getRequest()).getContextPath());
577             out.print(I18nContentSupportFactory.getI18nSupport().toI18NURI(child.getHandle()));
578             out.print(".html\"");
579 
580             if (StringUtils.isNotEmpty(accesskey)) {
581                 out.print(" accesskey=\"");
582                 out.print(accesskey);
583                 out.print("\"");
584             }
585 
586             if (nofollow != null && child.getNodeData(this.nofollow).getBoolean())
587             {
588                 out.print(" rel=\"nofollow\"");
589             }
590 
591             out.print(">");
592 
593             if (StringUtils.isNotEmpty(this.wrapperElement)) {
594                 out.print("<" + this.wrapperElement + ">");
595             }
596 
597             out.print(StringEscapeUtils.escapeHtml(title));
598 
599             if (StringUtils.isNotEmpty(this.wrapperElement)) {
600                 out.print("</" + this.wrapperElement + ">");
601             }
602 
603             out.print(" </a>");
604 
605             if (self) {
606                 out.println("</strong>");
607             }
608 
609             if (showChildren) {
610                 drawChildren(child, activePage, out);
611             }
612             out.print("</li>");
613         }
614 
615         out.print("</ul>");
616     }
617 
618     /**
619      * Checks if the page has a visible children. Pages with the <code>hide in nav</code> attribute set to <code>true</code> are ignored.
620      * 
621      * @param page root page
622      * @return <code>true</code> if the given page has at least one visible child.
623      */
624     private boolean hasVisibleChildren(Content page) {
625         Collection<Content> children = page.getChildren();
626         if (children.size() > 0 && expandAll.equalsIgnoreCase(EXPAND_ALL)) {
627             return true;
628         }
629         for (Content ch : children) {
630             if (!ch.getNodeData(StringUtils.defaultString(this.hideInNav, DEFAULT_HIDEINNAV_NODEDATA)).getBoolean()) {
631                 return true;
632             }
633         }
634         return false;
635     }
636 
637     protected Content getCurrentActivePage() {
638         Content currentActpage = MgnlContext.getAggregationState().getCurrentContent();
639         if (currentActpage == null) {
640             currentActpage = MgnlContext.getAggregationState().getMainContent();
641         }
642         return currentActpage;
643     }
644 
645 }