KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > taglibs > html > controls > TreeTag


1 package org.jahia.taglibs.html.controls;
2
3 import java.io.IOException JavaDoc;
4 import java.util.ArrayList JavaDoc;
5 import java.util.Iterator JavaDoc;
6 import javax.servlet.http.HttpServletRequest JavaDoc;
7 import javax.servlet.jsp.JspException JavaDoc;
8 import javax.servlet.jsp.JspWriter JavaDoc;
9 import javax.servlet.jsp.tagext.BodyTagSupport JavaDoc;
10
11 import javax.swing.JTree JavaDoc;
12 import javax.swing.tree.DefaultMutableTreeNode JavaDoc;
13 import javax.swing.tree.TreePath JavaDoc;
14
15 import org.jahia.data.beans.RequestBean;
16 import org.jahia.params.ParamBean;
17 import org.jahia.resourcebundle.JahiaResourceBundle;
18 import org.jahia.utils.GUITreeTools;
19 import org.jahia.urls.QueryMapURL;
20
21 /**
22  * <p>Title: HTML Tree control</p>
23  * <p>Description: This HTML-specific tag handles the display AND handling of
24  * a tree control. It includes all the logic for session-handling, looping,
25  * selection. It should be generic enough to be used in any kind of
26  * application, for any kind of user objects.</p>
27  * <p>Copyright: Copyright (c) 2002</p>
28  * <p>Company: Jahia Ltd</p>
29  * @author Serge Huber
30  * @version 1.0
31  */

