/
SessionManager.java
77 lines (63 loc) · 1.98 KB
/
SessionManager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.pastdev.jsch;
import java.io.Closeable;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
/**
* Provides a convenience wrapper to sessions that maintains the session
* connection for you. Every time you obtain your session through a call to
* {@link #getSession()} the current session will have its connection verified,
* and will reconnect if necessary.
*/
public class SessionManager implements Closeable {
private static final Logger logger = LoggerFactory.getLogger( SessionManager.class );
private final SessionFactory sessionFactory;
private Session session;
/**
* Creates a SessionManager for the supplied <code>sessionFactory</code>.
*
* @param sessionFactory
* The session factory
*/
public SessionManager( SessionFactory sessionFactory ) {
this.sessionFactory = sessionFactory;
}
@Override
public void close() throws IOException {
if ( session != null && session.isConnected() ) {
session.disconnect();
}
session = null;
}
/**
* Returns a connected session.
*
* @return A connected session
*
* @throws JSchException
* If unable to connect the session
*/
public Session getSession() throws JSchException {
if ( session == null || !session.isConnected() ) {
logger.debug( "getting new session from factory session" );
session = sessionFactory.newSession();
logger.debug( "connecting session" );
session.connect();
}
return session;
}
/**
* Returns the session factory used by this manager.
*
* @return The session factory
*/
public SessionFactory getSessionFactory() {
return sessionFactory;
}
@Override
public String toString() {
return sessionFactory.toString();
}
}