001 /**
002 * Copyright (C) 2010-2011, FuseSource Corp. All rights reserved.
003 *
004 * http://fusesource.com
005 *
006 * The software in this package is published under the terms of the
007 * CDDL license a copy of which has been included with this distribution
008 * in the license.txt file.
009 */
010 package org.fusesource.hawtdispatch.transport;
011
012 import java.io.IOException;
013 import java.nio.channels.ReadableByteChannel;
014 import java.nio.channels.WritableByteChannel;
015
016
017 /**
018 * Interface to encode and decode commands in and out of a a non blocking channel.
019 *
020 * @author <a href="http://hiramchirino.com">Hiram Chirino</a>
021 */
022 public interface ProtocolCodec {
023
024 ///////////////////////////////////////////////////////////////////
025 //
026 // Methods related with reading from the channel
027 //
028 ///////////////////////////////////////////////////////////////////
029
030 /**
031 * @param channel
032 */
033 public void setReadableByteChannel(ReadableByteChannel channel) throws Exception;
034
035 /**
036 * Non-blocking channel based decoding.
037 *
038 * @return
039 * @throws IOException
040 */
041 Object read() throws IOException;
042
043 /**
044 * Pushes back a buffer as being unread.
045 *
046 * @param buffer
047 */
048 void unread(byte[] buffer);
049
050 /**
051 * @return The number of bytes received.
052 */
053 public long getReadCounter();
054
055 /**
056 * @return The number of bytes read in the last read io performed.
057 */
058 public long getLastReadSize();
059
060
061 ///////////////////////////////////////////////////////////////////
062 //
063 // Methods related with writing to the channel
064 //
065 ///////////////////////////////////////////////////////////////////
066
067
068 enum BufferState {
069 EMPTY,
070 WAS_EMPTY,
071 NOT_EMPTY,
072 FULL,
073 }
074
075 public void setWritableByteChannel(WritableByteChannel channel) throws Exception;
076
077 public int getReadBufferSize();
078 public int getWriteBufferSize();
079
080 /**
081 * Non-blocking channel based encoding.
082 *
083 * @return true if the write completed.
084 * @throws IOException
085 */
086 BufferState write(Object value) throws IOException;
087
088 /**
089 * Attempts to complete the previous write which did not complete.
090 * @return
091 * @throws IOException
092 */
093 BufferState flush() throws IOException;
094
095 /**
096 * Is the codec's buffer full?
097 * @return
098 */
099 boolean full();
100
101 /**
102 * @return The number of bytes written.
103 */
104 public long getWriteCounter();
105
106 /**
107 * @return The number of bytes read in the last write io performed.
108 */
109 public long getLastWriteSize();
110
111
112 }