1 package org.andromda.core.common;
2
3 import java.util.ArrayList;
4 import java.util.Collection;
5 import java.util.Iterator;
6 import java.util.StringTokenizer;
7
8 /***
9 * A utility object useful for formatting html paragraph output.
10 *
11 * <p> Represents a paragraph, made of lines. The whole
12 * paragraph has a limit for the line width.
13 * Words can be added, the class will reformat the
14 * paragraph according to max. line width. </p>
15 *
16 * @author Matthias Bohlen
17 *
18 */
19 public class HTMLParagraph
20 {
21 private ArrayList lines = new ArrayList();
22 private StringBuffer currentLine = new StringBuffer();
23 private int maxLineWidth;
24
25 /***
26 * <p>Constructs an HTMLParagraph with a specified maximum line
27 * width.</p>
28 * @param lineWidth maximum line width
29 */
30 public HTMLParagraph(int lineWidth)
31 {
32 this.maxLineWidth = lineWidth;
33 }
34
35 /***
36 * <p>Appends another word to this paragraph.</p>
37 * @param word the word
38 */
39 public void appendWord(String word)
40 {
41 if ((currentLine.length() + word.length() + 1) > maxLineWidth)
42 {
43 nextLine();
44 }
45 currentLine.append(" ");
46 currentLine.append(word);
47 }
48
49 /***
50 * <p>Appends a bunch of words to the paragraph.</p>
51 * @param text the text to add to the paragraph
52 */
53 public void appendText(String text)
54 {
55 if ((currentLine.length() + text.length() + 1) <= maxLineWidth)
56 {
57 currentLine.append(" ");
58 currentLine.append(text);
59 return;
60 }
61
62 StringTokenizer st = new StringTokenizer(text);
63 while (st.hasMoreTokens())
64 {
65 appendWord(st.nextToken());
66 }
67 }
68
69 /***
70 * <p>Returns the lines in this paragraph.</p>
71 * @return Collection the lines as collection of Strings
72 */
73 public Collection getLines()
74 {
75 if (currentLine.length() > 0)
76 {
77 nextLine();
78 }
79
80 return lines;
81 }
82
83 /***
84 * @see java.lang.Object#toString()
85 */
86 public String toString()
87 {
88 StringBuffer st = new StringBuffer();
89 for (Iterator it = getLines().iterator(); it.hasNext(); )
90 {
91 st.append((String)it.next());
92 st.append("\n");
93 }
94 return st.toString();
95 }
96
97 private void nextLine()
98 {
99 lines.add(currentLine.toString());
100 currentLine = new StringBuffer();
101 }
102 }