Example usage for twitter4j Twitter getPlaceTrends

List of usage examples for twitter4j Twitter getPlaceTrends

Introduction

In this page you can find the example usage for twitter4j Twitter getPlaceTrends.

Prototype

Trends getPlaceTrends(int woeid) throws TwitterException;

Source Link

Document

Returns the top 10 trending topics for a specific WOEID, if trending information is available for it.<br> The response is an array of "trend" objects that encode the name of the trending topic, the query parameter that can be used to search for the topic on <a href="http://search.twitter.com/">Twitter Search</a>, and the Twitter Search URL.<br> This information is cached for 5 minutes.

Usage

From source file:twitfeedbot.BotherSomeoneServlet.java

License:Open Source License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Twitter twit;
    StringBuilder builder = new StringBuilder();
    User victim = null;//from w w  w .jav  a  2  s.c  o  m
    long cursor = -1;
    long[] friendIDs, victimIDs;
    Random r = new Random();

    resp.setContentType("text/html");
    resp.getWriter().println("<html>");
    resp.getWriter().println("<body>");
    try {
        ConfigurationBuilder twitterConfigBuilder = new ConfigurationBuilder();
        twitterConfigBuilder.setDebugEnabled(false);

        System.setProperty("WORDNIK_API_KEY", WORDNIK_KEY);
        twitterConfigBuilder.setOAuthConsumerKey(CONSUMER_KEY);
        twitterConfigBuilder.setOAuthConsumerSecret(CONSUMER_SECRET);
        twitterConfigBuilder.setOAuthAccessToken(ACCESS_TOKEN);
        twitterConfigBuilder.setOAuthAccessTokenSecret(ACCESS_SECRET);

        twit = new TwitterFactory(twitterConfigBuilder.build()).getInstance();

        Trends t = twit.getPlaceTrends(1); //global trends
        friendIDs = twit.getFollowersIDs(twit.getId(), cursor).getIDs();
        if (friendIDs.length == 0)
            resp.getWriter().println("Cannot find any followers to bother");
        else {
            victimIDs = twit.getFollowersIDs(friendIDs[r.nextInt(friendIDs.length)], cursor).getIDs();
            if (victimIDs.length == 0)
                resp.getWriter().println("Cannot find any followers to bother");
            else {
                victim = twit.showUser(victimIDs[r.nextInt(victimIDs.length)]);
                builder.append("@" + victim.getScreenName()).append(" ");
                //Append Wordnik example sentence
                builder.append(WordApi.topExample(WordsApi.randomWord().getWord()).getText());
                if (builder.length() > 140) //Tweets are maximum 140 characters
                {
                    if (builder.lastIndexOf(";", 110) > 0)
                        builder.setLength(builder.lastIndexOf(";", 110));
                    else if (builder.lastIndexOf(":", 110) > 0)
                        builder.setLength(builder.lastIndexOf(":", 110));
                    else if (builder.lastIndexOf(",", 110) > 0)
                        builder.setLength(builder.lastIndexOf(",", 110));
                    else
                        builder.setLength(110);
                }
                builder.append(" " + t.getTrends()[r.nextInt(t.getTrends().length)].getName());

                if (builder.length() > 140)
                    builder.setLength(140); //Tweets are limited to 140 characters

                twit.updateStatus(builder.toString());
                resp.getWriter().println("Tweet posted: " + builder.toString() + "<br>");
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("Input file(s) not found<br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (TwitterException e) {
        resp.getWriter().println("Problem with Twitter <br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (KnickerException e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("Problem with Wordnik <br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (Exception e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    }
}

From source file:twitter4j.examples.trends.GetPlaceTrends.java

/**
 * Usage: java twitter4j.examples.trends.GetPlaceTrends [WOEID=0]
 *
 * @param args message//from ww w. ja  v  a 2s. c o  m
 */
public static void main(String[] args) {
    try {
        int woeid = args.length > 0 ? Integer.parseInt(args[0]) : 1;
        Twitter twitter = new TwitterFactory().getInstance();
        Trends trends = twitter.getPlaceTrends(woeid);

        System.out.println("Showing trends for " + trends.getLocation().getName());

        for (Trend trend : trends.getTrends()) {
            System.out.println(String.format("%s (tweet_volume: %d)", trend.getName(), trend.getTweetVolume()));
        }

        System.out.println("done.");
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get trends: " + te.getMessage());
        System.exit(-1);
    } catch (NumberFormatException nfe) {
        nfe.printStackTrace();
        System.out.println("WOEID must be number");
        System.exit(-1);
    }
}

From source file:twitterapidemo.TwitterAPIDemo.java

License:Apache License

public static void main(String[] args) throws IOException, TwitterException {

    //TwitterAPIDemo twitterApiDemo = new TwitterAPIDemo();

    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(consumerKey);
    builder.setOAuthConsumerSecret(consumerSecret);
    Configuration configuration = builder.build();

    TwitterFactory twitterFactory = new TwitterFactory(configuration);
    Twitter twitter = twitterFactory.getInstance();
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    Scanner sc = new Scanner(System.in);
    System.out.println(// ww  w . j  a  va 2s  .  co m
            "Enter your choice:\n1. To post tweet\n2.To search tweets\n3. Recent top 3 trends and number of posts of each trending topic");
    int choice = sc.nextInt();
    switch (choice) {
    case 1:
        System.out.println("What's happening: ");
        String post = sc.next();
        StatusUpdate statusUpdate = new StatusUpdate(post + "-Posted by TwitterAPI");
        Status status = twitter.updateStatus(statusUpdate);

        System.out.println("status.toString() = " + status.toString());
        System.out.println("status.getInReplyToScreenName() = " + status.getInReplyToScreenName());
        System.out.println("status.getSource() = " + status.getSource());
        System.out.println("status.getText() = " + status.getText());
        System.out.println("status.getContributors() = " + Arrays.toString(status.getContributors()));
        System.out.println("status.getCreatedAt() = " + status.getCreatedAt());
        System.out.println("status.getCurrentUserRetweetId() = " + status.getCurrentUserRetweetId());
        System.out.println("status.getGeoLocation() = " + status.getGeoLocation());
        System.out.println("status.getId() = " + status.getId());
        System.out.println("status.getInReplyToStatusId() = " + status.getInReplyToStatusId());
        System.out.println("status.getInReplyToUserId() = " + status.getInReplyToUserId());
        System.out.println("status.getPlace() = " + status.getPlace());
        System.out.println("status.getRetweetCount() = " + status.getRetweetCount());
        System.out.println("status.getRetweetedStatus() = " + status.getRetweetedStatus());
        System.out.println("status.getUser() = " + status.getUser());
        System.out.println("status.getAccessLevel() = " + status.getAccessLevel());
        System.out.println("status.getHashtagEntities() = " + Arrays.toString(status.getHashtagEntities()));
        System.out.println("status.getMediaEntities() = " + Arrays.toString(status.getMediaEntities()));
        if (status.getRateLimitStatus() != null) {
            System.out.println(
                    "status.getRateLimitStatus().getLimit() = " + status.getRateLimitStatus().getLimit());
            System.out.println("status.getRateLimitStatus().getRemaining() = "
                    + status.getRateLimitStatus().getRemaining());
            System.out.println("status.getRateLimitStatus().getResetTimeInSeconds() = "
                    + status.getRateLimitStatus().getResetTimeInSeconds());
            System.out.println("status.getRateLimitStatus().getSecondsUntilReset() = "
                    + status.getRateLimitStatus().getSecondsUntilReset());
        }
        System.out.println("status.getURLEntities() = " + Arrays.toString(status.getURLEntities()));
        System.out.println(
                "status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities()));
        break;
    case 2:
        System.out.println("Enter keyword");
        String keyword = sc.next();
        try {
            Query query = new Query(keyword);
            QueryResult result;
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    System.out.println(tweet.getCreatedAt() + ":\t@" + tweet.getUser().getScreenName() + " - "
                            + tweet.getText());
                }
            } while ((query = result.nextQuery()) != null);
            System.exit(0);
        } catch (TwitterException te) {
            System.out.println("Failed to search tweets: " + te.getMessage());
            System.exit(-1);
            break;
        }
    case 3:
        //WOEID for India = 23424848
        Trends trends = twitter.getPlaceTrends(23424848);
        int count = 0;
        for (Trend trend : trends.getTrends()) {
            if (count < 3) {
                Query query = new Query(trend.getName());
                QueryResult result;
                int numberofpost = 0;
                do {
                    result = twitter.search(query);
                    List<Status> tweets = result.getTweets();
                    for (Status tweet : tweets) {
                        numberofpost++;
                    }
                } while ((query = result.nextQuery()) != null);
                System.out
                        .println("Number of post for the topic '" + trend.getName() + "' is: " + numberofpost);
                count++;
            } else
                break;
        }
        break;
    default:
        System.out.println("Invalid input");
    }
}

From source file:twitterapp.TwitterApp.java

public static void streamTweets() throws TwitterException {
    /*getting the trends */
    ConfigurationBuilder cb2 = new ConfigurationBuilder();

    cb2.setDebugEnabled(true).setOAuthConsumerKey("S01GsVwuCAwZFp5BLg5C4k8PT")
            .setOAuthConsumerSecret("6jo0jo4b05Ec5ZJcf74v5yGUQu5v8DryUwypOBjPD6jaItRNzd")
            .setOAuthAccessToken("794259549297446912-Z3AWruBmLa7QmCO6BnybCSj1tZXNqbB")
            .setOAuthAccessTokenSecret("6ezMQPQVziW9yxyTITZA8Wc2RJWjcBKvbXZU4dOjo4bge");

    TwitterFactory tf = new TwitterFactory(cb2.build());
    Twitter twitter = tf.getInstance();
    Trends trends = twitter.getPlaceTrends(23424977);

    String top_trend = "";
    int top = 0;//from w  w  w  .  j  a  va2 s.c om
    for (Trend trend : trends.getTrends()) {
        if (top < 1) {
            top_trend = trend.getName();
            top++;
        }
    }

    System.out.println("top trend : " + top_trend);

    //Using the Streaming API to get real time tweets based on the trending topics as keywords
    /* configurating twiter4j */

    ConfigurationBuilder cb = new ConfigurationBuilder();

    cb.setDebugEnabled(true).setOAuthConsumerKey("S01GsVwuCAwZFp5BLg5C4k8PT")
            .setOAuthConsumerSecret("6jo0jo4b05Ec5ZJcf74v5yGUQu5v8DryUwypOBjPD6jaItRNzd")
            .setOAuthAccessToken("794259549297446912-Z3AWruBmLa7QmCO6BnybCSj1tZXNqbB")
            .setOAuthAccessTokenSecret("6ezMQPQVziW9yxyTITZA8Wc2RJWjcBKvbXZU4dOjo4bge")
            .setJSONStoreEnabled(true);
    /* end of configuration */

    MongoClient mongo = new MongoClient("localhost", 27017);
    MongoDatabase database = mongo.getDatabase("myTweetdb2");
    MongoCollection<Document> collection = database.getCollection("myTweetCol5");
    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
    StatusListener listener;
    listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {

            String rawJSON = TwitterObjectFactory.getRawJSON(status);
            Document doc = Document.parse(rawJSON);

            collection.insertOne(doc);

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
            System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
        }

        @Override
        public void onStallWarning(StallWarning warning) {
            System.out.println("Got stall warning:" + warning);
        }

        @Override
        public void onException(Exception ex) {
            ex.printStackTrace();
        }
    };

    // twitterStream.sample();
    twitterStream.addListener(listener);
    FilterQuery fq = new FilterQuery();

    String keywords[] = { top_trend };
    fq.track(keywords);
    twitterStream.filter(fq);
}

From source file:twittermongodbapp.CollectTweets.java

static public void getTopTrends(twitter4j.Twitter twitter, TwitterStream twitterStream,
        StatusListener listener) {/*from   w ww. j  a  v a2 s.  com*/
    FilterQuery filterQuery = new FilterQuery();

    Timer t = new Timer();
    t.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            Trends trends;
            try {
                trends = twitter.getPlaceTrends(23424833);//trends = twitter.getPlaceTrends(1);(23424833)
                String[] keywords = new String[trends.getTrends().length];
                System.out.println("Top Trends in Greece");
                for (int i = 0; i < trends.getTrends().length; i++) {
                    keywords[i] = trends.getTrends()[i].getName();
                    System.out.println(keywords[i]);
                }
                filterQuery.track(keywords);
                filterQuery.language(new String[] { "el" });
                twitterStream.addListener(listener);
                twitterStream.filter(filterQuery);
            } catch (TwitterException ex) {
                Logger.getLogger(TwitterMongoDBApp.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }, 1000, 360000);

}

From source file:twittersentimentanalysis.TwitterSentimentAnalysis.java

private static ArrayList<Tweet> getAllTweets(Twitter twitter) {
    logger.info("getAllTweets");
    List<Status> listTweets = null;
    ArrayList<Tweet> listOfTweets = new ArrayList<Tweet>();
    try {/*from   w w  w  .j a  va  2  s  .c o m*/
        Trends trends = twitter.getPlaceTrends(23424977);
        // System.out.println(trends.getLocation());
        Trend trend[] = trends.getTrends();
        logger.info("Number of Trends : " + trend.length);
        for (Trend trendTemp : trend) {
            //System.out.println("Name = " + trendTemp.getName());
            //System.out.println("***************");
            Query query = new Query(trendTemp.getQuery());
            query.setCount(100);
            QueryResult queryResult = twitter.search(query);
            listTweets = queryResult.getTweets();
            StanfordCoreNLPTool.init();
            for (Status status : listTweets) {
                //System.out.println(status.getText());
                Tweet tweet = getTweetObject(status);
                if (tweet != null) {
                    tweet.setTrend(trendTemp.getName());
                    listOfTweets.add(tweet);
                }
            }
        }
    } catch (TwitterException ex) {
        Logger.getLogger(TwitterSentimentAnalysis.class.getName()).log(Level.SEVERE, null, ex);
        logger.info(ex.getMessage());
    }
    return listOfTweets;
}

From source file:wap.twitter.model.TwitterUtility.java

public List<Trend> getTrends(GeoLocation loc) throws TwitterException {
    TwitterFactory tf = config();//from   ww  w.j a  va  2  s  . c om
    Twitter twitter = tf.getInstance();
    List<Trend> tds = new ArrayList<Trend>();
    ResponseList<Location> locations;
    locations = twitter.getClosestTrends(loc);
    for (Location location : locations) {
        Trends trends = twitter.getPlaceTrends(location.getWoeid());
        for (int i = 0; i < trends.getTrends().length; i++) {
            if (i == 10) {
                break;
            }
            tds.add(trends.getTrends()[i]);
        }
    }
    return tds;
}