blob: a7a3e6a28562da44c3e05e691e0bc1bbe432b5f3 [file] [log] [blame]
tomf110fff2014-09-26 00:38:18 -07001package org.onlab.onos.foo;
2
3import org.onlab.nio.IOLoop;
4import org.onlab.nio.MessageStream;
5
6import java.nio.ByteBuffer;
7import java.nio.channels.ByteChannel;
8
tom0e0863f2014-09-26 09:02:33 -07009import static com.google.common.base.Preconditions.checkState;
10
tomf110fff2014-09-26 00:38:18 -070011/**
12 * Fixed-length message transfer buffer.
13 */
14public class TestMessageStream extends MessageStream<TestMessage> {
15
16 private static final String E_WRONG_LEN = "Illegal message length: ";
tom0e0863f2014-09-26 09:02:33 -070017 private static final long START_TAG = 0xfeedcafedeaddeedL;
18 private static final long END_TAG = 0xbeadcafedeaddeedL;
19 private static final int META_LENGTH = 40;
tomf110fff2014-09-26 00:38:18 -070020
21 private final int length;
22
tom0e0863f2014-09-26 09:02:33 -070023 public TestMessageStream(int length, ByteChannel ch, IOLoop<TestMessage, ?> loop) {
tomf110fff2014-09-26 00:38:18 -070024 super(loop, ch, 64 * 1024, 500);
25 this.length = length;
26 }
27
28 @Override
29 protected TestMessage read(ByteBuffer rb) {
30 if (rb.remaining() < length) {
31 return null;
32 }
tom0e0863f2014-09-26 09:02:33 -070033
34 long startTag = rb.getLong();
35 checkState(startTag == START_TAG, "Incorrect message start");
36
37 long size = rb.getLong();
38 long requestorTime = rb.getLong();
39 long responderTime = rb.getLong();
40 byte[] padding = padding(length);
41 rb.get(padding);
42
43 long endTag = rb.getLong();
44 checkState(endTag == END_TAG, "Incorrect message end");
45
46 return new TestMessage((int) size, requestorTime, responderTime, padding);
tomf110fff2014-09-26 00:38:18 -070047 }
48
tomf110fff2014-09-26 00:38:18 -070049 @Override
50 protected void write(TestMessage message, ByteBuffer wb) {
51 if (message.length() != length) {
52 throw new IllegalArgumentException(E_WRONG_LEN + message.length());
53 }
tom0e0863f2014-09-26 09:02:33 -070054
55 wb.putLong(START_TAG);
56 wb.putLong(message.length());
57 wb.putLong(message.requestorTime());
58 wb.putLong(message.responderTime());
59 wb.put(message.padding(), 0, length - META_LENGTH);
60 wb.putLong(END_TAG);
tomf110fff2014-09-26 00:38:18 -070061 }
62
tom0e0863f2014-09-26 09:02:33 -070063 public byte[] padding(int msgLength) {
64 return new byte[msgLength - META_LENGTH];
65 }
tomf110fff2014-09-26 00:38:18 -070066}