Example usage for twitter4j Twitter getDirectMessages

List of usage examples for twitter4j Twitter getDirectMessages

Introduction

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

Prototype

DirectMessageList getDirectMessages(int count) throws TwitterException;

Source Link

Document

Returns all Direct Message events (both sent and received) within the last 30 days.

Usage

From source file:br.com.porcelli.hornetq.integration.twitter.stream.reclaimer.AbstractBaseReclaimLostTweets.java

License:Apache License

protected void loadDirectMessages(final Long lastDMId, final Twitter twitter) throws Exception {
    try {//  w  w  w. ja v a 2  s. c om
        if (lastDMId == null) {
            return;
        }
        int page = 1;
        while (true) {
            final Paging paging = new Paging(page, lastDMId);
            final ResponseList<DirectMessage> rl = twitter.getDirectMessages(paging);
            if (rl.size() == 0) {
                break;
            }
            for (final DirectMessage dm : rl) {
                message.postMessage(dm, true);
            }
            page++;
        }
    } catch (Exception e) {
        exceptionNotifier.notifyException(e);
    }
}

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;/*from ww w  .  j  a  va  2s.  c  om*/
    }

    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;/*  w  ww  .  j a  va  2s .  c o 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.ikungolf.java.javatwitter.directmessage.GetDirectMessages.java

License:Apache License

private String getLastestMessage() {
    Twitter twitter = new TwitterFactory().getInstance();
    String msg = new String();
    try {/*ww  w. j a v a  2 s  .c o  m*/
        Paging paging = new Paging(1);
        List<DirectMessage> messages;

        messages = twitter.getDirectMessages(paging);
        System.out.println(messages.size());
        DirectMessage dm = messages.get(0);

        System.out.println("Message: " + dm.getText());
        messageId = dm.getId();
        if (messageId != tempMsgId) {
            tempMsgId = messageId;
        }
        msg = dm.getText();

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

    return msg;
}

From source file:com.javielinux.database.EntityTweetUser.java

License:Apache License

