c342e9d56bcf74ec323348822db5b95d2b4c73aa
[openflowjava.git] / openflow-protocol-impl / src / main / java / org / opendaylight / openflowjava / protocol / impl / core / OFFrameDecoder.java
1 /* Copyright (C)2013 Pantheon Technologies, s.r.o. All rights reserved. */
2
3 package org.opendaylight.openflowjava.protocol.impl.core;
4
5 import io.netty.buffer.ByteBuf;
6 import io.netty.channel.ChannelHandlerContext;
7 import io.netty.handler.codec.ByteToMessageDecoder;
8
9 import java.util.List;
10
11 import org.opendaylight.openflowjava.protocol.impl.util.ByteBufUtils;
12 import org.slf4j.Logger;
13 import org.slf4j.LoggerFactory;
14
15 /**
16  * Decodes incoming messages into message frames.
17  * @author michal.polkorab
18  */
19 public class OFFrameDecoder extends ByteToMessageDecoder {
20
21     /** Length of OpenFlow 1.3 header */
22     public static final byte LENGTH_OF_HEADER = 8;
23     private static final byte LENGTH_INDEX_IN_HEADER = 2;
24     private static final Logger LOGGER = LoggerFactory.getLogger(OFFrameDecoder.class);
25
26     /**
27      * Constructor of class.
28      */
29     public OFFrameDecoder() {
30         LOGGER.debug("Creating OFFrameDecoder");
31     }
32
33     @Override
34     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
35         LOGGER.warn("Unexpected exception from downstream.", cause);
36         ctx.close();
37     }
38
39     @Override
40     protected void decode(ChannelHandlerContext chc, ByteBuf bb, List<Object> list) throws Exception {
41         int readableBytes = bb.readableBytes();
42         if (readableBytes < LENGTH_OF_HEADER) {
43             LOGGER.debug("skipping bb - too few data for header: " + readableBytes);
44             return;
45         }
46         
47         int length = bb.getUnsignedShort(bb.readerIndex() + LENGTH_INDEX_IN_HEADER);
48         LOGGER.debug("length of actual message: {}", length);
49         
50         if (readableBytes < length) {
51             if (LOGGER.isDebugEnabled()) {
52                 LOGGER.debug("skipping bb - too few data for msg: " +
53                         readableBytes + " < " + length);
54                 LOGGER.debug("bb: " + ByteBufUtils.byteBufToHexString(bb));
55                 LOGGER.debug("readableBytes: " + readableBytes);
56             }
57             
58             return;
59         } else {
60             LOGGER.debug("[enough bytes] readableBytes: " + readableBytes);
61         }
62         LOGGER.info("OF Protocol message received, type:{}", bb.getByte(bb.readerIndex() + 1));
63         
64         ByteBuf messageBuffer = bb.slice(bb.readerIndex(), length);
65         list.add(messageBuffer);
66         messageBuffer.retain();
67         bb.skipBytes(length);
68     }
69
70 }