summaryrefslogtreecommitdiff
path: root/src/main/Main.java
blob: 4b02223c9bbdf3a2904fcdc62efe5ceac3772297 (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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package main;

import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
import mining.TwitterApi;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Class for manually testing the Twitter API.
 */
public class Main {

    /**
     * Command and parameters without options.
     */
    private Command command;
    private String[] params;
    /**
     * Whether to use the Bearer method or OAuth-signed requests.
     */
    private boolean useBearer = true;
    private boolean rawOutput = false;
    private TwitterApi api_cached;

    public Main(String[] args) throws IOException {
        // parse options and command and return the parameters.
        parseGlobalOptions(args);
    }

    private TwitterApi getApi() throws IOException {
        if (api_cached == null) {
            if (useBearer) {
                api_cached = TwitterApi.getAppOnly();
            } else {
                api_cached = TwitterApi.getOAuth(new ConsolePinSupplier());
            }
        }
        return api_cached;
    }

    private String getParam(int index, String name) {
        if (index >= params.length) {
            System.err.println("Missing parameter: " + name);
            System.exit(1);
        }
        return params[index];
    }

    private void parseGlobalOptions(String[] args) {
        int firstParam = -1;
        /* parse global options */
        for (int i = 0; i < args.length; i++) {
            if ("--oauth".equals(args[i])) {
                useBearer = false;
            } else if ("--raw".equals(args[i])) {
                rawOutput = true;
            } else if (args[i].startsWith("-")) {
                throw new IllegalArgumentException("Invalid option: " + args[i]);
            } else {
                /* not an option, must be a command */
                if (args[i].startsWith("?")) {
                    command = Command.help;
                } else {
                    command = Command.fromString(args[i]);
                }
                firstParam = i + 1;
                break;
            }
        }
        if (firstParam == -1) {
            throw new IllegalArgumentException("Missing command, use \"help\"");
        }
        params = Arrays.copyOfRange(args, firstParam, args.length);
    }

    public static void main(String[] args) throws IOException {
        try {
            Main main = new Main(args);
            main.execute();
        } catch (IllegalArgumentException ex) {
            System.err.println(ex.getMessage());
            System.exit(1);
        }
    }

    enum Command {

        user,
        tweet,
        searchtweets,
        shell,
        hack,
        help;

        public static Command fromString(String command) {
            for (Command cmd : values()) {
                if (cmd.name().equals(command)) {
                    return cmd;
                }
            }
            throw new IllegalArgumentException("Unrecognized command ");
        }
    };

    private final static String[] HELP = {
        "Global options:",
        "   --oauth    Use OAuth (PIN) instead of Bearer tokens",
        "   --raw      Do not beautify JSON output",
        "",
        "Available commands:"
    };

    private void searchTweets(String q) throws IOException, JSONException {
        TwitterApi.Builder req = getApi().build("search/tweets");
        req.param("q", q);
        req.param("count", "100"); // max number of tweets, cannot be higher
        req.param("lang", "en");
        JSONObject resp = req.request();
        JSONArray statuses = resp.getJSONArray("statuses");
        for (int i = 0; i < statuses.length(); i++) {
            JSONObject tweet = statuses.getJSONObject(i);
            System.out.println(tweet);
        }
    }

    public void execute() throws IOException {
        TwitterApi.Builder req = null;
        /* build a request for commands */
        switch (command) {
            case user:
                req = getApi().build("users/show");
                req.param("screen_name", getParam(0, "screen name"));
                break;
            case tweet:
                req = getApi().build("statuses/show");
                req.param("id", getParam(0, "numerical ID of tweet"));
                break;
            case searchtweets:
                try {
                    searchTweets(getParam(0, "search query"));
                } catch (JSONException ex) {
                    throw new IOException(ex);
                }
                /* no req, will be handled by search */
                break;
            case hack:
                String name = getParam(0, "resource name");
                req = getApi().build(name);
                if (name.startsWith("-")) {
                    throw new IllegalArgumentException("Resource expected, got option");
                }
                for (int i = 1; i < params.length; i++) {
                    String keyval[] = params[i].split("=", 2);
                    if (keyval.length == 2) {
                        req.param(keyval[0], keyval[1]);
                    } else {
                        req.param(keyval[0], "");
                    }
                }
                break;
            case help:
                for (String line : HELP) {
                    System.out.println(line);
                }
                for (Command cmd : Command.values()) {
                    System.out.println("  " + cmd.name());
                }
                break;
            case shell:
                TweetShell shell = new TweetShell();
                // pass any remaining parameters to the shell
                if (params.length > 0) {
                    for (String cmd : params) {
                        shell.execute(cmd);
                    }
                }
                shell.process_forever();
                break;
            default:
                throw new AssertionError(command.name());
        }
        if (req != null) {
            System.err.println("Executing: " + req.toString());
            JSONObject result = req.request();
            try {
                if (rawOutput) {
                    System.out.println(result);
                } else {
                    System.out.println(result.toString(4));
                }
            } catch (JSONException ex) {
                /* cannot happen */
                System.err.println("Warning: got JSON exception: " + ex);
                System.out.println(result);
            }
        }
    }

    private static class ConsolePinSupplier implements TwitterApi.PinSupplier {

        private final Scanner scanner;

        public ConsolePinSupplier() {
            scanner = new Scanner(System.in);
        }

        @Override
        public String requestPin(String url) throws IOException {
            System.out.println(url);
            System.err.println("Please open the above URL and enter PIN:");
            return scanner.nextLine();
        }
    }
}