1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.filter.codec.support;
21
22 import org.apache.mina.common.ByteBuffer;
23 import org.apache.mina.common.WriteFuture;
24 import org.apache.mina.filter.codec.ProtocolEncoderOutput;
25 import org.apache.mina.util.Queue;
26
27
28
29
30
31
32
33 public abstract class SimpleProtocolEncoderOutput implements
34 ProtocolEncoderOutput {
35 private final Queue bufferQueue = new Queue();
36
37 public SimpleProtocolEncoderOutput() {
38 }
39
40 public Queue getBufferQueue() {
41 return bufferQueue;
42 }
43
44 public void write(ByteBuffer buf) {
45 bufferQueue.push(buf);
46 }
47
48 public void mergeAll() {
49 int sum = 0;
50 final int size = bufferQueue.size();
51
52 if (size < 2) {
53
54 return;
55 }
56
57
58 for (int i = size - 1; i >= 0; i--) {
59 sum += ((ByteBuffer) bufferQueue.get(i)).remaining();
60 }
61
62
63 ByteBuffer newBuf = ByteBuffer.allocate(sum);
64
65
66 for (;;) {
67 ByteBuffer buf = (ByteBuffer) bufferQueue.pop();
68 if (buf == null) {
69 break;
70 }
71
72 newBuf.put(buf);
73 buf.release();
74 }
75
76
77 newBuf.flip();
78 bufferQueue.push(newBuf);
79 }
80
81 public WriteFuture flush() {
82 Queue bufferQueue = this.bufferQueue;
83 WriteFuture future = null;
84 if (bufferQueue.isEmpty()) {
85 return null;
86 } else {
87 for (;;) {
88 ByteBuffer buf = (ByteBuffer) bufferQueue.pop();
89 if (buf == null) {
90 break;
91 }
92
93
94 if (buf.hasRemaining()) {
95 future = doFlush(buf);
96 }
97 }
98 }
99
100 return future;
101 }
102
103 protected abstract WriteFuture doFlush(ByteBuffer buf);
104 }