Merge "Remove redundant exception declarations"
[openflowplugin.git] / samples / simple-client / src / main / java / org / opendaylight / openflowjava / protocol / impl / clients / UdpSimpleClientFramer.java
1 /*
2  * Copyright (c) 2014 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.channel.socket.DatagramPacket;
15 import io.netty.handler.codec.MessageToMessageDecoder;
16 import java.util.List;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
19
20 /**
21  * Class for decoding incoming udp messages into message frames.
22  *
23  * @author michal.polkorab
24  */
25 public class UdpSimpleClientFramer extends MessageToMessageDecoder<DatagramPacket> {
26
27     /** Length of OpenFlow 1.3 header .*/
28     public static final byte LENGTH_OF_HEADER = 8;
29     private static final byte LENGTH_INDEX_IN_HEADER = 2;
30     private static final Logger LOG = LoggerFactory.getLogger(UdpSimpleClientFramer.class);
31
32     /**
33      * Constructor of class.
34      */
35     public UdpSimpleClientFramer() {
36         LOG.trace("Creating OFFrameDecoder");
37     }
38
39     @Override
40     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
41         LOG.warn("Unexpected exception from downstream.", cause);
42         ctx.close();
43     }
44
45     @Override
46     protected void decode(ChannelHandlerContext chc, DatagramPacket msg, List<Object> list) {
47         ByteBuf bb = msg.content();
48         if (bb.readableBytes() < LENGTH_OF_HEADER) {
49             LOG.debug("skipping bb - too few data for header: {}", bb.readableBytes());
50             return;
51         }
52
53         int length = bb.getUnsignedShort(bb.readerIndex() + LENGTH_INDEX_IN_HEADER);
54         if (bb.readableBytes() < length) {
55             LOG.debug("skipping bb - too few data for msg: {} < {}", bb.readableBytes(), length);
56             return;
57         }
58         LOG.debug("OF Protocol message received, type:{}", bb.getByte(bb.readerIndex() + 1));
59
60         ByteBuf messageBuffer = bb.slice(bb.readerIndex(), length);
61         list.add(messageBuffer);
62         messageBuffer.retain();
63         bb.skipBytes(length);
64     }
65 }