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:com.mycompany.omnomtweets.RetweetersOfCandidate.java

/**
 * Method to get the 200 most recent tweets from a candidate.
 * @return List of 200 most recent tweet ids.
 *//*www .j  a v a 2  s.  c  om*/
public List<String> getCandidateTweetIds() {
    List<String> candidateTweetIds = new ArrayList<>();

    //First try to read in unprocessed tweets
    List<String> processedIds = new ArrayList<>();
    String tempFileName = (candidate.name + "Tweets.txt").replace(" ", "");
    File f1 = new File(tempFileName);
    FileReader fr;
    try {
        fr = new FileReader(f1);
        BufferedReader br = new BufferedReader(fr);
        String line;
        while ((line = br.readLine()) != null) {
            if (line.contains("Processed")) {
                processedIds.add(line.split(",")[0]);
            } else {
                candidateTweetIds.add(line);
            }
        }
        fr.close();
        br.close();
    } catch (Exception ex) {
        System.out.println("Something went wrong with file IO");
    }

    //If there weren't any unproccessed ones, get some new ones.
    if (candidateTweetIds.isEmpty()) {
        try {
            List<Status> statuses;

            Paging paging = new Paging(1, 200);
            statuses = twitter.getUserTimeline(candidate.account, paging);
            //System.out.println("Gathered: " + statuses.size() + " tweet ids");
            for (Status status : statuses) {
                candidateTweetIds.add(String.valueOf(status.getId()));
            }

            //File to store tweetIds in as an intermediary.
            FileWriter writeCandidateTweets = new FileWriter(new File(tempFileName), true);
            for (String tweetId : candidateTweetIds) {
                writeCandidateTweets.write(tweetId + "\n");
            }
            writeCandidateTweets.close();

        } catch (TwitterException te) {
            System.out.println("Failed to get timeline: " + te.getMessage());
        } catch (IOException ex) {
            Logger.getLogger("FileWriting sucks");
        }
    }
    return candidateTweetIds;
}

From source file:com.mycompany.omnomtweets.RetweetersOfCandidate.java

/**
 * Method user IDs of retweeters.  Paginates on cursor.
 * @param tweetId id of the tweet we are getting retweeters of
 * @param calls number of API calls left
 * @return List of users that retweeted the given tweet.
 */// w  w  w.ja v a2 s.c  o  m
public List<String> getRetweeters(String tweetId) {
    //System.out.println("Getting retweeters of " + tweetId);
    List<String> retweeters = new ArrayList<>();
    IDs currentIDs;
    try {
        if (calls > 0) {
            calls -= 1;
            currentIDs = twitter.getRetweeterIds(Long.parseLong(tweetId), -1);
            long[] longIDs = currentIDs.getIDs();
            //System.out.println("Got " + longIDs.length + " retweeters");
            for (int i = 0; i < longIDs.length; i++) {
                retweeters.add("" + longIDs[i]);
            }
            while (calls > 0 && currentIDs.hasNext()) {
                calls -= 1;
                currentIDs = twitter.getRetweeterIds(Long.parseLong(tweetId), currentIDs.getNextCursor());
                longIDs = currentIDs.getIDs();
                //System.out.println("Adding " + longIDs.length + " retweeters");
                for (int i = 0; i < longIDs.length; i++) {
                    retweeters.add("" + longIDs[i]);
                }
            }
        } else {
            System.out.println("Cut off early");
            return retweeters;
        }
    } catch (TwitterException ex) {
        System.out.println("Failed to get rate limit status: " + ex.getMessage());
        return retweeters;
    }
    return retweeters;
}

From source file:com.mycompany.omnomtweets.TweetsAboutCandidates.java

/**
 * Searches for tweets using the given query string.
 * @param str the query to use// w w w.j a v a 2  s.  co m
 * @return List of the tweet statuses that match the query.
 */
public List<Status> search(String str, long maxId) {
    List<Status> tweets = null;
    try {
        Query query = new Query(str);
        query.setCount(100);
        //English only.
        query.setLang("en");
        QueryResult result;
        query.setMaxId(maxId);
        result = twitter.search(query);
        tweets = result.getTweets();
    } catch (TwitterException te) {
        System.out.println("Failed to search tweets: " + te.getMessage());
    }
    return tweets;
}

From source file:com.mycompany.twitterapp.TwitterApp.java

