//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//

package com.cloud.utils.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.security.GeneralSecurityException;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;

import org.apache.log4j.Logger;

public class NioClient extends NioConnection {
    private static final Logger s_logger = Logger.getLogger(NioClient.class);

    protected String _host;
    protected String _bindAddress;

    public NioClient(String name, String host, int port, int workers, HandlerFactory factory) {
        super(name, port, workers, factory);
        _host = host;
    }

    public void setBindAddress(String ipAddress) {
        _bindAddress = ipAddress;
    }

    @Override
    protected void init() throws IOException {
        _selector = Selector.open();
        Task task = null;

        try (SocketChannel sch = SocketChannel.open()) {
            sch.configureBlocking(true);
            s_logger.info("Connecting to " + _host + ":" + _port);

            if (_bindAddress != null) {
                s_logger.info("Binding outbound interface at " + _bindAddress);

                InetSocketAddress bindAddr = new InetSocketAddress(_bindAddress, 0);
                sch.socket().bind(bindAddr);
            }

            InetSocketAddress peerAddr = new InetSocketAddress(_host, _port);
            sch.connect(peerAddr);

            SSLEngine sslEngine = null;
            // Begin SSL handshake in BLOCKING mode
            sch.configureBlocking(true);

            SSLContext sslContext = Link.initSSLContext(true);
            sslEngine = sslContext.createSSLEngine(_host, _port);
            sslEngine.setUseClientMode(true);

            Link.doHandshake(sch, sslEngine, true);
            s_logger.info("SSL: Handshake done");
            s_logger.info("Connected to " + _host + ":" + _port);


            sch.configureBlocking(false);
            Link link = new Link(peerAddr, this);
            link.setSSLEngine(sslEngine);
            SelectionKey key = sch.register(_selector, SelectionKey.OP_READ);
            link.setKey(key);
            key.attach(link);
            // Notice we've already connected due to the handshake, so let's get the
            // remaining task done
            task = _factory.create(Task.Type.CONNECT, link, null);
        } catch (GeneralSecurityException e) {
            throw new IOException("Failed to initialise security", e);
        } finally {
            _selector.close();
        }
        _executor.execute(task);
    }

    @Override
    protected void registerLink(InetSocketAddress saddr, Link link) {
        // don't do anything.
    }

    @Override
    protected void unregisterLink(InetSocketAddress saddr) {
        // don't do anything.
    }
}

@@ -1343,16 +1343,63 @@
 Address;
+%0A    protected SocketChannel _clientConnection;
 %0A%0A    pu
@@ -1795,26 +1795,39 @@
 try 
-(SocketChannel sch
+%7B%0A            _clientConnection
  = S
@@ -1845,19 +1845,17 @@
 l.open()
-) %7B
+;
 %0A       
@@ -1851,35 +1851,49 @@
 ();%0A            
-sch
+_clientConnection
 .configureBlocki
@@ -2192,19 +2192,33 @@
         
-sch
+_clientConnection
 .socket(
@@ -2336,27 +2336,41 @@
             
-sch
+_clientConnection
 .connect(pee
@@ -2474,35 +2474,49 @@
 ode%0A            
-sch
+_clientConnection
 .configureBlocki
@@ -2731,19 +2731,33 @@
 ndshake(
-sch
+_clientConnection
 , sslEng
@@ -2885,17 +2885,16 @@
 port);%0A%0A
-%0A
         
@@ -2897,19 +2897,33 @@
         
-sch
+_clientConnection
 .configu
@@ -3068,11 +3068,25 @@
 y = 
-sch
+_clientConnection
 .reg
@@ -3415,24 +3415,55 @@
 eption e) %7B%0A
+            _selector.close();%0A
             
@@ -3535,15 +3535,29 @@
   %7D 
-finally
+catch (IOException e)
  %7B%0A 
@@ -3578,32 +3578,53 @@
 lector.close();%0A
+            throw e;%0A
         %7D%0A      
@@ -3617,16 +3617,17 @@
       %7D%0A
+%0A
         
@@ -3884,16 +3884,255 @@
 ything.%0A
-
     %7D%0A
+%0A    @Override%0A    public void cleanUp() throws IOException %7B%0A        super.cleanUp();%0A        if (_clientConnection != null) %7B%0A            _clientConnection.close();%0A        %7D%0A        s_logger.info(%22NioClient connection closed%22);%0A%0A    %7D%0A%0A
 %7D%0A

Fix a stupid bug i introduced