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