View Javadoc
1   package emissary.core.channels;
2   
3   import org.apache.commons.io.IOUtils;
4   
5   import java.io.IOException;
6   import java.nio.ByteBuffer;
7   import java.nio.channels.SeekableByteChannel;
8   import java.util.Arrays;
9   
10  import static org.junit.jupiter.api.Assertions.assertArrayEquals;
11  import static org.junit.jupiter.api.Assertions.assertEquals;
12  
13  public class ChannelTestHelper {
14      private ChannelTestHelper() {}
15  
16      public static void checkByteArrayAgainstSbc(final byte[] bytesToVerify, final SeekableByteChannelFactory sbcf)
17              throws IOException {
18          try (SeekableByteChannel sbc = sbcf.create()) {
19              int startIndex;
20              int length;
21              for (startIndex = 0; startIndex < bytesToVerify.length; startIndex++) {
22                  for (length = bytesToVerify.length - startIndex; length > 0; length--) {
23                      checkSegment(sbc, bytesToVerify, startIndex, length);
24                  }
25              }
26  
27              // Do the same as above but starting from the end of the string/file
28              for (startIndex = (bytesToVerify.length - 1); startIndex > -1; startIndex--) {
29                  for (length = bytesToVerify.length - startIndex; length > 0; length--) {
30                      checkSegment(sbc, bytesToVerify, startIndex, length);
31                  }
32              }
33          }
34      }
35  
36      private static void checkSegment(final SeekableByteChannel sbc, final byte[] bytesToVerify, final int startIndex,
37              final int length) throws IOException {
38          sbc.position(startIndex);
39          assertEquals(startIndex, sbc.position(), "Setting initial position of sbc is incorrect!");
40  
41          final ByteBuffer buff = ByteBuffer.allocate(length);
42          final int bytesRead = IOUtils.read(sbc, buff);
43  
44          assertEquals(length, bytesRead, "bytesRead value is incorrect!");
45          assertEquals(startIndex + length, sbc.position(), "Sbc position after read is incorrect!");
46          assertArrayEquals(Arrays.copyOfRange(bytesToVerify, startIndex, startIndex + length), buff.array(),
47                  "Bytes read are incorrect!");
48      }
49  }