1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.wss4j.common.util;
20
21 import java.io.FilterOutputStream;
22 import java.io.IOException;
23 import java.io.OutputStream;
24
25 public class CRLFOutputStream extends FilterOutputStream {
26
27 private static final byte CR = '\r';
28 private static final byte LF = '\n';
29 private static final byte[] CRLF = new byte[]{CR, LF};
30
31 private boolean lastByteCR = false;
32
33 public CRLFOutputStream(OutputStream out) {
34 super(out);
35 }
36
37 @Override
38 public void write(int b) throws IOException {
39 if (b == CR) {
40 out.write(CRLF);
41 lastByteCR = true;
42 } else if (b == LF) {
43 if (lastByteCR) {
44 lastByteCR = false;
45 } else {
46 out.write(CRLF);
47 }
48 } else {
49 out.write(b);
50 lastByteCR = false;
51 }
52 }
53
54 @Override
55 public void write(byte[] b, int off, int len) throws IOException {
56
57 int start = off;
58 for (int i = off; i < len; i++) {
59 if (b[i] == CR) {
60 out.write(b, start, i + 1 - start);
61 out.write(LF);
62 lastByteCR = true;
63 start = i + 1;
64 } else if (b[i] == LF) {
65 if (lastByteCR) {
66 lastByteCR = false;
67 start++;
68 } else {
69 int l = i - start;
70 if (l > 0) {
71 out.write(b, start, l);
72 }
73 out.write(CRLF);
74 start = i + 1;
75 }
76 } else {
77 lastByteCR = false;
78 }
79 }
80 out.write(b, start, len - start);
81 }
82 }