1 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 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 return; 57 } 58 59 for (Object o : bufferQueue) { 61 sum += ((ByteBuffer) o).remaining(); 62 } 63 64 ByteBuffer newBuf = ByteBuffer.allocate(sum); 66 67 for (;;) { 69 ByteBuffer buf = bufferQueue.poll(); 70 if (buf == null) { 71 break; 72 } 73 74 newBuf.put(buf); 75 buf.release(); 76 } 77 78 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 if (buf.hasRemaining()) { 97 future = doFlush(buf); 98 } 99 } 100 } 101 102 return future; 103 } 104 105 protected abstract WriteFuture doFlush(ByteBuffer buf); 106 } | Popular Tags |