KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > hudson > util > LineEndNormalizingWriter


1 package hudson.util;
2
3 import java.io.FilterWriter JavaDoc;
4 import java.io.Writer JavaDoc;
5 import java.io.IOException JavaDoc;
6
7 /**
8  * Finds the lone LF and converts that to CR+LF.
9  *
10  * <p>
11  * Internet Explorer's <tt>XmlHttpRequest.responseText</tt> seems to
12  * normalize the line end, and if we only send LF without CR, it will
13  * not recognize that as a new line. To work around this problem,
14  * we use this filter to always convert LF to CR+LF.
15  *
16  * @author Kohsuke Kawaguchi
17  */

18 public class LineEndNormalizingWriter extends FilterWriter JavaDoc {
19
20     private boolean seenCR;
21
22     public LineEndNormalizingWriter(Writer JavaDoc out) {
23         super(out);
24     }
25
26     public void write(char cbuf[]) throws IOException JavaDoc {
27         write(cbuf, 0, cbuf.length);
28     }
29
30     public void write(String JavaDoc str) throws IOException JavaDoc {
31         write(str,0,str.length());
32     }
33
34     public void write(int c) throws IOException JavaDoc {
35         if(!seenCR && c==LF)
36             super.write("\r\n");
37         else
38             super.write(c);
39         seenCR = (c==CR);
40     }
41
42     public void write(char cbuf[], int off, int len) throws IOException JavaDoc {
43         int end = off+len;
44         int writeBegin = off;
45
46         for( int i=off; i<end; i++ ) {
47             char ch = cbuf[i];
48             if(!seenCR && ch==LF) {
49                 // write up to the char before LF
50
super.write(cbuf,writeBegin,i-writeBegin);
51                 super.write("\r\n");
52                 writeBegin=i+1;
53             }
54             seenCR = (ch==CR);
55         }
56
57         super.write(cbuf,writeBegin,end-writeBegin);
58     }
59
60     public void write(String JavaDoc str, int off, int len) throws IOException JavaDoc {
61         int end = off+len;
62         int writeBegin = off;
63
64         for( int i=off; i<end; i++ ) {
65             char ch = str.charAt(i);
66             if(!seenCR && ch==LF) {
67                 // write up to the char before LF
68
super.write(str,writeBegin,i-writeBegin);
69                 super.write("\r\n");
70                 writeBegin=i+1;
71             }
72             seenCR = (ch==CR);
73         }
74
75         super.write(str,writeBegin,end-writeBegin);
76     }
77
78     private static final int CR = 0x0D;
79     private static final int LF = 0x0A;
80 }
81
Popular Tags