Example usage for twitter4j TwitterException getMessage

List of usage examples for twitter4j TwitterException getMessage

Introduction

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

Prototype

@Override
    public String getMessage() 

Source Link

Usage

From source file:de.jetwick.tw.MyTweetGrabber.java

License:Apache License

public QueueThread queueTweetPackage() {
    return new QueueThread() {

        @Override/*  w  w  w.j a v  a 2  s  . co m*/
        public void run() {
            if (!tweetSearch.isInitialized())
                return;

            int rl = tweetSearch.getRateLimit();
            if (rl <= TwitterSearch.LIMIT) {
                doAbort(new RuntimeException("Couldn't process query (TwitterSearch+Index)."
                        + " Rate limit is smaller than " + TwitterSearch.LIMIT + ":" + rl));
                return;
            }

            String feedSource = "";
            if (tweets == null) {
                if (userName != null && !userName.isEmpty()) {
                    // TODO exlude friendSearch
                    try {
                        if (!isSearchDoneInLastMinutes("user:" + userName)) {
                            //                                logger.info("lastsearches hashcode:" + lastSearches.hashCode());
                            tweets = new LinkedBlockingQueue<JTweet>();
                            feedSource = "grab user:" + userName;
                            tweets.addAll(tweetSearch.getTweets(new JUser(userName), new ArrayList<JUser>(),
                                    tweetCount));
                            logger.info("add " + tweets.size() + " tweets from user search: " + userName);
                        }
                    } catch (TwitterException ex) {
                        doAbort(ex);
                        logger.warn("Couldn't update user: " + userName + " " + ex.getLocalizedMessage());
                    }
                } else if (queryStr != null && !queryStr.isEmpty()) {
                    try {
                        if (!isSearchDoneInLastMinutes(queryStr)) {
                            //                                logger.info("lastsearches hashcode:" + lastSearches.hashCode());
                            tweets = new LinkedBlockingQueue<JTweet>();
                            feedSource = "grab query:" + queryStr;
                            tweetSearch.search(queryStr, tweets, tweetCount, 0);
                            logger.info("added " + tweets.size() + " tweets via twitter search: " + queryStr);
                        }
                    } catch (TwitterException ex) {
                        doAbort(ex);
                        logger.warn("Couldn't query twitter: " + queryStr + " " + ex.getLocalizedMessage());
                    }
                }
            } else
                feedSource = "filledTweets:" + tweets.size();

            try {
                if (tweets != null && tweets.size() > 0 && !feedSource.isEmpty()) {
                    for (JTweet tw : tweets) {
                        rmiClient.get().init().send(tw.setFeedSource(feedSource));
                    }
                }
            } catch (Exception ex) {
                logger.warn("Error while sending tweets to queue server" + ex.getMessage());
            }
        }
    };
}

From source file:de.jetwick.tw.TwitterSearch.java

License:Apache License

public int getSecondsUntilReset() {
    try {/*from w w  w  .  j  a  v a  2  s  .com*/
        RateLimitStatus rls = twitter.getRateLimitStatus();
        rateLimit = rls.getRemainingHits();
        return rls.getSecondsUntilReset();
    } catch (TwitterException ex) {
        logger.error("Cannot determine rate limit:" + ex.getMessage());
        return -1;
    }
}

From source file:de.jetwick.tw.TwitterSearch.java

License:Apache License

