1 package org.sapia.ubik.net.nio; 2 3 import java.io.ByteArrayOutputStream ; 4 import java.io.IOException ; 5 import java.nio.ByteBuffer ; 6 7 import org.sapia.ubik.net.nio.ChannelHandler; 8 import org.sapia.ubik.net.nio.Cycle; 9 10 19 public class TestHandler implements ChannelHandler{ 20 21 private int _expectedSize; 22 private ByteArrayOutputStream _out = new ByteArrayOutputStream (); 23 private byte[] _toWrite; 24 private int _pos; 25 26 public TestHandler(int expectedSize){ 27 _expectedSize = expectedSize; 28 } 29 30 public TestHandler(byte[] toWrite){ 31 _toWrite = toWrite; 32 } 33 34 public void completed(Cycle cycle) { 35 } 36 public void error(Cycle cycle) { 37 } 38 public void process(Cycle cycle) { 39 } 40 public boolean read(Cycle cycle){ 41 ByteBuffer buf = cycle.getByteBuffer(); 42 byte[] data = new byte[buf.remaining()]; 43 buf.get(data); 44 try{ 45 _out.write(data); 46 }catch(IOException e){ 47 throw new RuntimeException (e); 48 } 49 return _out.size() >= _expectedSize; 50 } 51 52 public boolean write(Cycle cycle) { 53 ByteBuffer to = cycle.getByteBuffer(); 54 byte[] buf = new byte[to.remaining()]; 55 if(_pos < _toWrite.length){ 56 int remaining = to.remaining(); 57 int count = 0; 58 while(_pos < _toWrite.length && 59 count < remaining && 60 count < _toWrite.length){ 61 62 buf[count++] = _toWrite[_pos++]; 63 } 64 to.put(buf, 0, count); 65 } 66 else{ 67 return true; 68 } 69 return _pos >= _toWrite.length; 70 } 71 72 public byte[] getBytes(){ 73 return _out.toByteArray(); 74 } 75 76 public void started(Cycle cycle) { 77 } 78 } 79 | Popular Tags |