KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > info > magnolia > cms > util > ContentUtil


1 /**
2  *
3  * Magnolia and its source-code is licensed under the LGPL.
4  * You may copy, adapt, and redistribute this file for commercial or non-commercial use.
5  * When copying, adapting, or redistributing this document in keeping with the guidelines above,
6  * you are required to provide proper attribution to obinary.
7  * If you reproduce or distribute the document without making any substantive modifications to its content,
8  * please use the following attribution line:
9  *
10  * Copyright 1993-2006 obinary Ltd. (http://www.obinary.com) All rights reserved.
11  *
12  */

13 package info.magnolia.cms.util;
14
15 import info.magnolia.cms.core.Content;
16 import info.magnolia.cms.core.HierarchyManager;
17 import info.magnolia.cms.core.ItemType;
18 import info.magnolia.cms.core.NodeData;
19 import info.magnolia.cms.core.Content.ContentFilter;
20 import info.magnolia.cms.security.AccessDeniedException;
21 import info.magnolia.context.MgnlContext;
22
23 import java.lang.reflect.InvocationTargetException JavaDoc;
24 import java.util.ArrayList JavaDoc;
25 import java.util.Collection JavaDoc;
26 import java.util.HashMap JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.List JavaDoc;
29 import java.util.Map JavaDoc;
30
31 import javax.jcr.PathNotFoundException;
32 import javax.jcr.RepositoryException;
33
34 import org.apache.commons.beanutils.BeanUtils;
35 import org.apache.commons.lang.StringUtils;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40  * Some easy to use methods to handle with Content objects.
41  * @author philipp
42  */

