1 /***
2 *
3 */
4 package de.cohesion.bssh.impl;
5
6 import java.io.IOException;
7
8 import ch.ethz.ssh2.Connection;
9 import de.cohesion.bssh.Command;
10 import de.cohesion.bssh.Member;
11 import de.cohesion.bssh.Result;
12 import de.cohesion.bssh.impl.util.Cache;
13
14 /***
15 * @author schulzs
16 */
17 public abstract class SSHCommand implements Command<Result> {
18
19 private final Cache<Member, Connection> ccache;
20
21 public SSHCommand(final Cache<Member, Connection> ccache) {
22 this.ccache = ccache;
23 }
24
25 public Result execute(final Member m) throws Exception {
26
27 LocalPortForwardCommand fwdCmd = null;
28 if (m.getGateway() != null) {
29 fwdCmd = new LocalPortForwardCommand(m, Ports.getPort(), ccache);
30 fwdCmd.execute(m.getGateway());
31 }
32
33 Connection c = null;
34 try {
35 c = ccache.get(fwdCmd == null ? m : new GatewayMemberImpl(fwdCmd
36 .getProxy(), m));
37 } catch (InstantiationException ie) {
38 throw (Exception) ie.getCause();
39 }
40
41 try {
42 return perform(m, c);
43 } finally {
44 if (fwdCmd != null) {
45 fwdCmd.release();
46 }
47 }
48
49 }
50
51 protected abstract Result perform(final Member m, final Connection c)
52 throws IOException;
53
54 }