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