public void getFriendsOrFollowers(String userName, AnyExecutor<JUser> executor, boolean friends) {
    long cursor = -1;
    resetRateLimitCache();/*from w  w w  . j a  v a 2 s .  c o m*/
    MAIN: while (true) {
        while (getRateLimitFromCache() < LIMIT) {
            int reset = getSecondsUntilReset();
            if (reset != 0) {
                logger.info("no api points left while getFriendsOrFollowers! Skipping ...");
                return;
            }
            resetRateLimitCache();
            myWait(0.5f);
        }

        ResponseList res = null;
        IDs ids = null;
        try {
            if (friends)
                ids = twitter.getFriendsIDs(userName, cursor);
            else
                ids = twitter.getFollowersIDs(userName, cursor);

            rateLimit--;
        } catch (TwitterException ex) {
            logger.warn(ex.getMessage());
            break;
        }
        if (ids.getIDs().length == 0)
            break;

        long[] intids = ids.getIDs();

        // split into max 100 batch            
        for (int offset = 0; offset < intids.length; offset += 100) {
            long[] limitedIds = new long[100];
            for (int ii = 0; ii + offset < intids.length && ii < limitedIds.length; ii++) {
                limitedIds[ii] = intids[ii + offset];
            }

            // retry at max N times for every id bunch
            for (int i = 0; i < 5; i++) {
                try {
                    res = twitter.lookupUsers(limitedIds);
                    rateLimit--;
                    for (Object o : res) {
                        User user = (User) o;
                        // strange that this was necessary for ibood
                        if (user.getScreenName().trim().isEmpty())
                            continue;

                        JUser jUser = new JUser(user);
                        if (executor.execute(jUser) == null)
                            break MAIN;
                    }
                    break;
                } catch (Exception ex) {
                    ex.printStackTrace();
                    myWait(5);
                    continue;
                }
            }

            if (res == null) {
                logger.error("giving up");
                break;
            }
        }

        if (!ids.hasNext())
            break;

        cursor = ids.getNextCursor();
    }
}

From source file:de.vanita5.twittnuker.util.Utils.java

License:Open Source License

public static String getTwitterErrorMessage(final Context context, final CharSequence action,
        final TwitterException te) {
    if (context == null)
        return null;
    if (te == null)
        return context.getString(R.string.error_unknown_error);
    if (te.exceededRateLimitation()) {
        final RateLimitStatus status = te.getRateLimitStatus();
        final long secUntilReset = status.getSecondsUntilReset() * 1000;
        final String nextResetTime = ParseUtils
                .parseString(getRelativeTimeSpanString(System.currentTimeMillis() + secUntilReset));
        if (isEmpty(action))
            return context.getString(R.string.error_message_rate_limit, nextResetTime.trim());
        return context.getString(R.string.error_message_rate_limit_with_action, action, nextResetTime.trim());
    } else if (te.getErrorCode() > 0) {
        final String msg = StatusCodeMessageUtils.getTwitterErrorMessage(context, te.getErrorCode());
        return getErrorMessage(context, action, msg != null ? msg : trimLineBreak(te.getMessage()));
    } else if (te.getCause() instanceof SSLException) {
        final String msg = te.getCause().getMessage();
        if (msg != null && msg.contains("!="))
            return getErrorMessage(context, action, context.getString(R.string.ssl_error));
        else/*from   ww  w.  ja  v a2 s. c om*/
            return getErrorMessage(context, action, context.getString(R.string.network_error));
    } else if (te.getCause() instanceof IOException)
        return getErrorMessage(context, action, context.getString(R.string.network_error));
    else if (te.getCause() instanceof JSONException)
        return getErrorMessage(context, action, context.getString(R.string.api_data_corrupted));
    else
        return getErrorMessage(context, action, trimLineBreak(te.getMessage()));
}

From source file:de.vanita5.twittnuker.util.Utils.java

License:Open Source License

public static String getTwitterErrorMessage(final Context context, final TwitterException te) {
    if (te == null)
        return null;
    if (StatusCodeMessageUtils.containsTwitterError(te.getErrorCode()))
        return StatusCodeMessageUtils.getTwitterErrorMessage(context, te.getErrorCode());
    else if (StatusCodeMessageUtils.containsHttpStatus(te.getStatusCode()))
        return StatusCodeMessageUtils.getHttpStatusMessage(context, te.getStatusCode());
    else/*  w w w.jav  a2 s .  c o  m*/
        return te.getMessage();
}