43 public class ContentUtil {
44
45     private static Logger log = LoggerFactory.getLogger(ContentUtil.class);
46
47     /**
48      * Content filter accepting everything
49      */

50     public static ContentFilter ALL_NODES_CONTENT_FILTER = new ContentFilter() {
51
52         public boolean accept(Content content) {
53             return true;
54         }
55     };
56     
57     /**
58      * @author Philipp Bracher
59      * @version $Id: ContentUtil.java 6740 2006-10-13 10:42:47Z philipp $
60      *
61      */

62     public interface Visitor {
63         void visit(Content node) throws Exception JavaDoc;
64     }
65     
66     /**
67      * Content filter accepting everything
68      */

69     public static ContentFilter EXCLUDE_META_DATA_CONTENT_FILTER = new ContentFilter() {
70         public boolean accept(Content content) {
71             return !content.getName().startsWith("jcr:") && !content.isNodeType(ItemType.NT_METADATA);
72         }
73     };
74
75     /**
76      * Returns a Content object of the named repository or null if not existing.
77      * @param repository
78      * @param path
79      * @return null if not found
80      */

81     public static Content getContent(String JavaDoc repository, String JavaDoc path) {
82         try {
83             return MgnlContext.getHierarchyManager(repository).getContent(path);
84         }
85         catch (RepositoryException e) {
86             return null;
87         }
88     }
89
90     /**
91      * Get the node or null if not exists
92      * @param node
93      * @param name
94      * @return the sub node
95      */

96     public static Content getContent(Content node, String JavaDoc name) {
97         try {
98             return node.getContent(name);
99         }
100         catch (RepositoryException e) {
101             return null;
102         }
103     }
104
105     /**
106      * If the node doesn't exist just create it.
107      * @param node
108      * @param name
109      * @param contentType
110      * @return
111      * @throws AccessDeniedException
112      * @throws RepositoryException
113      */

114     public static Content getOrCreateContent(Content node, String JavaDoc name, ItemType contentType)
115         throws AccessDeniedException, RepositoryException {
116         Content res = null;
117         try {
118             res = node.getContent(name);
119         }
120         catch (PathNotFoundException e) {
121             res = node.createContent(name, contentType);
122         }
123         return res;
124     }
125
126     /**
127      * Get a subnode case insensitive.
128      * @param node
129      * @param name
130      * @param type
131      * @return
132      */

133     public static Content getCaseInsensitive(Content node, String JavaDoc name) {
134         if (name == null || node == null) {
135             return null;
136         }
137         name = name.toLowerCase();
138         for (Iterator JavaDoc iter = node.getChildren(ALL_NODES_CONTENT_FILTER).iterator(); iter.hasNext();) {
139             Content child = (Content) iter.next();
140             if (child.getName().toLowerCase().equals(name)) {
141                 return child;
142             }
143         }
144         return null;
145     }
146
147     /**
148      * Get all children recursively (content and contentnode)
149      */

150     public static List JavaDoc collectAllChildren(Content node) {
151         List JavaDoc nodes = new ArrayList JavaDoc();
152         return collectAllChildren(nodes, node, new ItemType[]{ItemType.CONTENT, ItemType.CONTENTNODE});
153     }
154
155     /**
156      * Get all children using a filter
157      * @param node
158      * @param filter
159      * @return list of all found nodes
160      */

161     public static List JavaDoc collectAllChildren(Content node, ContentFilter filter) {
162         List JavaDoc nodes = new ArrayList JavaDoc();
163         return collectAllChildren(nodes, node, filter);
164     }
165
166     /**
167      * Get the children using a filter
168      * @param nodes collection of already found nodes
169      * @param node
170      * @param filter the filter to use
171      * @return
172      */

173     private static List JavaDoc collectAllChildren(List JavaDoc nodes, Content node, ContentFilter filter) {
174         // get filtered sub nodes first
175
Collection JavaDoc children = node.getChildren(filter);
176         for (Iterator JavaDoc iter = children.iterator(); iter.hasNext();) {
177             Content child = (Content) iter.next();
178             nodes.add(child);
179         }
180
181         // get all children to find recursively
182
Collection JavaDoc allChildren = node.getChildren(EXCLUDE_META_DATA_CONTENT_FILTER);
183
184         // recursion
185
for (Iterator JavaDoc iter = allChildren.iterator(); iter.hasNext();) {
186             Content child = (Content) iter.next();
187             collectAllChildren(nodes, child, filter);
188         }
189
190         return nodes;
191     }
192
193     /**
194      * Get all children of a particular type
195      * @param node
196      * @param type
197      * @return
198      */

199     public static List JavaDoc collectAllChildren(Content node, ItemType type) {
200         List JavaDoc nodes = new ArrayList JavaDoc();
201         return collectAllChildren(nodes, node, new ItemType[]{type});
202     }
203     
204     /**
205      * Returns all children (not recursively) indpendent of there type
206      * @param node
207      * @return
208      */

209     public static Collection JavaDoc getAllChildren(Content node){
210         return node.getChildren(EXCLUDE_META_DATA_CONTENT_FILTER);
211     }
212
213     /**
214      * Get all children of a particular type
215      * @param node
216      * @param type
217      * @return
218      */

219     public static List JavaDoc collectAllChildren(Content node, ItemType[] types) {
220         List JavaDoc nodes = new ArrayList JavaDoc();
221         return collectAllChildren(nodes, node, types);
222     }
223
224     /**
225      * Get all subnodes recursively and add them to the nodes collection.
226      * @param nodes
227      * @param node
228      * @param types
229      * @return the list
230      */

231     private static List JavaDoc collectAllChildren(List JavaDoc nodes, Content node, ItemType[] types) {
232         for (int i = 0; i < types.length; i++) {
233             ItemType type = types[i];
234
235             Collection JavaDoc children = node.getChildren(type);
236             for (Iterator JavaDoc iter = children.iterator(); iter.hasNext();) {
237                 Content child = (Content) iter.next();
238                 nodes.add(child);
239                 collectAllChildren(nodes, child, types);
240             }
241         }
242         return nodes;
243     }
244     
245     public static void orderNodes(Content node, String JavaDoc[] nodes) throws RepositoryException{
246         for (int i = nodes.length - 1; i > 0; i--) {
247             node.orderBefore(nodes[i-1], nodes[i]);
248         }
249         node.save();
250     }
251     
252     public static void visit(Content node, Visitor visitor) throws Exception JavaDoc{
253         visit(node, visitor, EXCLUDE_META_DATA_CONTENT_FILTER);
254     }
255     
256     public static void visit(Content node, Visitor visitor, ContentFilter filter) throws Exception JavaDoc{
257         visitor.visit(node);
258         for (Iterator JavaDoc iter = node.getChildren(filter).iterator(); iter.hasNext();) {
259             visit((Content) iter.next(), visitor);
260         }
261     }
262
263     public static Content createPath(HierarchyManager hm, String JavaDoc path) throws AccessDeniedException,
264         PathNotFoundException, RepositoryException {
265         return ContentUtil.createPath(hm, path, ItemType.CONTENT);
266     }
267
268     public static Content createPath(HierarchyManager hm, String JavaDoc path, ItemType type) throws AccessDeniedException,
269         PathNotFoundException, RepositoryException {
270         Content node = hm.getRoot();
271         return createPath(node, path, type);
272     }
273
274     /**
275      * @param node
276      * @param path
277      * @param type
278      * @return
279      * @throws RepositoryException
280      * @throws PathNotFoundException
281      * @throws AccessDeniedException
282      */

283     public static Content createPath(Content node, String JavaDoc path, ItemType type) throws RepositoryException,
284         PathNotFoundException, AccessDeniedException {
285         // remove leading /
286
path = StringUtils.removeStart(path, "/");
287
288         if (StringUtils.isEmpty(path)) {
289             return node;
290         }
291
292         String JavaDoc[] names = path.split("/"); //$NON-NLS-1$
293

294         for (int i = 0; i < names.length; i++) {
295             String JavaDoc name = names[i];
296             if (node.hasContent(name)) {
297                 node = node.getContent(name);
298             }
299             else {
300                 node = node.createContent(name, type);
301             }
302         }
303         return node;
304     }
305
306     /**
307      * Transforms the nodes data into a map containting the names and values.
308      * @param node
309      * @return a flat map
310      */

311     public static Map JavaDoc toMap(Content node) {
312         Map JavaDoc map = new HashMap JavaDoc();
313         for (Iterator JavaDoc iter = node.getNodeDataCollection().iterator(); iter.hasNext();) {
314             NodeData nd = (NodeData) iter.next();
315             Object JavaDoc val = NodeDataUtil.getValue(nd);
316             if (val != null) {
317                 map.put(nd.getName(), val);
318             }
319         }
320         return map;
321     }
322
323     /**
324      * Takes a nodes data and and sets the beans properties which follow the naming of the nodes nodedatas.
325      * @param bean the bean you like to populate
326      * @param node the node containing the data
327      * @return the bean
328      */

329     public static Object JavaDoc setProperties(Object JavaDoc bean, Content node) {
330         try {
331             BeanUtils.populate(bean, toMap(node));
332         }
333         catch (IllegalAccessException JavaDoc e) {
334             log.error("can't set properties", e);
335         }
336         catch (InvocationTargetException JavaDoc e) {
337             log.error("can't set properties", e);
338         }
339         return bean;
340     }
341
342     /**
343      * Takes a nodes data and and sets the beans properties which follow the naming of the nodes nodedatas.
344      * @param bean the bean you like to populate
345      * @param repository
346      * @param path
347      * @return the bean
348      */

349     public static Object JavaDoc setProperties(Object JavaDoc bean, String JavaDoc repository, String JavaDoc path) {
350         Content node = getContent(repository, path);
351         if (node != null) {
352             setProperties(bean, node);
353         }
354         return bean;
355     }
356
357     public static void setNodeDatas(Content node, Object JavaDoc obj) throws RepositoryException {
358         try {
359             setNodeDatas(node, BeanUtils.describe(obj));
360         }
361         catch (InvocationTargetException JavaDoc e) {
362             log.error("can't persist", e);
363         }
364         catch (NoSuchMethodException JavaDoc e) {
365             log.error("can't persist", e);
366         }
367         catch (IllegalAccessException JavaDoc e) {
368             log.error("can't persist", e);
369         }
370     }
371
372     public static void setNodeDatas(Content node, Map JavaDoc map) throws RepositoryException {
373         for (Iterator JavaDoc iter = map.keySet().iterator(); iter.hasNext();) {
374             String JavaDoc name = (String JavaDoc) iter.next();
375             NodeDataUtil.getOrCreate(node, name).setValue(map.get(name).toString());
376         }
377     }
378
379     public static void setNodeDatas(Content node, Object JavaDoc bean, String JavaDoc[] excludes) throws RepositoryException {
380         try {
381             Map JavaDoc properties = BeanUtils.describe(bean);
382             for (int i = 0; i < excludes.length; i++) {
383                 String JavaDoc exclude = excludes[i];
384                 properties.remove(exclude);
385             }
386             setNodeDatas(node, properties);
387         }
388         catch (InvocationTargetException JavaDoc e) {
389             log.error("can't persist", e);
390         }
391         catch (NoSuchMethodException JavaDoc e) {
392             log.error("can't persist", e);
393         }
394         catch (IllegalAccessException JavaDoc e) {
395             log.error("can't persist", e);
396         }
397     }
398     
399     public static String JavaDoc uuid2path(String JavaDoc repository, String JavaDoc uuid){
400         if(StringUtils.isNotEmpty(uuid)){
401             HierarchyManager hm = MgnlContext.getHierarchyManager(repository);
402             try {
403                 Content node = hm.getContentByUUID(uuid);
404                 return node.getHandle();
405             }
406             catch (Exception JavaDoc e) {
407                 // return the uuid
408
}
409             
410         }
411         return uuid;
412     }
413
414 }
Popular Tags