1 20 package org.apache.mina.filter.codec; 21 22 import org.apache.mina.common.ByteBuffer; 23 import org.apache.mina.common.IoSession; 24 25 96 public abstract class CumulativeProtocolDecoder extends ProtocolDecoderAdapter { 97 98 private static final String BUFFER = CumulativeProtocolDecoder.class 99 .getName() 100 + ".Buffer"; 101 102 105 protected CumulativeProtocolDecoder() { 106 } 107 108 117 public void decode(IoSession session, ByteBuffer in, 118 ProtocolDecoderOutput out) throws Exception { 119 boolean usingSessionBuffer = true; 120 ByteBuffer buf = (ByteBuffer) session.getAttribute(BUFFER); 121 if (buf != null) { 124 buf.put(in); 125 buf.flip(); 126 } else { 127 buf = in; 128 usingSessionBuffer = false; 129 } 130 131 for (;;) { 132 int oldPos = buf.position(); 133 boolean decoded = doDecode(session, buf, out); 134 if (decoded) { 135 if (buf.position() == oldPos) { 136 throw new IllegalStateException ( 137 "doDecode() can't return true when buffer is not consumed."); 138 } 139 140 if (!buf.hasRemaining()) { 141 break; 142 } 143 } else { 144 break; 145 } 146 } 147 148 if (buf.hasRemaining()) { 152 if (usingSessionBuffer) 153 buf.compact(); 154 else 155 storeRemainingInSession(buf, session); 156 } else { 157 if (usingSessionBuffer) 158 removeSessionBuffer(session); 159 } 160 } 161 162 173 protected abstract boolean doDecode(IoSession session, ByteBuffer in, 174 ProtocolDecoderOutput out) throws Exception ; 175 176 181 public void dispose(IoSession session) throws Exception { 182 removeSessionBuffer(session); 183 } 184 185 private void removeSessionBuffer(IoSession session) { 186 ByteBuffer buf = (ByteBuffer) session.removeAttribute(BUFFER); 187 if (buf != null) { 188 buf.release(); 189 } 190 } 191 192 private void storeRemainingInSession(ByteBuffer buf, IoSession session) { 193 ByteBuffer remainingBuf = ByteBuffer.allocate(buf.capacity()); 194 remainingBuf.setAutoExpand(true); 195 remainingBuf.order(buf.order()); 196 remainingBuf.put(buf); 197 session.setAttribute(BUFFER, remainingBuf); 198 } 199 } 200 | Popular Tags |