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