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:Collector.TweetCollector.java

public static List<Status> printTimeLine(String account) {

    try {/*from   www .  j a v  a  2 s  .co m*/
        Query query = new Query(account);

        QueryResult result = twitter.search(query);

        List<Status> tweets = result.getTweets();

        for (Status tweet : tweets) {
            System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
        }
        return tweets;

    } catch (TwitterException te) {
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
    return null;
}

From source file:collector.TwitterCollector.java

public LinkedHashSet<Tweet> search(String queryExpression, int maxResults) {
    Query query = new Query(queryExpression);
    int numberOfTweets = maxResults;//512;
    long lastID = Long.MAX_VALUE;
    query = query.lang("pt");
    List<Status> tweets = new ArrayList<>();
    boolean finish = false;
    while ((tweets.size() < numberOfTweets) && !finish) {
        System.out.print(".");
        if (numberOfTweets - tweets.size() > 100) {//100) {
            query.setCount(100);//100);
        } else {/*from   w w  w  .  j  a v a 2s  .c  o  m*/
            query.setCount(numberOfTweets - tweets.size());
        }
        try {
            QueryResult result = twitter.search(query);
            List<Status> resultList = result.getTweets();
            if (resultList == null || resultList.isEmpty()) {
                finish = true;
                System.out.println("no foram encontrados mais tweets");
            } else {
                tweets.addAll(resultList);
                for (Status t : tweets) {
                    if (t.getId() < lastID) {
                        lastID = t.getId();
                    }
                }
            }
        } catch (TwitterException ex) {
            System.err.println(ex.getMessage());
        }
        query.setMaxId(lastID - 1);
    }
    LinkedHashSet<Tweet> out = new LinkedHashSet<>();
    for (Status status : tweets) {
        if (!status.getText().startsWith("RT")) {
            TwitterUser user;
            user = new TwitterUser().addID(status.getUser().getId()).addName(status.getUser().getName())
                    .addLocation(status.getUser().getLocation()).addDateSignin(status.getUser().getCreatedAt())
                    .addCountTweets(status.getUser().getStatusesCount())
                    .addCountFavorites(status.getUser().getFavouritesCount())
                    .addCountFriends(status.getUser().getFriendsCount())
                    .addCountFollowers(status.getUser().getFollowersCount());
            Tweet tweet = new Tweet().addUser(user).addText(status.getText()).addID(status.getId())
                    .addDate(status.getCreatedAt())
                    .addLatitude(status.getGeoLocation() != null ? status.getGeoLocation().getLatitude()
                            : Double.MAX_VALUE)
                    .addLongitude(status.getGeoLocation() != null ? status.getGeoLocation().getLongitude()
                            : Double.MAX_VALUE);
            out.add(tweet);
        }
    }
    return out;
}

From source file:collector.TwitterCollector.java

public LinkedHashSet<Tweet> userSearchData(String userName, int maxResults) {

    LinkedHashSet<Tweet> out = new LinkedHashSet<>();
    Paging paging = new Paging(1, 180);
    int numberOfTweets = maxResults;//512;
    long lastID = Long.MAX_VALUE;
    ArrayList<Status> status = new ArrayList<>();
    while (status.size() < numberOfTweets) {
        if (numberOfTweets - status.size() > 180) {//100) {
            paging.setCount(180);//100);
        } else {//w  w  w  .jav  a  2s .c  o m
            paging.setCount(numberOfTweets - status.size());
        }
        try {
            List<Status> timeLine = twitter.getUserTimeline(userName, paging);
            status.addAll(timeLine);
            for (Status t : status) {
                if (t.getId() < lastID) {
                    lastID = t.getId();
                }
            }
        } catch (TwitterException ex) {
            System.err.println(ex.getMessage());
        }
        paging.setMaxId(lastID - 1);
    }

    //armazenar os atributos interessantes a analise dos tweets
    int qtdretweet = 0;
    for (Status sta : status) {
        String text = sta.getText();
        if (!sta.isRetweet() && !sta.isRetweeted() && !text.startsWith("RT")) { //&& !TweetMediaDetect.detect(text)) {
            TwitterUser user;
            user = new TwitterUser().addID(sta.getUser().getId()).addName(sta.getUser().getName())
                    .addLocation(sta.getUser().getLocation()).addDateSignin(sta.getUser().getCreatedAt())
                    .addCountTweets(sta.getUser().getStatusesCount())
                    .addCountFavorites(sta.getUser().getFavouritesCount())
                    .addCountFriends(sta.getUser().getFriendsCount())
                    .addCountFollowers(sta.getUser().getFollowersCount());
            Tweet tweet = new Tweet().addUser(user).addText(sta.getText()).addID(sta.getId())
                    .addDate(sta.getCreatedAt())
                    .addLatitude(sta.getGeoLocation() != null ? sta.getGeoLocation().getLatitude()
                            : Double.MAX_VALUE)
                    .addLongitude(sta.getGeoLocation() != null ? sta.getGeoLocation().getLongitude()
                            : Double.MAX_VALUE);
            out.add(tweet);
        } else {
            qtdretweet++;
        }
    }

    return out;
}

From source file:com.adisayoga.earthquake.wrapper.EarthquakeTwitter.java

License:Apache License

/**
 * Kirim sebuah tweet pada timeline anda.
 * /*from ww w . j a v a  2s . c om*/
 * @param message Pesan yang dikirim
 * @return True jika tweet berhasil, false jika gagal
 */
public boolean postMessage(String message) {
    try {
        twitter.updateStatus(message);
        Log.d(TAG, "Post sent: " + message);
        return true;

    } catch (TwitterException e) {
        Log.e(TAG, "Post error: " + e.getMessage(), e);
        return false;
    }
}

From source file:com.adisayoga.earthquake.wrapper.TwitterLoginActivity.java

License:Apache License

/**
 * Buat sebuah request yang akan dikirim ke Twitter menanyakan 
 * <i>'apakah aplikasi ini punya ijin untuk menggunakan Twitter untuk user ini?</i>
 * <p>//from www  . java  2s  . c o m
 * Akan dikembalikan ke {@link #reqToken} yaitu sebuah pengenal unik
 * pada request ini.
 * Browse kemudian muncul pada website Twitter dan user login (kita tidak
 * pernah melihat informasi ini).
 * Twitter kemudian redirect ke callbackUrl jika login sukses.
 */
private void loginNewUser() {
    try {
        Log.d(TAG, "Request app authentication...");
        reqToken = twitter.getOAuthRequestToken(CALLBACK_URL);
        String url = reqToken.getAuthenticationURL();
        Log.d(TAG, "Authentication url: " + url);
        webView.loadUrl(url);

    } catch (TwitterException e) {
        Log.e(TAG, "Twitter login error: " + e.getMessage(), e);
        Toast.makeText(this, R.string.auth_fail, Toast.LENGTH_SHORT).show();
        finish();
    }
}

From source file:com.ahuralab.mozaic.ReplyTask.java

License:Open Source License

@Override
protected Boolean doInBackground(Void... params) {
    // TODO use global authenticator
    TwitterAuthenticator auth = new TwitterAuthenticator();
    Twitter twitter = auth.createTwitter(context);
    TwitterClient client = new TwitterClient(twitter);

    try {//w ww  .jav a 2  s.c  om
        client.replyTweetMessage(userName, reply);
    } catch (TwitterException e) {
        Log.e(TimelineActivity.TAG, "" + e.getMessage(), e);
        return false;
    }
    return true;
}

From source file:com.ahuralab.mozaic.ReTweetTask.java

License:Open Source License

@Override
protected Boolean doInBackground(Void... params) {

    // TODO use global authenticator
    TwitterAuthenticator auth = new TwitterAuthenticator();
    Twitter twitter = auth.createTwitter(context);

    TwitterClient client = new TwitterClient(twitter);
    try {/*from   w  w  w . j  a  va2 s  . co m*/
        client.reTweet(tweetId);
    } catch (TwitterException e) {
        Log.e(TimelineActivity.TAG, "" + e.getMessage(), e);
        return false;
    }
    return true;
}

From source file:com.ahuralab.mozaic.UnFollowTask.java

License:Open Source License

@Override
protected Boolean doInBackground(Void... params) {

    // TODO use global authenticator
    TwitterAuthenticator auth = new TwitterAuthenticator();
    Twitter twitter = auth.createTwitter(context);

    TwitterClient client = new TwitterClient(twitter);
    try {//from ww w . j ava2  s  .c  om
        client.destroyFriendship(userScreenName);
    } catch (TwitterException e) {
        Log.e(TimelineActivity.TAG, "" + e.getMessage(), e);
        return false;
    }
    return true;
}

From source file:com.aldebaran.demo.picture.GetAccessToken.java

License:Apache License

/**
 * Usage: java  twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]
 *
 * @param args message/*w  w  w .  j  a v a  2 s  . c  o m*/
 */
public static void main(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);
    }
}