public void getTimeline() {
    Set<String> keySet = listOfPeople.keySet();
    for (String key : keySet) {
        System.out.println("Debug Person - " + key);
        try {/*from w w w  .  j  a  v  a 2 s . c om*/
            List<Status> statuses = null;
            for (int i = 1; i < 16; i++) {
                statuses = twitter.getUserTimeline(key, new Paging(i));
                System.out.println("Debug - filling statuses = " + i + " - Size: " + statuses.size());

                if (statuses.size() < 1 || statuses == null) {
                    System.out.println("List Empty.");
                    break;
                }
                //System.out.println("Showing @" + statuses.get(0).getUser().getScreenName() + "'s home timeline.");
                for (Status status : statuses) {
                    //                        System.out.println("Debug - text: " + status.getText());
                    saveToFile(status.getUser().getId(), status.getText().replaceAll("\n", "\\\\n"),
                            status.getUser().getScreenName(), listOfPeople.get(key));
                    //                        System.out.println("debug - truncated: " + status.isTruncated());
                }
            }
            if (statuses.size() < 1 || statuses == null) {
                continue;
            }
            Status temp = statuses.get(0);
            saveToFile(temp.getUser().getId(), temp.getUser().getScreenName(), listOfPeople.get(key));
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to get timeline: " + te.getMessage());
            System.exit(-1);
        }
    }

}

From source file:com.mycompany.twitterproductanalysistool.TwitterAPI.java