public InfoSaveTweets saveTweets(Context context, Twitter twitter) {

    InfoSaveTweets out = new InfoSaveTweets();

    try {//from w  w  w  . j av  a2s.com
        String where = "type_id = " + tweet_type + " AND user_tt_id=" + getId();

        int nResult = DataFramework.getInstance().getEntityListCount("tweets_user", where);
        if (nResult > 0)
            mLastIdNotification = DataFramework.getInstance().getTopEntity("tweets_user", where, "date desc")
                    .getLong("tweet_id");

        boolean breakTimeline = false;

        PreferenceManager.setDefaultValues(context, R.xml.preferences, false);
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);

        int maxDownloadTweet = Integer.parseInt(pref.getString("prf_n_max_download", "60"));
        if (maxDownloadTweet <= 0)
            maxDownloadTweet = 60;

        ResponseList<twitter4j.Status> statii = null;
        ResponseList<twitter4j.DirectMessage> directs = null;

        if (mLastIdNotification > 0) {
            if (tweet_type == TweetTopicsUtils.TWEET_TYPE_TIMELINE) {

                Paging p = new Paging(1, maxDownloadTweet);
                p.setSinceId(mLastIdNotification);

                try {
                    statii = twitter.getHomeTimeline(p);
                } catch (OutOfMemoryError e) {
                    e.printStackTrace();
                }

                if (statii != null && statii.size() >= maxDownloadTweet - 10) {
                    p = new Paging(1, 10);
                    p.setSinceId(mLastIdNotification);
                    p.setMaxId(statii.get(statii.size() - 1).getId());
                    if (twitter.getHomeTimeline().size() > 0) {
                        breakTimeline = true;
                    }
                }

            } else if (tweet_type == TweetTopicsUtils.TWEET_TYPE_MENTIONS) {
                Paging p = new Paging();
                p.setCount(100);
                p.setSinceId(mLastIdNotification);
                statii = twitter.getMentionsTimeline(p);
            } else if (tweet_type == TweetTopicsUtils.TWEET_TYPE_DIRECTMESSAGES) {
                Paging p = new Paging();
                p.setCount(100);
                p.setSinceId(mLastIdNotification);
                directs = twitter.getDirectMessages(p);
            } else if (tweet_type == TweetTopicsUtils.TWEET_TYPE_SENT_DIRECTMESSAGES) {
                Paging p = new Paging();
                p.setCount(100);
                p.setSinceId(mLastIdNotification);
                directs = twitter.getSentDirectMessages(p);
            }
        } else {
            try {
                Log.d(Utils.TAG, "Primera carga de " + getTypeText());
                if (tweet_type == TweetTopicsUtils.TWEET_TYPE_TIMELINE) {
                    statii = twitter.getHomeTimeline(new Paging(1, 40));
                } else if (tweet_type == TweetTopicsUtils.TWEET_TYPE_MENTIONS) {
                    statii = twitter.getMentionsTimeline(new Paging(1, 40));
                } else if (tweet_type == TweetTopicsUtils.TWEET_TYPE_DIRECTMESSAGES) {
                    directs = twitter.getDirectMessages();
                } else if (tweet_type == TweetTopicsUtils.TWEET_TYPE_SENT_DIRECTMESSAGES) {
                    directs = twitter.getSentDirectMessages();
                }
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            }
        }

        // guardar statii

        if (statii != null) {

            if (statii.size() > 0) {
                out.setNewMessages(statii.size());
                out.setNewerId(statii.get(0).getId());
                out.setOlderId(statii.get(statii.size() - 1).getId());

                Log.d(Utils.TAG,
                        statii.size() + " mensajes nuevos en " + getTypeText() + " de " + getString("name"));

                long nextId = 1;
                Cursor c = DataFramework.getInstance().getCursor("tweets_user",
                        new String[] { DataFramework.KEY_ID }, null, null, null, null,
                        DataFramework.KEY_ID + " desc", "1");
                if (!c.moveToFirst()) {
                    c.close();
                    nextId = 1;
                } else {
                    long Id = c.getInt(0) + 1;
                    c.close();
                    nextId = Id;
                }

                DataFramework.getInstance().getDB().beginTransaction();

                try {
                    boolean isFirst = true;
                    for (int i = statii.size() - 1; i >= 0; i--) {
                        User u = statii.get(i).getUser();
                        if (u != null) {
                            ContentValues args = new ContentValues();
                            args.put(DataFramework.KEY_ID, "" + nextId);
                            args.put("type_id", tweet_type);
                            args.put("user_tt_id", "" + getId());
                            if (u.getProfileImageURL() != null) {
                                args.put("url_avatar", u.getProfileImageURL().toString());
                            } else {
                                args.put("url_avatar", "");
                            }
                            args.put("username", u.getScreenName());
                            args.put("fullname", u.getName());
                            args.put("user_id", "" + u.getId());
                            args.put("tweet_id", Utils.fillZeros("" + statii.get(i).getId()));
                            args.put("source", statii.get(i).getSource());
                            args.put("to_username", statii.get(i).getInReplyToScreenName());
                            args.put("to_user_id", "" + statii.get(i).getInReplyToUserId());
                            args.put("date", String.valueOf(statii.get(i).getCreatedAt().getTime()));
                            if (statii.get(i).getRetweetedStatus() != null) {
                                args.put("is_retweet", 1);
                                args.put("retweet_url_avatar", statii.get(i).getRetweetedStatus().getUser()
                                        .getProfileImageURL().toString());
                                args.put("retweet_username",
                                        statii.get(i).getRetweetedStatus().getUser().getScreenName());
                                args.put("retweet_source", statii.get(i).getRetweetedStatus().getSource());
                                String t = Utils.getTwitLoger(statii.get(i).getRetweetedStatus());
                                if (t.equals("")) {
                                    args.put("text", statii.get(i).getRetweetedStatus().getText());
                                    args.put("text_urls",
                                            Utils.getTextURLs(statii.get(i).getRetweetedStatus()));
                                } else {
                                    args.put("text", t);
                                }
                                args.put("is_favorite", 0);
                            } else {
                                String t = Utils.getTwitLoger(statii.get(i));
                                if (t.equals("")) {
                                    args.put("text", statii.get(i).getText());
                                    args.put("text_urls", Utils.getTextURLs(statii.get(i)));
                                } else {
                                    args.put("text", t);
                                }

                                if (statii.get(i).isFavorited()) {
                                    args.put("is_favorite", 1);
                                }
                            }

                            if (statii.get(i).getGeoLocation() != null) {
                                args.put("latitude", statii.get(i).getGeoLocation().getLatitude());
                                args.put("longitude", statii.get(i).getGeoLocation().getLongitude());
                            }
                            args.put("reply_tweet_id", statii.get(i).getInReplyToStatusId());

                            if (breakTimeline && isFirst)
                                args.put("has_more_tweets_down", 1);

                            DataFramework.getInstance().getDB().insert("tweets_user", null, args);

                            out.addId(nextId);

                            nextId++;

                            if (isFirst)
                                isFirst = false;
                        }

                    }

                    // finalizar

                    int total = nResult + statii.size();

                    if (total > Utils.MAX_ROW_BYSEARCH && getValueNewCount() < Utils.MAX_ROW_BYSEARCH
                            || total > Utils.MAX_ROW_BYSEARCH_FORCE) {
                        try {
                            Log.d(Utils.TAG, "Limpiando base de datos de " + getTypeText() + " actualmente "
                                    + total + " registros");
                            String date = DataFramework.getInstance()
                                    .getEntityList("tweets_user",
                                            "type_id=" + tweet_type + " and user_tt_id=" + getId(), "date desc")
                                    .get(Utils.MAX_ROW_BYSEARCH).getString("date");
                            String sqldelete = "DELETE FROM tweets_user WHERE type_id=" + tweet_type
                                    + " and user_tt_id=" + getId() + " AND date  < '" + date + "'";
                            DataFramework.getInstance().getDB().execSQL(sqldelete);
                        } catch (OutOfMemoryError e) {
                        }
                    }

                    DataFramework.getInstance().getDB().setTransactionSuccessful();

                } catch (SQLException e) {
                    e.printStackTrace();
                } finally {
                    DataFramework.getInstance().getDB().endTransaction();
                }

            }

        }

        // guardar directs

        if (directs != null) {
            if (directs.size() > 0) {
                out.setNewMessages(directs.size());
                out.setNewerId(directs.get(0).getId());
                out.setOlderId(directs.get(directs.size() - 1).getId());

                Log.d(Utils.TAG, directs.size() + " mensajes directos a " + getString("name"));

                long nextId = 1;
                Cursor c = DataFramework.getInstance().getCursor("tweets_user",
                        new String[] { DataFramework.KEY_ID }, null, null, null, null,
                        DataFramework.KEY_ID + " desc", "1");
                if (!c.moveToFirst()) {
                    c.close();
                    nextId = 1;
                } else {
                    long Id = c.getInt(0) + 1;
                    c.close();
                    nextId = Id;
                }

                DataFramework.getInstance().getDB().beginTransaction();

                try {
                    for (int i = directs.size() - 1; i >= 0; i--) {
                        User u = directs.get(i).getSender();
                        if (u != null) {
                            ContentValues args = new ContentValues();
                            args.put(DataFramework.KEY_ID, "" + nextId);
                            args.put("type_id", tweet_type);
                            args.put("user_tt_id", "" + getId());
                            if (u.getProfileImageURL() != null) {
                                args.put("url_avatar", u.getProfileImageURL().toString());
                            } else {
                                args.put("url_avatar", "");
                            }
                            args.put("username", u.getScreenName());
                            args.put("fullname", u.getName());
                            args.put("user_id", "" + u.getId());
                            args.put("tweet_id", Utils.fillZeros("" + directs.get(i).getId()));
                            args.put("source", "");
                            args.put("to_username", directs.get(i).getRecipientScreenName());
                            args.put("to_user_id", "" + directs.get(i).getRecipientId());
                            args.put("date", String.valueOf(directs.get(i).getCreatedAt().getTime()));
                            args.put("text", directs.get(i).getText());

                            DataFramework.getInstance().getDB().insert("tweets_user", null, args);

                            out.addId(nextId);

                            Log.d(Utils.TAG,
                                    "getRecipientScreenName: " + directs.get(i).getRecipientScreenName());

                            nextId++;
                        }

                    }

                    // finalizar

                    int total = nResult + directs.size();

                    if (total > Utils.MAX_ROW_BYSEARCH && getValueNewCount() < Utils.MAX_ROW_BYSEARCH) {
                        Log.d(Utils.TAG, "Limpiando base de datos de " + getTypeText() + " actualmente " + total
                                + " registros");
                        String date = DataFramework.getInstance()
                                .getEntityList("tweets_user",
                                        "type_id=" + tweet_type + " and user_tt_id=" + getId(), "date desc")
                                .get(Utils.MAX_ROW_BYSEARCH).getString("date");
                        String sqldelete = "DELETE FROM tweets_user WHERE type_id=" + tweet_type
                                + " and user_tt_id=" + getId() + " AND date  < '" + date + "'";
                        DataFramework.getInstance().getDB().execSQL(sqldelete);
                    }

                    DataFramework.getInstance().getDB().setTransactionSuccessful();

                } catch (SQLException e) {
                    e.printStackTrace();
                } finally {
                    DataFramework.getInstance().getDB().endTransaction();
                }

            }

        }
    } catch (TwitterException e) {
        e.printStackTrace();
        RateLimitStatus rate = e.getRateLimitStatus();
        if (rate != null) {
            out.setError(Utils.LIMIT_ERROR);
            out.setRate(rate);
        } else {
            out.setError(Utils.UNKNOWN_ERROR);
        }
    } catch (Exception e) {
        e.printStackTrace();
        out.setError(Utils.UNKNOWN_ERROR);
    }
    return out;
}

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

