52d2cbf201255e4a8819d95bf88819a03617fe31
[netconf.git] / protocol / netconf-client / src / main / java / org / opendaylight / netconf / client / ClientTransportChannelListener.java
1 /*
2  * Copyright (c) 2024 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.netconf.client;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.util.concurrent.ListenableFuture;
13 import com.google.common.util.concurrent.SettableFuture;
14 import io.netty.util.concurrent.Future;
15 import io.netty.util.concurrent.FutureListener;
16 import org.eclipse.jdt.annotation.NonNull;
17 import org.opendaylight.netconf.transport.api.TransportChannel;
18 import org.opendaylight.netconf.transport.api.TransportChannelListener;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
21
22 final class ClientTransportChannelListener implements TransportChannelListener, FutureListener<NetconfClientSession> {
23     private static final Logger LOG = LoggerFactory.getLogger(ClientTransportChannelListener.class);
24
25     private final @NonNull SettableFuture<NetconfClientSession> sessionFuture = SettableFuture.create();
26     private final ClientChannelInitializer initializer;
27
28     ClientTransportChannelListener(final ClientChannelInitializer initializer) {
29         this.initializer = requireNonNull(initializer);
30     }
31
32     @NonNull ListenableFuture<NetconfClientSession> sessionFuture() {
33         return sessionFuture;
34     }
35
36     @Override
37     public void onTransportChannelEstablished(final TransportChannel channel) {
38         LOG.debug("Initializing established transport {}", channel);
39         final var nettyChannel = channel.channel();
40         final var promise = nettyChannel.eventLoop().<NetconfClientSession>newPromise();
41         initializer.initialize(nettyChannel, promise);
42         promise.addListener(this);
43     }
44
45     @Override
46     public void onTransportChannelFailed(final Throwable cause) {
47         sessionFuture.setException(cause);
48     }
49
50     @Override
51     public void operationComplete(final Future<NetconfClientSession> future) throws Exception {
52         final var cause = future.cause();
53         if (cause != null) {
54             sessionFuture.setException(cause);
55         } else {
56             sessionFuture.set(future.getNow());
57         }
58     }
59 }