public ArrayList<String> getQuery(String qry) {
    tweets = new ArrayList<>();
    tweetCountries = new ArrayList<>();
    tweetDates = new ArrayList<>();
    try {//  ww w.ja  va2s .  c  o m
        Query query = new Query(qry);
        query.setCount(99);
        result = twitter.search(query);
        for (Status status : result.getTweets()) {
            tweets.add(status.getText());
            tweetDates.add(status.getCreatedAt());
            if (status.getUser() == null) {
                tweetCountries.add("NO COUNTRY");
            } else {
                tweetCountries.add(status.getUser().getLocation());
            }
        }
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
    for (int i = 0; i < tweets.size(); i++) {
        String s = tweets.get(i);
        tweets.set(i, s.replace("\n", ""));
    }
    return tweets;
}

From source file:com.mycompany.twittersearch.SearchTwitter.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  www. ja v  a2  s  . c  o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, TwitterException {

    Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
    out.println(twitter.toString());
    String searchItem = request.getParameter("term");

    try {
        Query query = new Query(searchItem);

        QueryResult result = twitter.search(query);

        List<Status> tweets = result.getTweets();
        String list = "";
        for (Status tweet : tweets) {
            list += "@" + tweet.getUser().getScreenName() + " - " + tweet.getText() + "<br>";
        }

        request.setAttribute("list", list);

    } catch (TwitterException te) {
        te.printStackTrace();
        out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
    request.getRequestDispatcher("showTweets.jsp").forward(request, response);

}

From source file:com.nookdevs.twook.activities.Settings.java

License:Open Source License

public void setAccessToken(AccessToken accessToken) {
    this.access = accessToken;

    // fill out any info, like username and user id
    Twitter twitter = getConnection();//w ww . ja  va  2  s .c o m
    try {
        this.user = twitter.verifyCredentials();
        this.access = twitter.getOAuthAccessToken();
        // Log.d(TAG, "Access after verify: " + this.access);
        // Log.d(TAG, "User after verify: " + user);
        downloadIcon();
    } catch (TwitterException e) {
        Log.e(TAG, "Access credentials did not verify: " + e.getMessage());
        this.access = null;
    }
}

From source file:com.nookdevs.twook.activities.SettingsActivity.java

License:Open Source License

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // set the title at the top of the eink screen
    final Resources res = getResources();
    NAME = res.getText(R.string.app_name).toString() + res.getText(R.string.title_separator).toString()
            + res.getText(R.string.settings_title).toString();

    setContentView(R.layout.settings);/*from   www. j  ava 2 s  .com*/
    final InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    // get the buttons
    txtPin = (EditText) findViewById(R.id.pin);
    // set listeners
    txtPin.setOnKeyListener(credentialsListener);

    WebView engine = (WebView) findViewById(R.id.web_frame);
    engine.setOnKeyListener(credentialsListener);
    // the submit is done through jscript, so we'd better allow it...
    engine.getSettings().setJavaScriptEnabled(true);

    // set credentials from Settings
    Settings settings = Settings.getSettings(this);

    ConfigurationBuilder confBuilder = settings.getConfiguration();

    // this doesn't seem to be used by the authorization object...
    // confBuilder.setUser(username);
    // confBuilder.setPassword(password);

    Configuration conf = confBuilder.build();
    mAuth = new OAuthAuthorization(conf);
    TextView validation = (TextView) findViewById(R.id.validation);

    try {
        // ask for the request token first, so we can ask the user for
        // authorization
        RequestToken requestToken = mAuth.getOAuthRequestToken();

        Log.d(TAG, "Request token: " + requestToken.toString());
        // this includes the oauth_token parameter and everything
        Log.d(TAG, "Sending user to " + requestToken.getAuthorizationURL());

        engine.loadUrl(requestToken.getAuthorizationURL());
        /*
         * Intent myIntent = new Intent(Intent.ACTION_VIEW,
         * Uri.parse(requestToken.getAuthorizationURL()));
         * startActivity(myIntent);
         */

        Log.d(TAG, "Will authorize to " + conf.getOAuthAccessTokenURL());
    } catch (TwitterException excep) {
        // TODO: better validation here
        validation.setText("Unknown error: " + excep.getMessage());
    }
    // spiner for selecting refresh times
    // Spinner refresh = (Spinner) findViewById(R.id.refresh_time);
    // ArrayAdapter adapter = ArrayAdapter.createFromResource(
    // this, R.array.refresh_times, android.R.layout.simple_spinner_item);
    // adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // refresh.setAdapter(adapter);
}

From source file:com.nookdevs.twook.activities.SettingsActivity.java

License:Open Source License

/**
 * Helper method used for processing events recieved from the soft keyboard.
 * //from   w  w w .j  av  a2 s  .  c o  m
 * @param keyCode
 *            the keyCode received from the soft keyboard
 * @see nookBaseSimpleActivity
 */
private void processCmd(int keyCode) {
    final String pin = txtPin.getText().toString();

    InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
    Settings settings = Settings.getSettings(this);

    switch (keyCode) {
    case nookBaseSimpleActivity.SOFT_KEYBOARD_SUBMIT:
        // if submit is pressed check if it is valid,
        // post a message if it is not or
        // set the settings and continue if it is
        // String auth = BasicAuthorization(username, password);
        TextView validation = (TextView) findViewById(R.id.validation);

        try {
            // we can specify the username and password here, but we'd need
            // to allow xauth
            // for this client, which requires an email to api@twitter.com.
            // Since we know
            // we have a browser available, launch that and let the user
            // authenticate there.
            AccessToken accessToken = mAuth.getOAuthAccessToken(pin);

            Log.d(TAG, "Auth result is: " + accessToken);

            // where do we set username/password?
            // accessToken includes username, userId, and auth tokens
            settings.setAccessToken(accessToken);

            settings.save();

            finish();

        } catch (TwitterException excep) {
            // TODO: resource-ize strings
            if (401 == excep.getStatusCode()) {
                validation.setText("Twitter rejected us: " + excep.getMessage());
            } else {
                // TODO: better validation here
                validation.setText("Unknown error: " + excep.getMessage());
            }
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
        } catch (IllegalStateException excep) {
            Log.e(TAG, "Internal error: " + excep.getMessage());
            validation.setText("Oops, something bad happened... Check the logs!");
        }

        break;
    case nookBaseSimpleActivity.SOFT_KEYBOARD_CANCEL:
        Log.d(TAG, "Token is: " + settings.getAccessToken());
        finish();
        break;
    case nookBaseSimpleActivity.NOOK_PAGE_DOWN_KEY_LEFT:
    case nookBaseSimpleActivity.NOOK_PAGE_DOWN_KEY_RIGHT:
    case nookBaseSimpleActivity.NOOK_PAGE_UP_KEY_LEFT:
    case nookBaseSimpleActivity.NOOK_PAGE_UP_KEY_RIGHT:
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
        break;
    }

}

From source file:com.puestodequipe.mvc.testing.GetAccessToken.java

License:Apache License

/**
 * Usage: java  twitter4j.examples.oauth.GetAccessToken [consumer key] [consumer secret]
 *
 * @param args message//from w  ww .j ava2 s .  co 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);
        }
        prop.setProperty("oauth.consumerKey", "mOpD2GQXUsc0tMKZHOvGJg");
        prop.setProperty("oauth.consumerSecret", "LnGRxSHrlzHDWC3R9aeTPDYmlr7LGXm7diNi6WZX3k");
        os = new FileOutputStream("twitter4j.properties");
        prop.store(os, "twitter4j.properties");

    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.exit(-1);
    } finally {
        if (null != is) {
            try {
                is.close();
            } catch (IOException ignore) {
            }
        }
        if (null != os) {
            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 (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 (null != os) {
                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);
    }
}