1 package org.sapia.ubik.net.nio; 2 3 import java.io.IOException ; 4 import java.nio.ByteBuffer ; 5 import java.nio.channels.Channel ; 6 7 import org.sapia.ubik.net.nio.util.ByteBufferPool; 8 9 26 public class CycleBase implements Cycle { 27 28 private int _state, _nextState; 29 private Channel _channel; 30 private ChannelHandler _handler; 31 private ChannelManager _manager; 32 private ByteBuffer _buffer; 33 private ByteBufferPool _pool; 34 private CycleListener _listener; 35 private Throwable _err; 36 37 protected CycleBase(int initialState, ChannelManager manager, 38 Channel channel, ByteBufferPool pool, CycleListener listener) { 39 assertState(initialState); 40 _state = initialState; 41 _channel = channel; 42 _listener = listener; 43 _manager = manager; 44 _pool = pool; 45 } 46 47 50 public int state() { 51 return _state; 52 } 53 54 57 public void state(int nextState) { 58 assertState(nextState); 59 _nextState = nextState; 60 } 61 62 65 public void error(Throwable err) { 66 state(STATE_ERROR); 67 _err = err; 68 } 69 70 73 public void next() { 74 _state = _nextState; 75 _listener.onNextState(this); 76 } 77 78 81 public boolean isComplete() { 82 return _state == STATE_COMPLETE; 83 } 84 85 88 public boolean isRecycle() { 89 return _state == STATE_RECYCLE; 90 } 91 92 95 public boolean isRead() { 96 return _state == STATE_READ; 97 } 98 99 102 public boolean isWrite() { 103 return _state == STATE_WRITE; 104 } 105 106 109 public boolean isProcess() { 110 return false; 111 } 112 113 116 public boolean isError() { 117 return _state == STATE_ERROR; 118 } 119 120 123 public Throwable getError() { 124 return _err; 125 } 126 127 130 public Channel getChannel() { 131 return _channel; 132 } 133 134 137 public ChannelManager getChannelManager() { 138 return _manager; 139 } 140 141 144 public ByteBuffer getByteBuffer() { 145 if(_buffer == null) { 146 try { 147 _buffer = (ByteBuffer ) _pool.acquire(); 148 } catch(Exception e) { 149 throw new RuntimeException ("Could not acquire byte buffer"); 150 } 151 } 152 return _buffer; 153 } 154 155 158 public ChannelHandler getHandler() { 159 if(_handler == null) { 160 _handler = _manager.createHandler(); 161 } 162 return _handler; 163 } 164 165 168 public void destroy() { 169 if(_buffer != null) { 170 _pool.release(_buffer); 171 } 172 try { 173 _channel.close(); 174 } catch(IOException e) { 175 } 176 } 177 178 181 public void releaseByteBuffer() { 182 if(_buffer != null) { 183 _pool.release(_buffer); 184 } 185 } 186 187 protected void handler(ChannelHandler handler) { 188 _handler = handler; 189 } 190 191 protected void byteBuffer(ByteBuffer buf) { 192 _buffer = buf; 193 } 194 195 protected void assertState(int state) { 196 if(state < STATE_READ || state > STATE_ERROR) { 197 throw new IllegalStateException ("Invalid state: " + state); 198 } 199 } 200 201 } 202 | Popular Tags |