32
33 public class TreeTag extends BodyTagSupport JavaDoc {
34
35     private static org.apache.log4j.Logger logger =
36         org.apache.log4j.Logger.getLogger(TreeTag.class);
37
38     private String JavaDoc treeName = null;
39     private String JavaDoc flatTreeName = null;
40     private Iterator JavaDoc listIterator = null;
41     private Object JavaDoc userObject = null;
42     private boolean initialized = false;
43     private JTree JavaDoc tree = null;
44     private ArrayList JavaDoc flatTree = null;
45     private String JavaDoc userObjectID = null;
46     private ParamBean paramBean = null;
47     private int nodeCounter = 0;
48     private String JavaDoc actionURL = null;
49     private String JavaDoc selectionParamName = null;
50     private String JavaDoc nodeIndexID = null;
51     private String JavaDoc selectedUserObjectID = null;
52     private String JavaDoc selectedNodeIndexID = null;
53     private int selectedNodeIndex = 0;
54     private String JavaDoc selectionURLID = null;
55     private String JavaDoc vLineIcon = "vLineIcon";
56     private String JavaDoc lineNodeIcon = "lineNodeIcon";
57     private String JavaDoc lastNodeIcon = "lastNodeIcon";
58     private String JavaDoc spacerIcon = "org.jahia.pix.image";
59     private String JavaDoc expandIcon = "plusNodeIcon";
60     private String JavaDoc collapseIcon = "minusNodeIcon";
61     private String JavaDoc expandAllIcon = "expandAllNodeIcon";
62
63     public TreeTag() {
64     }
65
66     /**
67      * Sets the name of the pageContext attribute that contains the JTree
68      * instance we will operate on.
69      * @param treeName the name of the pageContext attribute that contains
70      * the JTree instance
71      */

72     public void setTreeName(String JavaDoc treeName) {
73         this.treeName = treeName;
74     }
75
76     /**
77      * Sets the name of the pageContext attribute that will be used to store
78      * the current UserObject in the current iteration over the visible tree
79      * nodes
80      * @param userObjectID the name of the pageContext attribute for the
81      * current UserObject
82      */

83     public void setUserObjectID(String JavaDoc userObjectID) {
84         this.userObjectID = userObjectID;
85     }
86
87     /**
88      * Sets the base action URL that is used to generate URLs that will
89      * perform tree display modifications.
90      * @param actionURL the base URL to use
91      */

92     public void setActionURL(String JavaDoc actionURL) {
93         this.actionURL = actionURL;
94     }
95
96     /**
97      * Sets the name of the query string URL parameter that is used to
98      * specify the currently selected tree node. If this property is never set,
99      * the default name "selectednode" will be used.
100      * @param selectionParamName the name of the URL query string parameter
101      * name to be used for the selected node index
102      */

103     public void setSelectionParamName(String JavaDoc selectionParamName) {
104         this.selectionParamName = selectionParamName;
105     }
106
107     /**
108      * Sets the name of the pageContext attribute to use to store the current
109      * node index.
110      * @param nodeIndexID the name of the pageContext attribute
111      */

112     public void setNodeIndexID(String JavaDoc nodeIndexID) {
113       this.nodeIndexID = nodeIndexID;
114     }
115
116     /**
117      * Sets the name of the pageContext attribute to use to store the selected
118      * UserObject instance
119      * @param selectedUserObjectID the name of the pageContext attribute
120      */

121     public void setSelectedUserObjectID(String JavaDoc selectedUserObjectID) {
122       this.selectedUserObjectID = selectedUserObjectID;
123     }
124
125     /**
126      * Sets the name of the pageContext attribute to use to store the selected
127      * node index Integer
128      * @param selectedNodeIndexID the name of the pageContext attribute
129      */

130     public void setSelectedNodeIndexID(String JavaDoc selectedNodeIndexID) {
131       this.selectedNodeIndexID = selectedNodeIndexID;
132     }
133
134     /**
135      * Sets the name of the pageContext attribute to use to store the URL
136      * that selects the current node in the iteration
137      * @param selectionURLID the name of the pageContext attribute
138      */

139     public void setSelectionURLID(String JavaDoc selectionURLID) {
140       this.selectionURLID = selectionURLID;
141     }
142
143     /**
144      * Sets the name of the key for the image to use for vertical lines.
145      * If not set defaults to a value of "vLineIcon".
146      * @param vLineIcon the common resource key name
147      */

148     public void setVLineIcon(String JavaDoc vLineIcon) {
149       this.vLineIcon = vLineIcon;
150     }
151
152     /**
153      * Sets the name of the key for the image to use for horizontal lines.
154      * If not set defaults to a value of "lineNodeIcon".
155      * @param lineNodeIcon the common resource key name
156      */

157     public void setLineNodeIcon(String JavaDoc lineNodeIcon) {
158       this.lineNodeIcon = lineNodeIcon;
159     }
160
161     /**
162      * Sets the name of the key for the image to use for the last node on a
163      * node line.
164      * If not set defaults to a value of "lastNodeIcon".
165      * @param lastNodeIcon the common resource key name
166      */

167     public void setLastNodeIcon(String JavaDoc lastNodeIcon) {
168       this.lastNodeIcon = lastNodeIcon;
169     }
170
171     /**
172      * Sets the name of the key for the image used as a spacer (usually a
173      * 1x1 GIF image).
174      * If not set defaults to a value of "org.jahia.pix.image".
175      * @param spacerIcon the common resource key name
176      */

177     public void setSpacerIcon(String JavaDoc spacerIcon) {
178       this.spacerIcon = spacerIcon;
179     }
180
181     /**
182      * Sets the name of the key for the image to be used to expand a node.
183      * If not set defaults to a value of "plusNodeIcon";
184      * @param expandIcon the common resource key name;
185      */

186     public void setExpandIcon(String JavaDoc expandIcon) {
187       this.expandIcon = expandIcon;
188     }
189
190     /**
191      * Sets the name of the key for the image to be used to collapse a node.
192      * If not set defaults to a value of "minusNodeIcon";
193      * @param collapseIcon the common resource key name
194      */

195     public void setCollapseIcon(String JavaDoc collapseIcon) {
196       this.collapseIcon = collapseIcon;
197     }
198
199     /**
200      * Sets the name of the key for the image to be used to expand all the
201      * nodes below a certain node.
202      * If not set defaults to a value of "expandAllNodeIcon";
203      * @param expandAllIcon the common resource key name
204      */

205     public void setExpandAllIcon(String JavaDoc expandAllIcon) {
206       this.expandAllIcon = expandAllIcon;
207     }
208
209     private void init() {
210         tree = (JTree JavaDoc) pageContext.findAttribute(treeName);
211
212         nodeCounter = 0;
213
214         RequestBean requestBean = (RequestBean) pageContext.findAttribute("currentRequest");
215         paramBean = requestBean.getParamBean();
216
217         HttpServletRequest JavaDoc request = requestBean.getParamBean().getRequest();
218         String JavaDoc targetTreeName = request.getParameter("targettree");
219
220         selectedNodeIndex = 0;
221         DefaultMutableTreeNode JavaDoc rootNode =
222             (DefaultMutableTreeNode JavaDoc)tree.getModel().getRoot();
223         DefaultMutableTreeNode JavaDoc selectedNode = rootNode;
224
225         if (targetTreeName != null) {
226             if (targetTreeName.equals(treeName)) {
227                 // before we modify the tree, we must handle the currently
228
// selected node.
229
if (selectionParamName == null) {
230                     selectionParamName = "selectednode";
231                 }
232                 String JavaDoc selectedNodeIndexStr = request.getParameter(selectionParamName);
233                 if (selectedNodeIndexStr != null) {
234                     selectedNodeIndex = Integer.parseInt(selectedNodeIndexStr);
235                 }
236                 ArrayList JavaDoc nodeList =
237                     GUITreeTools.getFlatTree(tree, rootNode);
238                 if (selectedNodeIndex > (nodeList.size() - 1) ) {
239                     selectedNodeIndex = 0;
240                 }
241                 selectedNode
242                     = (DefaultMutableTreeNode JavaDoc)
243                       nodeList.get(selectedNodeIndex);
244                 TreePath JavaDoc selectedNodePath = new TreePath JavaDoc(selectedNode.getPath());
245                 tree.clearSelection();
246                 tree.setSelectionPath(selectedNodePath);
247
248                 GUITreeTools.updateGUITree(tree, request);
249
250                 // now we must test if the selectedNode is still visible. If
251
// it's not we must adjust the selection to a visible node
252
// (preferably a parent node of the currently selected node).
253
if (!tree.isVisible(selectedNodePath)) {
254                     TreePath JavaDoc currentPath = selectedNodePath.getParentPath();
255                     while ((currentPath != null) && (!tree.isVisible(currentPath))) {
256                         currentPath = currentPath.getParentPath();
257                     }
258                     if (currentPath != null) {
259                         // now that we found a visible parent, we must figure
260
// out it's index.
261
selectedNode = (DefaultMutableTreeNode JavaDoc) currentPath.getLastPathComponent();
262                         selectedNodePath = currentPath;
263                         tree.clearSelection();
264                         tree.setSelectionPath(selectedNodePath);
265
266                         flatTree = GUITreeTools.getFlatTree(tree,rootNode);
267                         selectedNodeIndex = flatTree.indexOf(selectedNode);
268                     }
269                 }
270
271
272             }
273         }
274
275         if (selectedUserObjectID != null) {
276             pageContext.setAttribute(selectedUserObjectID, selectedNode.getUserObject());
277         }
278
279         if (selectedNodeIndexID != null) {
280             pageContext.setAttribute(selectedNodeIndexID, new Integer JavaDoc(selectedNodeIndex));
281         }
282
283         if ( rootNode != null ){
284             flatTree = GUITreeTools.getFlatTree(tree,rootNode);
285         }
286         listIterator = flatTree.iterator();
287
288         if (actionURL == null) {
289             actionURL = paramBean.getRequest().getRequestURI();
290         }
291
292
293         initialized = true;
294     }
295
296     public int doStartTag () {
297
298         logger.debug("startTag");
299
300         // first let's see if we are handling a previous call or if we need
301
// to create the tree for the first time.
302

303         JspWriter JavaDoc out = pageContext.getOut();
304         if (!initialized) {
305             init();
306         }
307
308         try {
309             if (!listIterator.hasNext()) {
310                 return SKIP_BODY;
311             } else {
312                 out.println("<!-- begin tree control -->");
313                 out.println(
314                     "<table class=\"text\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
315             }
316
317             startNextNode(out, actionURL);
318
319         } catch (IOException JavaDoc ioe) {
320             logger.error("Error:", ioe);
321         }
322
323         return EVAL_BODY_BUFFERED;
324     }
325
326     public int doAfterBody () {
327
328         logger.debug("afterBody");
329
330         JspWriter JavaDoc out = bodyContent.getEnclosingWriter();
331         try {
332             bodyContent.writeOut(out);
333             bodyContent.clearBody();
334
335             out.println("</td>");
336             out.println("<td>&nbsp;&nbsp;&nbsp;&nbsp;</td>");
337             out.println("</tr>");
338
339             if (!listIterator.hasNext()) {
340                 out.println("</table>");
341                 out.println("<!-- end tree control -->");
342                 return SKIP_BODY;
343             } else {
344                 startNextNode(out, actionURL);
345             }
346
347         } catch (IOException JavaDoc ioe) {
348             logger.error("Error:", ioe);
349         }
350
351         return EVAL_BODY_BUFFERED;
352     }
353
354     public int doEndTag ()
355         throws JspException JavaDoc {
356         // let's reinitialize the tag variables to allow tag object reuse in
357
// pooling.
358
treeName = null;
359         flatTreeName = null;
360         listIterator = null;
361         userObject = null;
362         initialized = false;
363         tree = null;
364         flatTree = null;
365         userObjectID = null;
366         paramBean = null;
367         nodeCounter = 0;
368         actionURL = null;
369         selectionParamName = null;
370         nodeIndexID = null;
371         selectedUserObjectID = null;
372         selectedNodeIndexID = null;
373         selectedNodeIndex = 0;
374         selectionURLID = null;
375         vLineIcon = "vLineIcon";
376         lineNodeIcon = "lineNodeIcon";
377         lastNodeIcon = "lastNodeIcon";
378         spacerIcon = "org.jahia.pix.image";
379         expandIcon = "plusNodeIcon";
380         collapseIcon = "minusNodeIcon";
381         expandAllIcon = "expandAllNodeIcon";
382         return EVAL_PAGE;
383     }
384
385     private void startNextNode (JspWriter JavaDoc out, String JavaDoc actionURL)
386         throws IOException JavaDoc {
387         DefaultMutableTreeNode JavaDoc node = (DefaultMutableTreeNode JavaDoc) listIterator.
388                                       next();
389
390         out.println("<tr class=\"sitemap1\">");
391         out.println(" <td>&nbsp;</td>");
392         out.print(" <td class=\"text\" nowrap>");
393
394         ArrayList JavaDoc verticalLineCells = GUITreeTools.
395                                       getLevelsWithVerticalLine(node);
396         int nodeLevel = node.getLevel();
397         for (int level = 0; level < nodeLevel; level++) {
398             DefaultMutableTreeNode JavaDoc parentNode =
399                 (DefaultMutableTreeNode JavaDoc) node.getParent();
400             boolean isLastChild = (parentNode != null &&
401                                    node.equals(parentNode.getLastChild()));
402
403             if (level < nodeLevel - 1) {
404                 if (verticalLineCells.contains(new Integer JavaDoc(level + 1))) {
405                     displayIcon(vLineIcon, "", null, null, null, null, "absmiddle", out);
406                 } else {
407                     displayIcon(spacerIcon, "", null, null, new Integer JavaDoc(14), new Integer JavaDoc(0), "absmiddle", out);
408                 }
409             } else {
410                 if (!isLastChild) {
411                     displayIcon(lineNodeIcon, "", null, null, null, null, "absmiddle", out);
412                 } else if (isLastChild || node.isLeaf()) {
413                     displayIcon(lastNodeIcon, "", null, null, null, null, "absmiddle", out);
414                 } else {
415                     displayIcon(spacerIcon, "", null, null, new Integer JavaDoc(14), new Integer JavaDoc(0), "absmiddle", out);
416                 }
417             }
418         }
419
420         QueryMapURL treeActionURL = new QueryMapURL(actionURL);
421         treeActionURL.setQueryParameter("targettree", treeName);
422         treeActionURL.setQueryParameter("nodeindex", Integer.toString(nodeCounter));
423         treeActionURL.setQueryParameter(selectionParamName, Integer.toString(selectedNodeIndex));
424         if (!node.isLeaf() && tree.isExpanded(new TreePath JavaDoc(node.getPath()))) {
425             treeActionURL.setQueryParameter("guitree", "collapse");
426             out.print("<a HREF=\"" + treeActionURL.toString() + "\">");
427             displayIcon(collapseIcon, JahiaResourceBundle.getCommonResource(
428                 "org.jahia.taglibs.html.controls.TreeTag.collapse.label",
429                 paramBean), null, null, null, null, "absmiddle", out);
430             out.print("</a>");
431         } else if (!node.isLeaf()) {
432             treeActionURL.setQueryParameter("guitree", "expandall");
433             out.print("<a HREF=\"" + treeActionURL.toString() + "\">");
434             displayIcon(expandAllIcon,
435                         JahiaResourceBundle.
436                         getCommonResource(
437                 "org.jahia.taglibs.html.controls.TreeTag.expandAll.label",
438                 paramBean), null, null, null, null,
439                         "absmiddle", out);
440             out.print("</a>");
441             treeActionURL.setQueryParameter("guitree", "expand");
442             out.print("<a HREF=\"" + treeActionURL.toString() + "\">");
443             displayIcon(expandIcon,
444                         JahiaResourceBundle.getCommonResource(
445                 "org.jahia.taglibs.html.controls.TreeTag.expand.label",
446                 paramBean), null, null, null, null, "absmiddle", out);
447             out.print("</a>");
448         } else {
449             displayIcon("org.jahia.pix.image", "", null, null, new Integer JavaDoc(14), new Integer JavaDoc(0), "absmiddle", out);
450         }
451
452         userObject = node.getUserObject();
453
454         pageContext.setAttribute(userObjectID, userObject);
455
456         if (nodeIndexID != null) {
457             pageContext.setAttribute(nodeIndexID, new Integer JavaDoc(nodeCounter));
458         }
459
460         if (selectionURLID != null) {
461             treeActionURL.setQueryParameter("guitree", "expand");
462             treeActionURL.setQueryParameter(selectionParamName, Integer.toString(nodeCounter));
463             pageContext.setAttribute(selectionURLID, treeActionURL.toString());
464         }
465
466         nodeCounter++;
467     }
468
469     private void displayIcon (String JavaDoc src, String JavaDoc alt, String JavaDoc altKey, String JavaDoc bundleName,
470                               Integer JavaDoc width, Integer JavaDoc height,
471                               String JavaDoc align, JspWriter JavaDoc out)
472         throws IOException JavaDoc {
473
474         // now let's resolve the alt text if resource bundle keys are being used.
475
if (altKey != null) {
476             alt = JahiaResourceBundle.getResource(bundleName, altKey,
477                 paramBean.getLocale(), paramBean);
478         }
479
480         StringBuffer JavaDoc str = new StringBuffer JavaDoc("");
481         // Resolve file name
482
String JavaDoc imagePath = JahiaResourceBundle.getUrlPathCommonResource(
483             src, paramBean);
484         if (imagePath == null) {
485             str.append("<!-- couldn't find resource with key " + src + " -->");
486         } else {
487             // Write image HTML tag
488
str.append("<img alt=\"");
489             str.append(alt);
490             str.append("\" border=\"0\" SRC=\"");
491             str.append(imagePath);
492             str.append("\"");
493             if (height != null) {
494                 str.append(" height=\"");
495                 str.append(height.intValue());
496                 str.append("\"");
497             }
498             if (width != null) {
499                 str.append(" width=\"");
500                 str.append(width.intValue());
501                 str.append("\"");
502             }
503             if (align != null) {
504                 str.append(" align=\"");
505                 str.append(align);
506                 str.append("\"");
507             }
508             str.append(">");
509         }
510         out.print(str.toString());
511
512     }
513
514 }
Popular Tags