From source file:de.vanita5.twittnuker.util.Utils.java

License:Open Source License

public static void showTwitterErrorMessage(final Context context, final CharSequence action,
        final TwitterException te, final boolean long_message) {
    if (context == null)
        return;// w ww .  ja v  a  2 s  .  c om
    final String message;
    if (te != null) {
        if (action != null) {
            if (te.exceededRateLimitation()) {
                final RateLimitStatus status = te.getRateLimitStatus();
                final long sec_until_reset = status.getSecondsUntilReset() * 1000;
                final String next_reset_time = ParseUtils
                        .parseString(getRelativeTimeSpanString(System.currentTimeMillis() + sec_until_reset));
                message = context.getString(R.string.error_message_rate_limit_with_action, action,
                        next_reset_time.trim());
            } else if (isErrorCodeMessageSupported(te)) {
                final String msg = StatusCodeMessageUtils.getMessage(context, te.getStatusCode(),
                        te.getErrorCode());
                message = context.getString(R.string.error_message_with_action, action,
                        msg != null ? msg : trimLineBreak(te.getMessage()));
            } else if (te.getCause() instanceof SSLException) {
                final String msg = te.getCause().getMessage();
                if (msg != null && msg.contains("!=")) {
                    message = context.getString(R.string.error_message_with_action, action,
                            context.getString(R.string.ssl_error));
                } else {
                    message = context.getString(R.string.error_message_with_action, action,
                            context.getString(R.string.network_error));
                }
            } else if (te.getCause() instanceof IOException) {
                message = context.getString(R.string.error_message_with_action, action,
                        context.getString(R.string.network_error));
            } else {
                message = context.getString(R.string.error_message_with_action, action,
                        trimLineBreak(te.getMessage()));
            }
        } else {
            message = context.getString(R.string.error_message, trimLineBreak(te.getMessage()));
        }
    } else {
        message = context.getString(R.string.error_unknown_error);
    }
    showErrorMessage(context, message, long_message);
}

From source file:edu.allegheny.gatortweet.GetHomeTimeline.java

License:Apache License

