KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > ecs > examples > HtmlTree


1 /*
2  * ====================================================================
3  *
4  * The Apache Software License, Version 1.1
5  *
6  * Copyright (c) 1999-2003 The Apache Software Foundation. All rights
7  * reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in
18  * the documentation and/or other materials provided with the
19  * distribution.
20  *
21  * 3. The end-user documentation included with the redistribution, if
22  * any, must include the following acknowlegement:
23  * "This product includes software developed by the
24  * Apache Software Foundation (http://www.apache.org/)."
25  * Alternately, this acknowlegement may appear in the software itself,
26  * if and wherever such third-party acknowlegements normally appear.
27  *
28  * 4. The names "The Jakarta Project", "Jakarta Element Construction Set",
29  * "Jakarta ECS" , and "Apache Software Foundation" must not be used
30  * to endorse or promote products derived
31  * from this software without prior written permission. For written
32  * permission, please contact apache@apache.org.
33  *
34  * 5. Products derived from this software may not be called "Apache",
35  * "Jakarta Element Construction Set" nor "Jakarta ECS" nor may "Apache"
36  * appear in their names without prior written permission of the Apache Group.
37  *
38  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
39  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
40  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
41  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
42  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
43  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
44  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
45  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
46  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
47  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
48  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
49  * SUCH DAMAGE.
50  * ====================================================================
51  *
52  * This software consists of voluntary contributions made by many
53  * individuals on behalf of the Apache Software Foundation. For more
54  * information on the Apache Software Foundation, please see
55  * <http://www.apache.org/>.
56  *
57  */

58 package org.apache.ecs.examples;
59
60 import java.io.*;
61 import java.util.*;
62 import javax.swing.tree.*;
63 import org.apache.ecs.xml.*;
64 import org.apache.ecs.html.*;
65
66 /**
67  * This JavaBean returns the hierarchical structure described in a
68  * javax.swing.tree.DefaultMutableTreeNode as valid XHTML. This class
69  * is a very simple counterpart of the javax.swing.JTree with the
70  * exception that the external Controller is integrated into this View.
71  * If you want your tree elements (nodes and leafs) to be marked with an
72  * anchor, you'll have to make sure that the name of your node contains
73  * such an anchor.
74  *
75  * <p>A specific node in a tree can be identified by a path, described as
76  * colon separated integer values (e.g. &quot;0:1&quot;). Unlike Swing's
77  * JTree component, this JavaBean expands only the requested node, leaving
78  * all its parent nodes collapsed. An <i>expanded</i> node is one displays
79  * its children. A <i>collapsed</i> node is one which hides them.</p>
80  *
81  * <p>You can use this class in a JavaServerPage like this:</p>
82  *
83  * <p><blockquote>
84  * <p>...template text...</p>
85  * <p><code>
86  * &lt;%-- Get the bean from the request scope or
87  * create a new one if none exists --%&gt;<br />
88  * &lt;jsp:useBean id="tree" scope="request"
89  * class="org.apache.ecs.examples.HtmlTree"&gt;
90  * <blockquote>
91  * <p>&lt;%-- Read the path from the request --%&gt;<br />
92  * &lt;jsp:setProperty name="tree"
93  * property="path" param="path" /&gt;</p>
94  * <p>&lt;%-- Set UI properties --%&gt;<br />
95  * &lt;jsp:setProperty name="tree"
96  * property="rootVisible" value="true" /&gt;<br />
97  * &lt;jsp:setProperty name="tree"
98  * property="indentation" value="2" /&gt;<br />
99  * &lt;jsp:setProperty name="tree"
100  * property="openIcon" value="open.gif" /&gt;<br />
101  * &lt;jsp:setProperty name="tree"
102  * property="closedIcon" value="closed.gif" /&gt;<br />
103  * &lt;jsp:setProperty name="tree"
104  * property="leafIcon" value="leaf.gif" /&gt;</p>
105  * <p>&lt;%-- Workaround for Netscape
106  * and Opera browsers --%&gt;<br />
107  * &lt;jsp:setProperty name="tree"
108  * property="action" value="tree.jsp" /&gt;</p>
109  * </blockquote>
110  * &lt;/jsp:useBean&gt;
111  * </code></p>
112  * <p>...template text...</p>
113  * <p><code>
114  * &lt;%-- Get the XHTML output from the bean --%&gt;<br />
115  * &lt;jsp:getProperty name="tree" property="html" /&gt;
116  * </code></p>
117  * </blockquote></p>
118  *
119  * Although this class is just an example of using parts of the Element
120  * Construction Set, you can use it quite well in real web applications.
121  *
122  * @version 1.1, 2001/12/30, added ability to use a DefaultTreeModel as the
123  * data model, added some useful methods including
124  * one for basic HTML encoding, improved javadoc
125  * comments and fixed minor bugs
126  * @version 1.0, 2001/10/30, initial release
127  * @author <a HREF="mailto:horombo@gmx.de">Christian Brensing</a>
128  */

