aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/fil/libre/repwifiapp/helpers/ShellCommand.java
blob: fbeb7192c0dfc9fc886b3816e81f9d817e51bbfe (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
package fil.libre.repwifiapp.helpers;

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

public class ShellCommand {

    protected String _cmdOut = "";
    protected 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;

    }

    protected 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;
         */

    }

}