first draft implementation of openflowjava-core
[openflowjava.git] / openflow-protocol-impl / src / main / java / org / openflow / core / OFVersionDetector.java
1 /* Copyright (C)2013 Pantheon Technologies, s.r.o. All rights reserved. */
2 package org.openflow.core;
3
4 import io.netty.buffer.ByteBuf;
5 import io.netty.channel.ChannelHandlerContext;
6 import io.netty.handler.codec.ByteToMessageDecoder;
7 import java.util.List;
8 import org.slf4j.Logger;
9 import org.slf4j.LoggerFactory;
10 import org.openflow.core.TCPHandler.COMPONENT_NAMES;
11
12 /**
13  * Class that detects version of used OpenFlow Protocol and engages right OFCodec into
14  * pipeline.
15  *
16  * @author michal.polkorab
17  */
18 public class OFVersionDetector extends ByteToMessageDecoder {
19
20     private static final byte OF13_VERSION_ID = 0x04;
21     private static final Logger LOGGER = LoggerFactory.getLogger(OFVersionDetector.class);
22
23     /**
24      * Constructor of class.
25      */
26     public OFVersionDetector() {
27         LOGGER.info("Creating OFVersionDetector");
28     }
29
30     @Override
31     protected void decode(ChannelHandlerContext chc, ByteBuf bb, List<Object> list) throws Exception {
32         LOGGER.info("Decoding frame");
33
34         LOGGER.debug("RI: " + bb.readerIndex());
35         byte version = bb.readByte();
36
37         if (version == OF13_VERSION_ID) {
38             LOGGER.debug("detected version: " + version);
39             enableOF13Codec(chc);
40         } else {
41             LOGGER.warn("detected version: " + version + " - currently not supported");
42             return;
43         }
44
45         ByteBuf messageBuffer = bb.slice();
46         list.add(messageBuffer);
47         messageBuffer.retain();
48         bb.skipBytes(bb.readableBytes());
49     }
50
51     private void enableOF13Codec(ChannelHandlerContext chc) {
52         if (chc.pipeline().get(COMPONENT_NAMES.OF_CODEC.name()) == null) {
53             LOGGER.info("Engaging OF13Codec");
54             chc.pipeline().addLast(COMPONENT_NAMES.OF_CODEC.name(), new OF13Codec());
55         } else {
56             LOGGER.debug("OF13Codec already in pipeline");
57         }
58     }
59 }