Example usage for twitter4j Paging Paging

List of usage examples for twitter4j Paging Paging

Introduction

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

Prototype

public Paging(long sinceId) 

Source Link

Usage

From source file:au.edu.anu.portal.portlets.tweetal.servlet.TweetalServlet.java

License:Apache License

public void getTweets(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();

    String userToken = request.getParameter("u");
    String userSecret = request.getParameter("s");

    Twitter twitter = twitterLogic.getTwitterAuthForUser(userToken, userSecret);
    if (twitter == null) {
        // no connection
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;/*from ww  w .  j  a v  a  2s . c o m*/
    }

    String cacheKey = userToken;
    Element element = null;

    // force refresh
    boolean force = Boolean.parseBoolean(request.getParameter("force"));
    if (force) {
        log.debug("force refresh for " + userToken);
        // remove tweets cache
        tweetsCache.remove(cacheKey);
    } else {
        element = tweetsCache.get(cacheKey);
    }

    if (element == null) {
        synchronized (tweetsCache) {
            // if it is still null after acquiring lock
            element = tweetsCache.get(cacheKey);

            if (element == null) {
                log.debug("cache miss: getting tweets for " + userToken);
                System.out.println("Last refreshed: " + Calendar.getInstance().getTime());

                try {
                    ResponseList<Status> friendStatus = twitter.getFriendsTimeline();

                    long maxId = Long.MIN_VALUE;

                    JSONObject json = new JSONObject();

                    lastRefreshed = Calendar.getInstance().getTime().toString();

                    if (lastRefreshed == null) {
                        json.element("lastRefreshed", "unable to retrieve last refreshed");
                    } else {
                        json.element("lastRefreshed", lastRefreshed.toString());
                    }

                    User currentUser = twitter.showUser(twitter.getId());
                    Status lastUserStatus = currentUser.getStatus();
                    if (lastUserStatus == null) {
                        json.element("lastStatusUpdate", "unable to retrieve last status");
                    } else {
                        Date lastStatusUpdate = lastUserStatus.getCreatedAt();
                        json.element("lastStatusUpdate", lastStatusUpdate.toString());
                    }

                    for (Status status : friendStatus) {
                        maxId = Math.max(maxId, status.getId());
                        json.accumulate("statusList", getStatusJSON(twitter, status));
                    }

                    if (log.isDebugEnabled()) {
                        log.debug(json.toString(2));
                    }

                    out.print(json.toString());

                    element = new Element(cacheKey,
                            new TweetsCacheElement(System.currentTimeMillis(), maxId, json));

                    tweetsCache.put(element);

                    return;

                } catch (TwitterException e) {
                    log.error("GetTweets: " + e.getStatusCode() + ": " + e.getClass() + e.getMessage());

                    if (e.getStatusCode() == 401) {
                        // invalid credentials
                        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                    } else if (e.getStatusCode() == -1) {
                        // no connection
                        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                    } else {
                        // general error
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    }

                    return;
                }
            }
        }
    }

    // tweets available in cache
    log.debug("cache hit: getting tweets for " + userToken);

    TweetsCacheElement tweets = (TweetsCacheElement) element.getObjectValue();

    // if just refreshed too quickly, don't request update, just use
    // whatever in cache
    long period = System.currentTimeMillis() - tweets.getLastRefresh();
    System.out.println("Already refreshed: " + (period / 1000) + " second(s) ago");

    if (period < 2 * 60 * 1000) {
        log.debug("refreshed too quickly: " + (period / 1000) + " seconds");
        JSONObject json = tweets.getResult();
        lastRefreshed = Calendar.getInstance().getTime().toString();
        json.element("lastRefreshed", lastRefreshed.toString());
        out.print(json.toString());
        return;
    }

    // get new updates since the last id
    long maxId = tweets.lastId;
    try {
        JSONObject json = tweets.getResult();

        ResponseList<Status> friendStatus = twitter.getFriendsTimeline(new Paging(maxId));

        tweets.setLastRefresh(System.currentTimeMillis());

        log.debug(String.format("Got %d new tweets", friendStatus.size()));

        if (friendStatus.size() > 0) {
            JSONArray newTweets = new JSONArray();

            lastRefreshed = Calendar.getInstance().getTime().toString();
            json.element("lastRefreshed", lastRefreshed.toString());

            for (Status status : friendStatus) {
                maxId = Math.max(maxId, status.getId());
                newTweets.add(getStatusJSON(twitter, status));
            }

            if (log.isDebugEnabled()) {
                log.debug("new tweets:\n" + newTweets.toString(2));
            }

            json.getJSONArray("statusList").addAll(0, newTweets);

            tweets.setLastId(maxId);

            User currentUser = twitter.showUser(twitter.getId());
            Status lastUserStatus = currentUser.getStatus();
            if (lastUserStatus == null) {
                json.element("lastStatusUpdate", "unable to retrieve last status");
            } else {
                Date lastStatusUpdate = lastUserStatus.getCreatedAt();
                json.element("lastStatusUpdate", lastStatusUpdate.toString());
            }
        }

        out.print(json.toString());

    } catch (TwitterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        log.error(e);
    }
}

