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;
21
22 import java.util.Queue;
23 import java.util.concurrent.ConcurrentLinkedQueue;
24
25 import org.apache.mina.core.buffer.IoBuffer;
26
27
28
29
30
31
32 public abstract class AbstractProtocolEncoderOutput implements ProtocolEncoderOutput {
33 private final Queue<Object> messageQueue = new ConcurrentLinkedQueue<Object>();
34
35 private boolean buffersOnly = true;
36
37 public AbstractProtocolEncoderOutput() {
38
39 }
40
41 public Queue<Object> getMessageQueue() {
42 return messageQueue;
43 }
44
45 public void write(Object encodedMessage) {
46 if (encodedMessage instanceof IoBuffer) {
47 IoBuffer buf = (IoBuffer) encodedMessage;
48 if (buf.hasRemaining()) {
49 messageQueue.offer(buf);
50 } else {
51 throw new IllegalArgumentException("buf is empty. Forgot to call flip()?");
52 }
53 } else {
54 messageQueue.offer(encodedMessage);
55 buffersOnly = false;
56 }
57 }
58
59 public void mergeAll() {
60 if (!buffersOnly) {
61 throw new IllegalStateException("the encoded message list contains a non-buffer.");
62 }
63
64 final int size = messageQueue.size();
65
66 if (size < 2) {
67
68 return;
69 }
70
71
72 int sum = 0;
73 for (Object b : messageQueue) {
74 sum += ((IoBuffer) b).remaining();
75 }
76
77
78 IoBuffer newBuf = IoBuffer.allocate(sum);
79
80
81 for (;;) {
82 IoBuffer buf = (IoBuffer) messageQueue.poll();
83 if (buf == null) {
84 break;
85 }
86
87 newBuf.put(buf);
88 }
89
90
91 newBuf.flip();
92 messageQueue.add(newBuf);
93 }
94 }