001package org.andromda.core.common;
002
003import java.util.ArrayList;
004import java.util.Collection;
005import java.util.StringTokenizer;
006
007/**
008 * A utility object useful for formatting paragraph output.
009 * <p>
010 * Represents a paragraph, made of lines. The whole paragraph has a limit for the line length. Words can be added, the
011 * class will reformat the paragraph according to max. line length. </p>
012 *
013 * @author Matthias Bohlen
014 * @author Chad Brandon
015 */
016public class Paragraph
017{
018    private StringBuffer currentLine = new StringBuffer();
019    private int maxLineWidth;
020
021    /**
022     * <p>
023     * Constructs an HtmlParagraph with a specified maximum line length. </p>
024     *
025     * @param lineLength maximum line length
026     */
027    public Paragraph(final int lineLength)
028    {
029        this.maxLineWidth = lineLength;
030    }
031
032    /**
033     * <p>
034     * Appends another word to this paragraph. </p>
035     *
036     * @param word the word
037     */
038    public void appendWord(final String word)
039    {
040        if ((currentLine.length() + word.length() + 1) > maxLineWidth)
041        {
042            nextLine();
043        }
044        currentLine.append(' ');
045        currentLine.append(word);
046    }
047
048    /**
049     * <p>
050     * Appends a bunch of words to the paragraph. </p>
051     *
052     * @param text the text to add to the paragraph
053     */
054    public void appendText(final String text)
055    {
056        if ((currentLine.length() + text.length() + 1) <= maxLineWidth)
057        {
058            currentLine.append(' ');
059            currentLine.append(text);
060            return;
061        }
062        StringTokenizer tokenizer = new StringTokenizer(text);
063        while (tokenizer.hasMoreTokens())
064        {
065            appendWord(tokenizer.nextToken());
066        }
067    }
068
069    private final Collection<String> lines = new ArrayList<String>();
070
071    /**
072     * <p>
073     * Returns the lines in this paragraph. </p>
074     *
075     * @return Collection the lines as collection of Strings
076     */
077    public Collection<String> getLines()
078    {
079        if (currentLine.length()>0)
080        {
081            nextLine();
082        }
083        return lines;
084    }
085
086    /**
087     * @see Object#toString()
088     */
089    public String toString()
090    {
091        final StringBuilder buffer = new StringBuilder();
092        for (final String line : this.getLines())
093        {
094            buffer.append(line);
095            buffer.append('\n');
096        }
097        return buffer.toString();
098    }
099
100    private void nextLine()
101    {
102        lines.add(currentLine.toString());
103        currentLine = new StringBuffer();
104    }
105}