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