blob: 7f9401515483f0a567d53bbf1ecb106725b54181 [file] [log] [blame]
Madan Jampani890bc352014-10-01 22:35:29 -07001package org.onlab.onos.store.messaging.impl;
2
3import java.util.Arrays;
4import java.util.List;
5
6import static com.google.common.base.Preconditions.checkState;
7
8import org.onlab.onos.store.cluster.messaging.SerializationService;
9import org.onlab.onos.store.messaging.Endpoint;
10
11import io.netty.buffer.ByteBuf;
12import io.netty.channel.ChannelHandlerContext;
13import io.netty.handler.codec.ByteToMessageDecoder;
14
15/**
16 * Decode bytes into a InrenalMessage.
17 */
18public class MessageDecoder extends ByteToMessageDecoder {
19
20 private final NettyMessagingService messagingService;
21 private final SerializationService serializationService;
22
23 public MessageDecoder(NettyMessagingService messagingService, SerializationService serializationService) {
24 this.messagingService = messagingService;
25 this.serializationService = serializationService;
26 }
27
28 @Override
29 protected void decode(ChannelHandlerContext context, ByteBuf in,
30 List<Object> messages) throws Exception {
31
32 byte[] preamble = in.readBytes(MessageEncoder.PREAMBLE.length).array();
33 checkState(Arrays.equals(MessageEncoder.PREAMBLE, preamble), "Message has wrong preamble");
34
35 // read message Id.
36 long id = in.readLong();
37
38 // read message type; first read size and then bytes.
39 String type = new String(in.readBytes(in.readInt()).array());
40
41 // read sender host name; first read size and then bytes.
42 String host = new String(in.readBytes(in.readInt()).array());
43
44 // read sender port.
45 int port = in.readInt();
46
47 Endpoint sender = new Endpoint(host, port);
48
49 // read message payload; first read size and then bytes.
50 Object payload = serializationService.decode(in.readBytes(in.readInt()).array());
51
52 InternalMessage message = new InternalMessage.Builder(messagingService)
53 .withId(id)
54 .withSender(sender)
55 .withType(type)
56 .withPayload(payload)
57 .build();
58
59 messages.add(message);
60 }
61}