Example usage for twitter4j User getScreenName

List of usage examples for twitter4j User getScreenName

Introduction

In this page you can find the example usage for twitter4j User getScreenName.

Prototype

String getScreenName();

Source Link

Document

Returns the screen name of the user

Usage

From source file:peoplesearch.FindFriendsAndFollowers.java

public void GetFollowersIDs() {
    try {//from   w  ww .j  a va 2s  .  c om
        // I need to pass the Person name and the TwitterID.
        //String targetname="Philip Bergkvist";
        Twitter twitter = new TwitterFactory().getInstance();
        long cursor = -1;
        IDs ids;

        ResponseList<User> users1 = null;
        ResponseList<User> users2 = null;
        System.out.println("Listing followers's ids.");

        GraphManager mgr = EmbeddedGraphManager.getInstance();

        mgr.init(new File("/usr/local/Cellar/neo4j/2.1.7/libexec/data/forlang1.db"));
        //mgr.addTwitterAccount(new TwitterAccountImpl(new Date(), "I am Studying", 13, 82, true,"Aalborg", "Philiptwoshoes", 2730631792L));
        List<TwitterAccount> twitteraccountslist;
        twitteraccountslist = null;
        twitteraccountslist = mgr.listTwitterAccounts();
        System.out.println("the number of twitter account in the neo4J DB is" + twitteraccountslist.size());
        for (TwitterAccount Twit : twitteraccountslist) {

            do {
                TwitterLimitWait tlw = new TwitterLimitWait();
                tlw.CheckLimit();

                if (0 < twitteraccountslist.size()) {
                    ids = twitter.getFollowersIDs(Twit.getScreenName(), cursor); //.getFollowersIDs(pep[0], cursor);
                    //ids = twitter.getFollowersIDs("Philiptwoshoes", cursor); //.getFollowersIDs(pep[0], cursor);
                    tlw.CheckLimit();
                    users1 = twitter.getFollowersList(Twit.getScreenName(), cursor);
                    tlw.CheckLimit();
                    users2 = twitter.getFriendsList(Twit.getScreenName(), cursor);

                } else {
                    tlw.CheckLimit();
                    ids = twitter.getFollowersIDs(cursor);

                }

                for (User user : users1) {
                    tlw.CheckLimit();
                    System.out.println("the follower called " + user.getName() + " with twitter handler "
                            + user.getScreenName());
                    String username = user.getName();
                    //mgr.addPerson(new PersonImpl(username));
                    Date Creation = user.getCreatedAt();
                    tlw.CheckLimit();
                    String descript = user.getDescription();
                    boolean empty1 = user.getDescription().isEmpty();
                    if (empty1 == true) {
                        descript = " ";
                    }
                    tlw.CheckLimit();
                    int followers = user.getFollowersCount();
                    tlw.CheckLimit();
                    int following = user.getFriendsCount();
                    boolean geo = user.isGeoEnabled();
                    String loc = user.getLocation();
                    boolean empty2 = user.getLocation().isEmpty();
                    if (empty2 == true) {
                        loc = " ";
                    }
                    String screenname = user.getScreenName();
                    boolean empty3 = user.getScreenName().isEmpty();
                    if (empty3 == true) {
                        screenname = " ";
                    }
                    tlw.CheckLimit();
                    long twitID = user.getId();

                    mgr.linkPersonToTwitterAccount(new PersonImpl(username), new TwitterAccountImpl(Creation,
                            descript, followers, following, geo, loc, screenname, twitID));
                    mgr.linkTwitterAccounts(new TwitterAccountImpl(Creation, descript, followers, following,
                            geo, loc, screenname, twitID), Twit);
                }

                System.out.println("The total number of followers is: " + users1.size());
                // the same procedure for the Following
                for (User user : users2) {
                    tlw.CheckLimit();
                    System.out.println("the following called " + user.getName() + " with twitter handler "
                            + user.getScreenName());
                    String username1 = user.getName();
                    //mgr.addPerson(new PersonImpl(username1));
                    Date Creation = user.getCreatedAt();
                    String descript = user.getDescription();
                    boolean empty1 = user.getDescription().isEmpty();
                    if (empty1 == true) {
                        descript = " ";
                    }
                    int followers = user.getFollowersCount();
                    int following = user.getFriendsCount();
                    boolean geo = user.isGeoEnabled();
                    String loc = user.getLocation();
                    boolean empty2 = user.getLocation().isEmpty();
                    if (empty2 == true) {
                        loc = " ";
                    }
                    String screenname = user.getScreenName();
                    tlw.CheckLimit();
                    boolean empty3 = user.getScreenName().isEmpty();
                    if (empty3 == true) {
                        screenname = " ";
                    }
                    tlw.CheckLimit();
                    long twitID = user.getId();
                    //mgr.addTwitterAccount(new TwitterAccountImpl(Creation,descript,followers,following,geo,loc,screenname,twitID));
                    mgr.linkPersonToTwitterAccount(new PersonImpl(username1), new TwitterAccountImpl(Creation,
                            descript, followers, following, geo, loc, screenname, twitID));
                    mgr.linkTwitterAccounts(Twit, new TwitterAccountImpl(Creation, descript, followers,
                            following, geo, loc, screenname, twitID));
                }
                System.out.println("The total number of friend is: " + users2.size());

                //}
            } while ((cursor = ids.getNextCursor()) != 0);

        }
        mgr.destroy(); // I have to check that the second iteration works fine, because i could not test that.
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get followers' ids: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:peoplesearch.SearchTwitterUsers.java

public void SearchTwitterUsers() {
    int page = 1;
    int numberofpages = 0;
    Date TwitterAccCreatedAt = new Date();
    String TwitterAccDescr = " ";
    int TwitterFollowersCount = 0;
    int TwitterFriendsCount = 0;
    boolean TwitterGeoEnabled = false;
    String TwitterLocation = " ";
    String TwiterAccScrName = " ";
    long TwitterID = 0L;

    try {/*w w w  .ja v a 2 s  .  c om*/

        Twitter twitter = new TwitterFactory().getInstance();
        ResponseList<User> users;
        List<Person> people = null;
        GraphManager mgr = EmbeddedGraphManager.getInstance();
        mgr.init(new File("/usr/local/Cellar/neo4j/2.1.7/libexec/data/forlang1.db"));

        mgr.addPerson(new PersonImpl("wgaura"));
        mgr.addPerson(new PersonImpl("Derek Mizak"));
        mgr.addPerson(new PersonImpl("Swiderek"));
        mgr.addPerson(new PersonImpl("Microsoft"));
        mgr.addPerson(new PersonImpl("BBC"));
        mgr.addPerson(new PersonImpl("RTE"));
        mgr.addPerson(new PersonImpl("CNBC"));
        mgr.addPerson(new PersonImpl("Poland"));
        mgr.addPerson(new PersonImpl("Ireland"));
        mgr.addPerson(new PersonImpl("Ergo"));

        people = mgr.listPeople();

        for (Person person : people) {
            do {
                TwitterLimitWait tlw = new TwitterLimitWait();
                tlw.CheckLimit();

                users = twitter.searchUsers(person.getName(), page);
                numberofpages = users.size() / 20;

                for (User user : users) {
                    if (user.getStatus() != null) {

                        TwitterAccCreatedAt = user.getCreatedAt();
                        if (!user.getDescription().isEmpty()) {
                            TwitterAccDescr = user.getDescription();
                        }
                        //if (user.getFollowersCount()>0) {TwitterFollowersCount=user.getFavouritesCount();}
                        //if  (user.getFriendsCount()>0) {TwitterFriendsCount=user.getFriendsCount();}
                        TwitterFollowersCount = user.getFollowersCount();
                        TwitterFriendsCount = user.getFriendsCount();
                        TwitterGeoEnabled = user.isGeoEnabled();
                        if (!user.getLocation().isEmpty()) {
                            TwitterLocation = user.getLocation();
                        }
                        TwiterAccScrName = user.getScreenName();
                        TwitterID = user.getId();

                        System.out.println("@" + user.getScreenName() + " - " + TwitterFollowersCount + " _ "
                                + TwitterFriendsCount);

                        //mgr.addTwitterAccount(new TwitterAccountImpl(TwitterAccCreatedAt,TwitterAccDescr,TwitterFollowersCount,TwitterFriendsCount,TwitterGeoEnabled,TwitterLocation,TwiterAccScrName,TwitterID));
                        mgr.linkPersonToTwitterAccount(person,
                                new TwitterAccountImpl(TwitterAccCreatedAt, TwitterAccDescr,
                                        TwitterFollowersCount, TwitterFriendsCount, TwitterGeoEnabled,
                                        TwitterLocation, TwiterAccScrName, TwitterID));

                        TwitterAccDescr = " ";
                        TwitterLocation = " ";
                        TwitterFollowersCount = 0;
                        TwitterFriendsCount = 0;

                        //numberofusers++;

                    } else {
                        // the user is protected
                        System.out.println("@" + user.getScreenName());
                    }
                }

                page++;
                //System.out.println(page);
            } while (users.size() != 0 && page < numberofpages);
        }
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}

From source file:stemrps.MentionListener.java

License:Open Source License

@Override
public void onStatus(Status status) {
    System.out.println(status.getUser().getScreenName() + ": " + status.getText());
    String[] inp = status.getText().split(" ");
    String player = "";
    if (inp[1].equalsIgnoreCase("stats")) {
        try {/*from  w  w  w  .  ja v a 2 s .  c  om*/
            long user = status.getUser().getId();
            String whoStats = "";
            if (inp.length >= 3) {
                if (inp[2] != null && !inp[2].equalsIgnoreCase("me")) {
                    User acc = STEMrps.t.showUser(inp[2]);
                    user = acc.getId();
                    whoStats = acc.getScreenName() + " ";
                }
            }
            String tweet = "@" + status.getUser().getScreenName() + " " + whoStats
                    + GameLogic.getStatsString(user);
            STEMrps.t.updateStatus(tweet);

        } catch (Exception ex) {
            Logger.getLogger(MentionListener.class.getName()).log(Level.SEVERE, null, ex);
            return;
        }
    } else {
        try {
            if (status.getUser().getId() == 4741197613L) { //If it is our's?
                return;
            }
            STEMrps.makeSureUsrSetup(status.getUser().getId());
            for (String s : inp) {
                if (STEMrps.getFromString(s) != null) {
                    player = s;
                    break;
                }
            }
            stemrps.GameResult match = STEMrps.playGame(status.getUser().getId(), player);
            String tweet = "@" + status.getUser().getScreenName() + " ";
            if (match == null) {
                tweet += "Something went wrong! Please use r, rock, p, paper, s, or scissors to play!";
            } else if (match.outcome == stemrps.Status.W) {
                tweet += "You (" + match.player.name() + ") won against me (" + match.comp.name() + ")";
            } else if (match.outcome == stemrps.Status.T) {
                tweet += "You (" + match.player.name() + ") tied against me (" + match.comp.name() + ")";
            } else if (match.outcome == stemrps.Status.L) {
                tweet += "You (" + match.player.name() + ") lost against me (" + match.comp.name() + ")";
            }
            tweet += " (Game #" + STEMrps.gamesPlayed() + ")";
            StatusUpdate rt = new StatusUpdate(tweet);
            STEMrps.t.updateStatus(rt);
        } catch (Exception ex) {
            Logger.getLogger(MentionListener.class.getName()).log(Level.SEVERE, null, ex);
            String tweet = "@" + status.getUser().getScreenName() + " Oops, did't catch that. "
                    + LocalDateTime.now();
            StatusUpdate rt = new StatusUpdate(tweet);
            try {
                STEMrps.t.updateStatus(rt);
            } catch (TwitterException ex1) {
                Logger.getLogger(MentionListener.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }
    }
}

From source file:t.twitter.TTwitterModule.java

License:Open Source License

@Kroll.method
public void connect(HashMap args) {
    KrollDict arg = new KrollDict(args);

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(arg.optString("apikey", ""))
            .setOAuthConsumerSecret(arg.optString("apisecret", ""))
            .setOAuthAccessToken(arg.optString("accesstoken", ""))
            .setOAuthAccessTokenSecret(arg.optString("accesssecret", ""));
    AsyncTwitterFactory tf = new AsyncTwitterFactory(cb.build());
    twitter = tf.getInstance();/*from  w w  w .j av a  2  s .co  m*/

    twitter.addListener(new TwitterAdapter() {
        @Override
        public void updatedStatus(Status status) {
            Log.d("Twitter", "text: " + status.getText());
        }

        @Override
        public void searched(QueryResult result) {
            HashMap<String, KrollDict[]> event = new HashMap<String, KrollDict[]>();
            List<Status> tweets = result.getTweets();
            KrollDict[] dList = new KrollDict[tweets.size()];

            // sort tweets
            Collections.sort(tweets, new Comparator<Status>() {
                public int compare(Status o1, Status o2) {

                    if (desc) {
                        if (o2.getId() < o1.getId()) {
                            return 1;
                        } else {
                            return -1;
                        }
                    } else {
                        if (o2.getId() > o1.getId()) {
                            return 1;
                        } else {
                            return -1;
                        }
                    }
                }
            });

            // return tweets to titanium
            int i = 0;
            for (Status tweet : tweets) {
                if (lastID == -1 || lastID < tweet.getId()) {
                    KrollDict d = new KrollDict();
                    d.put("username", tweet.getUser().getScreenName());
                    d.put("userimage", tweet.getUser().getProfileImageURL());
                    d.put("text", tweet.getText());
                    d.put("date", tweet.getCreatedAt());
                    d.put("id", Long.toString(tweet.getId()));
                    dList[i] = d;
                    lastID = tweet.getId();
                    i++;
                }
            }

            KrollDict[] dList2 = new KrollDict[i];

            // shorten array
            System.arraycopy(dList, 0, dList2, 0, i);

            event.put("tweets", dList2);
            success.call(getKrollObject(), event);

            synchronized (LOCK) {
                LOCK.notify();
            }
        }

        @Override
        public void verifiedCredentials(User user) {

            HashMap<String, KrollDict> event = new HashMap<String, KrollDict>();
            KrollDict d = new KrollDict();

            d.put("user_name", user.getName());
            d.put("screen_name", user.getScreenName());
            d.put("image_path", user.getProfileImageURL());
            event.put("user_info", d);
            success.call(getKrollObject(), event);
            synchronized (LOCK) {
                LOCK.notify();
            }
        }

        @Override
        public void onException(TwitterException e, TwitterMethod method) {
            synchronized (LOCK) {
                LOCK.notify();
            }
            Log.e("twitter", "error: " + e.getErrorMessage());
        }
    });
    Log.d("Twitter", "connected");
}

From source file:tweetcrawling.TweetCrawler.java

public ArrayList<String> getValueToWrite(Status status) {

    // Getting the value to be written

    Long tid = status.getId();/*from   w  w  w .  ja  v  a2  s.  c o m*/
    String tweetid = tid.toString();

    ArrayList<String> valueToWrite = new ArrayList<String>();

    User user = status.getUser();
    String screenname = user.getScreenName();
    String name = user.getName();
    String url = getTweetUrl(screenname, tweetid);

    String body = status.getText().replace("\n", " ");

    valueToWrite.add(body.replace(",", " ")); // element: body
    valueToWrite.add(url); // element: id
    valueToWrite.add(screenname); // element: userid
    valueToWrite.add(name); // element: user

    // element: gender
    if (name != null && !name.isEmpty()) {
        valueToWrite.add(getUserGender(name));
    } else if (screenname != null && !screenname.isEmpty()) {
        valueToWrite.add(getUserGender(screenname));
    } else {
        valueToWrite.add("");
    }

    valueToWrite.add(user.getLocation()); // element: location
    valueToWrite.add("" + user.getFollowersCount()); // element: followercount
    valueToWrite.add("" + user.getFriendsCount()); // element: friendscount
    valueToWrite.add("" + user.getStatusesCount()); // element: statuscount

    try {
        List<String> coor = new ArrayList<String>();
        String latitude = "" + status.getGeoLocation().getLatitude();
        String longitude = "" + status.getGeoLocation().getLongitude();
        coor.add(latitude);
        coor.add(longitude);

        if (coor != null && !coor.isEmpty() && coor.size() > 0) {
            valueToWrite.add(coor.get(0)); // element: latitude
            valueToWrite.add(coor.get(1)); // element: longitude
            valueToWrite.add(coor.get(0) + "," + coor.get(1));
        } else {
            valueToWrite.add(null);
            valueToWrite.add(null);
            valueToWrite.add(null);
        }
    } catch (Exception e) {
        valueToWrite.add(null);
        valueToWrite.add(null);
        valueToWrite.add(null);
    }

    try {

        String geoname = status.getPlace().getName();
        String country = status.getPlace().getCountry();

        if (geoname != null) {
            valueToWrite.add(geoname);
        } else {
            valueToWrite.add(null);
        }

        if (country != null) {
            valueToWrite.add(country);
        } else {
            valueToWrite.add(null);
        }

    } catch (Exception e) {
        valueToWrite.add(null);
        valueToWrite.add(null);
    }

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    Date date = status.getCreatedAt();
    valueToWrite.add(dateFormat.format(date)); // element: date
    valueToWrite.add(getDateCrawler()); // element: datecrawler
    valueToWrite.add(status.getInReplyToScreenName()); // element: replyto

    String tooltip = "";
    try {

        String geoname = status.getPlace().getName();
        if (geoname != null) {
            tooltip = "user = " + name + ", geoname = " + geoname;
        }

    } catch (Exception e) {
        tooltip = "";
    }
    valueToWrite.add(tooltip.trim()); // element: tooltip
    valueToWrite.add(SOURCE); // element: source

    return valueToWrite;
}

From source file:tweetcrawling.TweetCrawler.java

public void printTweets(String csvOut) throws IOException, TwitterException {

    for (Status status : getStatuses()) {

        // Getting the value to be written

        Long tid = status.getId();
        String tweetid = tid.toString();

        ArrayList<String> valueToWrite = new ArrayList<String>();

        User user = status.getUser();
        String screenname = user.getScreenName();
        String name = user.getName();
        String url = getTweetUrl(screenname, tweetid);

        valueToWrite.add(url); // element: id
        valueToWrite.add(screenname); // element: userid
        valueToWrite.add(name); // element: user

        // element: gender
        if (name != null && !name.isEmpty()) {
            valueToWrite.add(getUserGender(name));
        } else if (screenname != null && !screenname.isEmpty()) {
            valueToWrite.add(getUserGender(screenname));
        } else {//ww w .  j  a  v a  2s  .c  om
            valueToWrite.add("");
        }

        valueToWrite.add(user.getLocation()); // element: location
        valueToWrite.add("" + user.getFollowersCount()); // element: followercount
        valueToWrite.add("" + user.getFriendsCount()); // element: friendscount
        valueToWrite.add("" + user.getStatusesCount()); // element: statuscount

        try {
            List<String> coor = new ArrayList<String>();
            String latitude = "" + status.getGeoLocation().getLatitude();
            String longitude = "" + status.getGeoLocation().getLongitude();
            coor.add(latitude);
            coor.add(longitude);

            if (coor != null && !coor.isEmpty() && coor.size() > 0) {
                valueToWrite.add(coor.get(0)); // element: latitude
                valueToWrite.add(coor.get(1)); // element: longitude
                valueToWrite.add(coor.get(0) + "," + coor.get(1));
            } else {
                valueToWrite.add(null);
                valueToWrite.add(null);
                valueToWrite.add(null);
            }
        } catch (Exception e) {
            valueToWrite.add(null);
            valueToWrite.add(null);
            valueToWrite.add(null);
        }

        try {

            String geoname = status.getPlace().getName();
            String country = status.getPlace().getCountry();

            if (geoname != null) {
                valueToWrite.add(geoname);
            } else {
                valueToWrite.add(null);
            }

            if (country != null) {
                valueToWrite.add(country);
            } else {
                valueToWrite.add(null);
            }

        } catch (Exception e) {
            valueToWrite.add(null);
            valueToWrite.add(null);
        }

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        Date date = status.getCreatedAt();
        valueToWrite.add(dateFormat.format(date)); // element: date
        valueToWrite.add(getDateCrawler()); // element: datecrawler
        valueToWrite.add(status.getText()); // element: body
        valueToWrite.add(status.getInReplyToScreenName()); // element: replyto

        String tooltip = "";
        try {

            String geoname = status.getPlace().getName();
            if (geoname != null) {
                tooltip = "user = " + name + ", geoname = " + geoname;
            }

        } catch (Exception e) {
            tooltip = "";
        }
        valueToWrite.add(tooltip.trim()); // element: tooltip
        valueToWrite.add(SOURCE); // element: source

        // Write valueToWrite to csv external file

        FileWriter fw = new FileWriter(csvOut, true);
        PrintWriter pw = new PrintWriter(fw);

        String content = "'";

        for (int i = 0; i < valueToWrite.size() - 1; i++) {
            content += valueToWrite.get(i) + "','";
        }

        content += valueToWrite.get(valueToWrite.size()) + "'";

        pw.print(content);

        pw.flush();
        pw.close();
        fw.close();

    }
}

From source file:twitbak.MentionBak.java

License:Open Source License

public void statusToJson(Status status) throws TwitterException, JSONException {
    JSONObject result = new JSONObject();
    User poster = status.getUser();
    result.put("Poster ID", poster.getId());
    result.put("Poster", poster.getScreenName());
    result.put("Poster Name", poster.getName());
    result.put("Created At", status.getCreatedAt().toString());
    result.put("ID", status.getId());
    result.put("Text", status.getText());
    long inReplyToStatusId = status.getInReplyToStatusId();
    if (inReplyToStatusId != -1) {
        result.put("In Reply To Status ID", status.getInReplyToStatusId());
    }/*w w w  .j  a  v  a 2 s.  c o  m*/
    long inReplyToUserID = status.getInReplyToUserId();
    result.put("In Reply To User ID", inReplyToUserID);
    if (inReplyToUserID != -1) {
        result.put("In Reply To Screen Name", status.getInReplyToScreenName());
    }
    boolean isFavorited = status.isFavorited();
    if (isFavorited) {
        result.put("Favorited", status.isFavorited());
    }
    statusArray().put(result);
}

From source file:twitbak.TwitBak.java

License:Open Source License

/**
 * Returns a JSONObject containing user data.
 * @param user/*  w w w. j a v a  2  s  . c o  m*/
 * @return
 * @throws TwitterException
 * @throws JSONException
 */
//TODO - should be void to match other Bak classes 
static JSONObject userToJson(User user) throws TwitterException, JSONException {
    JSONObject result = new JSONObject();
    JSONObject userData = new JSONObject();
    userData.put("ID", user.getId());
    userData.put("Screen Name", user.getScreenName());
    userData.put("Name", user.getName());
    userData.put("Description", user.getDescription());
    userData.put("Profile Image URL", user.getProfileImageURL());
    userData.put("URL", user.getURL());
    userData.put("Protected", user.isProtected());
    userData.put("Followers", user.getFollowersCount());
    userData.put("Created At", user.getCreatedAt().toString());
    userData.put("Favorites", user.getFavouritesCount());
    userData.put("Friends", user.getFriendsCount());
    userData.put("Location", user.getLocation());
    userData.put("Statuses", user.getStatusesCount());
    userData.put("Profile Background Color", user.getProfileBackgroundColor());
    userData.put("Profile Background Image URL", user.getProfileBackgroundImageUrl());
    userData.put("Profile Sidebar Border Color", user.getProfileSidebarBorderColor());
    userData.put("Profile Sidebar Fill Color", user.getProfileSidebarFillColor());
    userData.put("Profile Text Color", user.getProfileTextColor());
    userData.put("Time Zone", user.getTimeZone());
    result.put("User data", userData);
    return result;
}

From source file:twitfeedbot.BotherSomeoneServlet.java

License:Open Source License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Twitter twit;// www .j  a  va  2s  .  com
    StringBuilder builder = new StringBuilder();
    User victim = null;
    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:twitter.crawler.TwitterCrawler.java

public static void main(String[] args) {
    try {/* ww  w  .  j a  v a2  s .c  o  m*/
        // Authorise the library
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setOAuthConsumerKey("AhoydO8uSe4v8NEq7j2ISGFlq");
        cb.setOAuthConsumerSecret("ptKEYwq3G9vpFkqAhvwFLSWFcBW8U1SfqycECwK4cH6wThVba6");
        cb.setOAuthAccessToken("778240255577194496-taafqDIHebrg972oxT5kTqcNd3Uojod");
        cb.setOAuthAccessTokenSecret("DMRmeRahnLJRvCBIGQGTaTzE6Pr3PAZMgMsfWIT5ue3PD");
        Twitter twitter = new TwitterFactory(cb.build()).getInstance();
        User user = twitter.verifyCredentials(); // Get main user

        long cursor = -1;

        // Print user profile
        System.out.println("@" + user.getScreenName());
        System.out.println(user.getId());
        System.out.println(user.getProfileImageURL());
        System.out.println(user.getFriendsCount() + " friends.");
        System.out.println("-------");

        // Print Home Timeline
        List<Status> statuses = twitter.getHomeTimeline();
        System.out.println("Showing @" + user.getScreenName() + "'s home timeline.");

        for (Status status : statuses) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
        }

        //Print followers
        System.out.println("-------");
        System.out.println("Showing Follwers:");

        PagableResponseList<User> followers;

        //do
        //{
        followers = twitter.getFollowersList(user.getScreenName(), cursor);

        for (User follower : followers) {
            System.out.println("@" + follower.getScreenName());
        }
        //}
        //while ((cursor = followers.getNextCursor())!=-1);

        //Print follwees

        System.out.println("-------");
        System.out.println("Showing Followees:");

        PagableResponseList<User> followees;

        do {
            followees = twitter.getFriendsList(user.getScreenName(), cursor);

            for (User followee : followees) {
                System.out.println("@" + followee.getScreenName());
            }
        } while ((cursor = followees.getNextCursor()) != -1);
    }

    catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    }
}