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:gohai.simpletweet.SimpleTweet.java

License:Apache License

/**
 *  Tweet an image// ww  w  . j  a v a 2 s . com
 *  @param img PImage instance to attach
 *  @param update twitter4j StatusUpdate instance to use
 *  @return partial URL of the tweet (e.g. "mrgohai/status/841086396194529280")
 */
public String tweetImage(PImage img, StatusUpdate update) {
    File temp;

    // write image into temporary file that gets deleted when the VM exits
    try {
        // make sure one pixel is somewhat transparent
        // to prevent Twitter from recompressing the image
        // to JPEG
        PImage copy = new PImage(img.width, img.height, PImage.ARGB);
        copy.copy(img, 0, 0, img.width, img.height, 0, 0, img.width, img.height);
        copy.set(0, 0, 254 << 24 | (copy.get(0, 0) & 0xffffff));
        temp = File.createTempFile("out", ".png");
        temp.deleteOnExit();
        copy.save(temp.getCanonicalPath());
    } catch (IOException e) {
        throw new RuntimeException("Error exporting image to PNG");
    }

    try {
        update.setMedia(temp);
        Status status = twitter.updateStatus(update);
        temp.delete();

        User user = status.getUser();
        return user.getScreenName() + "/status/" + status.getId();
    } catch (TwitterException e) {
        System.err.println(e.getMessage());
        throw new RuntimeException("Error posting tweet");
    }
}

From source file:h2weibo.controllers.CallbackServlet.java

License:Open Source License

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpServletRouter r = new HttpServletRouter(request);
    r.setPattern("/:type");

    if (request.getParameter("denied") != null) {
        response.sendRedirect("/");
        return;/*w  w  w. j a  va 2  s  .  c o m*/
    }

    HttpSession session = request.getSession(false);
    String loginUser = (String) session.getAttribute(Keys.SESSION_LOGIN_USER);
    String token = (String) session.getAttribute(Keys.SESSION_TOKEN);
    String tokenSecret = (String) session.getAttribute(Keys.SESSION_TOKEN_SECRET);
    String oauthVerifier = request.getParameter("oauth_verifier");

    DBHelper helper = (DBHelper) request.getAttribute(Keys.REQUEST_DB_HELPER);

    if (r.is(":type", "weibo")) {
        try {
            Weibo weibo = new Weibo();

            AccessToken accessToken = weibo.getOAuthAccessToken(token, tokenSecret, oauthVerifier);
            if (accessToken != null) {
                T2WUser tid = helper.findOneByUser(loginUser);

                if (tid.getToken() == null) { // send for the first time
                    session.setAttribute(Keys.SESSION_PROMPT_TWEET,
                            "You are ready to go! Do you want to tweet about this service and share it with your friends?");
                }

                tid.setToken(accessToken.getToken());
                tid.setTokenSecret(accessToken.getTokenSecret());
                helper.saveUser(tid);
            } else {
                log.error("Can't auth " + loginUser + " for Weibo. " + request.getQueryString());
            }
        } catch (WeiboException e) {
            log.error("Weibo Exception", e);
            throw new RuntimeException(e);
        }
    } else if (r.is(":type", "twitter")) {
        try {
            TwitterFactory factory = new TwitterFactory();
            Twitter t = factory.getInstance();

            twitter4j.auth.RequestToken req = (RequestToken) session.getAttribute(Keys.SESSION_REQUEST_TOKEN);
            twitter4j.auth.AccessToken accessToken = t.getOAuthAccessToken(req, oauthVerifier);
            session.removeAttribute(Keys.SESSION_REQUEST_TOKEN);

            if (accessToken != null) {
                t.setOAuthAccessToken(accessToken);
                User user = t.verifyCredentials();
                loginUser = user.getScreenName();

                T2WUser tid = helper.findOneByUser(loginUser);

                if (tid.getTwitterToken() == null) {
                    // save latest id for the first time. sync from that tweet
                    ResponseList<Status> tl = t.getUserTimeline();
                    if (tl.size() > 0) {
                        Status s = tl.get(0);
                        tid.setLatestId(s.getId());
                    }
                }

                tid.setTwitterToken(accessToken.getToken());
                tid.setTwitterTokenSecret(accessToken.getTokenSecret());
                helper.saveUser(tid);

                session.setAttribute(Keys.SESSION_LOGIN_USER, loginUser);
            }
        } catch (TwitterException e) {
            log.error("Twitter Exception", e);
            throw new RuntimeException(e);
        }
    }

    String requestUrl = (String) session.getAttribute(Keys.SESSION_REQUEST_URL);
    if (requestUrl != null) {
        session.removeAttribute(Keys.SESSION_REQUEST_URL);
        response.sendRedirect(requestUrl);
    } else {
        response.sendRedirect("/u/" + loginUser);
    }
}