public static void main(String[] args) {
    try {/*w  w w  .  j  ava  2  s. c o m*/
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey("rPtRCCRqdDyoxHS3E2UARA")
                .setOAuthConsumerSecret("hhDnR4NETStvN4F84km2xuBy3eXJ8l2FnjdL23YPs");
        // gets Twitter instance with default credentials
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();
        /* Twitter twitter = new TwitterFactory().getInstance(); */
        User user = twitter.verifyCredentials();
        List<Status> statuses = twitter.getHomeTimeline();
        //System.out.println("Showing @" + user.getScreenName() + "'s home timeline.");
        for (Status status : statuses) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
        }
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:edu.mum.cs.wap.TwitterUtil.java

private static List<Status> getStatusesByKeyword(String keyword) {
    try {/*from www . java  2  s  . co  m*/
        Query query = new Query("movie " + keyword + "-filter:retweets");
        query.setCount(8);
        QueryResult result;
        do {
            result = twitter.search(query);
            return result.getTweets();
        } while ((query = result.nextQuery()) != null);
    } catch (TwitterException te) {
        System.out.println("Failed to search tweets: " + te.getMessage());
    }
    return null;
}

From source file:edu.umich.cse.pyongjoo.twittercrawl.GetUserTimeline.java

License:Apache License

/**
 * Usage: java twitter4j.examples.timeline.GetUserTimeline
 *
 * @param args String[]//from www.jav  a2s . c  o m
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    OAuthTokenReader oauth = new OAuthTokenReader("oauth_tokens.csv");

    TwitterFactory tf = new TwitterFactory(oauth.getNextConfiguration());

    // gets Twitter instance with default credentials
    Twitter twitter = tf.getInstance();

    if (args.length < 2) {
        System.err.println("Usuage: command [username] [outputfile]");
        System.exit(-1);
    }
    String filename = args[1];

    FileWriter fstream = new FileWriter(filename, true);
    BufferedWriter out = new BufferedWriter(fstream);

    String user = "";
    if (args.length >= 1) {
        user = args[0];
    }
    //      out.write("#document starts with username: " + user + "\n");

    for (int i = 1; i <= 1; i++) {
        Paging pagingOption = new Paging(i, 200);

        try {
            List<Status> statuses;

            statuses = twitter.getUserTimeline(user, pagingOption);

            System.out.println("My Custom Showing @" + user + "'s user timeline.");

            for (Status status : statuses) {
                out.write(status.toString() + '\n');
                System.out.println(status.getUser().getScreenName() + "tweets written.");
            }
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to get timeline: " + te.getMessage());

            // close the file
            out.close();
            //              output.close();

            System.exit(-1);
        }
    }

    // close the file
    out.close();
    //      output.close();
}

From source file:ehealth.external.twitter.GetAccessToken.java

License:Apache License

/**
 * Usage: java  twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]
 *
 * @param args message/*w ww  . j a  va2s. c o m*/
 */

protected void loginTwitter(String[] args) {
    File file = new File("twitter4j.properties");
    Properties prop = new Properties();
    InputStream is = null;
    OutputStream os = null;
    try {
        if (file.exists()) {
            is = new FileInputStream(file);
            prop.load(is);
        }
        if (args.length < 2) {
            if (null == prop.getProperty("oauth.consumerKey")
                    && null == prop.getProperty("oauth.consumerSecret")) {
                // consumer key/secret are not set in twitter4j.properties
                System.out.println(
                        "Usage: java twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]");
                System.exit(-1);
            }
        } else {
            prop.setProperty("oauth.consumerKey", args[0]);
            prop.setProperty("oauth.consumerSecret", args[1]);
            os = new FileOutputStream("twitter4j.properties");
            prop.store(os, "twitter4j.properties");
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.exit(-1);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ignore) {
            }
        }
        if (os != null) {
            try {
                os.close();
            } catch (IOException ignore) {
            }
        }
    }
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        RequestToken requestToken = twitter.getOAuthRequestToken();
        System.out.println("Got request token.");
        System.out.println("Request token: " + requestToken.getToken());
        System.out.println("Request token secret: " + requestToken.getTokenSecret());
        AccessToken accessToken = null;

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        while (null == accessToken) {
            System.out.println("Open the following URL and grant access to your account:");
            System.out.println(requestToken.getAuthorizationURL());
            try {
                Desktop.getDesktop().browse(new URI(requestToken.getAuthorizationURL()));
            } catch (UnsupportedOperationException ignore) {
            } catch (IOException ignore) {
            } catch (URISyntaxException e) {
                throw new AssertionError(e);
            }
            System.out.print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:");
            String pin = br.readLine();
            try {
                if (pin.length() > 0) {
                    accessToken = twitter.getOAuthAccessToken(requestToken, pin);
                } else {
                    accessToken = twitter.getOAuthAccessToken(requestToken);
                }
            } catch (TwitterException te) {
                if (401 == te.getStatusCode()) {
                    System.out.println("Unable to get the access token.");
                } else {
                    te.printStackTrace();
                }
            }
        }
        System.out.println("Got access token.");
        System.out.println("Access token: " + accessToken.getToken());
        System.out.println("Access token secret: " + accessToken.getTokenSecret());

        try {
            prop.setProperty("oauth.accessToken", accessToken.getToken());
            prop.setProperty("oauth.accessTokenSecret", accessToken.getTokenSecret());
            os = new FileOutputStream(file);
            prop.store(os, "twitter4j.properties");
            os.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
            System.exit(-1);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException ignore) {
                }
            }
        }
        System.out.println("Successfully stored access token to " + file.getAbsolutePath() + ".");
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get accessToken: " + te.getMessage());
        System.exit(-1);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.out.println("Failed to read the system input.");
        System.exit(-1);
    }
}