1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.codec.binary;
19
20 import static org.apache.commons.codec.binary.BaseNCodec.EOF;
21
22 import java.io.FilterOutputStream;
23 import java.io.IOException;
24 import java.io.OutputStream;
25
26 import org.apache.commons.codec.binary.BaseNCodec.Context;
27
28
29
30
31
32
33
34 public class BaseNCodecOutputStream extends FilterOutputStream {
35
36 private final boolean doEncode;
37
38 private final BaseNCodec baseNCodec;
39
40 private final byte[] singleByte = new byte[1];
41
42 private final Context context = new Context();
43
44
45 public BaseNCodecOutputStream(OutputStream out, BaseNCodec basedCodec, boolean doEncode) {
46 super(out);
47 this.baseNCodec = basedCodec;
48 this.doEncode = doEncode;
49 }
50
51
52
53
54
55
56
57
58
59 @Override
60 public void write(int i) throws IOException {
61 singleByte[0] = (byte) i;
62 write(singleByte, 0, 1);
63 }
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83 @Override
84 public void write(byte b[], int offset, int len) throws IOException {
85 if (b == null) {
86 throw new NullPointerException();
87 } else if (offset < 0 || len < 0) {
88 throw new IndexOutOfBoundsException();
89 } else if (offset > b.length || offset + len > b.length) {
90 throw new IndexOutOfBoundsException();
91 } else if (len > 0) {
92 if (doEncode) {
93 baseNCodec.encode(b, offset, len, context);
94 } else {
95 baseNCodec.decode(b, offset, len, context);
96 }
97 flush(false);
98 }
99 }
100
101
102
103
104
105
106
107
108
109
110 private void flush(boolean propogate) throws IOException {
111 int avail = baseNCodec.available(context);
112 if (avail > 0) {
113 byte[] buf = new byte[avail];
114 int c = baseNCodec.readResults(buf, 0, avail, context);
115 if (c > 0) {
116 out.write(buf, 0, c);
117 }
118 }
119 if (propogate) {
120 out.flush();
121 }
122 }
123
124
125
126
127
128
129
130 @Override
131 public void flush() throws IOException {
132 flush(true);
133 }
134
135
136
137
138
139
140
141 @Override
142 public void close() throws IOException {
143
144 if (doEncode) {
145 baseNCodec.encode(singleByte, 0, EOF, context);
146 } else {
147 baseNCodec.decode(singleByte, 0, EOF, context);
148 }
149 flush();
150 out.close();
151 }
152
153 }