2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.protocol.framework;
10 import io.netty.channel.Channel;
11 import io.netty.channel.ChannelHandlerContext;
12 import io.netty.channel.ChannelInboundHandlerAdapter;
13 import io.netty.util.concurrent.Promise;
15 import org.slf4j.Logger;
16 import org.slf4j.LoggerFactory;
18 import com.google.common.base.Preconditions;
21 * Abstract base class for session negotiators. It implements the basic
22 * substrate to implement SessionNegotiator API specification, with subclasses
23 * needing to provide only
25 * @param <M> Protocol message type
26 * @param <S> Protocol session type, has to extend ProtocolSession<M>
28 public abstract class AbstractSessionNegotiator<M, S extends AbstractProtocolSession<?>> extends ChannelInboundHandlerAdapter implements SessionNegotiator<S> {
29 private final Logger logger = LoggerFactory.getLogger(AbstractSessionNegotiator.class);
30 private final Promise<S> promise;
31 protected final Channel channel;
33 public AbstractSessionNegotiator(final Promise<S> promise, final Channel channel) {
34 this.promise = Preconditions.checkNotNull(promise);
35 this.channel = Preconditions.checkNotNull(channel);
38 protected abstract void startNegotiation() throws Exception;
39 protected abstract void handleMessage(M msg) throws Exception;
41 protected final void negotiationSuccessful(final S session) {
42 logger.debug("Negotiation on channel {} successful with session {}", channel, session);
43 channel.pipeline().replace(this, "session", session);
44 promise.setSuccess(session);
47 protected final void negotiationFailed(final Throwable cause) {
48 logger.debug("Negotiation on channel {} failed", channel, cause);
50 promise.setFailure(cause);
54 public final void channelActive(final ChannelHandlerContext ctx) {
55 logger.debug("Starting session negotiation on channel {}", channel);
58 } catch (Exception e) {
59 logger.warn("Unexpected negotiation failure", e);
65 public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
66 logger.debug("Negotiation read invoked on channel {}", channel);
68 handleMessage((M)msg);
69 } catch (Exception e) {
70 logger.debug("Unexpected exception during negotiation", e);