Add documentation for Netty Replication utility
[mdsal.git] / replicate / mdsal-replicate-netty / src / main / java / org / opendaylight / mdsal / replicate / netty / KeepaliveHandler.java
1 /*
2  * Copyright (c) 2020 PANTHEON.tech, 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 package org.opendaylight.mdsal.replicate.netty;
9
10 import static java.util.Objects.requireNonNull;
11
12 import io.netty.channel.ChannelDuplexHandler;
13 import io.netty.channel.ChannelHandlerContext;
14 import io.netty.handler.timeout.IdleStateEvent;
15 import org.slf4j.Logger;
16 import org.slf4j.LoggerFactory;
17
18 class KeepaliveHandler extends ChannelDuplexHandler {
19     private static final Logger LOG = LoggerFactory.getLogger(KeepaliveHandler.class);
20
21     private final Runnable reconnect;
22
23     KeepaliveHandler(final Runnable reconnectCallback) {
24         this.reconnect = requireNonNull(reconnectCallback, "Reconnect callback should not be null");
25     }
26
27     @Override
28     public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) {
29         if (evt instanceof IdleStateEvent) {
30             ctx.writeAndFlush(Constants.PING);
31         } else {
32             ctx.fireUserEventTriggered(evt);
33         }
34     }
35
36     @Override
37     public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
38         LOG.warn("There was an exception on the channel. Attempting to reconnect.", cause);
39         reconnect.run();
40     }
41 }