TwitterAnalytics.TwitterAPI.java Source code

Java tutorial

Introduction

Here is the source code for TwitterAnalytics.TwitterAPI.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package TwitterAnalytics;

import java.io.*;
import java.util.*;

import twitter4j.*;
import twitter4j.auth.*;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;

public final class TwitterAPI {
    private final String consumerKey = "Fr6vpDB2TmYtKXRYTkuZkCNIW";
    private final String consumeSecretKey = "USLQOURW1QsCAKFmjB69hXOg0uT9kYSGRoytuCHnLH1L1XxBvw";
    private final String accessToken = "2465787618-woyks29y3sgrYONWeXGqblD9eaUcsVENedfIdki";
    private final String accessSecretToken = "Gs9NXzHFtVAEVwUr9K9jAfa1IRlJxA3bnkYPXgwvfRqVD";

    private int maxQuery = 100;

    private static final TwitterAPI instance = new TwitterAPI();
    private final Twitter twitter;
    private List<Status> statusCache = new ArrayList<>();

    private TwitterAPI() {
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(consumerKey);
        builder.setOAuthConsumerSecret(consumeSecretKey);
        builder.setOAuthAccessToken(accessToken);
        builder.setOAuthAccessTokenSecret(accessSecretToken);
        Configuration configuration = builder.build();

        TwitterFactory factory = new TwitterFactory(configuration);

        twitter = factory.getInstance();
    }

    public static TwitterAPI getSingleton() {
        return instance;
    }

    public List<Status> getStatusCache() {
        return statusCache;
    }

    public int getMaxQuerySize() {
        return maxQuery;
    }

    public void setMaxQuerySize(int size) {
        maxQuery = size;
    }

    public void getTweets(List<String> keywords) throws TwitterException {
        statusCache.clear();

        Query query = makeQuery(keywords);
        query.count(maxQuery);
        QueryResult res = twitter.search(query);
        statusCache = res.getTweets();
    }

    private Query makeQuery(List<String> keywords) throws TwitterException {
        // asumsi: pake OR
        if (keywords.isEmpty()) {
            throw new TwitterException("No keyword entered!");
        } else {
            StringBuilder sb = new StringBuilder();

            int i = 0;
            sb.append("(").append(keywords.get(i)).append(")");
            i++;

            while (i < keywords.size()) {
                sb.append("OR (").append(keywords.get(i)).append(")");
                i++;
            }

            return new Query(sb.toString());
        }
    }

    public void writeToFile(String filename) throws IOException {
        FileWriter fw = new FileWriter(new File(filename));

        int idx = 1;
        for (Status status : statusCache) {
            StatusView view = new StatusView(status);

            fw.write("Data ke-" + idx);
            fw.write(view.rawOutput());
            idx++;
            fw.write("\n");
            fw.flush();
        }
    }

    public List<StatusView> readFromFile(String filename) throws Exception {
        // ini buat baca dari file!
        Scanner scan = new Scanner(new File(filename));
        List<StatusView> ret = new ArrayList<>();
        for (int i = 0; i < maxQuery; i++) {
            boolean match = false;

            scan.nextLine(); // Baca "data ke i"
            String text = scan.nextLine(); // baca tweetnya (text)
            String temp = scan.nextLine(); // baca tweetnya (kalo 2 baris)
            String url;

            if (temp.startsWith("https")) {
                url = temp;
            } else {
                text += temp;
                url = scan.nextLine(); // baca url
            }
            scan.nextLine(); // baca "\n"

            ret.add(new StatusView(getUsername(text), url, getIDFromURL(url)));
        }

        return ret;
    }

    private String getUsername(String text) throws Exception {
        int idx = text.indexOf(':');
        if (idx == -1) {
            throw new Exception("Text format not valid!");
        }
        if (!text.startsWith("@")) {
            throw new Exception("Text format not valid!");
        } else {
            return text.substring(1, idx);
        }
    }

    private long getIDFromURL(String url) throws Exception {
        int i = 0;
        int j = 0;

        while (i < 5 && j < url.length()) {
            if (url.charAt(j) == '/') {
                i++;
            }
            j++;
        }

        if (j == url.length() && i != 5) {
            throw new Exception("Invalid URL!");
        } else {
            int k = j;
            while (k < url.length() && url.charAt(k) != '/')
                k++;
            long ret = Long.getLong(url.substring(j, k));

            return ret;
        }
    }
}