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