summaryrefslogtreecommitdiff
path: root/src/Chapter2/restapi/RESTSearchExample.java
blob: e9a5dd7ad5c9a9ef7d456fd1ac7c71dc977f54f5 (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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/* TweetTracker. Copyright (c) Arizona Board of Regents on behalf of Arizona State University
 * @author shamanth
 */
package Chapter2.restapi;

import Chapter2.support.OAuthTokenSecret;
import Chapter2.openauthentication.OAuthExample;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.basic.DefaultOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

public class RESTSearchExample
{
    BufferedWriter OutFileWriter;
    OAuthTokenSecret OAuthTokens;
    OAuthConsumer Consumer;
    String query = "#protest";
    String DEF_FILENAME = "searchresults.json";

    /**
     * Creates a OAuthConsumer with the current consumer & user access tokens and secrets
     * @return consumer
     */
    public OAuthConsumer GetConsumer()
    {
        OAuthConsumer consumer = new DefaultOAuthConsumer(utils.Configuration.CONSUMER_KEY,utils.Configuration.CONSUMER_SECRET);
        consumer.setTokenWithSecret(OAuthTokens.getAccessToken(), OAuthTokens.getAccessSecret());
        return consumer;
    }

    /**
     * Load the User Access Token, and the User Access Secret
     */
    public void LoadTwitterToken()
    {
        //Un-comment before release
//        OAuthExample oae = new OAuthExample();
//        OAuthTokens =  oae.GetUserAccessKeySecret();
        //Remove before release
        OAuthTokens = OAuthExample.DEBUGUserAccessSecret();
    }

    /**
     * Fetches tweets matching a query
     * @param query for which tweets need to be fetched
     * @return an array of status objects
     */
    public JSONArray GetSearchResults(String query)
    {
        try{
            //construct the request url
            String URL_PARAM_SEPERATOR = "&";
            StringBuilder url = new StringBuilder();
            url.append("https://api.twitter.com/1.1/search/tweets.json?q=");
            //query needs to be encoded
            url.append(URLEncoder.encode(query, "UTF-8"));
            url.append(URL_PARAM_SEPERATOR);
            url.append("count=100");
            URL navurl = new URL(url.toString());
            HttpURLConnection huc = (HttpURLConnection) navurl.openConnection();
            huc.setReadTimeout(5000);
            Consumer.sign(huc);
            huc.connect();
            if(huc.getResponseCode()==400||huc.getResponseCode()==404||huc.getResponseCode()==429)
            {
                System.out.println(huc.getResponseMessage());
                try {
                    huc.disconnect();
                    Thread.sleep(this.GetWaitTime("/friends/list"));
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
            if(huc.getResponseCode()==500||huc.getResponseCode()==502||huc.getResponseCode()==503)
            {
                System.out.println(huc.getResponseMessage());
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(RESTSearchExample.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            BufferedReader bRead = new BufferedReader(new InputStreamReader((InputStream) huc.getInputStream()));
            String temp;
            StringBuilder page = new StringBuilder();
            while( (temp = bRead.readLine())!=null)
            {
                page.append(temp);
            }
            JSONTokener jsonTokener = new JSONTokener(page.toString());
            try {
                JSONObject json = new JSONObject(jsonTokener);
                JSONArray results = json.getJSONArray("statuses");
                return results;
            } catch (JSONException ex) {
                Logger.getLogger(RESTSearchExample.class.getName()).log(Level.SEVERE, null, ex);
            }            
        } catch (OAuthCommunicationException ex) {
            Logger.getLogger(RESTSearchExample.class.getName()).log(Level.SEVERE, null, ex);
        } catch (OAuthMessageSignerException ex) {
            Logger.getLogger(RESTSearchExample.class.getName()).log(Level.SEVERE, null, ex);
        } catch (OAuthExpectationFailedException ex) {
            Logger.getLogger(RESTSearchExample.class.getName()).log(Level.SEVERE, null, ex);
        }catch(IOException ex)
        {
            ex.printStackTrace();
        }
        return null;
    }

     /**
     * Retrieves the rate limit status of the application
     * @return
     */
   public JSONObject GetRateLimitStatus()
   {
     try{
            URL url = new URL("https://api.twitter.com/1.1/application/rate_limit_status.json");
            HttpURLConnection huc = (HttpURLConnection) url.openConnection();
            huc.setReadTimeout(5000);
            OAuthConsumer consumer = new DefaultOAuthConsumer(utils.Configuration.CONSUMER_KEY,utils.Configuration.CONSUMER_SECRET);
            consumer.setTokenWithSecret(OAuthTokens.getAccessToken(), OAuthTokens.getAccessSecret());
            consumer.sign(huc);
            huc.connect();
            BufferedReader bRead = new BufferedReader(new InputStreamReader((InputStream) huc.getContent()));
            StringBuffer page = new StringBuffer();
            String temp= "";
            while((temp = bRead.readLine())!=null)
            {
                page.append(temp);
            }
            bRead.close();
            return (new JSONObject(page.toString()));
        } catch (JSONException ex) {
            Logger.getLogger(RESTApiExample.class.getName()).log(Level.SEVERE, null, ex);
        } catch (OAuthCommunicationException ex) {
            Logger.getLogger(RESTApiExample.class.getName()).log(Level.SEVERE, null, ex);
        }  catch (OAuthMessageSignerException ex) {
            Logger.getLogger(RESTApiExample.class.getName()).log(Level.SEVERE, null, ex);
        } catch (OAuthExpectationFailedException ex) {
            Logger.getLogger(RESTApiExample.class.getName()).log(Level.SEVERE, null, ex);
        }catch(IOException ex)
        {
            Logger.getLogger(RESTApiExample.class.getName()).log(Level.SEVERE, null, ex);
        }
     return null;
   }

   /**
    * Initialize the file writer
    * @param path of the file
    * @param outFilename name of the file
    */
   public void InitializeWriters(String outFilename) {
        try {
            File fl = new File(outFilename);
            if(!fl.exists())
            {
                fl.createNewFile();
            }
            /**
             * Use UTF-8 encoding when saving files to avoid
             * losing Unicode characters in the data
             */
            OutFileWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFilename,true),"UTF-8"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

   /**
    * Close the opened filewriter to save the data
    */
   public void CleanupAfterFinish()
   {
        try {
            OutFileWriter.close();
        } catch (IOException ex) {
            Logger.getLogger(RESTSearchExample.class.getName()).log(Level.SEVERE, null, ex);
        }
   }

   /**
    * Writes the retrieved data to the output file
    * @param data containing the retrived information in JSON
    * @param user name of the user currently being written
    */
    public void WriteToFile(JSONArray searchResults)
    {
        try
        {
            for(int i=0;i<searchResults.length();i++)
            {
                try {
                    OutFileWriter.write(searchResults.getJSONObject(i).toString());
                    OutFileWriter.newLine();
                } catch (JSONException ex) {
                    Logger.getLogger(RESTSearchExample.class.getName()).log(Level.SEVERE, null, ex);
                }                
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    
    /**
     * Retrieves the wait time if the API Rate Limit has been hit
     * @param api the name of the API currently being used
     * @return the number of milliseconds to wait before initiating a new request
     */
    public long GetWaitTime(String api)
    {
        JSONObject jobj = this.GetRateLimitStatus();
        if(jobj!=null)
        {
            try {
                if(!jobj.isNull("resources"))
                {
                    JSONObject resourcesobj = jobj.getJSONObject("resources");
                    JSONObject statusobj = resourcesobj.getJSONObject("statuses");
                    JSONObject apilimit = statusobj.getJSONObject(api);
                    int numremhits = apilimit.getInt("remaining");
                    if(numremhits<=1)
                    {
                        long resettime = apilimit.getInt("reset");
                        resettime = resettime*1000; //convert to milliseconds
                        return resettime;
                    }
                }
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
        }
        return 0;
    }

    /**
     * Creates an OR search query from the supplied terms
     * @param queryTerms
     * @return a String formatted as term1 OR term2
     */
    public String CreateORQuery(ArrayList<String> queryTerms)
    {
        String OR_Operator = " OR ";
        StringBuffer querystr = new StringBuffer();
        int count = 1;
        for(String term:queryTerms)
        {
            if(count==1)
            {
                querystr.append(term);
            }
            else
            {
                querystr.append(OR_Operator).append(term);
            }
        }
        return querystr.toString();
    }

    public static void main(String[] args)
    {
        RESTSearchExample rse = new RESTSearchExample();
        ArrayList<String> queryterms = new ArrayList<String>();        
        String outfilename = rse.DEF_FILENAME;
        if(args!=null)
        {
            if(args.length>0)
            {
                for(int i=0;i<args.length;i++)
                {
                    queryterms.add(args[i]);
                }
            }
            else
            {
                queryterms.add(rse.query);
            }
        }
        rse.LoadTwitterToken();
        rse.Consumer = rse.GetConsumer();
        System.out.println(rse.GetRateLimitStatus());
        rse.InitializeWriters(outfilename);
        JSONArray results = rse.GetSearchResults(rse.CreateORQuery(queryterms));
        if(results!=null)
        {
            rse.WriteToFile(results);
        }
        rse.CleanupAfterFinish();
    }
}