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 | |
| 8 | import org.onlab.onos.store.cluster.messaging.SerializationService; |
| 9 | import org.onlab.onos.store.messaging.Endpoint; |
| 10 | |
| 11 | import io.netty.buffer.ByteBuf; |
| 12 | import io.netty.channel.ChannelHandlerContext; |
| 13 | import io.netty.handler.codec.ByteToMessageDecoder; |
| 14 | |
| 15 | /** |
| 16 | * Decode bytes into a InrenalMessage. |
| 17 | */ |
| 18 | public 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 | } |