1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.appender;
18
19 import java.io.IOException;
20 import java.io.OutputStream;
21
22
23
24
25
26 public class OutputStreamManager extends AbstractManager {
27
28 private OutputStream os;
29
30 private byte[] footer = null;
31 private byte[] header = null;
32
33 protected OutputStreamManager(final OutputStream os, final String streamName) {
34 super(streamName);
35 this.os = os;
36 }
37
38
39
40
41
42
43
44
45
46
47 public static <T> OutputStreamManager getManager(final String name, final T data,
48 final ManagerFactory<? extends OutputStreamManager, T> factory) {
49 return AbstractManager.getManager(name, factory, data);
50 }
51
52
53
54
55
56 public synchronized void setHeader(final byte[] header) {
57 if (header != null) {
58 this.header = header;
59 try {
60 this.os.write(header, 0, header.length);
61 } catch (final IOException ioe) {
62 LOGGER.error("Unable to write header", ioe);
63 }
64 }
65 }
66
67
68
69
70
71 public synchronized void setFooter(final byte[] footer) {
72 if (footer != null) {
73 this.footer = footer;
74 }
75 }
76
77
78
79
80 @Override
81 public void releaseSub() {
82 if (footer != null) {
83 write(footer);
84 }
85 close();
86 }
87
88
89
90
91
92 public boolean isOpen() {
93 return getCount() > 0;
94 }
95
96 protected OutputStream getOutputStream() {
97 return os;
98 }
99
100 protected void setOutputStream(final OutputStream os) {
101 this.os = os;
102 if (header != null) {
103 try {
104 this.os.write(header, 0, header.length);
105 } catch (final IOException ioe) {
106 LOGGER.error("Unable to write header", ioe);
107 }
108 }
109 }
110
111
112
113
114
115
116
117
118
119 protected synchronized void write(final byte[] bytes, final int offset, final int length) {
120
121 try {
122 os.write(bytes, offset, length);
123 } catch (final IOException ex) {
124 final String msg = "Error writing to stream " + getName();
125 throw new AppenderRuntimeException(msg, ex);
126 }
127 }
128
129
130
131
132
133
134
135 protected void write(final byte[] bytes) {
136 write(bytes, 0, bytes.length);
137 }
138
139 protected void close() {
140 if (os == System.out || os == System.err) {
141 return;
142 }
143 try {
144 os.close();
145 } catch (final IOException ex) {
146 LOGGER.error("Unable to close stream " + getName() + ". " + ex);
147 }
148 }
149
150
151
152
153 public void flush() {
154 try {
155 os.flush();
156 } catch (final IOException ex) {
157 final String msg = "Error flushing stream " + getName();
158 throw new AppenderRuntimeException(msg, ex);
159 }
160 }
161 }