]> git.argeo.org Git - gpl/argeo-slc.git/blob - ext/javax.mail.mbox/src/com/sun/mail/mbox/NewlineOutputStream.java
Make logging synchronous during native image build
[gpl/argeo-slc.git] / ext / javax.mail.mbox / src / com / sun / mail / mbox / NewlineOutputStream.java
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 Public License v. 2.0, which is available at
6 * http://www.eclipse.org/legal/epl-2.0.
7 *
8 * This Source Code may also be made available under the following Secondary
9 * Licenses when the conditions for such availability set forth in the
10 * Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
11 * version 2 with the GNU Classpath Exception, which is available at
12 * https://www.gnu.org/software/classpath/license.html.
13 *
14 * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
15 */
16
17 package com.sun.mail.mbox;
18
19 import java.io.*;
20 import java.nio.charset.StandardCharsets;
21
22 /**
23 * Convert the various newline conventions to the local platform's
24 * newline convention. Optionally, make sure the output ends with
25 * a blank line.
26 */
27 public class NewlineOutputStream extends FilterOutputStream {
28 private int lastb = -1;
29 private int bol = 1; // number of times in a row we're at beginning of line
30 private final boolean endWithBlankLine;
31 private static final byte[] newline;
32
33 static {
34 String s = null;
35 try {
36 s = System.lineSeparator();
37 } catch (SecurityException sex) {
38 // ignore, should never happen
39 }
40 if (s == null || s.length() <= 0)
41 s = "\n";
42 newline = s.getBytes(StandardCharsets.ISO_8859_1);
43 }
44
45 public NewlineOutputStream(OutputStream os) {
46 this(os, false);
47 }
48
49 public NewlineOutputStream(OutputStream os, boolean endWithBlankLine) {
50 super(os);
51 this.endWithBlankLine = endWithBlankLine;
52 }
53
54 public void write(int b) throws IOException {
55 if (b == '\r') {
56 out.write(newline);
57 bol++;
58 } else if (b == '\n') {
59 if (lastb != '\r') {
60 out.write(newline);
61 bol++;
62 }
63 } else {
64 out.write(b);
65 bol = 0; // no longer at beginning of line
66 }
67 lastb = b;
68 }
69
70 public void write(byte b[]) throws IOException {
71 write(b, 0, b.length);
72 }
73
74 public void write(byte b[], int off, int len) throws IOException {
75 for (int i = 0 ; i < len ; i++) {
76 write(b[off + i]);
77 }
78 }
79
80 public void flush() throws IOException {
81 if (endWithBlankLine) {
82 if (bol == 0) {
83 // not at bol, return to bol and add a blank line
84 out.write(newline);
85 out.write(newline);
86 } else if (bol == 1) {
87 // at bol, add a blank line
88 out.write(newline);
89 }
90 }
91 bol = 2;
92 out.flush();
93 }
94 }