Ordered message execution ensured
[openflowjava.git] / simple-client / src / main / java / org / opendaylight / openflowjava / protocol / impl / clients / SimpleClientHandler.java
1 /* Copyright (C)2013 Pantheon Technologies, s.r.o. All rights reserved. */\r
2 \r
3 package org.opendaylight.openflowjava.protocol.impl.clients;\r
4 \r
5 import io.netty.buffer.ByteBuf;\r
6 import io.netty.channel.ChannelHandlerContext;\r
7 import io.netty.channel.ChannelInboundHandlerAdapter;\r
8 \r
9 import org.opendaylight.openflowjava.protocol.impl.util.ByteBufUtils;\r
10 import org.slf4j.Logger;\r
11 import org.slf4j.LoggerFactory;\r
12 \r
13 import com.google.common.util.concurrent.SettableFuture;\r
14 \r
15 /**\r
16  *\r
17  * @author michal.polkorab\r
18  */\r
19 public class SimpleClientHandler extends ChannelInboundHandlerAdapter {\r
20 \r
21     protected static final Logger LOGGER = LoggerFactory.getLogger(SimpleClientHandler.class);\r
22     private static final int OFP_HEADER_LENGTH = 8;\r
23     private SettableFuture<Boolean> isOnlineFuture;\r
24     protected ScenarioHandler scenarioHandler;\r
25 \r
26     /**\r
27      * @param isOnlineFuture future notifier of connected channel\r
28      * @param scenarioHandler handler of scenario events\r
29      */\r
30     public SimpleClientHandler(SettableFuture<Boolean> isOnlineFuture, ScenarioHandler scenarioHandler) {\r
31         this.isOnlineFuture = isOnlineFuture;\r
32         this.scenarioHandler = scenarioHandler;\r
33     }\r
34 \r
35     @Override\r
36     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {\r
37         LOGGER.info("SimpleClientHandler - start of read");\r
38         ByteBuf bb = (ByteBuf) msg;\r
39         if (LOGGER.isDebugEnabled()) {\r
40             LOGGER.debug("<< " + ByteBufUtils.byteBufToHexString(bb));\r
41         }\r
42         \r
43         if (bb.readableBytes() < OFP_HEADER_LENGTH) {\r
44             LOGGER.debug("too few bytes received: "+bb.readableBytes()+" - wait for next data portion");\r
45             return;\r
46         }\r
47         int msgSize = bb.getUnsignedShort(2);\r
48         byte[] message = new byte[msgSize];\r
49         bb.readBytes(message);\r
50         scenarioHandler.addOfMsg(message);\r
51         LOGGER.info("end of read");\r
52     }\r
53 \r
54     @Override\r
55     public void channelActive(ChannelHandlerContext ctx) throws Exception {\r
56         LOGGER.info("Client is active");\r
57         if (isOnlineFuture != null) {\r
58             isOnlineFuture.set(true);\r
59             isOnlineFuture = null;\r
60         }\r
61         scenarioHandler.setCtx(ctx);\r
62         scenarioHandler.start();\r
63         \r
64     }\r
65 \r
66     /**\r
67      * @param scenarioHandler handler of scenario events\r
68      */\r
69     public void setScenario(ScenarioHandler scenarioHandler) {\r
70         this.scenarioHandler = scenarioHandler;\r
71     }\r
72 \r
73 }\r