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