Example usage for twitter4j TwitterFactory getSingleton

List of usage examples for twitter4j TwitterFactory getSingleton

Introduction

In this page you can find the example usage for twitter4j TwitterFactory getSingleton.

Prototype

public static Twitter getSingleton() 

Source Link

Document

Returns default singleton Twitter instance.

Usage

From source file:edu.cmu.cs.lti.discoursedb.io.twitter.converter.TwitterConverterService.java

License:Open Source License

/**
 * For each user in the mongodb dataset, import the whole timeline of that user (API limit: latest 3,200 tweets)
 * /*w ww . j a  v a 2s .c  om*/
 * @param users
 * @param discourseName
 * @param datasetName
 */
public void importUserTimelines(List<String> users, String discourseName, String datasetName) {
    Twitter twitter = TwitterFactory.getSingleton();

    log.info("Importing timelines for " + users.size() + " users into DiscourseDB");

    for (String screenname : users) {
        log.info("Retrieving timeline for user " + screenname);
        List<Status> tweets = new ArrayList<>();

        //There's an API limit of 3,200 tweets you can get from a timeline and 200 per request (page). 
        //This makes 16 requests with 200 tweets per page (pages 1 to 17)
        //This also works if the users has less than 3,200 tweets
        for (int i = 1; i < 17; i++) {
            try {
                tweets.addAll(twitter.getUserTimeline(screenname, new Paging(i, 200)));
            } catch (TwitterException e) {
                log.error("Error retrieving timeline for user " + screenname, e);
            }
        }

        log.info("Retrieved timeline (" + tweets.size() + " Tweets) for user " + screenname);
        log.info("Mapping tweets for user " + screenname);
        for (Status tweet : tweets) {
            log.info("Mapping tweet " + tweet.getId());
            mapTweet(discourseName, datasetName, tweet, null);
        }
    }
}

From source file:ikemen.Main.java

License:Apache License

public static void main(String[] args) {
    final Twitter twitter = TwitterFactory.getSingleton();
    final TwitterStream stream = TwitterStreamFactory.getSingleton();
    stream.addListener(new UserStreamAdapter() {
        public void onStatus(Status status) {
            if (yonda(status.getText())) {
                try {
                    twitter.createFavorite(status.getId());
                } catch (TwitterException ignore) {
                }/*from  w  ww .  j  a va 2  s.c om*/
                try {
                    twitter.sendDirectMessage("yusuke", "http://twitter.com/yusuke/status/" + status.getId());
                } catch (TwitterException ignore) {
                }
            }
        }
    });
    stream.user();
}

From source file:info.maslowis.twitterripper.command.AbstractTwitterCommand.java

License:Open Source License

protected AbstractTwitterCommand() {
    super();
    this.twitter = TwitterFactory.getSingleton();
}

From source file:info.maslowis.twitterripper.twitter.OAuthTwitter.java

License:Open Source License

/**
 * Displays authorization URL and gets PIN for connection to twitter under authorized user
 *//*from w  w w .ja v a2s.c o m*/
public void authorization() throws IOException {
    try {
        Twitter twitter = TwitterFactory.getSingleton();
        twitter.setOAuthConsumer(consumerKey, consumerKeySecret);
        RequestToken requestToken = twitter.getOAuthRequestToken();
        out.println(ansi().a(Attribute.INTENSITY_BOLD).fg(Color.GREEN).a("Authorization URL:").reset());
        out.println(ansi().a(Attribute.INTENSITY_BOLD).fg(Color.CYAN).a(requestToken.getAuthorizationURL()));
        out.println(ansi().a(Attribute.INTENSITY_BOLD).fg(Color.RED).a("Enter PIN please:").reset());
        String pin = reader.readLine();
        twitter.getOAuthAccessToken(requestToken, pin);
    } catch (TwitterException e) {
        logger.error("Authorization fail! Please try to run application again and enter PIN.");
        exit(1);
    }
}

From source file:jp.xxxxxxxx.l3fish.twnyaan.MainApp.java

License:Open Source License

@Override
public void init() throws Exception {
    // DI//from w w  w.j  a v  a 2  s .c  om
    Injector injector = Guice.createInjector();
    injector.injectMembers(this);

    // Twitter?ConsumerKey/ConsumerSecret?
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(TwitterAPIKey.getConsumerKey(), TwitterAPIKey.getConsumerSecret());
    AccessToken accessToken = repository.load();
    if (accessToken != null) {
        twitter.setOAuthAccessToken(accessToken);
    }
}

From source file:jp.xxxxxxxx.l3fish.twnyaan.service.AuthenticationService.java

License:Open Source License

/**
 * RequestToken?PIN??AccessToken??/* w  ww .j av  a  2  s  .c o  m*/
 * RequestToken??????????{@code null}?
 *
 * @param requestToken RequestToken
 * @param pinCode ???PIN
 * @return AccessToken??????????{@code null}
 */
