-
Notifications
You must be signed in to change notification settings - Fork 78
/
MockServletOutputStream.java
78 lines (63 loc) · 1.85 KB
/
MockServletOutputStream.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package jakarta.servlet;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class MockServletOutputStream extends ServletOutputStream {
private final OutputStream out;
public MockServletOutputStream() {
this(null);
}
public MockServletOutputStream(OutputStream out) {
this.out = out == null ? new ByteArrayOutputStream() : out;
}
@Override
public void close() throws IOException {
out.close();
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public boolean isReady() {
return false;
}
public void reset() {
if (out instanceof ByteArrayOutputStream)
((ByteArrayOutputStream) out).reset();
}
@Override
public void setWriteListener(WriteListener writeListener) {
throw new UnsupportedOperationException();
}
@Override
public void write(byte[] b) throws IOException {
out.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
}
@Override
public void write(int b) throws IOException {
out.write(b);
}
public String takeOutputAsString() {
return takeOutputAsString(StandardCharsets.ISO_8859_1);
}
public String takeOutputAsString(Charset charset) {
byte[] bytes = takeOutput();
return bytes == null ? null : new String(bytes, charset);
}
public byte[] takeOutput() {
if (out instanceof ByteArrayOutputStream) {
ByteArrayOutputStream bout = (ByteArrayOutputStream) out;
byte[] bytes = bout.toByteArray();
bout.reset();
return bytes;
}
return null;
}
}