From source file:com.allenzheng.twittersyn.controller.AccountServlet.java

License:Apache License

    public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws IOException, ServletException{
      String action = request.getParameter(PARAM_ACTION);
      // www  . jav a2  s  . c om
      HttpSession session = request.getSession();
      
      if(ACTION_TWITTER_SIGN_IN.equals(action)){
         logger.debug("Signing in with Twitter...");
         TwitterAPIImpl twitterapi = new TwitterAPIImpl();
         
         String id = null;
         Cookie[] cookies = request.getCookies();
         for (int i = 0; i < cookies.length; i++) {
            Cookie cookie;
            cookie = cookies[i];
            if (COOKIE_TWITTER_ID.equals(cookie.getName())) {
               id = cookie.getValue();
            }
         }
         
         AccessToken accessToken = null;
         if (id != null){
            
         }
         
         
      }
      
      String oauthToken = request.getParameter(PARAM_OAUTH_TOKEN);
      if(oauthToken != null){
         logger.debug(PARAM_OAUTH_TOKEN + " received from Twitter");
         try {
            Twitter twitter = (Twitter) session.getAttribute(ATTR_TWITTER);
            RequestToken requestToken = (RequestToken) session
                  .getAttribute(ATTR_REQUEST_TOKEN);
            AccessToken accessToken;
            if (callbackUrl == null) {
               accessToken = twitter.getOAuthAccessToken(requestToken);
            } else {
               String oauthVerifier = request
                     .getParameter(PARAM_OAUTH_VERIFIER);
               logger.debug(PARAM_OAUTH_VERIFIER
                     + " received from Twitter");
               accessToken = twitter.getOAuthAccessToken(requestToken.getToken(), requestToken.getTokenSecret(),
                     oauthVerifier);
            }
            twitter.setOAuthAccessToken(accessToken);
            session.removeAttribute(ATTR_REQUEST_TOKEN);
            session.setAttribute(ATTR_TWITTER, twitter);

            int id = twitter.verifyCredentials().getId();
            logger.debug("Access token retrieved for user " + id
                  + " from Twitter");
//            storeAccessToken(id, accessToken);
            Cookie cookie = new Cookie(COOKIE_TWITTER_ID, "" + id);
            cookie.setMaxAge(63072000); // Valid for 2 years
            response.addCookie(cookie);
            logger.debug("Cookie set for user " + id);

            // Get last status and friends' timelines
//            getMyLastStatusAndStoreInSession(session);
//            getFriendsTimelinesAndStoreInSession(session);

            // Go to the update status page
//            request.getRequestDispatcher(PAGE_UPDATE_STATUS).forward(
//                  request, response);
         } catch (TwitterException e) {
            logger.error("Failed to retrieve access token - "
                  + e.getMessage());
            throw new ServletException(e);
         }
      }
   }