From source file:h2weibo.controllers.UserServlet.java

License:Open Source License

@Override
protected Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context ctx) {
    HttpServletRouter r = new HttpServletRouter(request);
    r.setPattern("/:id");

    HttpSession session = request.getSession(false);

    DBHelper helper = (DBHelper) request.getAttribute(Keys.REQUEST_DB_HELPER);

    // Service limit
    String uId = r.get(":id");
    if (!helper.isUser(uId) && helper.getUserCount() > 50) {
        return getTemplate("full.vm");
    }//  w  ww  . j  a v a  2  s. c  o  m

    T2WUser user = helper.findOneByUser(uId);
    if (r.has(":id")) {
        log.info("Displaying user info for @" + uId);

        ctx.put("user_id", uId);
        ctx.put("user", helper.findOneByUser(uId));

        try {
            weibo4j.User weiboUser = (weibo4j.User) session.getAttribute(Keys.SESSION_WEIBO_USER);
            if (weiboUser == null) {
                Weibo w = new Weibo();
                w.setToken(user.getToken(), user.getTokenSecret());
                weiboUser = w.verifyCredentials();

                session.setAttribute(Keys.SESSION_WEIBO_USER, weiboUser);
            }

            ctx.put("weibo_user", weiboUser.getScreenName());
            ctx.put("weibo_user_image", weiboUser.getProfileImageURL().toString());
            ctx.put("weibo_login", 1);

            // save weiboUser ID mapping
            helper.setWeiboId(user.getUserId(), weiboUser.getScreenName());
        } catch (Exception e) {
            // 401 = not logged in
            if (e instanceof WeiboException && ((WeiboException) e).getStatusCode() != 401) {
                e.printStackTrace();
            }
        }

        try {
            twitter4j.User twitterUser = (twitter4j.User) session.getAttribute(Keys.SESSION_TWITTER_USER);
            if (twitterUser == null) {
                TwitterFactory factory = new TwitterFactory();
                Twitter t = factory.getInstance();
                t.setOAuthAccessToken(new AccessToken(user.getTwitterToken(), user.getTwitterTokenSecret()));

                twitterUser = t.verifyCredentials();
                session.setAttribute(Keys.SESSION_TWITTER_USER, twitterUser);
            }

            ctx.put("twitter_user", twitterUser.getScreenName());
            ctx.put("twitter_user_image", twitterUser.getProfileImageURL().toString());
            ctx.put("twitter_login", 1);
        } catch (Exception e) {
            // 401 = not logged in
            if (e instanceof TwitterException && ((TwitterException) e).getStatusCode() != 401) {
                e.printStackTrace();
            }
        }
    }

    Object message = session.getAttribute(Keys.SESSION_MESSAGE);
    if (message != null) {
        ctx.put("message", message);
        session.removeAttribute(Keys.SESSION_MESSAGE);
    }

    Object prompt = session.getAttribute(Keys.SESSION_PROMPT_TWEET);
    if (prompt != null) {
        ctx.put("prompt", prompt);
        session.removeAttribute(Keys.SESSION_PROMPT_TWEET);
    }

    return getTemplate("user.vm");
}

From source file:info.maslowis.twitterripper.util.Util.java

License:Open Source License

/**
 * Returns a representation the user as string
 *
 * @return a representation the user as string in format <em>User{id=, name='', screenName='', location='', description=''}</em>
 *///  w w  w. j  a va2  s .com
