I'am running into trouble implementing a proper code. I have several objects that use a ssh tunnel and I don't want to close and open a new connection each time. So I implemented singleton pattern to get the instance of my connection and I pass it to each object. After readings It seems that singleton pattern aren't a proper way to code, but I don't see any other way recoding my classes.
Instance class :
public class ServerConnection {
String ip = "localhost";
String user = "tom1";
String pass = "1";
int port = 22;
private static Session session;
private ServerConnection() throws JSchException {
try {
JSch jsch = new JSch();
session = jsch.getSession(user, ip, port);
session.setPassword(pass);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
}catch(Exception e){
System.out.println(e);
}
}
public static Session getInstance() throws JSchException {
if (session == null) {
System.out.println("Creation de la connection");
new ServerConnection();
}else{
System.out.println("La connection existe deja");
}
return session;
}
}
My objects :
public class EchoText implements InterfaceScript
{
/**
*Message to display with the Echo.
*/
String message;
/**
* Params of the test.
*/
String params;
/**
*Result of the test.
*/
String result="Failed";
/**
*Constructor of EchoText.
*/
public void EchoText (){
}
@Override
public String run(String params) {
this.params=params;
treatParameters();
Session session;
try {
//Verify if an instance of the server is running.
session = ServerConnection.getInstance();
//Open a channel to send informations
ChannelExec channel = (ChannelExec) session.openChannel("exec");
BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream()));
//Set the command to send
channel.setCommand("cmd /c echo "+this.message);
channel.connect();
// Read the outptut
String msg = null;
while ((msg = in.readLine()) != null) {
System.out.println(msg);
}
channel.disconnect();
this.result();
return this.result;
} catch (JSchException | IOException e)
{
System.out.println(e);
return this.result;
}
}
}
Aucun commentaire:
Enregistrer un commentaire