tom | 1d416c5 | 2014-09-29 20:55:24 -0700 | [diff] [blame^] | 1 | package org.onlab.onos.store.cluster.messaging.impl; |
| 2 | |
| 3 | import org.onlab.onos.store.cluster.messaging.ClusterMessage; |
| 4 | import org.onlab.onos.store.cluster.messaging.MessageSubject; |
| 5 | import org.onlab.onos.store.cluster.messaging.SerializationService; |
| 6 | |
| 7 | import java.nio.ByteBuffer; |
| 8 | |
| 9 | import static com.google.common.base.Preconditions.checkState; |
| 10 | |
| 11 | /** |
| 12 | * Factory for parsing messages sent between cluster members. |
| 13 | */ |
| 14 | public class MessageSerializer implements SerializationService { |
| 15 | |
| 16 | private static final int METADATA_LENGTH = 16; // 8 + 4 + 4 |
| 17 | private static final int LENGTH_OFFSET = 12; |
| 18 | |
| 19 | private static final long MARKER = 0xfeedcafebeaddeadL; |
| 20 | |
| 21 | @Override |
| 22 | public ClusterMessage decode(ByteBuffer buffer) { |
| 23 | try { |
| 24 | // Do we have enough bytes to read the header? If not, bail. |
| 25 | if (buffer.remaining() < METADATA_LENGTH) { |
| 26 | return null; |
| 27 | } |
| 28 | |
| 29 | // Peek at the length and if we have enough to read the entire message |
| 30 | // go ahead, otherwise bail. |
| 31 | int length = buffer.getInt(buffer.position() + LENGTH_OFFSET); |
| 32 | if (buffer.remaining() < length) { |
| 33 | return null; |
| 34 | } |
| 35 | |
| 36 | // At this point, we have enough data to read a complete message. |
| 37 | long marker = buffer.getLong(); |
| 38 | checkState(marker == MARKER, "Incorrect message marker"); |
| 39 | |
| 40 | int subjectOrdinal = buffer.getInt(); |
| 41 | MessageSubject subject = MessageSubject.values()[subjectOrdinal]; |
| 42 | length = buffer.getInt(); |
| 43 | |
| 44 | // TODO: sanity checking for length |
| 45 | byte[] data = new byte[length - METADATA_LENGTH]; |
| 46 | buffer.get(data); |
| 47 | |
| 48 | // TODO: add deserialization hook here; for now this hack |
| 49 | return null; // actually deserialize |
| 50 | |
| 51 | } catch (Exception e) { |
| 52 | // TODO: recover from exceptions by forwarding stream to next marker |
| 53 | e.printStackTrace(); |
| 54 | } |
| 55 | return null; |
| 56 | } |
| 57 | |
| 58 | @Override |
| 59 | public void encode(ClusterMessage message, ByteBuffer buffer) { |
| 60 | try { |
| 61 | int i = 0; |
| 62 | // Type based lookup for proper encoder |
| 63 | } catch (Exception e) { |
| 64 | // TODO: recover from exceptions by forwarding stream to next marker |
| 65 | e.printStackTrace(); |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | } |