Example usage for twitter4j Twitter getUserTimeline

List of usage examples for twitter4j Twitter getUserTimeline

Introduction

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

Prototype

ResponseList<Status> getUserTimeline(String screenName) throws TwitterException;

Source Link

Document

Returns the 20 most recent statuses posted from the authenticating user.

Usage

From source file:com.ikungolf.java.javatwitter.GetUserTimeline.java

/**
 * Usage: java twitter4j.examples.timeline.GetUserTimeline
 *
 * @param args String[]//from  w w  w .  ja v a  2s  . c  o  m
 */
public static void main(String[] args) {
    // gets Twitter instance with default credentials
    Twitter twitter = new TwitterFactory().getInstance();
    try {
        List<Status> statuses;
        String user;
        //            if (args.length == 1) {
        //                user = args[0];
        user = "WebUpd8";
        statuses = twitter.getUserTimeline(user);
        //            } else {
        //                user = twitter.verifyCredentials().getScreenName();
        //                statuses = twitter.getUserTimeline();
        //            }
        System.out.println("Showing @" + user + "'s user timeline.");
        for (Status status : statuses) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
        }
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:com.industrialtsi.mylyn.twitter.persistor.TwitterPersistor.java

License:Open Source License

@Override
public List<String> findTasks(TaskRepository repository, IndustrialQueryParams criteria)
        throws SQLException, CoreException {
    Twitter t = getTwitter(repository);

    List<String> result = new ArrayList<String>();
    try {/*ww w  . j ava 2  s  . co m*/
        for (String user : criteria.getOwnerOrEmpty()) {
            List<twitter4j.Status> timeline;
            timeline = t.getUserTimeline(getScreenName(user));
            for (twitter4j.Status s : timeline) {
                if (matches(s, criteria))
                    result.add(Long.toString(s.getId()));
            }
        }
        return result;
    } catch (TwitterException e) {
        IStatus status = CoreLogger.createStatus(IStatus.ERROR, e);
        throw new CoreException(status);
    }
}

From source file:com.wavemaker.runtime.ws.TwitterFeedService.java

License:Open Source License

/**
 * Reads from the InputStream of the specified URL and builds the feed object from the returned XML.
 * //from   w w w  .ja  v a 2s  .co m
 * @param screenId users screen Id
 * @return A feed object.
 */
@ExposeToClient
public Feed getFeed(String screenId) {
    try {
        Twitter twitter = getTwitter();
        User user = twitter.showUser(screenId);
        if (user == null) {
            logger.debug("No user present with the screen name [" + screenId + "]");
            throw new WMRuntimeException("No user present with the screen name [" + screenId + "]");
        }
        if (user.isProtected()) {
            logger.debug("Tweets for the user with the screen name [" + screenId + "] are protected");
            throw new WMRuntimeException(
                    "Tweets for the user with the screen name [" + screenId + "] are protected");
        }
        ResponseList<Status> tweetStatus = twitter.getUserTimeline(screenId);
        return FeedBuilder.getFeed(screenId, tweetStatus);
    } catch (TwitterException e) {
        logger.warn("Cannot get the twitter feed for the user [" + screenId + "]", e);
        throw new WMRuntimeException(e);
    }
}

From source file:h2weibo.Twitter2Weibo.java

License:Open Source License

public void syncTwitter(String userId) {
    T2WUser user = helper.findOneByUser(userId);

    weibo.setToken(user.getToken(), user.getTokenSecret());

    Twitter twitter = new TwitterFactory().getInstance();
    if (user.getTwitterToken() != null) {
        twitter.setOAuthAccessToken(new AccessToken(user.getTwitterToken(), user.getTwitterTokenSecret()));
        log.debug(String.format("Using OAuth for %s", user.getUserId()));
    }//from ww w . ja v  a 2s. c  o m

    StatusFilters filters = new StatusFilters();
    filters.use(new NoSyncFilter()); // should be used first
    filters.use(new TcoStatusFilter()).use(new URLStatusFilter()).use(new TagStatusFilter())
            .use(new FlickrImageFilter());

    NoMentionFilter mentionFilter = new NoMentionFilter();
    UserMappingFilter mappingFilter = new UserMappingFilter(helper);

    if (!user.ready()) {
        log.debug(String.format("Skipping @%s ...", user.getUserId()));
        return;
    }

    // gets Twitter instance with default credentials
    String screenName = user.getUserId();
    long latestId = user.getLatestId();

    log.debug(String.format("Checking @%s's timeline, latest ID = %d.", userId, latestId));

    try {
        if (latestId == 0) {
            List<Status> statuses = twitter.getUserTimeline(screenName);
            if (statuses.size() > 0) {
                user.setLatestId(statuses.get(0).getId()); // Record latestId, and sync next time
            }
            log.info(String.format("First time use for @%s. Set latest ID to %d.", userId, latestId));
        } else {
            Paging paging = new Paging(latestId);
            List<Status> statuses = twitter.getUserTimeline(screenName, paging);

            // sync from the oldest one
            for (int i = statuses.size() - 1; i >= 0; i--) {
                Status status = statuses.get(i);

                if (status.getId() < user.getLatestId())
                    continue; // safe keeper

                String name = status.getUser().getScreenName();
                String statusText = status.getText();
                log.info(String.format("%s - %s", name, statusText));
                try {
                    if (status.isRetweet()) {
                        if (user.isDropRetweets()) {
                            user.setLatestId(status.getId());
                            log.debug("Skipped " + statusText + " because status is a retweet.");
                            continue;
                        } else {
                            filters.remove(mentionFilter);
                            filters.use(mappingFilter);
                        }
                    } else {
                        if (user.isDropMentions()) {
                            filters.remove(mappingFilter);
                            filters.use(mentionFilter);
                        } else {
                            filters.remove(mentionFilter);
                            filters.use(mappingFilter);
                        }
                    }

                    statusText = filters.filter(statusText);
                    if (statusText == null) {
                        user.setLatestId(status.getId());
                        log.info(String.format("Skipped %s because of the filter.", statusText));
                        continue;
                    }

                    if (!user.isNoImage()) {
                        // add twitter images to status text
                        MediaEntity[] mediaEntities = status.getMediaEntities();
                        if (mediaEntities != null) {
                            for (MediaEntity entity : mediaEntities) {
                                statusText += " " + entity.getMediaURL();
                            }
                            log.info("with media url: " + statusText);
                        }

                        StatusImageExtractor ex = new StatusImageExtractor();
                        StringBuffer buf = new StringBuffer(statusText);
                        byte[] image = ex.extract(buf);
                        if (image != null) {
                            user.setLatestId(status.getId());
                            try {
                                statusText = buf.toString(); // with image urls removed
                                weibo.uploadStatus(statusText, new ImageItem(image));
                                log.info(String.format("@%s - %s sent with image.", name, statusText));
                            } catch (WeiboException e) {
                                log.error("Faile to update image.", e);
                            }
                            continue;
                        }
                    }

                    GeoLocation location = status.getGeoLocation();
                    if (user.isWithGeo() && location != null) {
                        weibo.updateStatus(statusText, location.getLatitude(), location.getLongitude());
                        log.info(String.format("@%s - %s sent with geo locations.", name, statusText));
                    } else {
                        weibo.updateStatus(statusText);
                        log.info(String.format("@%s - %s sent.", name, statusText));
                    }
                } catch (WeiboException e) {
                    if (e.getStatusCode() != 400) { // resending same tweet
                        log.error("Failed to update Weibo", e);
                        break;
                    } else {
                        log.error("Sending same message", e);
                    }
                }
                log.info(String.format("Sent: by %s - %s", name, statusText));
                user.setLatestId(status.getId());
            }
        }
        helper.saveUser(user);
    } catch (Exception e) {
        if (!(e instanceof TwitterException)) {
            log.error("Failed to update.", e);
        }
    }
}

From source file:info.usbo.skypetwitter.Run.java

License:Apache License

public static void main(String[] args) throws SkypeException, IOException {
    System.out.println("Working Directory = " + System.getProperty("user.dir"));
    Properties props = new Properties();
    loadProperties(props, "twitter4j.properties");
    loadProperties(props, "skype.properties");
    loadProperties(props, "app.properties");
    String chat_group_id = props.getProperty("skype.chat_group_id");
    String twitter_user_id = props.getProperty("twitter.user");
    data_dir = props.getProperty("data.dir");
    Integer twitter_timeout = Integer.parseInt(props.getProperty("twitter.timeout"));
    System.out.println("Twitter user: " + twitter_user_id);
    System.out.println("Twitter timeout: " + twitter_timeout);
    if ("".equals(twitter_user_id)) {
        return;//ww w. j  a va  2s.c  om
    }
    if (load_file() == 0) {
        System.out.println("File not found");
        return;
    }
    while (true) {
        bChanged = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
        System.out.println("Looking at " + sdf.format(Calendar.getInstance().getTime()));
        Chat ch = Skype.chat(chat_group_id);
        Twitter twitter = new TwitterFactory().getInstance();
        try {
            List<Status> statuses;
            statuses = twitter.getUserTimeline(twitter_user_id);
            String sText;
            for (Status status : statuses) {
                Date d = status.getCreatedAt();
                //  ?
                Calendar cal = Calendar.getInstance();
                cal.setTime(d);
                cal.add(Calendar.HOUR_OF_DAY, 7);
                d = cal.getTime();
                sText = "@" + status.getUser().getScreenName() + "  " + sdf.format(d)
                        + " ( https://twitter.com/" + twitter_user_id + "/status/" + status.getId() + " ): \r\n"
                        + status.getText() + "\r\n***";
                for (URLEntity e : status.getURLEntities()) {
                    sText = sText.replaceAll(e.getURL(), e.getExpandedURL());
                }
                for (MediaEntity e : status.getMediaEntities()) {
                    sText = sText.replaceAll(e.getURL(), e.getMediaURL());
                }
                if (twitter_ids.indexOf(status.getId()) == -1) {
                    System.out.println(sText);
                    ch.send(sText);
                    twitter_ids.add(status.getId());
                    bChanged = 1;
                }
            }
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to get timeline: " + te.getMessage());
            // System.exit(-1);
        } catch (SkypeException ex) {
            ex.printStackTrace();
            System.out.println("Failed to send message: " + ex.getMessage());
        }

        // VK
        try {
            vk();
            for (VK v : vk) {
                if (vk_ids.indexOf(v.getId()) == -1) {
                    Date d = v.getDate();
                    //  ?
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(d);
                    cal.add(Calendar.HOUR_OF_DAY, 7);
                    d = cal.getTime();
                    String sText = "@Depersonilized (VK)  " + sdf.format(d)
                            + " ( http://vk.com/Depersonilized?w=wall-0_" + v.getId() + " ): \r\n"
                            + v.getText();
                    if (!"".equals(v.getAttachment())) {
                        sText += "\r\n" + v.getAttachment();
                    }
                    sText += "\r\n***";
                    System.out.println(sText);
                    ch.send(sText);
                    vk_ids.add(v.getId());
                    bChanged = 1;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println("Failed to get vk: " + e.getMessage());
            // System.exit(-1);
        } catch (SkypeException ex) {
            ex.printStackTrace();
            System.out.println("Failed to send message: " + ex.getMessage());
        }
        if (bChanged == 1) {
            save_file();
        }
        try {
            Thread.sleep(1000 * 60 * twitter_timeout);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
            System.out.println("Failed to sleep: " + ex.getMessage());
        }
    }
}

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  w  w w .  j av a 2  s .com*/
        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:org.apache.nutch.protocol.http.api.HttpBase.java

License:Apache License

private HttpResponse getTwitterResponse(String url)
        throws MalformedURLException, TwitterException, UnsupportedEncodingException, CharacterCodingException {
    url = URLDecoder.decode(url, "UTF-8");
    Map<String, String> map = getQueryParams(url);
    String consumerKey = map.get("consumer_key");
    String consumerSecret = map.get("consumer_secret");
    String accessToken = map.get("oauth_key");
    String accessTokenSecret = map.get("oauth_secret");

    Twitter twitter = getTwitterInstance(consumerKey, consumerSecret, accessToken, accessTokenSecret);
    Paging paging = new Paging();
    paging.setCount(10);/* w  ww  .  java 2s  .c o m*/
    twitter4j.internal.http.HttpResponse twitterResponse;
    String result = null;
    if (!(url.indexOf("statuses/show.json") >= 0)) {
        String max_id = map.get("max_id");
        if (null != max_id)
            paging.setMaxId(Long.parseLong(max_id));
        ResponseList<Status> homeTimeline = twitter.getUserTimeline(paging);
        twitterResponse = homeTimeline.getResponse();
        result = twitterResponse.asJSONArray().toString();
    } else {
        String id = map.get("id");
        Long statusId = Long.parseLong(id);
        Status status = twitter.showStatus(statusId);
        twitterResponse = status.getResponse();
        result = twitterResponse.asJSONObject().toString();
    }

    u = new URL(twitterResponse.getRequestURL());
    code = twitterResponse.getStatusCode();
    ByteBuffer buffer = toByteBUffer(result);
    contents = buffer.array();
    contentType = "text/javascript";

    headers = new SpellCheckedMetadata();
    Map<String, List<String>> responseHeaders = twitterResponse.getResponseHeaderFields();
    for (String key : responseHeaders.keySet()) {
        List<String> values = responseHeaders.get(key);
        for (String value : values) {
            if (null == key)
                continue;
            if (null == value)
                continue;
            headers.add(key, value);
        }
    }
    return null;
}

From source file:org.examproject.tweet.service.SimpleTweetService.java

License:Apache License

private ResponseList<Status> getResponseList() {
    LOG.debug("called.");

    long cursol = -1;
    int listId = 0;
    int count = 50;
    int pageNumber = 1;

    Paging paging = new Paging(pageNumber, count);

    try {/*from w ww. j a  v a 2s  .co  m*/
        // TODO: polymorphism to here? -> plugin.

        // home
        if (paramValue.getResponseListMode().equals("home")) {
            Twitter twitter = getTwitter();
            return twitter.getHomeTimeline(paging);
        }

        // user
        if (paramValue.getResponseListMode().equals("user")) {
            Twitter twitter = getTwitter();
            return twitter.getUserTimeline(paging);
        }

        // list
        if (paramValue.getResponseListMode().equals("list")) {
            if (paramValue.getUserListName().length() != 0) {
                Twitter twitter = getTwitter();
                PagableResponseList<UserList> lists = twitter.getUserLists(twitter.getScreenName(), cursol);
                for (UserList list : lists) {
                    String listFullName = list.getFullName();
                    if (listFullName.equals(paramValue.getUserListName())) {
                        listId = list.getId();
                        return twitter.getUserListStatuses(listId, paging);
                    }
                }
            }
        }

        // default..
        Twitter twitter = getTwitter();
        return twitter.getHomeTimeline();

    } catch (TwitterException te) {
        // TODO: transition to an error page here?
        throw new RuntimeException(te);
    }
}

From source file:org.junjun.twitter.GetUserTimeline.java

License:Apache License

/**
 * Usage: java twitter4j.examples.timeline.GetUserTimeline
 *
 * @param args String[]/*from w ww .ja  v  a  2  s .  c o m*/
 */
public static void main(String[] args) {
    // gets Twitter instance with default credentials
    Twitter twitter = new TwitterFactory().getInstance();
    try {
        List<Status> statuses;
        String user;
        Paging paging = new Paging(1);
        paging.setCount(100);
        if (args.length == 1) {
            user = args[0];
            /* statuses = twitter.getUserTimeline(Long.parseLong(user),paging);*/
            statuses = twitter.getUserTimeline(Long.parseLong(user));
        } else {
            user = twitter.verifyCredentials().getScreenName();
            statuses = twitter.getUserTimeline();
        }
        System.out.println("Showing @" + user + "'s user timeline.");
        int i = 0;

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

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

From source file:org.luwrain.app.twitter.Base.java

License:Open Source License

static private TweetWrapper[] userTimeline(Twitter twitter, String user) {
    NullCheck.notNull(twitter, "twitter");
    NullCheck.notEmpty(user, "user");
    try {//from   w  w w . j a  va  2  s  .  com
        final List<Status> result = twitter.getUserTimeline(user);
        if (result == null)
            return null;
        final LinkedList<TweetWrapper> wrappers = new LinkedList<TweetWrapper>();
        for (Status s : result)
            wrappers.add(new TweetWrapper(s));
        return wrappers.toArray(new TweetWrapper[wrappers.size()]);
    } catch (TwitterException e) {
        e.printStackTrace();
        return null;
    }
}