public AccessToken requestAccessToken(RequestToken requestToken, String pinCode) {
    Twitter twitter = TwitterFactory.getSingleton();

    AccessToken accessToken = null;
    try {
        accessToken = twitter.getOAuthAccessToken(requestToken, pinCode);
        twitter.setOAuthAccessToken(accessToken);
    } catch (IllegalStateException e) {
        System.err.println(ErrorCode.NO_TOKEN_AVAILABLE);
    } catch (TwitterException e) {
        System.err.println(ErrorCode.TWITTER_AUTHORIZATION_FAILED);
    }

    return accessToken;
}

From source file:jp.xxxxxxxx.l3fish.twnyaan.service.UserService.java

License:Open Source License

/**
 * ????// ww  w . ja  va2  s . c om
 * ??????????????{@code null}?
 * 
 * @return ??????????{@code null}
 */
public User getUser() {
    Twitter twitter = TwitterFactory.getSingleton();

    User user = null;
    try {
        user = twitter.verifyCredentials();
    } catch (IllegalStateException e) {
        System.err.println(ErrorCode.MISSING_AUTHENTICATION_CREDENTIALS);
    } catch (TwitterException e) {
        if (e.getStatusCode() == 401) {
            System.err.println(ErrorCode.UNAUTHORIZED);
        } else {
            System.err.println(ErrorCode.TWITTER_SERVICE_UNAVAILABLE);
        }
    }

    return user;
}

From source file:kagechiyo.Kagechiyo.java

License:Apache License

public Kagechiyo() throws TwitterException {
    listener = new Listener(TwitterFactory.getSingleton());
    stream.addListener(listener);

}

From source file:kerguelenpetrel.BotherSomeoneServlet.java

License:Apache License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    StringBuilder builder = new StringBuilder();
    long[] friendIDs, victimIDs;

    resp.setContentType("text/plain; charset=UTF-8");
    try {//from ww  w.  j a  v a2s .co  m
        //Get the Twitter object
        Twitter twit = TwitterFactory.getSingleton();

        //Find a friend of a follower to bother
        friendIDs = twit.getFollowersIDs(twit.getId(), cursor).getIDs();

        if (friendIDs.length == 0) {
            resp.getWriter().println("Cannot find any followers to bother \n");
            return;
        }

        //Load the potential victim IDs
        victimIDs = twit.getFollowersIDs(friendIDs[r.nextInt(friendIDs.length)], cursor).getIDs();

        if (victimIDs.length == 0) {
            resp.getWriter().println("Cannot find any followers to bother \n");
            return;
        }

        //Write to our victim
        String victim = twit.showUser(victimIDs[r.nextInt(victimIDs.length)]).getScreenName();

        //Get a global trend
        Trends t = twit.getPlaceTrends(1);
        String trend = t.getTrends()[r.nextInt(t.getTrends().length)].getName();
        builder.append(getWordnikContent(victim, trend, resp));

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

        //Set the status
        StatusUpdate status = new StatusUpdate(builder.toString());

        //Post the status
        twit.updateStatus(status);
        resp.getWriter().println("Tweet posted: " + status.getStatus());
    }

    catch (TwitterException e) {
        resp.getWriter().println("Problem with Twitter \n");
        e.printStackTrace(resp.getWriter());
    }
}

From source file:kerguelenpetrel.FriendSomeoneServlet.java

License:Apache License

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    User friend = null;//from  www .  ja  v  a  2s  .  c o  m
    resp.setContentType("text/plain; charset=UTF-8");
    try {
        //Get the Twitter object
        Twitter twit = TwitterFactory.getSingleton();

        //Find a friend of a follower to bother
        long[] followerIDs = twit.getFollowersIDs(twit.getId(), cursor, 30).getIDs();

        if (followerIDs.length == 0) {
            resp.getWriter().println("Cannot find any followers \n");
            return;
        }

        //Load the potential victim IDs
        long[] friendIDs = twit.getFollowersIDs(followerIDs[r.nextInt(followerIDs.length)], cursor).getIDs();

        if (friendIDs.length == 0) {
            resp.getWriter().println("Cannot find any followers to bother \n");
            return;
        }

        //Get a new friend
        friend = twit.showUser(friendIDs[r.nextInt(friendIDs.length)]);
        twit.createFriendship(friend.getId());
        resp.getWriter().println("Made a new friend with @" + friend.getScreenName());

        //Write to our new friend
        StatusUpdate status = new StatusUpdate(writeToFriend(friend.getScreenName(), resp));
        twit.updateStatus(status);
        resp.getWriter().println("Tweet posted: " + status.getStatus());
    } catch (TwitterException e) {
        resp.getWriter().println("Problem with Twitter \n");
        e.printStackTrace(resp.getWriter());
    }
}