コード例 #1
0
 public static final ByteBuffer makeMessageBuffer(
     final List<Long> msgIds, final List<PutCommand> reqs) {
   if (msgIds == null || reqs == null) {
     throw new IllegalArgumentException("Null id list or request list");
   }
   if (msgIds.size() != reqs.size()) {
     throw new IllegalArgumentException("id list is not adapte to request list");
   }
   int capacity = 0;
   for (final PutCommand req : reqs) {
     capacity += 4 + 4 + 8 + 4 + req.getData().length;
   }
   final ByteBuffer buffer = ByteBuffer.allocate(capacity);
   for (int i = 0; i < reqs.size(); i++) {
     final PutCommand req = reqs.get(i);
     final long msgId = msgIds.get(i);
     buffer.putInt(req.getData().length);
     buffer.putInt(CheckSum.crc32(req.getData()));
     buffer.putLong(msgId);
     buffer.putInt(req.getFlag());
     buffer.put(req.getData());
   }
   buffer.flip();
   return buffer;
 }
コード例 #2
0
 /**
  * 校验checksum
  *
  * @param msg
  * @param checksum
  */
 public static final void vailidateMessage(
     final int offset, final int msgLen, final int checksum, final byte[] data)
     throws InvalidMessageException {
   if (checksum != CheckSum.crc32(data, offset, msgLen)) {
     throw new InvalidMessageException("Invalid message");
   }
 }
コード例 #3
0
 @Test
 public void testCheckSum() throws Exception {
   byte[] data2 = new byte[1024];
   byte[] data1 = new byte[1024];
   for (int i = 0; i < data1.length; i++) {
     data1[i] = (byte) (i % 127);
     data2[i] = (byte) (i % 127);
   }
   assertEquals(CheckSum.crc32(data1), CheckSum.crc32(data1));
   assertEquals(CheckSum.crc32(data2), CheckSum.crc32(data2));
   assertEquals(CheckSum.crc32(data1), CheckSum.crc32(data2));
 }
コード例 #4
0
 /**
  * 创建消息buffer,实际存储在服务器的结构如下:
  *
  * <ul>
  *   <li>message length(4 bytes),including attribute and payload
  *   <li>checksum(4 bytes)
  *   <li>message id(8 bytes)
  *   <li>message flag(4 bytes)
  *   <li>attribute length(4 bytes) + attribute,optional
  *   <li>payload
  * </ul>
  *
  * @param req
  * @return
  */
 public static final ByteBuffer makeMessageBuffer(final long msgId, final PutCommand req) {
   // message length + checksum + id +flag + data
   final ByteBuffer buffer = ByteBuffer.allocate(4 + 4 + 8 + 4 + req.getData().length);
   buffer.putInt(req.getData().length);
   int checkSum = CheckSum.crc32(req.getData());
   // If client passes checksum,compare them
   if (req.getCheckSum() != -1) {
     if (checkSum != req.getCheckSum()) {
       throw new InvalidCheckSumException(
           "Checksum failure,message may be corrupted when transfering on networking.");
     }
   }
   buffer.putInt(checkSum);
   buffer.putLong(msgId);
   buffer.putInt(req.getFlag());
   buffer.put(req.getData());
   buffer.flip();
   return buffer;
 }