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 package org.apache.hc.core5.http2;
29
30 import java.io.IOException;
31 import java.nio.ByteBuffer;
32 import java.nio.channels.ClosedChannelException;
33 import java.nio.channels.WritableByteChannel;
34
35 public class WritableByteChannelMock implements WritableByteChannel {
36
37 private final int capacityLimit;
38
39 private int capacityUsed;
40 private ByteBuffer buf;
41 private boolean closed;
42
43 public WritableByteChannelMock(final int initialSize, final int capacityLimit) {
44 this.buf = ByteBuffer.allocate(initialSize);
45 this.capacityLimit = capacityLimit;
46 }
47
48 public WritableByteChannelMock(final int initialSize) {
49 this(initialSize, 0);
50 }
51
52 private void expandCapacity(final int capacity) {
53 final ByteBuffer oldbuffer = this.buf;
54 this.buf = ByteBuffer.allocate(capacity);
55 oldbuffer.flip();
56 this.buf.put(oldbuffer);
57 }
58
59 private void ensureCapacity(final int requiredCapacity) {
60 if (requiredCapacity > this.buf.capacity()) {
61 expandCapacity(requiredCapacity);
62 }
63 }
64
65 @Override
66 public int write(final ByteBuffer src) throws IOException {
67 if (this.closed) {
68 throw new ClosedChannelException();
69 }
70 final int len = src.remaining();
71 ensureCapacity(this.buf.position() + len);
72 if (this.capacityLimit > 0) {
73 final int chunk = Math.min(this.capacityLimit - this.capacityUsed, len);
74 if (chunk > 0) {
75 final int limit = src.limit();
76 src.limit(src.position() + chunk);
77 this.buf.put(src);
78 src.limit(limit);
79 this.capacityUsed += chunk;
80 return chunk;
81 }
82 return 0;
83 }
84 this.buf.put(src);
85 return len;
86 }
87
88 @Override
89 public boolean isOpen() {
90 return !this.closed;
91 }
92
93 @Override
94 public void close() throws IOException {
95 this.closed = true;
96 }
97
98 public void flush() {
99 this.capacityUsed = 0;
100 }
101
102 public void reset() {
103 this.capacityUsed = 0;
104 this.buf.clear();
105 }
106
107 public byte[] toByteArray() {
108 final ByteBuffer dup = this.buf.duplicate();
109 dup.flip();
110 final byte[] bytes = new byte[dup.remaining()];
111 dup.get(bytes);
112 return bytes;
113 }
114
115 }