blob: c357fe430359c2e6c548fc509dd78388d267020f [file] [log] [blame]
toma7083182014-09-25 21:38:03 -07001package org.onlab.nio;
2
3import java.nio.ByteBuffer;
4import java.nio.channels.ByteChannel;
5
tom1ae3d162014-09-26 09:38:16 -07006import static com.google.common.base.Preconditions.checkArgument;
7import static com.google.common.base.Preconditions.checkState;
8
toma7083182014-09-25 21:38:03 -07009/**
10 * Fixed-length message transfer buffer.
11 */
12public class TestMessageStream extends MessageStream<TestMessage> {
13
14 private static final String E_WRONG_LEN = "Illegal message length: ";
tom1ae3d162014-09-26 09:38:16 -070015 private static final long START_TAG = 0xfeedcafedeaddeedL;
16 private static final long END_TAG = 0xbeadcafedeaddeedL;
17 private static final int META_LENGTH = 40;
toma7083182014-09-25 21:38:03 -070018
19 private final int length;
tom1ae3d162014-09-26 09:38:16 -070020 private boolean isStrict = true;
toma7083182014-09-25 21:38:03 -070021
tom1ae3d162014-09-26 09:38:16 -070022 public TestMessageStream(int length, ByteChannel ch, IOLoop<TestMessage, ?> loop) {
toma7083182014-09-25 21:38:03 -070023 super(loop, ch, 64 * 1024, 500);
tom1ae3d162014-09-26 09:38:16 -070024 checkArgument(length >= META_LENGTH, "Length must be greater than header length of 40");
toma7083182014-09-25 21:38:03 -070025 this.length = length;
26 }
27
tom1ae3d162014-09-26 09:38:16 -070028 void setNonStrict() {
29 isStrict = false;
30 }
31
toma7083182014-09-25 21:38:03 -070032 @Override
33 protected TestMessage read(ByteBuffer rb) {
34 if (rb.remaining() < length) {
35 return null;
36 }
tom1ae3d162014-09-26 09:38:16 -070037
38 long startTag = rb.getLong();
39 if (isStrict) {
40 checkState(startTag == START_TAG, "Incorrect message start");
41 }
42
43 long size = rb.getLong();
44 long requestorTime = rb.getLong();
45 long responderTime = rb.getLong();
46 byte[] padding = padding();
47 rb.get(padding);
48
49 long endTag = rb.getLong();
50 if (isStrict) {
51 checkState(endTag == END_TAG, "Incorrect message end");
52 }
53
54 return new TestMessage((int) size, requestorTime, responderTime, padding);
toma7083182014-09-25 21:38:03 -070055 }
56
toma7083182014-09-25 21:38:03 -070057 @Override
58 protected void write(TestMessage message, ByteBuffer wb) {
59 if (message.length() != length) {
60 throw new IllegalArgumentException(E_WRONG_LEN + message.length());
61 }
tom1ae3d162014-09-26 09:38:16 -070062
63 wb.putLong(START_TAG);
64 wb.putLong(message.length());
65 wb.putLong(message.requestorTime());
66 wb.putLong(message.responderTime());
67 wb.put(message.padding(), 0, length - META_LENGTH);
68 wb.putLong(END_TAG);
toma7083182014-09-25 21:38:03 -070069 }
70
tom1ae3d162014-09-26 09:38:16 -070071 public byte[] padding() {
72 return new byte[length - META_LENGTH];
73 }
toma7083182014-09-25 21:38:03 -070074}