List of usage examples for twitter4j TwitterException getStatusCode
public int getStatusCode()
From source file:be.ugent.tiwi.sleroux.newsrec.newsreclib.twitter.UserHelper.java
License:Apache License
public void grantAccess() throws TwitterException { RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null;/*from ww w . j av a 2s . c om*/ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken) { try { System.out.println("Open the following URL and grant access to your account:"); System.out.println(requestToken.getAuthorizationURL()); System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:"); String pin = br.readLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { logger.error(te); } } } catch (IOException ex) { logger.error(ex); } } storeAccessToken(twitter.verifyCredentials().getId(), accessToken); }
From source file:be.ugent.tiwi.sleroux.newsrec.twittertest.GrantAccess.java
public static void main(String args[]) throws Exception { // The factory instance is re-useable and thread safe. Twitter twitter = TwitterFactory.getSingleton(); twitter.setOAuthConsumer("tQjT8XvB7OPNTl8qdhchDo3J2", "FXWVS3OEW7omiUDSLpET0aRInoUumGPWRxOVyk7GrhiwcfLBnV"); RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null;/*from ww w . j ava 2 s . c om*/ 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()); System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:"); String pin = br.readLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } storeAccessToken(twitter.verifyCredentials().getId(), accessToken); }
From source file:ch.schrimpf.core.AccessHandler.java
License:Open Source License
private AccessToken register() throws TwitterException { // The factory instance is re-useable and thread safe. RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null;//from w ww . j a va2s . co m 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()); System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:"); try { String pin = br.readLine(); if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } try { FileOutputStream fout = new FileOutputStream("token.ser"); ObjectOutputStream oos = new ObjectOutputStream(fout); oos.writeObject(accessToken); LOG.info("token saved in token.ser"); } catch (IOException e) { LOG.severe("Could not store access token."); } return accessToken; }
From source file:Collector.TweetCollector.java
public static List<Status> getTweets(final String q) { Timer timer = new Timer(); TimerTask hourlyTask = new TimerTask() { @Override/*from ww w . j a v a 2 s. c om*/ public void run() { long amountOfTweets = 0; try { long maxID = -1; Query query = new Query(q); //printTimeLine(query); Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search"); RateLimitStatus searchLimit = rateLimitStatus.get("/search/tweets"); for (int batchNumber = 0; MAX_QUERIES < 10; batchNumber++) { System.out.printf("\n\n!!! batch %d\n\n", batchNumber); if (searchLimit.getRemaining() == 0) { // so as to not get blocked by twitter Thread.sleep(searchLimit.getSecondsUntilReset() + 3 * 1001); } query.setCount(TWEETS_PER_QUERY);// constant value of 100 query.setResultType(Query.ResultType.recent); query.setLang("en");// only english tweets if (maxID != -1) { query.setMaxId(maxID - 1);// so the first querys not set to previous max } QueryResult result = twitter.search(query); if (result.getTweets().size() == 0) { break; } for (Status s : result.getTweets()) { amountOfTweets++; if (maxID == -1 || s.getId() < maxID) { maxID = s.getId(); } storeTweet(s);// where stored in db System.out.printf("At%s : %s\n", // debugging purposes s.getCreatedAt().toString(), s.getText()); searchLimit = result.getRateLimitStatus(); //resets System.out.printf("\n\nA total of %d tweet retrieved\n", amountOfTweets); } } } catch (TwitterException te) { System.out.println("Error Code :" + te.getErrorCode()); System.out.println("Exception Code " + te.getExceptionCode()); System.out.println("Status Code " + te.getStatusCode()); if (te.getStatusCode() == 401) { System.out.println("Twitter Error :\nAuthentication " + "credentials (https://dev.twitter.com/auth) " + " are either missing of incorrect, " + "\nplease check consumer key /secret"); } } catch (InterruptedException ex) { } } }; // schedule the task to run starting now and then every hour... timer.schedule(hourlyTask, 0l, 1000 * 60 * 60); return statuses; }
From source file:ColourUs.OAuth.java
private void reauthorize() throws Exception { // In case we lose the A_SECRET Twitter twitter = TwitterFactory.getSingleton(); twitter.setOAuthConsumer(C_KEY, C_SECRET); RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null;/*from ww w. j a va 2s. c o m*/ 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()); System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:"); String pin = br.readLine(); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(); } } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } show((int) twitter.verifyCredentials().getId(), accessToken); }
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 a2 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); } 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.alta189.cyborg.commandkit.twitter.TwitterCommands.java
License:Open Source License
@Command(name = "twitter", desc = "displays the last tweet of a twitter user", aliases = { "twit" }) @Usage(".twitter <user>") public CommandResult twitter(CommandSource source, CommandContext context) { if (source.getSource() == CommandSource.Source.USER && (context.getPrefix() == null || !context.getPrefix().equals("."))) { return null; }// w w w. ja v a2s .c o m if (context.getArgs() == null || context.getArgs().length < 1) { return get(ReturnType.NOTICE, "Correct usage is .twitter <user>", source, context); } try { List<Status> statusList = twitter.getUserTimeline(context.getArgs()[0]); if (statusList == null || statusList.size() < 1) { return get(ReturnType.MESSAGE, "User has no tweets!", source, context); } Status status = statusList.get(0); status.getUser(); StringBuilder builder = new StringBuilder(); builder.append(status.getUser().getScreenName()).append(Colors.BLUE).append(": ").append(Colors.NORMAL) .append(status.getText()).append(" ("); Period period = new Period(new DateTime(status.getCreatedAt()), new DateTime()); if (period.getWeeks() > 2 || period.getMonths() > 1 || period.getYears() > 1) { builder.append(longTimeFormatter.print(period)); } else { builder.append(timeFormatter.print(period)); } builder.append(" ago)"); return get(ReturnType.MESSAGE, builder.toString().replace(lineBreak, " "), source, context); } catch (TwitterException e) { if (e.getStatusCode() == 404) { return get(ReturnType.MESSAGE, "User not found!", source, context); } else if (e.getStatusCode() == 401) { return get(ReturnType.MESSAGE, "Access denied by Twitter!", source, context); } else { e.printStackTrace(); return get(ReturnType.MESSAGE, "There was an internal error!", source, context); } } }
From source file:com.alta189.cyborg.commandkit.twitter.TwitterCommands.java
License:Open Source License
@Command(name = "twituser", desc = "Add your twitter account so you can tweet from IRC") @Usage(".twituser <twitter username>") public CommandResult twituser(CommandSource source, CommandContext context) { if (source.getSource() != CommandSource.Source.USER) { return get(ReturnType.MESSAGE, "Muse be done from IRC.", source, context); }/*from w ww .j a va2 s . com*/ if (context.getPrefix() == null || !context.getPrefix().equals(".")) { return null; } if (context.getArgs() == null || context.getArgs().length < 1) { return get(ReturnType.MESSAGE, "Correct usage is .twituser <twitter username>", source, context); } String username = context.getArgs()[0]; CyborgUser permsAccount = getUser(source.getUser()); if (getUser(source.getUser()) == null) { return get(ReturnType.NOTICE, "You have not registered with me! You need to register to add a twitter account! Type .register for help!", source, context); } TwitterUser twitterUser = getDatabase().select(TwitterUser.class).where() .equal("permUser", permsAccount.getName()).execute().findOne(); if (twitterUser != null) { return get(ReturnType.NOTICE, "You already have an twitter user associated with your account!", source, context); } if (tokenMap.get(permsAccount.getName()) != null) { return get(ReturnType.NOTICE, "You already have twitter OAuth URL! Get your pin and type .twitpin <pin>", source, context); } Twitter twitter = defaultTwitterFactory.getInstance(); try { RequestToken token = twitter.getOAuthRequestToken(); tokenMap.put(permsAccount.getName(), token); StringBuilder body = new StringBuilder(); body.append("Here is your OAuth Auth URL: ").append(token.getAuthorizationURL()).append(lineBreak) .append("Go to it. Sign in to twitter and Authorize this Bot. After granting access, it will give you a pin.") .append(lineBreak).append("Execute this command to finish the registration: .twitpin <pin>"); return get(ReturnType.NOTICE, body.toString(), source, context); } catch (TwitterException e) { e.printStackTrace(); return get(ReturnType.MESSAGE, "Internal Twitter Exception httpcode:" + e.getStatusCode(), source, context); } }
From source file:com.alta189.cyborg.commandkit.twitter.TwitterCommands.java
License:Open Source License
@Command(name = "twitpin", desc = "Second stage of adding your twitter account") @Usage(".twitpin <pin>") public CommandResult twitpin(CommandSource source, CommandContext context) { if (source.getSource() != CommandSource.Source.USER) { return get(ReturnType.MESSAGE, "Muse be done from IRC.", source, context); }/*w ww. j a v a 2 s .co m*/ if (context.getPrefix() == null || !context.getPrefix().equals(".")) { return null; } if (context.getArgs() == null || context.getArgs().length < 1) { return get(ReturnType.MESSAGE, "Correct usage is .twitpin <pin>", source, context); } String pin = context.getArgs()[0]; CyborgUser permsAccount = getUser(source.getUser()); if (getUser(source.getUser()) == null) { return get(ReturnType.NOTICE, "You have not registered with me! You need to register to add a twitter account! Type .register for help!", source, context); } TwitterUser twitterUser = getDatabase().select(TwitterUser.class).where() .equal("permUser", permsAccount.getName()).execute().findOne(); if (twitterUser != null) { return get(ReturnType.NOTICE, "You already have an twitter user associated with your account!", source, context); } RequestToken requestToken = tokenMap.get(permsAccount.getName()); if (requestToken == null) { return get(ReturnType.NOTICE, "You haven't started the process! To start type .twituser <user>", source, context); } Twitter twitter = defaultTwitterFactory.getInstance(); try { AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, pin); twitterUser = new TwitterUser(); twitterUser.setAccessTokenObject(accessToken); twitterUser.setPermUser(permsAccount.getName()); getDatabase().save(TwitterUser.class, twitterUser); tokenMap.remove(permsAccount.getName()); return get(ReturnType.NOTICE, "Twitter account created! You can now use the tweet command!", source, context); } catch (TwitterException e) { tokenMap.remove(permsAccount.getName()); e.printStackTrace(); return get(ReturnType.MESSAGE, "Internal Twitter Exception http code:" + e.getStatusCode(), source, context); } }
From source file:com.alta189.cyborg.commandkit.twitter.TwitterCommands.java
License:Open Source License
@Command(name = "tweet", desc = "Updates your twitter status") @Usage(".tweet <status>...") public CommandResult tweet(CommandSource source, CommandContext context) { if (source.getSource() != CommandSource.Source.USER) { return get(ReturnType.MESSAGE, "Muse be done from IRC.", source, context); }/* w w w . j a v a 2 s . co m*/ if (context.getPrefix() == null || !context.getPrefix().equals(".")) { return null; } if (context.getArgs() == null || context.getArgs().length < 1) { return get(ReturnType.MESSAGE, "Correct usage is .tweet <status>", source, context); } CyborgUser permsAccount = getUser(source.getUser()); if (getUser(source.getUser()) == null) { return get(ReturnType.NOTICE, "You have not registered with me! You need to register to use a twitter account! Type .register for help!", source, context); } TwitterUser twitterUser = getDatabase().select(TwitterUser.class).where() .equal("permUser", permsAccount.getName()).execute().findOne(); if (twitterUser == null) { return get(ReturnType.NOTICE, "You don't have a twitter user associated with your account! Try .twituser <twitter user>", source, context); } String status = StringUtils.toString(context.getArgs()); Twitter twitter = defaultTwitterFactory.getInstance(); twitter.setOAuthAccessToken(twitterUser.getAccessTokenObject()); try { twitter.updateStatus(status); return get(ReturnType.MESSAGE, "Updated status!", source, context); } catch (TwitterException e) { e.printStackTrace(); return get(ReturnType.MESSAGE, "Internal Twitter Exception http code:" + e.getStatusCode(), source, context); } }