package se.six.cs.comm.cub; import com.sun.grizzly.ProtocolParser; import java.nio.ByteBuffer; import se.six.cs.xflow.message.XFlowMessage; public class XFlowProtocolParser implements ProtocolParser { private ByteBuffer saved; /* To fullfill the interface contract with we need to have a hasNextMessage() method. Since finding out if we have a message could be said to be the same thing as finding out by parsing, we have current_message that we store the message we have parsed but not yet delivered. */ private XFlowMessage current_message; private boolean wants_more_data = false; private boolean has_more_data = false; private int pos = 0; public XFlowProtocolParser() { System.out.println("XFlowProtocolParser created..."); } public boolean isExpectingMoreData() { return wants_more_data; } public boolean hasMoreBytesToParse() { return has_more_data; } public XFlowMessage getNextMessage() { if (current_message == null) { current_message = xGetXFlowMessage(); } XFlowMessage tmp_msg = null; if (current_message != null) { tmp_msg = current_message; current_message = null; } return tmp_msg; } public boolean hasNextMessage() { if (current_message == null) { current_message = xGetXFlowMessage(); } return (current_message != null); } public void startBuffer(ByteBuffer byteBuffer) { saved = byteBuffer; saved.flip(); System.out.println("\n********\nstartBuffer: Message buffer size : "+saved.limit()+"\n***********\n"); has_more_data = true; current_message = null; } private void xPrintBufferStats(ByteBuffer bb) { System.out.println(" Position : "+bb.position()+" Limit: "+bb.limit()); } public boolean releaseBuffer() { if (wants_more_data) { saved.compact(); } else { saved.clear(); } return wants_more_data; //To change body of implemented methods use File | Settings | File Templates. } /* The most common case: */ private XFlowMessage xGetXFlowMessage() { XFlowMessage msg = null; if (!saved.hasRemaining()) { wants_more_data = false; has_more_data = false; saved.clear(); return null; } // we need to save the position if there isn't a complete message in the buffer. pos = saved.position(); // the XFlowMessage contains its own parser. msg = XFlowMessage.parse(saved); if (msg == null) { // not enough bytes in the buffer wants_more_data = true; has_more_data = false; saved.position(pos); } else { if (saved.position() == saved.limit()) { has_more_data = false; } else { has_more_data = true; } } return msg; } }