View Javadoc

1   /**
2    * This file Copyright (c) 2008-2010 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.util;
35  
36  import java.util.ArrayList;
37  import java.util.Collection;
38  import java.util.Collections;
39  import java.util.Comparator;
40  import java.util.List;
41  
42  import javax.jcr.PathNotFoundException;
43  import javax.jcr.RepositoryException;
44  
45  import org.apache.commons.lang.StringUtils;
46  import org.slf4j.Logger;
47  import org.slf4j.LoggerFactory;
48  
49  import info.magnolia.cms.core.AbstractContent;
50  import info.magnolia.cms.core.Content;
51  import info.magnolia.cms.core.ItemType;
52  import info.magnolia.cms.core.NodeData;
53  
54  
55  /**
56   * This wrapper inherits content from the parent hierarchy. The method {@link #isAnchor()} defines
57   * the anchor to which the inheritance is performed relative to. By default the anchor is a page
58   * (mgnl:content).
59   * <p>
60   * The inheritance is then performed as follows:
61   * <ul>
62   * <li>try to get the content directly</li>
63   * <li>find next anchor</li>
64   * <li>try to get the content from the anchor</li>
65   * <li>repeat until no anchor can be found anymore (root)</li>
66   * </ul>
67   * <p>
68   * The {@link #getChildren()} methods merge the direct and inherited children by first adding the
69   * inherited children to the collection and then the direct children.
70   * @author pbracher
71   * @version $Id: InheritanceContentWrapper.java 36903 2010-09-02 16:01:20Z pbaerfuss $
72   */
73  public class InheritanceContentWrapper extends ContentWrapper {
74  
75      private static Logger log = LoggerFactory.getLogger(InheritanceContentWrapper.class);
76  
77      /**
78       * True if this node were achieved through inheritance.
79       */
80      private boolean inherited;
81  
82      /**
83       * Used if in the {@link #wrap(Content)} method.
84       * @param wrappedContent
85       * @param inherited true if this node is in the chain of inheritance.
86       */
87      public InheritanceContentWrapper(Content wrappedContent, boolean inherited) {
88          super(wrappedContent);
89          this.inherited = inherited;
90      }
91  
92      /**
93       * Starts the inheritance.
94       */
95      public InheritanceContentWrapper(Content node) {
96          this(node, false);
97      }
98  
99      @Override
100     public boolean hasContent(String name) throws RepositoryException {
101         return getContentSafely(name) != null;
102     }
103 
104     @Override
105     public Content getContent(String name) throws RepositoryException {
106         Content inherited = getContentSafely(name);
107         if(inherited == null){
108             throw new PathNotFoundException("Can't inherit a node [" + name + "] on node [" + getWrappedContent().getHandle() + "]");
109         }
110         return inherited;
111     }
112 
113     @Override
114     public Collection<Content> getChildren(ContentFilter filter, String namePattern, Comparator<Content> orderCriteria){
115         List children = new ArrayList();
116 
117         // add inherited children
118         try {
119             Content inherited = getContentSafely(findNextAnchor(), resolveInnerPath());
120             if(inherited != null){
121                 children.addAll(((AbstractContent)inherited).getChildren(filter, namePattern, orderCriteria));
122             }
123         }
124         catch (RepositoryException e) {
125             throw new RuntimeException("Can't inherit children from " + getWrappedContent(), e);
126         }
127 
128         // add direct children
129         children.addAll(((AbstractContent)getWrappedContent()).getChildren(filter, namePattern, orderCriteria));
130         if(orderCriteria != null){
131             Collections.sort(children, orderCriteria);
132         }
133 
134         return wrapContentNodes(children);
135     }
136 
137     /**
138      * Returns the inner path of the this node up to the anchor.
139      */
140     protected String resolveInnerPath() throws RepositoryException {
141         final String path;
142         InheritanceContentWrapper anchor = findAnchor();
143         // if no anchor left we are relative to the root
144         if(anchor == null){
145             path = this.getHandle();
146         }
147         else{
148             path = StringUtils.substringAfter(this.getHandle(), anchor.getHandle());
149         }
150         return StringUtils.removeStart(path,"/");
151     }
152 
153     /**
154      * This method returns null if no content has been found.
155      */
156     protected Content getContentSafely(String name) throws RepositoryException {
157         if(getWrappedContent().hasContent(name)){
158             return super.getContent(name);
159         }
160 
161         String innerPath = resolveInnerPath() + "/" + name;
162         innerPath = StringUtils.removeStart(innerPath,"/");
163 
164         Content inherited = getContentSafely(findNextAnchor(), innerPath);
165         return inherited;
166     }
167 
168     /**
169      * This method returns null if no content has been found.
170      */
171     protected Content getContentSafely(InheritanceContentWrapper anchor, String path) throws RepositoryException{
172         if(anchor == null){
173             return null;
174         }
175         if(StringUtils.isEmpty(path)){
176             return anchor;
177         }
178         return anchor.getContentSafely(path);
179     }
180 
181     /**
182      * Find the anchor for this node.
183      */
184     protected InheritanceContentWrapper findAnchor() throws RepositoryException{
185         if(getLevel() ==0){
186             return null;
187         }
188         if(isAnchor()){
189             return this;
190         }
191         // until the current node is the anchor
192         return ((InheritanceContentWrapper)getParent()).findAnchor();
193     }
194 
195     /**
196      * Find next anchor.
197      */
198     protected InheritanceContentWrapper findNextAnchor() throws RepositoryException{
199         final InheritanceContentWrapper currentAnchor = findAnchor();
200         if(currentAnchor != null && getLevel() >0){
201             return ((InheritanceContentWrapper)currentAnchor.getParent()).findAnchor();
202         }
203         return null;
204     }
205 
206     /**
207      * True if this node is an anchor. By default true if this node is of type mgnl:content (page)
208      */
209     protected boolean isAnchor() {
210         return isNodeType(ItemType.CONTENT.getSystemName());
211     }
212 
213     public NodeData getNodeData(String name) {
214         try {
215             if (getWrappedContent().hasNodeData(name)) {
216                 return getWrappedContent().getNodeData(name);
217             }
218             Content inherited = getContentSafely(findNextAnchor(), resolveInnerPath());
219             if(inherited != null){
220                 return inherited.getNodeData(name);
221             }
222         }
223         catch (RepositoryException e) {
224             throw new RuntimeException("Can't inherit nodedata " + name + "  for " + getWrappedContent(), e);
225 
226         }
227         // creates a none existing node data in the standard manner
228         return super.getNodeData(name);
229     }
230 
231     /**
232      * Wrap returned nodes. Sets the inherited flag
233      */
234     protected Content wrap(Content node) {
235         // only wrap once
236         if(node instanceof InheritanceContentWrapper){
237             return node;
238         }
239         // set the inherited flag
240         boolean inherited = !isSubNode(node);
241         return new InheritanceContentWrapper(node, inherited);
242     }
243 
244     /**
245      * True if the current node is an ancestor of node.
246      */
247     protected boolean isSubNode(Content node) {
248         return node.getHandle().startsWith(getWrappedContent().getHandle());
249     }
250 
251     public boolean isInherited() {
252         return this.inherited;
253     }
254 }