Debian Codegraph @

demo/src/main/java/CRLFOutputStream.java

raw
1 /*
2 * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
3 *
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Distribution License v. 1.0, which is available at
6 * http://www.eclipse.org/org/documents/edl-v10.php.
7 *
8 * SPDX-License-Identifier: BSD-3-Clause
9 */
10
11 import java.io.*;
12
13 /**
14 * Convert lines into the canonical MIME format, that is,
15 * terminate lines with CRLF. <p>
16 *
17 * This stream can be used with the Part.writeTo and Message.writeTo
18 * methods to generate the canonical MIME format of the data for the
19 * purpose of (e.g.) sending it via SMTP or computing a digital
20 * signature.
21 */
22 public class CRLFOutputStream extends FilterOutputStream {
23 protected int lastb = -1;
24 protected static byte[] newline;
25 static {
26 newline = new byte[2];
27 newline[0] = (byte)'\r';
28 newline[1] = (byte)'\n';
29 }
30
31 public CRLFOutputStream(OutputStream os) {
32 super(os);
33 }
34
35 public void write(int b) throws IOException {
36 if (b == '\r') {
37 out.write(newline);
38 } else if (b == '\n') {
39 if (lastb != '\r')
40 out.write(newline);
41 } else {
42 out.write(b);
43 }
44 lastb = b;
45 }
46
47 public void write(byte b[]) throws IOException {
48 write(b, 0, b.length);
49 }
50
51 public void write(byte b[], int off, int len) throws IOException {
52 int start = off;
53
54 len += off;
55 for (int i = start; i < len ; i++) {
56 if (b[i] == '\r') {
57 out.write(b, start, i - start);
58 out.write(newline);
59 start = i + 1;
60 } else if (b[i] == '\n') {
61 if (lastb != '\r') {
62 out.write(b, start, i - start);
63 out.write(newline);
64 }
65 start = i + 1;
66 }
67 lastb = b[i];
68 }
69 if ((len - start) > 0)
70 out.write(b, start, len - start);
71 }
72 }