BUG-58: refactor to take advantage of netty
[bgpcep.git] / framework / src / main / java / org / opendaylight / protocol / framework / AbstractProtocolSession.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. 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 package org.opendaylight.protocol.framework;
9
10 import io.netty.channel.ChannelHandlerContext;
11 import io.netty.channel.SimpleChannelInboundHandler;
12
13 import org.slf4j.Logger;
14 import org.slf4j.LoggerFactory;
15
16 public abstract class AbstractProtocolSession<M extends ProtocolMessage> extends SimpleChannelInboundHandler<Object> implements ProtocolSession<M> {
17         private final static Logger logger = LoggerFactory.getLogger(AbstractProtocolSession.class);
18
19         /**
20          * Handles incoming message (parsing, reacting if necessary).
21          * 
22          * @param msg incoming message
23          */
24         protected abstract void handleMessage(final M msg);
25
26         /**
27          * Called when reached the end of input stream while reading.
28          */
29         protected abstract void endOfInput();
30
31         /**
32          * Called when the session is added to the pipeline.
33          */
34         protected abstract void sessionUp();
35
36         @Override
37         final public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
38                 logger.debug("Channel inactive.");
39                 endOfInput();
40         }
41
42         @Override
43         final protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) throws Exception {
44                 logger.debug("Message was received: {}", msg);
45                 handleMessage((M)msg);
46         }
47
48         @Override
49         final public void handlerAdded(final ChannelHandlerContext ctx) {
50                 sessionUp();
51         }
52 }