View Javadoc
1   package org.andromda.core.common;
2   
3   import java.util.ArrayList;
4   import java.util.Collection;
5   import java.util.StringTokenizer;
6   
7   /**
8    * A utility object useful for formatting paragraph output.
9    * <p>
10   * Represents a paragraph, made of lines. The whole paragraph has a limit for the line length. Words can be added, the
11   * class will reformat the paragraph according to max. line length. </p>
12   *
13   * @author Matthias Bohlen
14   * @author Chad Brandon
15   */
16  public class Paragraph
17  {
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      {
29          this.maxLineWidth = lineLength;
30      }
31  
32      /**
33       * <p>
34       * Appends another word to this paragraph. </p>
35       *
36       * @param word the word
37       */
38      public void appendWord(final String word)
39      {
40          if ((currentLine.length() + word.length() + 1) > maxLineWidth)
41          {
42              nextLine();
43          }
44          currentLine.append(' ');
45          currentLine.append(word);
46      }
47  
48      /**
49       * <p>
50       * Appends a bunch of words to the paragraph. </p>
51       *
52       * @param text the text to add to the paragraph
53       */
54      public void appendText(final String text)
55      {
56          if ((currentLine.length() + text.length() + 1) <= maxLineWidth)
57          {
58              currentLine.append(' ');
59              currentLine.append(text);
60              return;
61          }
62          StringTokenizer tokenizer = new StringTokenizer(text);
63          while (tokenizer.hasMoreTokens())
64          {
65              appendWord(tokenizer.nextToken());
66          }
67      }
68  
69      private final Collection<String> lines = new ArrayList<String>();
70  
71      /**
72       * <p>
73       * Returns the lines in this paragraph. </p>
74       *
75       * @return Collection the lines as collection of Strings
76       */
77      public Collection<String> getLines()
78      {
79          if (currentLine.length()>0)
80          {
81              nextLine();
82          }
83          return lines;
84      }
85  
86      /**
87       * @see Object#toString()
88       */
89      public String toString()
90      {
91          final StringBuilder buffer = new StringBuilder();
92          for (final String line : this.getLines())
93          {
94              buffer.append(line);
95              buffer.append('\n');
96          }
97          return buffer.toString();
98      }
99  
100     private void nextLine()
101     {
102         lines.add(currentLine.toString());
103         currentLine = new StringBuffer();
104     }
105 }