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