KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sapia > ubik > net > nio > TestHandler


1 package org.sapia.ubik.net.nio;
2
3 import java.io.ByteArrayOutputStream JavaDoc;
4 import java.io.IOException JavaDoc;
5 import java.nio.ByteBuffer JavaDoc;
6
7 import org.sapia.ubik.net.nio.ChannelHandler;
8 import org.sapia.ubik.net.nio.Cycle;
9
10 /**
11  * @author Yanick Duchesne
12  *
13  * <dl>
14  * <dt><b>Copyright:</b><dd>Copyright &#169; 2002-2005 <a HREF="http://www.sapia-oss.org">Sapia Open Source Software</a>. All Rights Reserved.</dd></dt>
15  * <dt><b>License:</b><dd>Read the license.txt file of the jar or visit the
16  * <a HREF="http://www.sapia-oss.org/license.html">license page</a> at the Sapia OSS web site</dd></dt>
17  * </dl>
18  */

19 public class TestHandler implements ChannelHandler{
20   
21   private int _expectedSize;
22   private ByteArrayOutputStream JavaDoc _out = new ByteArrayOutputStream JavaDoc();
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 JavaDoc buf = cycle.getByteBuffer();
42     byte[] data = new byte[buf.remaining()];
43     buf.get(data);
44     try{
45       _out.write(data);
46     }catch(IOException JavaDoc e){
47       throw new RuntimeException JavaDoc(e);
48     }
49     return _out.size() >= _expectedSize;
50   }
51
52   public boolean write(Cycle cycle) {
53     ByteBuffer JavaDoc 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