View Javadoc
1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements. See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership. The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License. You may obtain a copy of the License at
9    *
10   * http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied. See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
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  }