OPNFLWPLUG-1032: Neon-MRI: Bump odlparent, yangtools, mdsal
[openflowplugin.git] / samples / simple-client / src / main / java / org / opendaylight / openflowjava / protocol / impl / clients / SimpleClientHandler.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 com.google.common.util.concurrent.SettableFuture;
13 import io.netty.buffer.ByteBuf;
14 import io.netty.channel.ChannelHandlerContext;
15 import io.netty.channel.ChannelInboundHandlerAdapter;
16 import org.opendaylight.openflowjava.util.ByteBufUtils;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
19
20 /**
21  * Simple client handler.
22  *
23  * @author michal.polkorab
24  */
25 public class SimpleClientHandler extends ChannelInboundHandlerAdapter {
26
27     private static final Logger LOG = LoggerFactory.getLogger(SimpleClientHandler.class);
28     private static final int LENGTH_INDEX_IN_HEADER = 2;
29     private SettableFuture<Boolean> isOnlineFuture;
30     protected ScenarioHandler scenarioHandler;
31
32     /**
33      * Constructor.
34      *
35      * @param isOnlineFuture future notifier of connected channel
36      * @param scenarioHandler handler of scenario events
37      */
38     public SimpleClientHandler(SettableFuture<Boolean> isOnlineFuture, ScenarioHandler scenarioHandler) {
39         this.isOnlineFuture = isOnlineFuture;
40         this.scenarioHandler = scenarioHandler;
41     }
42
43     @Override
44     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
45         ByteBuf bb = (ByteBuf) msg;
46         if (LOG.isDebugEnabled()) {
47             LOG.debug("Message {}", ByteBufUtils.byteBufToHexString(bb));
48         }
49         int length = bb.getUnsignedShort(bb.readerIndex() + LENGTH_INDEX_IN_HEADER);
50         LOG.trace("SimpleClientHandler - start of read");
51         byte[] message = new byte[length];
52         bb.readBytes(message);
53         scenarioHandler.addOfMsg(message);
54         LOG.trace("end of read");
55     }
56
57     @Override
58     public void channelActive(ChannelHandlerContext ctx) throws Exception {
59         LOG.debug("Client is active");
60         if (isOnlineFuture != null) {
61             isOnlineFuture.set(true);
62             isOnlineFuture = null;
63         }
64         scenarioHandler.setCtx(ctx);
65         scenarioHandler.start();
66
67     }
68
69     /**
70      * Sets the ScenarioHandler.
71      *
72      * @param handler handler of scenario events
73      */
74     public void setScenario(ScenarioHandler handler) {
75         this.scenarioHandler = handler;
76     }
77
78 }