1 /***
2 *
3 */
4 package de.cohesion.bssh.impl;
5
6 import java.io.IOException;
7 import java.io.InputStreamReader;
8 import java.lang.Thread.State;
9
10 import ch.ethz.ssh2.Connection;
11 import ch.ethz.ssh2.Session;
12 import ch.ethz.ssh2.StreamGobbler;
13 import de.cohesion.bssh.Member;
14 import de.cohesion.bssh.Result;
15 import de.cohesion.bssh.impl.lang.NotifyingThread;
16 import de.cohesion.bssh.impl.lang.ThreadStateListener;
17 import de.cohesion.bssh.impl.util.Cache;
18
19 /***
20 * @author schulzs
21 *
22 */
23 public class ExecuteSSHCommand extends SSHCommand {
24
25 private final String cmd;
26
27 public ExecuteSSHCommand(final String cmd,
28 final Cache<Member, Connection> ccache) {
29 super(ccache);
30 this.cmd = cmd;
31 }
32
33 @Override
34 protected Result perform(final Member m, final Connection c)
35 throws IOException {
36 final Session s = c.openSession();
37
38 Thread t = Thread.currentThread();
39 if (t instanceof NotifyingThread) {
40 ((NotifyingThread) t)
41 .addThreadStateListener(new ThreadStateListener() {
42 public void stateChanged(Thread t, State state) {
43 s.close();
44 ((NotifyingThread) t)
45 .removeThreadStateListener(this);
46 }
47 });
48 }
49 try {
50 s.execCommand(Substituter.substitute(cmd, m));
51 return new ResultImpl(m, this, new InputStreamReader(
52 new StreamGobbler(s.getStdout())), new InputStreamReader(
53 new StreamGobbler(s.getStderr())));
54 } finally {
55 s.close();
56 }
57
58 }
59
60 @Override
61 public String toString() {
62 return cmd;
63 }
64
65 }