blob: e45f7b77b61ad438ed949b6f335cfefa55e71b1e (
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
|
package mining;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import org.apache.commons.codec.Charsets;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import support.ConsumerKeySecret;
import utils.Configuration;
/**
* Accessors to the Twitter API.
*/
public class TwitterApi {
private static final String CFG_BEARER_TOKEN = "bearer-token";
private final Requester requester;
public TwitterApi(Requester requester) {
this.requester = requester;
}
/**
* Establishes an instance using application-only authentication using a
* file as cache.
*
* @return An API context usable for requests using app-only auth.
* @throws IOException
*/
public static TwitterApi getAppOnly() throws IOException {
Configuration cfg = Configuration.getConfig();
String token;
BearerRequester breq = null;
token = cfg.getProperty(CFG_BEARER_TOKEN);
if (token != null) {
breq = new BearerRequester(token);
if (!breq.isValid()) {
Logger.getLogger(TwitterApi.class.getName())
.info("Bearer token invalid, trying a new one...");
breq = null;
}
}
if (breq == null) {
ConsumerKeySecret cks = getConsumerKeySecret();
breq = new BearerRequester(cks);
cfg.setProperty(CFG_BEARER_TOKEN, breq.getAccessToken());
cfg.save();
}
return new TwitterApi(breq);
}
private static ConsumerKeySecret getConsumerKeySecret() {
// static consumer keys retrieved from dev.twitter.com
return new ConsumerKeySecret(Configuration.CONSUMER_KEY,
Configuration.CONSUMER_SECRET);
}
/**
* @param resource The resource to be requested.
* @return A builder for an API request.
*/
public Builder build(String resource) {
return new Builder(resource);
}
public class Builder {
private final String resource;
private final List<NameValuePair> params;
public Builder(String resource) {
this.resource = resource;
this.params = new ArrayList<>();
}
public Builder param(String key, String val) {
params.add(new BasicNameValuePair(key, val));
return this;
}
@Override
public String toString() {
if (params.isEmpty()) {
return this.resource;
}
return this.resource + "?" + URLEncodedUtils.format(params, Charsets.UTF_8);
}
public JSONObject request() throws IOException {
return TwitterApi.this.requester.getJSON(toString());
}
}
}
|