From source file:com.ahuralab.mozaic.app.TwitterClient.java

License:Open Source License

public List<Status> getHomeTimeline(long sinceId) throws TwitterException {
    return twitter.getHomeTimeline(new Paging(sinceId));
}

From source file:com.alainesp.fan.sanderson.SummaryFragment.java

License:Open Source License

protected int doWork() {
    int state = DownloadParseSaveTask.STATE_SUCCESS;

    try {//from   w ww  .  ja v  a 2 s  .c  o m
        List<twitter4j.Status> tweets;

        // Twitter client configuration
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(TwitterAPISecrets.CONSUMER_KEY)
                .setOAuthConsumerSecret(TwitterAPISecrets.CONSUMER_SECRET);
        // TODO: Use guest authentication instead of application
        builder.setApplicationOnlyAuthEnabled(true).setDebugEnabled(false).setGZIPEnabled(true);

        Twitter twitter = new TwitterFactory(builder.build()).getInstance();
        twitter.getOAuth2Token();

        // Get the tweets
        long lastTweetID = DB.Tweet.getLastTweetID();
        if (lastTweetID <= 0)
            tweets = twitter.getUserTimeline("BrandSanderson");
        else
            tweets = twitter.getUserTimeline("BrandSanderson", new Paging(lastTweetID));

        if (tweets != null) {
            long brandonID = 28187205;
            Hashtable<Long, DB.Tweet> findTweet = new Hashtable<>(tweets.size() * 16, 0.25f);
            List<DB.Tweet> dbTweets = new ArrayList<>(tweets.size());
            for (twitter4j.Status tweet : tweets) {
                // Create the tweet
                if (tweet.isRetweet())
                    tweet = tweet.getRetweetedStatus();

                long tweetID = tweet.getId();
                // TODO: Include the tweets in the DB
                if (findTweet.get(tweetID) == null)// This eliminate tweets already in the replies tree
                {
                    DB.Tweet dbTweet = new DB.Tweet(tweetID, getTweetText(tweet), tweet.getCreatedAt(), false,
                            tweet.getUser().getName(), tweet.getUser().getBiggerProfileImageURLHttps());
                    InternetHelper.getRemoteFile(tweet.getUser().getBiggerProfileImageURLHttps());
                    dbTweets.add(dbTweet);
                    findTweet.put(tweetID, dbTweet);

                    // Traverse the tree of the replies tweets
                    twitter4j.Status treeTweet = tweet;
                    while (treeTweet != null && treeTweet.getInReplyToStatusId() >= 0) {
                        try {
                            long id = treeTweet.getInReplyToStatusId();
                            long userID = treeTweet.getUser().getId();
                            treeTweet = null;
                            if (findTweet.get(id) == null || brandonID == userID)
                                treeTweet = twitter.showStatus(id);
                            else// Remove duplicates. Not sure why they appear, but the difference of the text is a dot at the end.
                                dbTweets.remove(dbTweets.size() - 1);
                        } catch (Exception ignore) {
                        }

                        if (treeTweet != null) {
                            findTweet.put(treeTweet.getId(), dbTweet);
                            StringBuilder replyBuilder = new StringBuilder();

                            replyBuilder.append("<blockquote>");

                            // Profile image
                            replyBuilder.append("<img src=\"");
                            InternetHelper.getRemoteFile(treeTweet.getUser().getBiggerProfileImageURLHttps());
                            replyBuilder.append(treeTweet.getUser().getBiggerProfileImageURLHttps());
                            replyBuilder.append("\"/>&nbsp;<b>");

                            // Username - date
                            replyBuilder.append(treeTweet.getUser().getName());
                            replyBuilder.append("</b> @");
                            replyBuilder.append(treeTweet.getUser().getScreenName());
                            replyBuilder.append(" - ");
                            replyBuilder
                                    .append(TwitterFragment.showDateFormat.format(treeTweet.getCreatedAt()));

                            // Tweet text
                            replyBuilder.append("<br/>");
                            replyBuilder.append(getTweetText(treeTweet));

                            // Remaining
                            replyBuilder.append(dbTweet.htmlReply);
                            replyBuilder.append("</blockquote>");

                            dbTweet.htmlReply = replyBuilder.toString();
                        }
                    }
                }
            }
            DB.Tweet.updateTwitter(dbTweets);
        }
    } catch (Exception e) {
        Logger.reportError(e.toString());
        state = DownloadParseSaveTask.STATE_ERROR_PARSING;
    }

    return state;
}

