1   /*
2    * Created on May 10, 2004
3    *
4    */
5   package org.neo.swarm.util.io;
6   
7   import java.io.IOException;
8   import java.nio.ByteBuffer;
9   
10  import org.neo.swarm.util.io.ByteBufferInputStream;
11  import org.neo.swarm.util.io.PacketInputStream;
12  import org.neo.swarm.util.io.StreamCallback;
13  
14  import junit.framework.TestCase;
15  
16  
17  /***
18   * Tests basic functionality of PacketStreams
19   *  @author navery
20   */
21  public class PacketStreamTest extends TestCase {
22      byte[] data = "Stuff".getBytes();
23      
24      public void testPacketInputStreamWithSimpleData() throws Exception {
25          
26          PacketInputStream pis = new PacketInputStream(new ByteBufferInputStream(PacketInputStream.START_DATA.length + 4, PacketInputStream.END_DATA.length, ByteBuffer.allocate(100), new MyCallback()));
27          
28          int avail = pis.available();
29          byte[] stuff = new byte[avail];
30          pis.read(stuff);
31          assertEquals(new String(data), new String(stuff));
32      }
33      
34      public class MyCallback implements StreamCallback {
35          
36          int calls = 0;
37  
38          /* (non-Javadoc)
39           * @see org.neo.swarm.util.io.StreamCallback#close()
40           */
41          public void close() {
42          }
43          
44          /* (non-Javadoc)
45           * @see org.neo.swarm.util.io.StreamCallback#execute(java.nio.ByteBuffer, int)
46           */
47          public int execute(ByteBuffer buffer, int availableBytes) throws IOException {
48              
49              if (calls == 0) {
50                  buffer.put(PacketInputStream.START_DATA);
51                  buffer.put(toBytes(data.length));
52              } else if (calls == 1) {
53                  buffer.put(data);
54              } else if (calls == 2) {
55                  buffer.put(PacketInputStream.END_DATA);
56              }
57              calls ++;
58              return buffer.position();
59          }
60          public byte[] toBytes(int n) {
61              byte[] b = new byte[4];
62              b[3] = (byte) (n);
63              n >>>= 8;
64              b[2] = (byte) (n);
65              n >>>= 8;
66              b[1] = (byte) (n);
67              n >>>= 8;
68              b[0] = (byte) (n);
69              return b;
70          } //toBytes
71      }   
72  }