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:twitter4j.examples.user.SearchUsers.java

License:Apache License

/**
 * Usage: java twitter4j.examples.user.SearchUsers [query]
 *
 * @param args message//from  w  w  w .  j  a  v  a 2 s  .co  m
 */
public static void main(String[] args) {
    if (args.length < 1) {
        System.out.println("Usage: java twitter4j.examples.user.SearchUsers [query]");
        System.exit(-1);
    }
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        int page = 1;
        ResponseList<User> users;
        do {
            users = twitter.searchUsers(args[0], page);
            for (User user : users) {
                if (user.getStatus() != null) {
                    System.out.println("@" + user.getScreenName() + " - " + user.getStatus().getText());
                } else {
                    // the user is protected
                    System.out.println("@" + user.getScreenName());
                }
            }
            page++;
        } while (users.size() != 0 && page < 50);
        System.out.println("done.");
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search users: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:twitter4j.examples.user.ShowUser.java

License:Apache License

/**
 * Usage: java twitter4j.examples.user.ShowUser [screen name]
 *
 * @param args message// www.  jav a2  s  .  c o  m
 */
public static void main(String[] args) {
    if (args.length < 1) {
        System.out.println("Usage: java twitter4j.examples.user.ShowUser [screen name]");
        System.exit(-1);
    }
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        User user = twitter.showUser(args[0]);
        if (user.getStatus() != null) {
            System.out.println("@" + user.getScreenName() + " - " + user.getStatus().getText());
        } else {
            // the user is protected
            System.out.println("@" + user.getScreenName());
        }
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to delete status: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:twitterapidemo.TwitterAPIDemo.java

License:Apache License

public static void main(String[] args) throws IOException, TwitterException {

    //TwitterAPIDemo twitterApiDemo = new TwitterAPIDemo();

    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(consumerKey);
    builder.setOAuthConsumerSecret(consumerSecret);
    Configuration configuration = builder.build();

    TwitterFactory twitterFactory = new TwitterFactory(configuration);
    Twitter twitter = twitterFactory.getInstance();
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    Scanner sc = new Scanner(System.in);
    System.out.println(/*w  w  w . jav a2 s . c o m*/
            "Enter your choice:\n1. To post tweet\n2.To search tweets\n3. Recent top 3 trends and number of posts of each trending topic");
    int choice = sc.nextInt();
    switch (choice) {
    case 1:
        System.out.println("What's happening: ");
        String post = sc.next();
        StatusUpdate statusUpdate = new StatusUpdate(post + "-Posted by TwitterAPI");
        Status status = twitter.updateStatus(statusUpdate);

        System.out.println("status.toString() = " + status.toString());
        System.out.println("status.getInReplyToScreenName() = " + status.getInReplyToScreenName());
        System.out.println("status.getSource() = " + status.getSource());
        System.out.println("status.getText() = " + status.getText());
        System.out.println("status.getContributors() = " + Arrays.toString(status.getContributors()));
        System.out.println("status.getCreatedAt() = " + status.getCreatedAt());
        System.out.println("status.getCurrentUserRetweetId() = " + status.getCurrentUserRetweetId());
        System.out.println("status.getGeoLocation() = " + status.getGeoLocation());
        System.out.println("status.getId() = " + status.getId());
        System.out.println("status.getInReplyToStatusId() = " + status.getInReplyToStatusId());
        System.out.println("status.getInReplyToUserId() = " + status.getInReplyToUserId());
        System.out.println("status.getPlace() = " + status.getPlace());
        System.out.println("status.getRetweetCount() = " + status.getRetweetCount());
        System.out.println("status.getRetweetedStatus() = " + status.getRetweetedStatus());
        System.out.println("status.getUser() = " + status.getUser());
        System.out.println("status.getAccessLevel() = " + status.getAccessLevel());
        System.out.println("status.getHashtagEntities() = " + Arrays.toString(status.getHashtagEntities()));
        System.out.println("status.getMediaEntities() = " + Arrays.toString(status.getMediaEntities()));
        if (status.getRateLimitStatus() != null) {
            System.out.println(
                    "status.getRateLimitStatus().getLimit() = " + status.getRateLimitStatus().getLimit());
            System.out.println("status.getRateLimitStatus().getRemaining() = "
                    + status.getRateLimitStatus().getRemaining());
            System.out.println("status.getRateLimitStatus().getResetTimeInSeconds() = "
                    + status.getRateLimitStatus().getResetTimeInSeconds());
            System.out.println("status.getRateLimitStatus().getSecondsUntilReset() = "
                    + status.getRateLimitStatus().getSecondsUntilReset());
        }
        System.out.println("status.getURLEntities() = " + Arrays.toString(status.getURLEntities()));
        System.out.println(
                "status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities()));
        break;
    case 2:
        System.out.println("Enter keyword");
        String keyword = sc.next();
        try {
            Query query = new Query(keyword);
            QueryResult result;
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    System.out.println(tweet.getCreatedAt() + ":\t@" + tweet.getUser().getScreenName() + " - "
                            + tweet.getText());
                }
            } while ((query = result.nextQuery()) != null);
            System.exit(0);
        } catch (TwitterException te) {
            System.out.println("Failed to search tweets: " + te.getMessage());
            System.exit(-1);
            break;
        }
    case 3:
        //WOEID for India = 23424848
        Trends trends = twitter.getPlaceTrends(23424848);
        int count = 0;
        for (Trend trend : trends.getTrends()) {
            if (count < 3) {
                Query query = new Query(trend.getName());
                QueryResult result;
                int numberofpost = 0;
                do {
                    result = twitter.search(query);
                    List<Status> tweets = result.getTweets();
                    for (Status tweet : tweets) {
                        numberofpost++;
                    }
                } while ((query = result.nextQuery()) != null);
                System.out
                        .println("Number of post for the topic '" + trend.getName() + "' is: " + numberofpost);
                count++;
            } else
                break;
        }
        break;
    default:
        System.out.println("Invalid input");
    }
}

From source file:twitterrest.GetHomeTimeline.java

License:Apache License

public static void main(String[] args) {
    try {//w  ww .j ava2  s.co  m
        // ?
        Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(CONSUMER_KEY)
                .setOAuthConsumerSecret(CONSUMER_SECRET).setOAuthAccessToken(ACCESS_TOKEN)
                .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET).build();
        Twitter twitter = new TwitterFactory(configuration).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:twittersentimentanalysis.TwitterSentimentAnalysis.java

private static ArrayList<Tweet> getAllTweets(Twitter twitter) {
    logger.info("getAllTweets");
    List<Status> listTweets = null;
    ArrayList<Tweet> listOfTweets = new ArrayList<Tweet>();
    try {//from   w ww .j  a  v a 2s. co  m
        Trends trends = twitter.getPlaceTrends(23424977);
        // System.out.println(trends.getLocation());
        Trend trend[] = trends.getTrends();
        logger.info("Number of Trends : " + trend.length);
        for (Trend trendTemp : trend) {
            //System.out.println("Name = " + trendTemp.getName());
            //System.out.println("***************");
            Query query = new Query(trendTemp.getQuery());
            query.setCount(100);
            QueryResult queryResult = twitter.search(query);
            listTweets = queryResult.getTweets();
            StanfordCoreNLPTool.init();
            for (Status status : listTweets) {
                //System.out.println(status.getText());
                Tweet tweet = getTweetObject(status);
                if (tweet != null) {
                    tweet.setTrend(trendTemp.getName());
                    listOfTweets.add(tweet);
                }
            }
        }
    } catch (TwitterException ex) {
        Logger.getLogger(TwitterSentimentAnalysis.class.getName()).log(Level.SEVERE, null, ex);
        logger.info(ex.getMessage());
    }
    return listOfTweets;
}

From source file:twittynumnum.BackwardGrinder.java

public void grind(String queryString) {

    try {/*from  ww  w.  j  ava  2 s  .c o  m*/
        Query query = new Query(queryString);
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText() + " - "
                        + tweet.getCreatedAt());
            }
        } while ((query = result.nextQuery()) != null);
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:uk.ac.cam.cl.dtg.segue.auth.TwitterAuthenticator.java

License:Apache License

@Override
public OAuth1Token getRequestToken() throws IOException {
    RequestToken requestToken;//  ww w . ja  va  2 s.  c  o m
    try {
        twitter.setOAuthAccessToken(null); // ensure we start from a blank slate
        requestToken = twitter.getOAuthRequestToken(callbackUri);
    } catch (TwitterException e) {
        throw new IOException(e.getMessage());
    }
    return new OAuth1Token(requestToken.getToken(), requestToken.getTokenSecret());
}

From source file:uk.ac.cam.cl.dtg.segue.auth.TwitterAuthenticator.java

License:Apache License

@Override
public synchronized UserFromAuthProvider getUserInfo(final String internalProviderReference)
        throws NoUserException, IOException, AuthenticatorSecurityException {
    Credential credentials = credentialStore.get(internalProviderReference);
    twitter.setOAuthAccessToken(new AccessToken(credentials.getAccessToken(), credentials.getRefreshToken()));

    try {//from w  ww . j a  v a2s .c om
        twitter4j.User userInfo = twitter.verifyCredentials();

        if (userInfo != null) {
            // Using twitter id for email field is a hack to avoid a duplicate
            // exception due to null email field. Alistair and Steve dislike this...
            String givenName = null;
            String familyName = null;
            if (userInfo.getName() != null) {
                String[] names = userInfo.getName().split(" ");
                if (names != null) {
                    if (names.length > 0) {
                        givenName = names[0];
                    }
                    if (names.length > 1) {
                        familyName = names[1];
                    }
                }
            }

            return new UserFromAuthProvider(String.valueOf(userInfo.getId()), givenName, familyName,
                    userInfo.getId() + "-twitter", EmailVerificationStatus.NOT_VERIFIED, null, null, null);
        } else {
            throw new NoUserException();
        }
    } catch (TwitterException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:uk.ac.susx.tag.method51.twitter.pipeline.TweetSearch.java

License:Apache License

@Override
protected void doWork() throws Exception {
    try {//from   www . j av  a2s  .  c  o m

        final QueryResult result = twitter.search(query);

        final List<Status> statuses = result.getTweets();
        final List<Tweet> tweets = new ArrayList<>();

        for (final Status status : statuses) {

            getStats().update(status);

            final Tweet tweet = new Tweet(status);

            //strip out descs and urls
            if (!incProfileDescriptionUrl) {
                tweet.setDescription(null);
                tweet.setUrl(null);
            }

            tweets.add(tweet);

        }

        LOG.info("got {} tweets", tweets.size());
        long minId = getStats().getMinId();
        LOG.info("min id {}", new DateTime(Util.getInfoFromId(minId)[0]).toString("yyyy-MM-dd HH:mm:ss"));

        getStats().incrementTotal(tweets.size());

        LOG.info("{} / {} = {} tps", getStats().getTotal(), getStats().getDuration(TimeUnit.SECONDS),
                getStats().getTweetsPer(TimeUnit.SECONDS));

        produce(tweets);

        if (false && !result.hasNext()) {
            throw new ProducerUnderflowException("No more search result available.");
        } else if (tweets.size() == 0) {
            throw new ProducerUnderflowException("No more search result available.");
        } else if (searchRequested >= 0 && getStats().getTotal() >= searchRequested) {
            throw new ProducerUnderflowException("Reached requested size.");
        } else {
            query.setMaxId(getStats().getMinId() - 1);
            //query = result.nextQuery();
        }

    } catch (final TwitterException e) {

        switch (e.getStatusCode()) {

        case 130: {
            //over-capacity
            LOG.warn(e.getMessage());
            query.setMaxId(getStats().getMinId());

            int retryAfter = 60;

            LOG.info("rate limited - sleeping for {} seconds", retryAfter);
            Thread.sleep(1000 * (retryAfter + 1));
            break;
        }
        case 403:
            query.setMaxId(getStats().getMinId());
            LOG.info("ID reached: {}", getStats().getMinId());
            LOG.warn(e.getMessage());
            throw e;
            //break;

        case 420:
            LOG.info("rate limited - sleeping for 60 seconds", e);
            Thread.sleep(60000);
            break;

        case 429:
            LOG.error("", e);

            Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus();
            int retryAfter = rateLimitStatus.get("/search/tweets").getSecondsUntilReset();

            LOG.info("rate limited - sleeping for {} seconds", retryAfter);
            Thread.sleep(1000 * (retryAfter + 1));

            break;
        default:
            throw e;
        }
    } catch (Method51Exception e) {
        setStateFailure(e);
    }
}

From source file:uk.ac.susx.tag.method51.webapp.handler.TwitterPinAuthHandler.java

License:Apache License

private void requestAuthUrl(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    Params params = new Params();

    params.addValidator("consumer_key", new SystemStringValidator(true));
    params.addValidator("consumer_secret", new SystemStringValidator(true));

    new DoSomethingAfterValidatingMyParams(params, request, response) {

        @Override//  ww  w  .ja  v a 2 s.co  m
        public void something() throws IOException {

            String consumerKey = request.getParameter("consumer_key");
            String consumerSecret = request.getParameter("consumer_secret");

            TwitterPinAuthentication auth = new TwitterPinAuthentication(consumerKey, consumerSecret);

            String url = null;

            if (auths.size() > maxConcurrentRequests) {

                error("too many auth requests, wait up to " + timeout + " seconds for a timeout.");
            } else {

                try {

                    url = auth.requestAuthUrl();

                    LOG.info("requested url: {}", url);
                } catch (TwitterException e) {

                    error("Something went wrong when requesting an aut URL, incorrect consumer key/secret? "
                            + e.getMessage());
                }
            }

            if (url != null) {
                final long timestamp = new Date().getTime();

                executor.schedule(new Runnable() {
                    @Override
                    public void run() {

                        auths.remove(timestamp);
                        LOG.info("{} timed out", timestamp);
                    }
                }, timeout, TimeUnit.SECONDS);

                auths.put(timestamp, auth);

                okHereIsYourJson(response, "timeout", timeout, "response_key", timestamp, "url", url);
            }
        }
    };
}