From source file:com.appspot.bitlyminous.service.impl.TwitterServiceImpl.java

License:Apache License

public void handleMentions() {
    try {//ww w  .  ja v a2s.com
        Twitter twitter = getTwitterClient();
        TwitterHandlerFactory factory = TwitterHandlerFactory.newInstance(new TwitterContext());
        Version version = getCurrentVersion();
        ResponseList<Status> homeTimeline = twitter
                .getMentions(new Paging(getCurrentVersion().getLastMentionId()));
        long lastMentionId = 0L;
        for (Status tweet : homeTimeline) {
            if (tweet.getId() > version.getLastMentionId()) {
                if (tweet.getId() > lastMentionId) {
                    lastMentionId = tweet.getId();
                }
                TwitterHandler command = factory.createCommand(tweet);
                StatusUpdate reply = command.execute(tweet);
                if (reply != null) {
                    twitter.updateStatus(reply);
                }
            }
        }
        if (lastMentionId > version.getLastMentionId()) {
            version.setLastMentionId(lastMentionId);
            EntityManager entityManager = createEntityManager();
            entityManager.persist(version);
            closeEntityManager(entityManager);
        }
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}

From source file:com.appspot.bitlyminous.service.impl.TwitterServiceImpl.java

License:Apache License

public void handleFriendsTimeline() {
    try {/* w  w  w. java2  s. c om*/
        Version version = getCurrentVersion();
        Twitter twitter = getTwitterClient();
        List<Status> homeTimeline = twitter.getFriendsTimeline(new Paging(version.getLastHomeTweetId()));
        long lastTweetId = 0L;
        for (Status status : homeTimeline) {
            if (status.getId() > lastTweetId) {
                lastTweetId = status.getId();
            }
            if (!ApplicationConstants.TWITTER_SCREEN_NAME.equalsIgnoreCase(status.getUser().getScreenName())) {
                TwitterContext context = new TwitterContext();
                context.setVersion(version);
                for (TwitterHandler command : getTimelineHandlers(context)) {
                    StatusUpdate reply = command.execute(status);
                    if (reply != null) {
                        twitter.updateStatus(reply);
                    }
                }
                saveUser(context.getUser());
            }
        }
        if (lastTweetId > version.getLastHomeTweetId()) {
            version.setLastHomeTweetId(lastTweetId);
            saveVersion(version);
        }
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}

From source file:com.appspot.socialinquirer.server.service.impl.UserServiceImpl.java

License:Apache License

@Override
public void aggregateQuotes() {
    EntityManager entityManager = createEntityManager();
    try {// w  ww.  j a  v a  2  s .c o  m
        DataAccessObject dao = getDao(entityManager);
        Version version = getCurrentVersion();
        Twitter twitter = getTwitterClient();
        List<Status> homeTimeline = twitter.getUserTimeline(ApplicationConstants.TWITTER_SCREEN_NAME,
                new Paging(version.getLastHomeTweetId()));
        long lastTweetId = 0L;
        for (Status status : homeTimeline) {
            if (status.getId() > lastTweetId) {
                lastTweetId = status.getId();
            }
            if (!status.isRetweet() && status.getInReplyToStatusId() == -1) {
                Quote quote = new Quote();
                quote.setPublishedDate(status.getCreatedAt());
                quote.setText(new Text(status.getText()));
                quote.setTweetId(status.getId());
                dao.saveOrUpdate(quote);
            }
        }
        if (lastTweetId > version.getLastHomeTweetId()) {
            version.setLastHomeTweetId(lastTweetId);
            dao.saveOrUpdate(version);
        }
    } catch (Exception e) {
        throw new ServiceException(e);
    } finally {
        closeEntityManager(entityManager);
    }
}

From source file:com.daiv.android.twitter.services.DirectMessageRefreshService.java

License:Apache License

@Override
public void onHandleIntent(Intent intent) {
    sharedPrefs = getSharedPreferences("com.daiv.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    Context context = getApplicationContext();
    AppSettings settings = AppSettings.getInstance(context);

    // if they have mobile data on and don't want to sync over mobile data
    if (Utils.getConnectionStatus(context) && !settings.syncMobile) {
        return;/*ww w  .  j  av a 2  s .c  o  m*/
    }

    boolean update = false;
    int numberNew = 0;

    try {
        Twitter twitter = Utils.getTwitter(context, settings);

        int currentAccount = sharedPrefs.getInt("current_account", 1);

        User user = twitter.verifyCredentials();
        long lastId = sharedPrefs.getLong("last_direct_message_id_" + currentAccount, 0);
        Paging paging;
        if (lastId != 0) {
            paging = new Paging(1).sinceId(lastId);
        } else {
            paging = new Paging(1, 500);
        }

        List<DirectMessage> dm = twitter.getDirectMessages(paging);
        List<DirectMessage> sent = twitter.getSentDirectMessages(paging);

        if (dm.size() != 0) {
            sharedPrefs.edit().putLong("last_direct_message_id_" + currentAccount, dm.get(0).getId()).commit();
            numberNew = dm.size();
        } else {
            numberNew = 0;
        }

        DMDataSource dataSource = DMDataSource.getInstance(context);
        int inserted = 0;

        for (DirectMessage directMessage : dm) {
            try {
                dataSource.createDirectMessage(directMessage, currentAccount);
            } catch (Exception e) {
                dataSource = DMDataSource.getInstance(context);
                dataSource.createDirectMessage(directMessage, currentAccount);
            }
            inserted++;
        }

        for (DirectMessage directMessage : sent) {
            try {
                dataSource.createDirectMessage(directMessage, currentAccount);
            } catch (Exception e) {
                dataSource = DMDataSource.getInstance(context);
                dataSource.createDirectMessage(directMessage, currentAccount);
            }
        }

        sharedPrefs.edit().putBoolean("refresh_me", true).commit();
        sharedPrefs.edit().putBoolean("refresh_me_dm", true).commit();

        if (settings.notifications && settings.dmsNot && inserted > 0) {
            int currentUnread = sharedPrefs.getInt("dm_unread_" + currentAccount, 0);
            sharedPrefs.edit().putInt("dm_unread_" + currentAccount, numberNew + currentUnread).commit();

            NotificationUtils.refreshNotification(context);
        }

        if (settings.syncSecondMentions) {
            startService(new Intent(context, SecondDMRefreshService.class));
        }

        sendBroadcast(new Intent("com.daiv.android.twitter.NEW_DIRECT_MESSAGE"));

    } catch (TwitterException e) {
        // Error in updating status
        Log.d("Twitter Update Error", e.getMessage());
    }
}

From source file:com.daiv.android.twitter.services.SecondDMRefreshService.java

License:Apache License

@Override
public void onHandleIntent(Intent intent) {
    sharedPrefs = getSharedPreferences("com.daiv.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    Context context = getApplicationContext();
    AppSettings settings = AppSettings.getInstance(context);

    // if they have mobile data on and don't want to sync over mobile data
    if (Utils.getConnectionStatus(context) && !settings.syncMobile) {
        return;/*  www .  j av  a  2s . co m*/
    }

    boolean update = false;
    int numberNew = 0;

    try {
        Twitter twitter = Utils.getSecondTwitter(context);

        int currentAccount = sharedPrefs.getInt("current_account", 1);

        if (currentAccount == 1) {
            currentAccount = 2;
        } else {
            currentAccount = 1;
        }

        User user = twitter.verifyCredentials();
        long lastId = sharedPrefs.getLong("last_direct_message_id_" + currentAccount, 0);
        Paging paging;
        if (lastId != 0) {
            paging = new Paging(1).sinceId(lastId);
        } else {
            paging = new Paging(1, 500);
        }

        List<DirectMessage> dm = twitter.getDirectMessages(paging);
        List<DirectMessage> sent = twitter.getSentDirectMessages(paging);

        if (dm.size() != 0) {
            sharedPrefs.edit().putLong("last_direct_message_id_" + currentAccount, dm.get(0).getId()).commit();
            numberNew = dm.size();
        } else {
            numberNew = 0;
        }

        DMDataSource dataSource = DMDataSource.getInstance(context);
        int inserted = 0;

        for (DirectMessage directMessage : dm) {
            try {
                dataSource.createDirectMessage(directMessage, currentAccount);
            } catch (Exception e) {
                dataSource = DMDataSource.getInstance(context);
                dataSource.createDirectMessage(directMessage, currentAccount);
            }
            inserted++;
        }

        for (DirectMessage directMessage : sent) {
            try {
                dataSource.createDirectMessage(directMessage, currentAccount);
            } catch (Exception e) {
                dataSource = DMDataSource.getInstance(context);
                dataSource.createDirectMessage(directMessage, currentAccount);
            }
        }

        sharedPrefs.edit().putBoolean("refresh_me", true).commit();
        sharedPrefs.edit().putBoolean("refresh_me_dm", true).commit();

        if (settings.notifications && settings.dmsNot && inserted > 0) {
            int currentUnread = sharedPrefs.getInt("dm_unread_" + currentAccount, 0);
            sharedPrefs.edit().putInt("dm_unread_" + currentAccount, numberNew + currentUnread).commit();

            NotificationUtils.notifySecondDMs(context, currentAccount);
        }

    } catch (TwitterException e) {
        // Error in updating status
        Log.d("Twitter Update Error", e.getMessage());
    }
}

From source file:com.daiv.android.twitter.ui.main_fragments.other_fragments.DMFragment.java

License:Apache License

@Override
public void onRefreshStarted() {
    new AsyncTask<Void, Void, Void>() {

        private boolean update;
        private int numberNew;

        @Override/*from  ww w  . j av  a2 s. co  m*/
        protected void onPreExecute() {
            DrawerActivity.canSwitch = false;
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                twitter = Utils.getTwitter(context, DrawerActivity.settings);

                User user = twitter.verifyCredentials();
                long lastId = sharedPrefs.getLong("last_direct_message_id_" + currentAccount, 0);
                Paging paging;
                if (lastId != 0) {
                    paging = new Paging(1).sinceId(lastId);
                } else {
                    paging = new Paging(1, 500);
                }

                List<DirectMessage> dm = twitter.getDirectMessages(paging);
                List<DirectMessage> sent = twitter.getSentDirectMessages(paging);

                if (dm.size() != 0) {
                    sharedPrefs.edit().putLong("last_direct_message_id_" + currentAccount, dm.get(0).getId())
                            .commit();
                    update = true;
                    numberNew = dm.size();
                } else {
                    update = false;
                    numberNew = 0;
                }

                DMDataSource dataSource = DMDataSource.getInstance(context);

                for (DirectMessage directMessage : dm) {
                    try {
                        dataSource.createDirectMessage(directMessage, currentAccount);
                    } catch (IllegalStateException e) {
                        dataSource = DMDataSource.getInstance(context);
                        dataSource.createDirectMessage(directMessage, currentAccount);
                    }
                }

                for (DirectMessage directMessage : sent) {
                    try {
                        dataSource.createDirectMessage(directMessage, currentAccount);
                    } catch (Exception e) {
                        dataSource = DMDataSource.getInstance(context);
                        dataSource.createDirectMessage(directMessage, currentAccount);
                    }
                }

            } catch (TwitterException e) {
                // Error in updating status
                Log.d("Twitter Update Error", e.getMessage());
            }

            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

            long now = new Date().getTime();
            long alarm = now + DrawerActivity.settings.dmRefresh;

            Log.v("alarm_date", "direct message " + new Date(alarm).toString());

            PendingIntent pendingIntent = PendingIntent.getService(context, DM_REFRESH_ID,
                    new Intent(context, DirectMessageRefreshService.class), 0);

            if (DrawerActivity.settings.dmRefresh != 0)
                am.setRepeating(AlarmManager.RTC_WAKEUP, alarm, DrawerActivity.settings.dmRefresh,
                        pendingIntent);
            else
                am.cancel(pendingIntent);

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            try {
                if (update) {
                    getCursorAdapter(false);

                    CharSequence text = numberNew == 1
                            ? numberNew + " " + getResources().getString(R.string.new_direct_message)
                            : numberNew + " " + getResources().getString(R.string.new_direct_messages);
                    showToastBar(text + "", jumpToTop, 400, true, toTopListener);

                    int size = toDP(5) + mActionBarSize
                            + (DrawerActivity.translucent ? DrawerActivity.statusBarHeight : 0);
                    listView.setSelectionFromTop(numberNew
                            + (MainActivity.isPopup || landscape || MainActivity.settings.jumpingWorkaround ? 1
                                    : 2),
                            size);
                } else {
                    getCursorAdapter(false);

                    CharSequence text = getResources().getString(R.string.no_new_direct_messages);
                    showToastBar(text + "", allRead, 400, true, toTopListener);
                }
                refreshLayout.setRefreshing(false);
            } catch (IllegalStateException e) {
                // fragment not attached to activity
            }

            DrawerActivity.canSwitch = true;
        }
    }.execute();
}

From source file:com.github.moko256.mastodon.MastodonTwitterImpl.java

License:Apache License

@Override
public ResponseList<Status> getFavorites() throws TwitterException {
    return getFavorites(new Paging(-1L));
}