aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/fil/libre/repwifiapp/helpers/ShellCommand.java
blob: e2004a7bc9199f476b52f0b6e29e47ca8d779e23 (plain)
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
78
79
80
81
82
83
84
85
package fil.libre.repwifiapp.helpers;

import java.io.IOException;
import java.io.InputStream;

public class ShellCommand {
	
	private String _cmdOut = "";
	private String _cmdTxt = "";

	public ShellCommand(String commandText){
		this._cmdTxt = commandText;
	}
	
	
	public int execute() throws Exception{

		if ( this._cmdTxt == null ){
			return -9;
		}
		
		Utils.logDebug("EXEC: " + this._cmdTxt);
		
		Process cmd = Runtime.getRuntime().exec(this._cmdTxt);

		InputStream os = cmd.getInputStream();
		InputStream es = cmd.getErrorStream();
		
		StringBuilder sb = new StringBuilder();

		sb.append(getStringFromStream(es));
		sb.append(getStringFromStream(os));

		int res = cmd.waitFor();

		//re-read the output, in case it was empty when first tried
		sb.append(getStringFromStream(es));
		sb.append(getStringFromStream(os));
			
		this._cmdOut = sb.toString();
		
		Utils.logDebug("EXITCODE: " + res);
		Utils.logDebug("OUT: " + getOutput());
		
		return res;
		
	}

	private String getStringFromStream(InputStream s) throws IOException{
		
		StringBuilder sb = new StringBuilder();
		while ( (s.available() > 0) ) {
			int b = s.read();
			if (b>=0){
				sb.append((char)b);
			}else{
				break;
			}
		}
		
		return sb.toString();
		
	}
	
	
	public String getOutput(){
		
		return this._cmdOut;
		
		/*String[] lastOut = Utils.readFileLines(Commons.getTempOutFile());
		if (lastOut == null){
			return this._cmdOut;
		}
		
		String fout = "";
		
		for (String s : lastOut){
			fout += s + "\n";
		}
		
		return fout;*/
		
	}

}