1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.doxia.util;
20
21 import java.io.BufferedWriter;
22 import java.io.IOException;
23 import java.io.Writer;
24
25 import org.codehaus.plexus.util.IOUtil;
26
27
28
29
30 public class LineBreaker {
31
32 public static final int DEFAULT_MAX_LINE_LENGTH = 78;
33
34
35 private static final String EOL = System.getProperty("line.separator");
36
37
38 private Writer destination;
39
40
41 private BufferedWriter writer;
42
43
44 private int maxLineLength;
45
46
47 private int lineLength = 0;
48
49
50 private StringBuilder word = new StringBuilder(1024);
51
52
53
54
55
56
57 public LineBreaker(Writer out) {
58 this(out, DEFAULT_MAX_LINE_LENGTH);
59 }
60
61
62
63
64
65
66
67 public LineBreaker(Writer out, int max) {
68 if (max <= 0) {
69 throw new IllegalArgumentException("max must be a positive integer");
70 }
71
72 destination = out;
73 this.maxLineLength = max;
74 writer = new BufferedWriter(out);
75 }
76
77
78
79
80
81
82 public Writer getDestination() {
83 return destination;
84 }
85
86
87
88
89
90
91
92 public void write(String text) throws IOException {
93 write(text, false);
94 }
95
96
97
98
99
100
101
102 public void write(String text, boolean preserveSpace) {
103 int length = text.length();
104
105 try {
106 for (int i = 0; i < length; ++i) {
107 char c = text.charAt(i);
108
109 switch (c) {
110 case ' ':
111 if (preserveSpace) {
112 word.append(c);
113 } else {
114 writeWord();
115 }
116 break;
117
118 case '\r':
119
120 if (i + 1 < length && text.charAt(i + 1) == '\n') {
121 break;
122 }
123
124 case '\n':
125 writeWord();
126 writer.write(EOL);
127 lineLength = 0;
128 break;
129
130 default:
131 word.append(c);
132 }
133 }
134 } catch (Exception e) {
135
136 }
137 }
138
139
140
141
142
143 public void flush() {
144 try {
145 writeWord();
146 writer.flush();
147 } catch (IOException e) {
148
149 }
150 }
151
152
153
154
155
156
157 private void writeWord() throws IOException {
158 int length = word.length();
159 if (length > 0) {
160 if (lineLength > 0) {
161 if (lineLength + 1 + length > maxLineLength) {
162 writer.write(EOL);
163 lineLength = 0;
164 } else {
165 writer.write(' ');
166 ++lineLength;
167 }
168 }
169
170 writer.write(word.toString());
171 word.setLength(0);
172
173 lineLength += length;
174 }
175 }
176
177
178
179
180 public void close() {
181 IOUtil.close(writer);
182 }
183 }