01: /*
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */
04: package com.tc.text;
05:
06: import java.util.Arrays;
07: import java.util.Iterator;
08: import java.util.List;
09:
10: public class ConsoleParagraphFormatter implements ParagraphFormatter {
11:
12: private final StringFormatter sf;
13: private final int maxWidth;
14:
15: public ConsoleParagraphFormatter(int maxWidth,
16: StringFormatter stringFormatter) {
17: this .maxWidth = maxWidth;
18: this .sf = stringFormatter;
19: }
20:
21: public String format(String in) {
22: StringBuffer buf = new StringBuffer();
23: if (in == null)
24: throw new AssertionError();
25: List words = parseWords(in);
26: int lineWidth = 0;
27: for (Iterator i = words.iterator(); i.hasNext();) {
28: String currentWord = (String) i.next();
29: if (lineWidth + currentWord.length() > maxWidth) {
30: if (lineWidth > 0) {
31: buf.append(sf.newline());
32: }
33: lineWidth = currentWord.length();
34: } else {
35: if (lineWidth > 0) {
36: buf.append(" ");
37: }
38: lineWidth += currentWord.length();
39: }
40: buf.append(currentWord);
41: }
42: return buf.toString();
43: }
44:
45: private List parseWords(String in) {
46: String[] words = in.split("\\s+");
47: return Arrays.asList(words);
48: }
49:
50: }
|