public static String toString(final User user) {
    return "User{id=" + user.getId() + ", name='" + user.getName() + "', screenName='" + user.getScreenName()
            + "', location='" + user.getLocation() + "', description='" + user.getDescription() + "'}";
}

From source file:io.druid.examples.twitter.TwitterSpritzerFirehoseFactory.java

License:Apache License

@Override
public Firehose connect(InputRowParser parser) throws IOException {
    final ConnectionLifeCycleListener connectionLifeCycleListener = new ConnectionLifeCycleListener() {
        @Override//from  w  w w .jav  a  2 s .  co  m
        public void onConnect() {
            log.info("Connected_to_Twitter");
        }

        @Override
        public void onDisconnect() {
            log.info("Disconnect_from_Twitter");
        }

        /**
         * called before thread gets cleaned up
         */
        @Override
        public void onCleanUp() {
            log.info("Cleanup_twitter_stream");
        }
    }; // ConnectionLifeCycleListener

    final TwitterStream twitterStream;
    final StatusListener statusListener;
    final int QUEUE_SIZE = 2000;
    /** This queue is used to move twitter events from the twitter4j thread to the druid ingest thread.   */
    final BlockingQueue<Status> queue = new ArrayBlockingQueue<Status>(QUEUE_SIZE);
    final long startMsec = System.currentTimeMillis();

    //
    //   set up Twitter Spritzer
    //
    twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addConnectionLifeCycleListener(connectionLifeCycleListener);
    statusListener = new StatusListener() { // This is what really gets called to deliver stuff from twitter4j
        @Override
        public void onStatus(Status status) {
            // time to stop?
            if (Thread.currentThread().isInterrupted()) {
                throw new RuntimeException("Interrupted, time to stop");
            }
            try {
                boolean success = queue.offer(status, 15L, TimeUnit.SECONDS);
                if (!success) {
                    log.warn("queue too slow!");
                }
            } catch (InterruptedException e) {
                throw new RuntimeException("InterruptedException", e);
            }
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            //log.info("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            // This notice will be sent each time a limited stream becomes unlimited.
            // If this number is high and or rapidly increasing, it is an indication that your predicate is too broad, and you should consider a predicate with higher selectivity.
            log.warn("Got track limitation notice:" + numberOfLimitedStatuses);
        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
            //log.info("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
        }

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

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

    twitterStream.addListener(statusListener);
    twitterStream.sample(); // creates a generic StatusStream
    log.info("returned from sample()");

    return new Firehose() {

        private final Runnable doNothingRunnable = new Runnable() {
            public void run() {
            }
        };

        private long rowCount = 0L;
        private boolean waitIfmax = (getMaxEventCount() < 0L);
        private final Map<String, Object> theMap = new TreeMap<>();
        // DIY json parsing // private final ObjectMapper omapper = new ObjectMapper();

        private boolean maxTimeReached() {
            if (getMaxRunMinutes() <= 0) {
                return false;
            } else {
                return (System.currentTimeMillis() - startMsec) / 60000L >= getMaxRunMinutes();
            }
        }

        private boolean maxCountReached() {
            return getMaxEventCount() >= 0 && rowCount >= getMaxEventCount();
        }

        @Override
        public boolean hasMore() {
            if (maxCountReached() || maxTimeReached()) {
                return waitIfmax;
            } else {
                return true;
            }
        }

        @Override
        public InputRow nextRow() {
            // Interrupted to stop?
            if (Thread.currentThread().isInterrupted()) {
                throw new RuntimeException("Interrupted, time to stop");
            }

            // all done?
            if (maxCountReached() || maxTimeReached()) {
                if (waitIfmax) {
                    // sleep a long time instead of terminating
                    try {
                        log.info("reached limit, sleeping a long time...");
                        sleep(2000000000L);
                    } catch (InterruptedException e) {
                        throw new RuntimeException("InterruptedException", e);
                    }
                } else {
                    // allow this event through, and the next hasMore() call will be false
                }
            }
            if (++rowCount % 1000 == 0) {
                log.info("nextRow() has returned %,d InputRows", rowCount);
            }

            Status status;
            try {
                status = queue.take();
            } catch (InterruptedException e) {
                throw new RuntimeException("InterruptedException", e);
            }

            theMap.clear();

            HashtagEntity[] hts = status.getHashtagEntities();
            String text = status.getText();
            theMap.put("text", (null == text) ? "" : text);
            theMap.put("htags", (hts.length > 0)
                    ? Lists.transform(Arrays.asList(hts), new Function<HashtagEntity, String>() {
                        @Nullable
                        @Override
                        public String apply(HashtagEntity input) {
                            return input.getText();
                        }
                    })
                    : ImmutableList.<String>of());

            long[] lcontrobutors = status.getContributors();
            List<String> contributors = new ArrayList<>();
            for (long contrib : lcontrobutors) {
                contributors.add(String.format("%d", contrib));
            }
            theMap.put("contributors", contributors);

            GeoLocation geoLocation = status.getGeoLocation();
            if (null != geoLocation) {
                double lat = status.getGeoLocation().getLatitude();
                double lon = status.getGeoLocation().getLongitude();
                theMap.put("lat", lat);
                theMap.put("lon", lon);
            } else {
                theMap.put("lat", null);
                theMap.put("lon", null);
            }

            if (status.getSource() != null) {
                Matcher m = sourcePattern.matcher(status.getSource());
                theMap.put("source", m.find() ? m.group(1) : status.getSource());
            }

            theMap.put("retweet", status.isRetweet());

            if (status.isRetweet()) {
                Status original = status.getRetweetedStatus();
                theMap.put("retweet_count", original.getRetweetCount());

                User originator = original.getUser();
                theMap.put("originator_screen_name", originator != null ? originator.getScreenName() : "");
                theMap.put("originator_follower_count",
                        originator != null ? originator.getFollowersCount() : "");
                theMap.put("originator_friends_count", originator != null ? originator.getFriendsCount() : "");
                theMap.put("originator_verified", originator != null ? originator.isVerified() : "");
            }

            User user = status.getUser();
            final boolean hasUser = (null != user);
            theMap.put("follower_count", hasUser ? user.getFollowersCount() : 0);
            theMap.put("friends_count", hasUser ? user.getFriendsCount() : 0);
            theMap.put("lang", hasUser ? user.getLang() : "");
            theMap.put("utc_offset", hasUser ? user.getUtcOffset() : -1); // resolution in seconds, -1 if not available?
            theMap.put("statuses_count", hasUser ? user.getStatusesCount() : 0);
            theMap.put("user_id", hasUser ? String.format("%d", user.getId()) : "");
            theMap.put("screen_name", hasUser ? user.getScreenName() : "");
            theMap.put("location", hasUser ? user.getLocation() : "");
            theMap.put("verified", hasUser ? user.isVerified() : "");

            theMap.put("ts", status.getCreatedAt().getTime());

            List<String> dimensions = Lists.newArrayList(theMap.keySet());

            return new MapBasedInputRow(status.getCreatedAt().getTime(), dimensions, theMap);
        }

        @Override
        public Runnable commit() {
            // ephemera in, ephemera out.
            return doNothingRunnable; // reuse the same object each time
        }

        @Override
        public void close() throws IOException {
            log.info("CLOSE twitterstream");
            twitterStream.shutdown(); // invokes twitterStream.cleanUp()
        }
    };
}

From source file:it.baywaylabs.jumpersumo.twitter.TwitterListener.java

License:Open Source License

/**
 * This method is called when invoke <b>execute()</b>.<br />
 * Do not invoke manually. Use: <i>new TwitterListener().execute("");</i>
 *
 * @param params//from w  ww  . j a  v  a2 s .  c o  m
 */
@Override
protected List<String> doInBackground(String... params) {

    Intelligence ai = new Intelligence();

    try {

        User user = twitter.verifyCredentials();
        Paging paging;
        if (idLastTwit != 0)
            paging = new Paging(idLastTwit + 1);
        else
            paging = new Paging();
        paging.count(100);
        statuses = twitter.getMentionsTimeline(paging);

        if (statuses.size() != 0 && statuses != null) {

            Log.d(TAG, "Showing @" + user.getScreenName() + "'s mentions:");
            Log.d(TAG, statuses.get(0).getText() + "-- ID: " + statuses.get(0).getId());

            if (!"".equals(statuses.get(0).getText()) && licenses.size() == 0) {

                extractCommand(ai, statuses);
                Log.d(TAG, "Non ho licenze attive!");

            } else if (!"".equals(statuses.get(0).getText()) && licenses.size() > 0
                    && f.boolContainsIgnoreCase(licenses, String.valueOf(statuses.get(0).getUser().getId()))) {

                extractCommand(ai, statuses);
                Log.i(TAG, "Seguo la lista delle licenze: " + licenses.toString());

            } else {
                publishProgress(false);
            }

            if (deviceController != null) {

                Random r = new Random();
                Interpreter interp = new Interpreter(deviceController);

                for (int i = 0; i < execute.size(); i++) {
                    Log.d(TAG, "Seguenza istruzioni rilevate: " + execute.toString());

                    if (execute.size() >= 1 && "EXECUTE".equals(execute.get(i))
                            && f.getUrls(statuses.get(0).getText()).size() != 0) {

                        String url = statuses.get(0).getURLEntities()[0].getExpandedURL();
                        // String url = f.getUrls(statuses.get(0).getText()).get(0);
                        File folder = new File(Constants.DIR_ROBOT);
                        Log.d(TAG, "URL Expanded: " + url);

                        if (downloadFileUrl(url, folder)) {
                            FileFilter ff = new FileFilter();
                            File[] list = folder.listFiles(ff);
                            Log.e(TAG, "Lista file: " + list.length);
                            if (list != null && list.length >= 1) {

                                if (list[0].getName().endsWith(".csv") || list[0].getName().endsWith(".txt")) {
                                    String commandsList = "";
                                    try {
                                        commandsList = f.getStringFromFile(list[0].getPath());
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    Log.d(TAG, "Lista comandi: " + commandsList);
                                    interp.doListCommands(commandsList);
                                    list[0].delete();

                                    if (i == execute.size() - 1) {
                                        try {
                                            StatusUpdate reply = new StatusUpdate(
                                                    ai.actionAnswer(execute.get(i)).get(
                                                            r.nextInt(ai.actionAnswer(execute.get(i)).size()))
                                                            + "@" + statuses.get(0).getUser().getScreenName());
                                            reply.setInReplyToStatusId(statuses.get(0).getId());
                                            twitter.updateStatus(reply);
                                        } catch (TwitterException te) {
                                            Log.e(TAG, "Twitter Post Error: " + te.getMessage());
                                        }
                                    }
                                }

                            }

                        }

                    } else if (execute.size() >= 1 && "PHOTO".equals(execute.get(i))) {
                        // Download immagine e post nel tweet
                        if (interp.doCommand(execute.get(i)) == 0) {

                            String result = FTPDownloadFile(ip_host, 21, "anonymous", "", context);

                            if (i == execute.size() - 1 && !"".equals(result)) {
                                try {
                                    StatusUpdate reply = new StatusUpdate(ai.actionAnswer(execute.get(i))
                                            .get(r.nextInt(ai.actionAnswer(execute.get(i)).size())) + "@"
                                            + statuses.get(0).getUser().getScreenName());
                                    reply.setInReplyToStatusId(statuses.get(0).getId());
                                    File image = new File(Constants.DIR_ROBOT_IMG + "/" + result);
                                    Log.d(TAG, "Nome File immagine: " + image.getPath());
                                    reply.media(image);
                                    twitter.updateStatus(reply);
                                    image.delete();
                                } catch (TwitterException te) {
                                    Log.e(TAG, "Twitter Post Error: " + te.getMessage());
                                }
                            }
                        }
                    } else if (execute.size() >= 1 && !"PHOTO".equals(execute.get(i))
                            && !"EXECUTE".equals(execute.get(i))) {

                        if (interp.doCommand(execute.get(i)) == 0) {

                            if (i == execute.size() - 1) {
                                try {
                                    StatusUpdate reply = new StatusUpdate(ai.actionAnswer(execute.get(i))
                                            .get(r.nextInt(ai.actionAnswer(execute.get(i)).size())) + "@"
                                            + statuses.get(0).getUser().getScreenName());
                                    reply.setInReplyToStatusId(statuses.get(0).getId());
                                    twitter.updateStatus(reply);
                                } catch (TwitterException te) {
                                    Log.e(TAG, "Twitter Post Error: " + te.getMessage());
                                }
                            }
                        }
                    }
                }

            }
        }

        Log.d(TAG, "ready exit");

    } catch (TwitterException te) {
        te.printStackTrace();
        Log.e(TAG, "Failed to get timeline: " + te.getMessage());
    }

    return execute;
}

From source file:it.greenvulcano.gvesb.social.twitter.directcall.TwitterOperationGetUserTimeline.java

License:Open Source License

@Override
public void execute(SocialAdapterAccount account) throws SocialAdapterException {
    try {//from ww  w . j  av  a2  s  .  c o m
        Twitter twitter = (Twitter) account.getProxyObject();
        Paging paging = new Paging();
        if ((sinceId != null) && !"".equals(sinceId)) {
            paging.setSinceId(Long.parseLong(sinceId));
        }
        if ((maxId != null) && !"".equals(maxId)) {
            paging.setMaxId(Long.parseLong(maxId));
        }
        if ((count != null) && !"".equals(count)) {
            paging.setCount(Integer.parseInt(count));
        }
        if ((userId == null) || "".equals(userId)) {
            dataUser = twitter.getScreenName();
            dataUserId = String.valueOf(twitter.getId());
            statusList = twitter.getUserTimeline(paging);
        } else {
            User user = null;
            try {
                long id = Long.parseLong(userId);
                user = twitter.showUser(id);
                statusList = twitter.getUserTimeline(id, paging);
            } catch (NumberFormatException exc) {
                user = twitter.showUser(userId);
                statusList = twitter.getUserTimeline(userId, paging);
            }
            dataUser = user.getScreenName();
            dataUserId = String.valueOf(user.getId());
        }
    } catch (NumberFormatException exc) {
        logger.error("Call to TwitterOperationGetUserTimeline failed. Check userId[" + userId + "], sinceId["
                + sinceId + "], maxId[" + maxId + "] and count[" + count + "] format.", exc);
        throw new SocialAdapterException("Call to TwitterOperationGetUserTimeline failed. Check followingId["
                + userId + "], sinceId[" + sinceId + "], maxId[" + maxId + "] and count[" + count + "] format.",
                exc);
    } catch (TwitterException exc) {
        logger.error("Call to TwitterOperationGetUserTimeline followingId[" + userId + "], sinceId[" + sinceId
                + "], maxId[" + maxId + "] and count[" + count + "] failed.", exc);
        throw new SocialAdapterException("Call to TwitterOperationGetUserTimeline followingId[" + userId
                + "], sinceId[" + sinceId + "], maxId[" + maxId + "] and count[" + count + "] failed.", exc);
    }
}

From source file:Jimbo.Cheerlights.TweetListener.java

License:Open Source License

private static String userText(User u) {
    return u.getName() + " (@" + u.getScreenName() + ")";
}

From source file:jp.xxxxxxxx.l3fish.twnyaan.controller.OAuthController.java

License:Open Source License

@FXML
private void printScreenName(ActionEvent event) {
    User user = userService.getUser();
    if (user == null) {
        System.err.println(ErrorCode.UNAUTHORIZED);
    } else {/*  w w w  . j av  a  2 s.  co  m*/
        System.out.println(user.getScreenName());
    }
}

From source file:kerguelenpetrel.FriendSomeoneServlet.java

License:Apache License

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    User friend = null;
    resp.setContentType("text/plain; charset=UTF-8");
    try {/* www  .  j a va 2 s.co  m*/
        //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());
    }
}