edu.mum.cs.wap.TwitterUtil.java Source code

Java tutorial

Introduction

Here is the source code for edu.mum.cs.wap.TwitterUtil.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 edu.mum.cs.wap;

import edu.mum.cs.wap.model.Trend;
import edu.mum.cs.wap.model.Tweet;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.util.stream.Collectors.toList;
import twitter4j.GeoLocation;
import twitter4j.Location;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Trends;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;

/**
 *
 * @author rXing
 */
public class TwitterUtil {

    private static Twitter twitter = getTwitter();

    private static Twitter getTwitter() {
        if (twitter == null) {
            ConfigurationBuilder cb = new ConfigurationBuilder();
            cb.setDebugEnabled(true).setOAuthConsumerKey("ZhsCVnhHjs54ZLCxgE82n6GEa")
                    .setOAuthConsumerSecret("FixRe4imh376SRWcxgoF14GdyaQjW7tLHE13mxcgNXNiObwSnr")
                    .setOAuthAccessToken("935445715-EcVDaqqw7QQgcviXSOWWDT5ZCT8LkHbBNP1Pzd1W")
                    .setOAuthAccessTokenSecret("PJIEzaRZB21tZP01CAaZEoEaVEcVvIRK6jMOlDyqc0peL");
            TwitterFactory tf = new TwitterFactory(cb.build());
            twitter = tf.getInstance();
        }
        return twitter;
    }

    private static List<Status> getStatusesByKeyword(String keyword) {
        try {
            Query query = new Query("movie " + keyword + "-filter:retweets");
            query.setCount(8);
            QueryResult result;
            do {
                result = twitter.search(query);
                return result.getTweets();
            } while ((query = result.nextQuery()) != null);
        } catch (TwitterException te) {
            System.out.println("Failed to search tweets: " + te.getMessage());
        }
        return null;
    }

    public static List<Tweet> getTweetsByKeyword(String keyword) {
        List<Status> statuses = getStatusesByKeyword(keyword);
        List<Tweet> tweets = statuses.stream()
                .map(status -> new Tweet(status.getText(), TwitterUtil.getTweetURL(status),
                        status.getUser().getName(), status.getUser().getBiggerProfileImageURL()))
                .collect(toList());
        return tweets;
    }

    private static String getTweetURL(Status status) {
        String url = "https://twitter.com/" + status.getUser().getScreenName() + "/status/" + status.getId();
        return url;
    }

    public static List<Trend> getTrends(double latitude, double longitude) {
        try {
            GeoLocation gl = new GeoLocation(latitude, longitude);
            ResponseList<Location> locations = twitter.getClosestTrends(gl);
            return TwitterUtil.getPlacedTrends(locations.get(0).getWoeid());
        } catch (TwitterException ex) {
            Logger.getLogger(TwitterUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    private static List<Trend> getPlacedTrends(int woeid) throws TwitterException {
        Trends trends = twitter.getPlaceTrends(woeid);
        return Arrays.stream(trends.getTrends())
                .map(t -> new Trend(t.getName(), TwitterUtil.buildTrendsURL(t.getName()))).limit(5)
                .collect(toList());
    }

    private static String buildTrendsURL(String trendName) {
        return "https://twitter.com/hashtag/" + trendName.substring(1) + "?src=tren";
    }

    public static void main(String[] args) {
        List<Trend> urls = getTrends(Double.valueOf("41.0127306"), Double.valueOf("-91.9597081"));
        urls.stream().forEach(System.out::println);
    }

}