Madan Jampani | 890bc35 | 2014-10-01 22:35:29 -0700 | [diff] [blame] | 1 | package org.onlab.onos.store.messaging.impl; |
| 2 | |
| 3 | import org.onlab.onos.store.cluster.messaging.SerializationService; |
| 4 | |
| 5 | import io.netty.buffer.ByteBuf; |
| 6 | import io.netty.channel.ChannelHandlerContext; |
| 7 | import io.netty.handler.codec.MessageToByteEncoder; |
| 8 | |
| 9 | /** |
| 10 | * Encode InternalMessage out into a byte buffer. |
| 11 | */ |
| 12 | public class MessageEncoder extends MessageToByteEncoder<InternalMessage> { |
| 13 | |
| 14 | // onosiscool in ascii |
| 15 | public static final byte[] PREAMBLE = "onosiscool".getBytes(); |
| 16 | |
| 17 | private final SerializationService serializationService; |
| 18 | |
| 19 | public MessageEncoder(SerializationService serializationService) { |
| 20 | this.serializationService = serializationService; |
| 21 | } |
| 22 | |
| 23 | @Override |
| 24 | protected void encode(ChannelHandlerContext context, InternalMessage message, |
| 25 | ByteBuf out) throws Exception { |
| 26 | |
| 27 | // write preamble |
| 28 | out.writeBytes(PREAMBLE); |
| 29 | |
| 30 | // write id |
| 31 | out.writeLong(message.id()); |
| 32 | |
| 33 | // write type length |
| 34 | out.writeInt(message.type().length()); |
| 35 | |
| 36 | // write type |
| 37 | out.writeBytes(message.type().getBytes()); |
| 38 | |
| 39 | // write sender host name size |
| 40 | out.writeInt(message.sender().host().length()); |
| 41 | |
| 42 | // write sender host name. |
| 43 | out.writeBytes(message.sender().host().getBytes()); |
| 44 | |
| 45 | // write port |
| 46 | out.writeInt(message.sender().port()); |
| 47 | |
| 48 | try { |
| 49 | serializationService.encode(message.payload()); |
| 50 | } catch (Exception e) { |
| 51 | e.printStackTrace(); |
| 52 | } |
| 53 | |
| 54 | byte[] payload = serializationService.encode(message.payload()); |
| 55 | |
| 56 | // write payload length. |
| 57 | out.writeInt(payload.length); |
| 58 | |
| 59 | // write payload bytes |
| 60 | out.writeBytes(payload); |
| 61 | } |
| 62 | } |