129 public class HtmlTree implements Serializable
130 {
131     /**
132      * Number of blank spaces around each hierarchical level
133      * will be indented in relation to its parent node.
134      * Default is 2.
135      */

136     protected int indentation = 2;
137     
138     /**
139      * Path to the requested node to be displayed,
140      * described as colon separated integer values.
141      * Default is an empty String.
142      */

143     protected String JavaDoc path = "";
144     
145     /**
146      * Parameter name used to build the query string for the
147      * anchor that acts as the Controller for opening and
148      * closing nodes. Default is &quot;path&quot;.
149      */

150     protected String JavaDoc parameterName = "path";
151     
152     /**
153      * Array that stores the index of each node
154      * read from the path property.
155      */

156     private int[] pathArray = new int[0];
157     
158     /**
159      * Icon for displaying leafs.
160      * Default is an empty String.
161      */

162     protected String JavaDoc leafIcon = "";
163     
164     /**
165      * Icon for displaying open nodes.
166      * Default is an empty String.
167      */

168     protected String JavaDoc openIcon = "";
169     
170     /**
171      * Icon for displaying closed nodes.
172      * Default is an empty String.
173      */

174     protected String JavaDoc closedIcon = "";
175     
176     /**
177      * Context path of a web resource for the workaround
178      * of a strange behaviour of Netscape and Opera
179      * browsers. Default is an empty String.
180      */

181     protected String JavaDoc action = "?";
182     
183     /**
184      * True if the root node is displayed, false if
185      * its children are the highest visible nodes.
186      * Default is true.
187      */

188     protected boolean rootVisible = true;
189     
190     /**
191      * The node that defines the tree displayed by this object.
192      * Default is a sample model.
193      */

194     protected DefaultMutableTreeNode root = getDefaultTreeModel();
195     
196     /**
197      * Stores the requested node to be displayed.
198      * Default is the root node.
199      */

200     protected DefaultMutableTreeNode displayNode = root;
201     
202     /**
203      * Returns a HtmlTree with a sample model.
204      */

205     public HtmlTree()
206     {
207         // do nothing
208
}
209     
210     /**
211      * Returns a HtmlTree with the specified DefaultMutableTreeNode
212      * as its root. If the DefaultMutableTreeNode is <tt>null</tt>,
213      * a sample model is set automatically.
214      *
215      * @param root a DefaultMutableTreeNode object
216      */

217     public HtmlTree(DefaultMutableTreeNode root)
218     {
219         setRoot(root);
220     }
221     
222     /**
223      * Returns a HtmlTree with the specified DefaultTreeModel as
224      * its model. If the specified DefaultTreeModel is <tt>null</tt>,
225      * a sample model is set automatically.
226      *
227      * @param model a DefaultTreeModel object
228      */

229     public HtmlTree(DefaultTreeModel model)
230     {
231         setModel(model);
232     }
233     
234     /**
235      * Sets the root node that will provide the data. If the
236      * specified DefaultMutableTreeNode is <tt>null</tt>,
237      * a sample model is set automatically.
238      *
239      * @param root a DefaultMutableTreeNode object
240      */

241     public void setRoot(DefaultMutableTreeNode root)
242     {
243         // Check property
244
if (root == null)
245         {
246             root = getDefaultTreeModel();
247         }
248     
249         // Set property
250
this.root = root;
251     }
252     
253     /**
254      * Returns the node that defines the tree displayed
255      * by this object.
256      *
257      * @return the root node that provides the data
258      */

259     public DefaultMutableTreeNode getRoot()
260     {
261         return root;
262     }
263     
264     /**
265      * Sets the tree model that will provide the data. If the
266      * specified DefaultTreeModel is <tt>null</tt>, a sample
267      * model is set automatically.
268      *
269      * @param model a DefaultTreeModel object
270      */

271     public void setModel(DefaultTreeModel model)
272     {
273         if (model != null)
274         {
275             setRoot((DefaultMutableTreeNode)
276             model.getRoot());
277         }
278         else
279         {
280             setRoot(null);
281         }
282     }
283     
284     /**
285      * Returns the model that defines the tree displayed
286      * by this object.
287      *
288      * @return the model that provides the data
289      */

290     public DefaultTreeModel getModel()
291     {
292         return new DefaultTreeModel(root);
293     }
294     
295     /**
296      * Sets the path - described as colon separated integer values -
297      * to the requested node to be displayed.
298      *
299      * @param path the path to the requested node to be displayed
300      */

301     public void setPath(String JavaDoc path)
302     {
303         try
304         {
305             // Tokenize the path
306
pathArray = getPathResolved(path);
307     
308             // Set path property
309
this.path = path;
310         }
311         catch (NumberFormatException JavaDoc nfe)
312         {
313             // Reset path property
314
this.path = "";
315         }
316     }
317     
318     /**
319      * Returns the path to the requested node.
320      *
321      * @return the path to the requested node
322      */

323     public String JavaDoc getPath()
324     {
325         return path;
326     }
327     
328     /**
329      * Returns a path constructed from the path array for the
330      * specified level.
331      *
332      * @param level the distance from the node to the root node.
333      * @return the path for the specified level
334      */

335     public String JavaDoc getPath(int level)
336     {
337         // Check property
338
if (level > pathArray.length)
339         {
340             level = pathArray.length;
341         }
342     
343         // New StringBuffer for the path generation
344
StringBuffer JavaDoc autoPath = new StringBuffer JavaDoc();
345     
346         // For each node
347
for (int i = 0; i < level; i++)
348         {
349             // Add node index (read from the path array)
350
autoPath.append(pathArray[i]);
351         
352             // Add path separator (colon)
353
if (i < (level - 1))
354             {
355                 autoPath.append(":");
356             }
357         }
358     
359         // Return generated path
360
return autoPath.toString();
361     }
362     
363     /**
364      * Returns an array that stores the index of each
365      * node read from the specified path.
366      *
367      * @return an array of node indices
368      * @throws java.lang.NumberFormatException if the specified
369      * path does not consist of colon separated integer values
370      */

371     public static int[] getPathResolved(String JavaDoc path)
372         throws NumberFormatException JavaDoc
373     {
374         try
375         {
376             // Initialize the token array
377
int[] returnArray = new int[0];
378         
379             // Tokenize the path
380
StringTokenizer st = new StringTokenizer(path,":");
381         
382             // Reset the array with the number of tokens
383
returnArray = new int[st.countTokens()];
384         
385             // Save value of each token in the array
386
if (st.countTokens() > 0)
387             {
388                 for (int i = 0; i < returnArray.length; i++)
389                 {
390                     returnArray[i] = Integer.parseInt
391                         (st.nextToken().trim());
392                 }
393             }
394         
395             // Return path array
396
return returnArray;
397         }
398         catch (Exception JavaDoc e)
399         {
400             // Wrap the exception in a NumberFormatException
401
throw new NumberFormatException JavaDoc(e.getMessage());
402         }
403     }
404     
405     /**
406      * Sets the name of the parameter used to build the query
407      * string for the anchor that acts as the Controller for
408      * opening and closing nodes. You only have to set this
409      * name if the default name &quot;path&quot; is already
410      * used by your web application.
411      *
412      * @param parameterName the name of the parameter used
413      * to build the query string
414      */

415     public void setParameterName(String JavaDoc parameterName)
416     {
417         // Check property
418
if (parameterName == null
419         || parameterName.equals(""))
420         {
421             parameterName = "path";
422         }
423     
424         // Set property
425
this.parameterName = parameterName;
426     }
427     
428     /**
429      * Returns the name of the parameter used to build the
430      * query string for the anchor that acts as the Controller
431      * for opening and closing nodes.
432      *
433      * @return the name of the parameter
434      */

435     public String JavaDoc getParameterName()
436     {
437         return parameterName;
438     }
439     
440     /**
441      * Determines whether or not the root node is visible.
442      *
443      * @param rootVisible true if the root node of the tree
444      * is to be displayed
445      */

446     public void setRootVisible(boolean rootVisible)
447     {
448         this.rootVisible = rootVisible;
449     }
450     
451     /**
452      * Returns true if the root node of the tree is displayed.
453      *
454      * @return true if the root node of the tree is displayed
455      */

456     public boolean isRootVisible()
457     {
458         return rootVisible;
459     }
460     
461     /**
462      * Sets the number of blank spaces around each hierarchical
463      * level will be indented in relation to its parent node.
464      *
465      * @param indentation the number of blank spaces
466      */

467     public void setIndentation(int indentation)
468     {
469         this.indentation = indentation;
470     }
471     
472     /**
473      * Returns the number of blank spaces around each
474      * hierarchical level is indented in relation to
475      * its parent node.
476      *
477      * @return the number of blank spaces
478      */

479     public int getIndentation()
480     {
481         return indentation;
482     }
483     
484     /**
485      * Returns the name of the currently expanded node.
486      *
487      * @return the name of the node
488      */

489     public String JavaDoc getNodeName()
490     {
491         return displayNode.toString();
492     }
493     
494     /**
495      * Returns the number of rows that are currently
496      * being displayed.
497      *
498      * @return the number of rows
499      */

500     public int getRowCount()
501     {
502         // Get level of the node to be displayed
503
int rowCount = displayNode.getLevel();
504     
505         // Add number of children
506
rowCount = rowCount + displayNode.getChildCount();
507     
508         // Increment by 1 if the root node is being displayed
509
if (rootVisible)
510         {
511             rowCount++;
512         }
513     
514         // Return number of rows
515
return rowCount;
516     }
517     
518     /**
519      * Sets the icon for displaying open nodes.
520      *
521      * @param openIcon the URI of an image file
522      */

523     public void setOpenIcon(String JavaDoc openIcon)
524     {
525         this.openIcon = openIcon;
526     }
527     
528     /**
529      * Sets the icon for displaying closed nodes.
530      *
531      * @param closedIcon the URI of an image file
532      */

533     public void setClosedIcon(String JavaDoc closedIcon)
534     {
535         this.closedIcon = closedIcon;
536     }
537     
538     /**
539      * Sets the icon for displaying leafs.
540      *
541      * @param leafIcon the URI of an image file
542      */

543     public void setLeafIcon(String JavaDoc leafIcon)
544     {
545         this.leafIcon = leafIcon;
546     }
547     
548     /**
549      * Workaround of a strange behaviour of Netscape and Opera browsers.
550      * In these browsers the relative URL containg only the query string
551      * with the path information (e.g. &quot;?path=0:1&quot;) are not
552      * translated correctly into an absoulte URL. By setting a context
553      * path, on which to append the query string, this behaviour should
554      * be fixed.
555      *
556      * @param action the context path of a web resource (e.g. a JSP-File)
557      */

558     public void setAction(String JavaDoc action)
559     {
560         // Check property
561
if (action == null)
562         {
563             action = "";
564         }
565     
566         // If the specified context path already contains
567
// a query string, append an ampersand character
568
// for further parameter concatenation
569
if (action.indexOf("=") != -1)
570         {
571             action = action + "&";
572         }
573         else
574         {
575             action = action + "?";
576         }
577     
578         // Set property
579
this.action = action;
580     }
581     
582     /**
583      * Constructs a valid XHTML &lt;img&gt;-tag from the specified icon.
584      * Although this method uses the xml-package to generate a valid tag,
585      * the xhtml-package would provide the same functionality.
586      *
587      * @param icon the URI of an image file
588      * @return a valid XHTML &lt;img&gt;-tag
589      */

590     public String JavaDoc getImg(String JavaDoc icon)
591     {
592         // New <img>
593
XML img = new XML("img",false);
594     
595         // Check specified icon property
596
if (icon == null)
597         {
598             icon = "";
599         }
600     
601         // Set src attribute
602
img.addAttribute("src",icon);
603     
604         // return <img>
605
return img.toString();
606     }
607     
608     /**
609      * Expands the tree by following the specified path
610      * and returns the requested node to be displayed.
611      *
612      * @return the requested node to be displayed
613      */

614     public DefaultMutableTreeNode getRequestedNode()
615     {
616         // Reset node to be displayed
617
displayNode = root;
618     
619         // Iterate trough the path array
620
for (int i = 0; i < pathArray.length; i++)
621         {
622             if (displayNode.getDepth() > 1)
623             {
624                 displayNode = (DefaultMutableTreeNode)
625                 displayNode.getChildAt(pathArray[i]);
626             }
627         }
628     
629         // Return node to be displayed
630
return displayNode;
631     }
632     
633     /**
634      * Returns the hierarchical structure described in the specified root
635      * node as valid XHTML. For perfomance reasons all parent nodes of the
636      * requested node are collapsed. The source code does not contain any
637      * formatting tags or attributes. I recommend that you use Cascading
638      * Style Sheets instead. For this purpose, the tree elements are marked
639      * with the class attribute values &quot;tree&quot;, &quot;parent&quot;
640      * and &quot;child&quot;.
641      *
642      * <p>A sample Style Sheet would look like this:</p>
643      *
644      * <p><blockquote>
645      * <code>
646      * a { color: black; text-decoration: none; }<br />
647      * a:hover { color: black; text-decoration: underline; }<br />
648      * img { margin-right: 5px; vertical-align: middle; border: none; }<br />
649      * table { font: normal 8pt Arial,Helvetica,sans-serif; }</br />
650      * td.parent { font-weight: bold; }<br />
651      * </code>
652      * </blockquote></p>
653      *
654      * @return the hierarchical structure within a &lt;table&gt;-tag
655      */

656     public String JavaDoc getHtml()
657     {
658         // Expand the tree
659
displayNode = getRequestedNode();
660     
661         // New <table>
662
Table table = new Table();
663         table.setClass("tree");
664     
665         // Reset auto indentation
666
int autoIndentation = 0;
667     
668         // Initialize ancestor node with the first child of
669
// the node to be displayed (for parent recursion)
670
TreeNode ancestor = displayNode.getFirstChild();
671     
672         // Read all ancestors into an array
673
ArrayList list = new ArrayList();
674         while ((ancestor = ancestor.getParent()) != null)
675         {
676             list.add(ancestor);
677         }
678     
679         // For each ancestor (ordered desc beginning at the root)
680
for (int i = list.size(); i > 0; i--)
681         {
682             // Get current ancestor
683
DefaultMutableTreeNode parent =
684                 (DefaultMutableTreeNode)list.get(i-1);
685         
686             // Displays the ancestor if it's not the root
687
// or the rootVisible property is set to true
688
if (!parent.isRoot() || rootVisible)
689             {
690                 // New <td>
691
TD td = new TD();
692                 td.setClass("parent");
693         
694                 // Generate href for this ancestor (the
695
// level is decreased by one to provide
696
// an anchor to its parent node)
697
String JavaDoc href = action + parameterName
698                     + "=" + getPath(parent.getLevel()-1);
699         
700                 // Add indentation to <td>
701
for (int j = 0; j < autoIndentation; j++)
702                 {
703                     td.addElement("&nbsp;");
704                 }
705         
706                 // Add icon with <a> to <td>
707
td.addElement(new A(href,getImg(openIcon)));
708         
709                 // Add ancestor with <nobr> to <td>
710
td.addElement(new NOBR(parent.toString()));
711         
712                 // Add <td> to <tr> to <table>
713
table.addElement(new TR(td));
714         
715                 // Increment auto indentation
716
autoIndentation = autoIndentation + indentation;
717             }
718         }
719     
720         // For each child
721
for (int i = 0; i < displayNode.getChildCount(); i++)
722         {
723             // New <td>
724
TD td = new TD();
725             td.setClass("child");
726         
727             // Get current child
728
DefaultMutableTreeNode child =
729                 (DefaultMutableTreeNode)displayNode
730                 .getChildAt(i);
731         
732             // Generate path == path + child index
733
String JavaDoc autoPath = getPath(child
734                 .getLevel()-1) + ":" + i;
735         
736             // Trim leading colon
737
if (autoPath.startsWith(":"))
738             {
739                 autoPath = autoPath.substring(1);
740             }
741         
742             // Generate href for this child
743
String JavaDoc href = action + parameterName
744                 + "=" + autoPath;
745         
746             // Add indentation to <td>
747
for (int j = 0; j < autoIndentation; j++)
748             {
749                 td.addElement("&nbsp;");
750             }
751         
752             // New <img> with default leaf icon
753
String JavaDoc img = getImg(leafIcon);
754         
755             // Set closed node icon, if child is not a leaf
756
if (!child.isLeaf())
757             {
758                 img = getImg(closedIcon);
759             }
760         
761             // Add icon with <a> (not for leafs) to <td>
762
if (!child.isLeaf())
763             {
764                 td.addElement(new A(href,img));
765             }
766         
767             // Add icon without <a> (leafs only) to <td>
768
if (child.isLeaf())
769             {
770                 td.addElement(img);
771             }
772         
773             // Add child with <nobr> to <td>
774
td.addElement(new NOBR(child.toString()));
775         
776             // Add <td> to <tr> to <table>
777
table.addElement(new TR(td));
778         }
779     
780         // Return <table>
781
return table.toString();
782     }
783     
784     /**
785      * Overrides <tt>toString()</tt> to print something meaningful.
786      * Returns the hierarchical structure described in the specified
787      * root node as valid XHTML.
788      *
789      * @see #getHtml
790      */

791     public String JavaDoc toString()
792     {
793         return getHtml();
794     }
795     
796     /**
797      * Creates and returns a sample tree model. Used primarily
798      * during the design of the JavaServerPage to show something
799      * interesting.
800      *
801      * @return a DefaultMutableTreeNode with a sample tree model
802      */

803     protected static DefaultMutableTreeNode getDefaultTreeModel()
804     {
805         // New root node
806
DefaultMutableTreeNode root =
807         new DefaultMutableTreeNode("Root");
808     
809         // First level
810
for (int i = 1; i <= 5; i++)
811         {
812             // New node
813
DefaultMutableTreeNode folder =
814                 new DefaultMutableTreeNode("Folder-" + i);
815         
816             // Add node to root
817
root.add(folder);
818         
819             // Second level
820
for (int j = 1; j <= 3; j++)
821             {
822                 // New node
823
DefaultMutableTreeNode subfolder =
824                 new DefaultMutableTreeNode("Subfolder-" + j);
825         
826                 // Add node to parent node
827
folder.add(subfolder);
828         
829                 // Third level
830
for (int k = 1; k <= 3; k++)
831                 {
832                     // New anchor
833
A a = new A("http://jakarta.apache.org");
834                     a.setTarget("target").addElement("Document-" + k);
835             
836                     // New node (leaf)
837
DefaultMutableTreeNode document =
838                         new DefaultMutableTreeNode(a.toString());
839             
840                     // Add node to parent node
841
subfolder.add(document);
842                 }
843             }
844         }
845     
846         // Return root node
847
return root;
848     }
849     
850     /**
851      * Returns the specified string encoded into a format suitable for
852      * HTML. All single-quote, double-quote, greater-than, less-than
853      * and ampersand characters are replaced with their corresponding
854      * HTML Character Entity codes. You can use this method to encode
855      * the designated node names before appending this node to your
856      * tree model. Please don't encode node names that already include
857      * a valid tag, because they are equally converted and thus won't
858      * be displayed by the browser.
859      *
860      * @param in the String to encode
861      * @return the encoded String
862      */

863     public static String JavaDoc encodeToHtml(String JavaDoc in)
864     {
865         // New StringBuffer for output concatenation
866
StringBuffer JavaDoc out = new StringBuffer JavaDoc();
867     
868         // For each character in the input string
869
for (int i = 0; in != null && i < in.length(); i++)
870         {
871             // Get the current character
872
char c = in.charAt(i);
873         
874             // Encode this character
875
if (c == '\'')
876             {
877                 out.append("&#039;");
878             }
879             else if (c == '\"')
880             {
881                 out.append("&quot;");
882             }
883             else if (c == '<')
884             {
885                 out.append("&lt;");
886             }
887             else if (c == '>')
888             {
889                 out.append("&gt;");
890             }
891             else if (c == '&')
892             {
893                 out.append("&amp;");
894             }
895             else
896             {
897                 out.append(c);
898             }
899         }
900     
901         // Return encoded string
902
return out.toString();
903     }
904 }
905
Popular Tags