1 | /** |
2 | * |
3 | */ |
4 | package org.apache.mina.protocol; |
5 | |
6 | import org.apache.mina.common.ByteBuffer; |
7 | import org.apache.mina.protocol.ProtocolEncoderOutput; |
8 | import org.apache.mina.util.Queue; |
9 | |
10 | /** |
11 | * A {@link ProtocolEncoderOutput} based on queue. |
12 | * |
13 | * @author The Apache Directory Project (dev@directory.apache.org) |
14 | * @author Trustin Lee (trustin@apache.org) |
15 | * @version $Rev: 210062 $, $Date: 2005-07-11 12:52:38 +0900 $ |
16 | */ |
17 | public class SimpleProtocolEncoderOutput implements ProtocolEncoderOutput |
18 | { |
19 | |
20 | private final Queue bufferQueue = new Queue(); |
21 | |
22 | public SimpleProtocolEncoderOutput() |
23 | { |
24 | } |
25 | |
26 | public Queue getBufferQueue() |
27 | { |
28 | return bufferQueue; |
29 | } |
30 | |
31 | public void write( ByteBuffer buf ) |
32 | { |
33 | bufferQueue.push( buf ); |
34 | } |
35 | |
36 | public void mergeAll() |
37 | { |
38 | int sum = 0; |
39 | final int size = bufferQueue.size(); |
40 | |
41 | if( size < 2 ) |
42 | { |
43 | // no need to merge! |
44 | return; |
45 | } |
46 | |
47 | // Get the size of merged BB |
48 | for( int i = size - 1; i >= 0; i -- ) |
49 | { |
50 | sum += ( ( ByteBuffer ) bufferQueue.get( i ) ).remaining(); |
51 | } |
52 | |
53 | // Allocate a new BB that will contain all fragments |
54 | ByteBuffer newBuf = ByteBuffer.allocate( sum ); |
55 | |
56 | // and merge all. |
57 | for( ;; ) |
58 | { |
59 | ByteBuffer buf = ( ByteBuffer ) bufferQueue.pop(); |
60 | if( buf == null ) |
61 | { |
62 | break; |
63 | } |
64 | |
65 | newBuf.put( buf ); |
66 | buf.release(); |
67 | } |
68 | |
69 | // Push the new buffer finally. |
70 | newBuf.flip(); |
71 | bufferQueue.push(newBuf); |
72 | } |
73 | } |