1 package de.hacksaar.andtuer;
3 import android.os.AsyncTask;
4 import android.util.Log;
5 import de.hacksaar.javatuer.InteractiveLogin;
6 import de.hacksaar.javatuer.TyshellClient;
8 import java.io.BufferedReader;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.InputStreamReader;
12 import java.util.LinkedList;
13 import java.util.Queue;
15 class AsyncTyshell extends AsyncTask<Void, Void, Void> {
17 private static final String TAG = "AsyncTyshell";
18 private final String hostname;
19 private final int port;
20 private final String username;
21 private final String keyFile;
22 private final Prompter prompter;
23 private final Queue<String> messages = new LinkedList<>();
24 private final Object promptWait = new Object();
25 private String promptResultString;
26 private boolean promptResultBoolean;
27 private boolean disconnect = true;
29 AsyncTyshell(String hostname, int port, String username, String keyFile, Prompter prompter) {
30 this.hostname = hostname;
32 this.username = username;
33 this.keyFile = keyFile;
34 this.prompter = prompter;
37 private void awaitPrompt() {
38 synchronized (promptWait) {
41 } catch (InterruptedException e) {
47 public void disconnect() {
49 synchronized (promptWait) {
52 synchronized (messages) {
57 private void readUnlimited(InputStreamReader inputStreamReader) {
58 final BufferedReader reader = new BufferedReader(inputStreamReader);
59 new Thread(new Runnable() {
64 while((line = reader.readLine()) != null) {
65 prompter.sendMessage(line);
67 } catch (Exception e) {
68 Log.w("end read unlimited!", e);
75 protected Void doInBackground(Void... voids) {
76 TyshellClient client = new TyshellClient(hostname, port, new AndroidLogging());
77 client.connect(username, keyFile, new AsyncInteractiveLogin());
78 readUnlimited(client.getInputStream());
81 synchronized (messages) {
82 while (disconnect && (msg = messages.poll()) == null) {
85 } catch (InterruptedException e) {
93 client.sendCommand(msg);
99 public void promptResult(boolean result) {
100 promptResultBoolean = result;
101 synchronized (promptWait) {
106 public void promptResult(String result) {
107 promptResultString = result;
108 synchronized (promptWait) {
113 public void sendCommand(String string) {
114 synchronized (messages) {
115 messages.add(string);
120 public interface Prompter {
121 void promptBoolean(String message);
123 void promptString(String message);
125 void sendMessage(String message);
128 private class AsyncInteractiveLogin extends InteractiveLogin {
130 AsyncInteractiveLogin() {
134 public String promptKeyPassphrase(String question) {
135 prompter.promptString(question);
137 return promptResultString;
141 public String promptUserPassword(String question) {
142 prompter.promptString(question);
144 return promptResultString;
148 public boolean promptYesNo(String question) {
149 prompter.promptBoolean(question);
151 return promptResultBoolean;
155 public void showMessage(String s) {
156 prompter.sendMessage(s);