Merge "Bug 1362: New AsyncWriteTransaction#submit method"
[controller.git] / opendaylight / netconf / netconf-netty-util / src / main / java / org / opendaylight / controller / netconf / nettyutil / handler / ssh / client / SshClient.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
9 package org.opendaylight.controller.netconf.nettyutil.handler.ssh.client;
10
11 import ch.ethz.ssh2.Connection;
12 import ch.ethz.ssh2.Session;
13 import java.io.IOException;
14 import java.util.HashMap;
15 import java.util.Map;
16 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
17 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.virtualsocket.VirtualSocket;
18
19 /**
20  * Wrapper class around GANYMED SSH java library.
21  */
22 class SshClient {
23     private final VirtualSocket socket;
24     private final Map<Integer, SshSession> openSessions = new HashMap<>();
25     private final AuthenticationHandler authenticationHandler;
26     private Connection connection;
27
28     public SshClient(VirtualSocket socket, AuthenticationHandler authenticationHandler) throws IOException {
29         this.socket = socket;
30         this.authenticationHandler = authenticationHandler;
31     }
32
33     public SshSession openSession() throws IOException {
34         if (connection == null) {
35             connect();
36         }
37
38         Session session = connection.openSession();
39         SshSession sshSession = new SshSession(session);
40         openSessions.put(openSessions.size(), sshSession);
41
42         return sshSession;
43     }
44
45     private void connect() throws IOException {
46         connection = new Connection(socket);
47
48         connection.connect();
49         authenticationHandler.authenticate(connection);
50     }
51
52
53     public void close() {
54         for (SshSession session : openSessions.values()){
55             session.close();
56         }
57
58         openSessions.clear();
59
60         if (connection != null) {
61             connection.close();
62         }
63     }
64
65     @Override
66     public String toString() {
67         return "SshClient{" +
68                 "socket=" + socket +
69                 '}';
70     }
71 }