License:Apache License

@Override
public void onHandleIntent(Intent intent) {
    sharedPrefs = getSharedPreferences("com.klinker.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;/*from  w w  w  . j  a  v  a2  s .com*/
    }

    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));
        }

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

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

License:Apache License

@Override
public void onHandleIntent(Intent intent) {
    sharedPrefs = getSharedPreferences("com.klinker.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;/*from w  w w. ja v  a  2 s .  c  o  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.test.GetDirectMessages.java

License:Apache License

/**
 * Usage: java twitter4j.examples.directmessage.GetDirectMessages
 *
 * @param args String[]// w ww . j  a  v a2  s  .com
 */
public static void main(String[] args) {
    //        Twitter twitter = new TwitterFactory().getInstance();
    Twitter twitter = AccountTwitterFactory.getWiseManTwitter();
    try {
        Paging paging = new Paging(1);
        List<DirectMessage> messages;
        do {
            messages = twitter.getDirectMessages(paging);
            for (DirectMessage message : messages) {
                System.out.println("From: @" + message.getSenderScreenName() + " id:" + message.getId() + " - "
                        + message.getText());
            }
            paging.setPage(paging.getPage() + 1);
        } while (messages.size() > 0 && paging.getPage() < 10);
        System.out.println("done.");
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get messages: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:org.wso2.carbon.connector.twitter.TwitterGetDirectMessages.java

License:Open Source License

@Override
public void connect(MessageContext messageContext) throws ConnectException {
    if (log.isDebugEnabled()) {
        log.info("executing twitter get user time line");
    }/* ww w  . j a va2 s.  c o  m*/

    try {
        String page = (TwitterUtils.lookupTemplateParamater(messageContext, PAGE) != null
                && !TwitterUtils.lookupTemplateParamater(messageContext, PAGE).isEmpty())
                        ? TwitterUtils.lookupTemplateParamater(messageContext, PAGE)
                        : null;

        String count = (TwitterUtils.lookupTemplateParamater(messageContext, COUNT) != null
                && !TwitterUtils.lookupTemplateParamater(messageContext, COUNT).isEmpty())
                        ? TwitterUtils.lookupTemplateParamater(messageContext, COUNT)
                        : null;

        String sinceID = (TwitterUtils.lookupTemplateParamater(messageContext, SINCE_ID) != null
                && !TwitterUtils.lookupTemplateParamater(messageContext, SINCE_ID).isEmpty())
                        ? TwitterUtils.lookupTemplateParamater(messageContext, SINCE_ID)
                        : null;

        String maxID = (TwitterUtils.lookupTemplateParamater(messageContext, MAX_ID) != null
                && !TwitterUtils.lookupTemplateParamater(messageContext, MAX_ID).isEmpty())
                        ? TwitterUtils.lookupTemplateParamater(messageContext, MAX_ID)
                        : null;

        Twitter twitter = new TwitterClientLoader(messageContext).loadApiClient();

        List<DirectMessage> results = null;
        if (page != null && !page.isEmpty()) {
            if (count == null && sinceID == null && maxID == null) {
                results = twitter.getDirectMessages(new Paging(Long.parseLong(page)));
            } else if (count != null && sinceID == null && maxID == null) {

                results = twitter
                        .getDirectMessages(new Paging(Integer.parseInt(page), Integer.parseInt(count)));
            } else if (count != null && sinceID != null && maxID == null) {
                results = twitter.getDirectMessages(
                        new Paging(Integer.parseInt(page), Integer.parseInt(count), Long.parseLong(sinceID)));
            } else {
                results = twitter.getDirectMessages(new Paging(Integer.parseInt(page), Integer.parseInt(count),
                        Long.parseLong(sinceID), Long.parseLong(maxID)));
            }
        } else if (page == null && sinceID != null) {
            results = twitter.getDirectMessages(new Paging(Integer.parseInt(sinceID)));
        } else {
            results = twitter.getDirectMessages();
        }
        OMElement element = this.performSearchMessages(results);

        super.preparePayload(messageContext, element);

    } catch (TwitterException te) {
        log.error("Failed to search twitter : " + te.getMessage(), te);
        TwitterUtils.storeErrorResponseStatus(messageContext, te);
    } catch (Exception te) {
        log.error("Failed to search generic: " + te.getMessage(), te);
        TwitterUtils.storeErrorResponseStatus(messageContext, te);
    }
}

From source file:org.wso2.carbon.connector.twitter.TwitterGetSentDirectMessages.java

License:Open Source License

@Override
public void connect(MessageContext messageContext) throws ConnectException {
    if (log.isDebugEnabled()) {
        log.info("executing twitter get user time line");
    }//from   www.jav  a  2 s .  co  m

    try {

        String page = (TwitterUtils.lookupTemplateParamater(messageContext, PAGE) != null
                && !TwitterUtils.lookupTemplateParamater(messageContext, PAGE).isEmpty())
                        ? TwitterUtils.lookupTemplateParamater(messageContext, PAGE)
                        : null;

        String count = (TwitterUtils.lookupTemplateParamater(messageContext, COUNT) != null
                && !TwitterUtils.lookupTemplateParamater(messageContext, COUNT).isEmpty())
                        ? TwitterUtils.lookupTemplateParamater(messageContext, COUNT)
                        : null;

        String sinceID = (TwitterUtils.lookupTemplateParamater(messageContext, SINCE_ID) != null
                && !TwitterUtils.lookupTemplateParamater(messageContext, SINCE_ID).isEmpty())
                        ? TwitterUtils.lookupTemplateParamater(messageContext, SINCE_ID)
                        : null;

        String maxID = (TwitterUtils.lookupTemplateParamater(messageContext, MAX_ID) != null
                && !TwitterUtils.lookupTemplateParamater(messageContext, MAX_ID).isEmpty())
                        ? TwitterUtils.lookupTemplateParamater(messageContext, MAX_ID)
                        : null;

        Twitter twitter = new TwitterClientLoader(messageContext).loadApiClient();

        List<DirectMessage> results = null;

        if (page != null && !page.isEmpty()) {
            if (count == null && sinceID == null && maxID == null) {
                results = twitter.getDirectMessages(new Paging(Long.parseLong(page)));
            } else if (count != null && sinceID == null && maxID == null) {

                results = twitter
                        .getSentDirectMessages(new Paging(Integer.parseInt(page), Integer.parseInt(count)));
            } else if (count != null && sinceID != null && maxID == null) {
                results = twitter.getSentDirectMessages(
                        new Paging(Integer.parseInt(page), Integer.parseInt(count), Long.parseLong(sinceID)));
            } else {
                results = twitter.getSentDirectMessages(new Paging(Integer.parseInt(page),
                        Integer.parseInt(count), Long.parseLong(sinceID), Long.parseLong(maxID)));
            }
        } else if (page == null && sinceID != null) {
            results = twitter.getSentDirectMessages(new Paging(Integer.parseInt(sinceID)));
        } else {
            results = twitter.getSentDirectMessages();
        }

        OMElement element = this.performSearchMessages(results);

        super.preparePayload(messageContext, element);

    } catch (TwitterException te) {
        log.error("Failed to search twitter : " + te.getMessage(), te);
        TwitterUtils.storeErrorResponseStatus(messageContext, te);
    } catch (Exception te) {
        log.error("Failed to search generic: " + te.getMessage(), te);
        TwitterUtils.storeErrorResponseStatus(messageContext, te);
    }
}