48d7e475ef01044b5cffc633e034c35bd6a8230d
[openflowjava.git] / simple-client / src / main / java / org / opendaylight / openflowjava / protocol / impl / clients / SimpleClientFramer.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.clients;
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.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20
21 /**
22  * Class for decoding incoming messages into message frames.
23  *
24  * @author michal.polkorab
25  */
26 public class SimpleClientFramer 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(SimpleClientFramer.class);
32
33     /**
34      * Constructor of class.
35      */
36     public SimpleClientFramer() {
37         LOGGER.debug("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         if (bb.readableBytes() < LENGTH_OF_HEADER) {
49             LOGGER.debug("skipping bb - too few data for header: " + bb.readableBytes());
50             return;
51         }
52
53         int length = bb.getUnsignedShort(LENGTH_INDEX_IN_HEADER);
54         if (bb.readableBytes() < length) {
55             LOGGER.debug("skipping bb - too few data for msg: " +
56                     bb.readableBytes() + " < " + length);
57             return;
58         }
59         LOGGER.info("OF Protocol message received, type:{}", bb.getByte(1));
60
61         ByteBuf messageBuffer = bb.slice(bb.readerIndex(), length);
62         list.add(messageBuffer);
63         messageBuffer.retain();
64         bb.skipBytes(length);
65     }
66
67 }