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 java.util.LinkedList;
23 import java.util.Queue;
24
25 import org.apache.mina.common.ByteBuffer;
26 import org.apache.mina.common.WriteFuture;
27 import org.apache.mina.filter.codec.ProtocolEncoderOutput;
28
29
30
31
32
33
34
35 public abstract class SimpleProtocolEncoderOutput implements
36 ProtocolEncoderOutput {
37 private final Queue<ByteBuffer> bufferQueue = new LinkedList<ByteBuffer>();
38
39 public SimpleProtocolEncoderOutput() {
40 }
41
42 public Queue<ByteBuffer> getBufferQueue() {
43 return bufferQueue;
44 }
45
46 public void write(ByteBuffer buf) {
47 bufferQueue.add(buf);
48 }
49
50 public void mergeAll() {
51 int sum = 0;
52 final int size = bufferQueue.size();
53
54 if (size < 2) {
55
56 return;
57 }
58
59
60 for (Object o : bufferQueue) {
61 sum += ((ByteBuffer) o).remaining();
62 }
63
64
65 ByteBuffer newBuf = ByteBuffer.allocate(sum);
66
67
68 for (;;) {
69 ByteBuffer buf = bufferQueue.poll();
70 if (buf == null) {
71 break;
72 }
73
74 newBuf.put(buf);
75 buf.release();
76 }
77
78
79 newBuf.flip();
80 bufferQueue.offer(newBuf);
81 }
82
83 public WriteFuture flush() {
84 Queue<ByteBuffer> bufferQueue = this.bufferQueue;
85 WriteFuture future = null;
86 if (bufferQueue.isEmpty()) {
87 return null;
88 } else {
89 for (;;) {
90 ByteBuffer buf = bufferQueue.poll();
91 if (buf == null) {
92 break;
93 }
94
95
96 if (buf.hasRemaining()) {
97 future = doFlush(buf);
98 }
99 }
100 }
101
102 return future;
103 }
104
105 protected abstract WriteFuture doFlush(ByteBuffer buf);
106 }