List of usage examples for twitter4j TwitterException getStatusCode
public int getStatusCode()
From source file:com.amandine.twitterpostforcoucou.Tweet.java
private void publishStatusUpdateWithMedia(String message) throws MalformedURLException, IOException { Status status = null;/* w w w.j a va 2s . c o m*/ try { Twitter twitter = new TwitterFactory().getInstance(); try { RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null; while (null == accessToken) { logger.fine("Open the following URL and grant access to your account:"); logger.fine(requestToken.getAuthorizationURL()); try { accessToken = twitter.getOAuthAccessToken(requestToken); } catch (TwitterException te) { if (401 == te.getStatusCode()) { logger.severe("Unable to get the access token."); } else { te.printStackTrace(); } } } logger.log(Level.INFO, "Got access token."); logger.log(Level.INFO, "Access token: {0}", accessToken.getToken()); logger.log(Level.INFO, "Access token secret: {0}", accessToken.getTokenSecret()); } catch (IllegalStateException ie) { // access token is already available, or consumer key/secret is not set. if (!twitter.getAuthorization().isEnabled()) { logger.severe("OAuth consumer key/secret is not set."); return; } } //Instantiate and initialize a new twitter status update StatusUpdate statusUpdate = new StatusUpdate(message); //attach any media, if you want to statusUpdate.setMedia( //title of media "Amandine Leforestier Spring Summer 2015 white", new URL("https://issuu.com/kadiemurphy/docs/volume_xxi_issuu/52?e=0").openStream()); //tweet or update status status = twitter.updateStatus(statusUpdate); //Status status = twitter.updateStatus(message); logger.log(Level.INFO, "Successfully updated the status to [{0}].", status.getText()); } catch (TwitterException te) { te.printStackTrace(); logger.log(Level.SEVERE, "Failed to get timeline: {0}", te.getMessage()); } }
From source file:com.amandine.twitterpostforcoucou.Tweet.java
public Twitter getTwitter() { Twitter twitter = new TwitterFactory().getInstance(); try {/*from w w w . j a va 2s . c om*/ RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null; while (null == accessToken) { logger.fine("Open the following URL and grant access to your account:"); logger.fine(requestToken.getAuthorizationURL()); try { accessToken = twitter.getOAuthAccessToken(requestToken); } catch (TwitterException te) { if (401 == te.getStatusCode()) { logger.severe("Unable to get the access token."); } else { logger.log(Level.SEVERE, "Failed to get timeline: {0}", te.getMessage()); } } } logger.log(Level.INFO, "Got access token."); logger.log(Level.INFO, "Access token: {0}", accessToken.getToken()); logger.log(Level.INFO, "Access token secret: {0}", accessToken.getTokenSecret()); } catch (IllegalStateException ie) { // access token is already available, or consumer key/secret is not set. if (!twitter.getAuthorization().isEnabled()) { logger.log(Level.SEVERE, "OAuth consumer key/secret is not set: {0}", ie.getMessage()); return null; } } catch (TwitterException te) { logger.log(Level.SEVERE, "OAuth request token: {0}", te.getMessage()); } return twitter; }
From source file:com.appdynamics.alerts.twitter.TwitterAlert.java
License:Apache License
public static void main(String[] args) { twitter = TwitterFactory.getSingleton(); twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET); twitter.addRateLimitStatusListener(new RateLimitStatusListener() { @Override/*from www. j a va 2 s .com*/ public void onRateLimitStatus(RateLimitStatusEvent rateLimitStatusEvent) { RateLimitStatus status = rateLimitStatusEvent.getRateLimitStatus(); if (status.getRemaining() <= 0) { logger.warn("Rate limit reached"); storeRateLimitStatus(status); } } @Override public void onRateLimitReached(RateLimitStatusEvent rateLimitStatusEvent) { //never called by API } }); if (args.length == 1 && args[0].equals("auth")) { try { getAuthorization(); System.out.println("Authenticated for user @" + twitter.getScreenName()); } catch (TwitterException e) { if (e.getStatusCode() == 401) { logger.error("Missing or incorrect authentication credentials"); } else { logger.error("Authentication failed", e); } } } else { try { parseEventParams(args); AccessToken accessToken = readAccessToken(); twitter.setOAuthAccessToken(accessToken); postUpdate(); } catch (IOException e) { logger.error("Access token unreadable,unable to authenticate. Please rerun authentication script"); } catch (ClassNotFoundException e) { logger.error("Access token unreadable,unable to authenticate. Please rerun authentication script"); } catch (Exception e) { logger.error("Failed to parse arguments"); } } }
From source file:com.appdynamics.alerts.twitter.TwitterAlert.java
License:Apache License
/** * Check for rate limit and protected status. Post status if permitted, log status otherwise *//*from w ww. j a va2 s .com*/ private static void postUpdate() { try { if (!isLimitReached()) { User user = twitter.verifyCredentials(); if (user.isProtected()) { twitter.updateStatus(createStatus(true)); } else { logger.error( "User @" + user.getScreenName() + " status is not protected, aborting status update"); } } else { logger.warn("Twitter rate limit reached, status update ignored until next reset"); logger.info("Ignored tweet: " + createStatus(false)); } } catch (TwitterException e) { if (e.getStatusCode() == 403 || e.getStatusCode() == 400) { logger.error(e.getErrorMessage()); } else { logger.error(e); } } }
From source file:com.appspot.bitlyminous.standalone.TwitterExample.java
License:Apache License
/** * The main method./*from w w w.j a v a 2 s .co m*/ * * @param args the arguments * * @throws Exception the exception */ public static void main(String[] args) throws Exception { // The factory instance is re-useable and thread safe. Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer("671O1zUicFBCYHHYVp0XA", "cP7WvfAtxXGSaf1Sz0ksZtWGcENosFcRr46WR7a9jU"); RequestToken requestToken = twitter.getOAuthRequestToken(); 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()); System.out.print("Enter the PIN(if available) 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(); } } } // persist to the accessToken for future reference. System.out.println("Screen name:" + accessToken.getScreenName()); System.out.println("Token:" + accessToken.getToken()); System.out.println("Secret:" + accessToken.getTokenSecret()); IDs friendsIDs = twitter.getFriendsIDs("gapinginfinity"); System.out.println(Arrays.toString(friendsIDs.getIDs())); ResponseList<Status> favorites = twitter.getFavorites("gapinginfinity"); System.out.println(favorites.size()); System.exit(0); }
From source file:com.aremaitch.codestock2010.library.TwitterLib.java
License:Apache License
public boolean sendRatingDM(String dmText) { boolean result = false; try {/*from w w w . j av a2 s.co m*/ t.sendDirectMessage(TwitterConstants.CODESTOCK_USERID, dmText); result = true; ACLogger.info(CSConstants.LOG_TAG, "successfully sent dm rating: " + dmText); } catch (TwitterException e) { if (e.getStatusCode() == 403) { ACLogger.info(CSConstants.LOG_TAG, "could not dm rating: " + e.getMessage()); } else { e.printStackTrace(); } } return result; }
From source file:com.avishkar.NewGetFollowersIDs.java
License:Apache License
private static List<Long> getUserFollwers(long twitterUserId) throws UnknownHostException, TwitterException, InterruptedException { Twitter twitter = new TwitterFactory(AccessTokenUtil.getConfig()).getInstance(); List<Long> filteredUserListOnFollowerCount = new ArrayList<Long>(); final Gson gson = new Gson(); try {/*from ww w. j a va 2 s . com*/ checkRateLimit("/followers/ids", twitter); System.out.println("Listing followers's Follower for ID:" + twitterUserId + System.lineSeparator()); IDs followerIDs = twitter.getFollowersIDs(twitterUserId, -1); JsonObject followerJSON = new JsonObject(); followerJSON.addProperty("id", twitterUserId); followerJSON.addProperty("followers", gson.toJson(followerIDs.getIDs())); DBAccess.insert(gson.toJson(followerJSON)); System.out.println("Current Followers Fetched Size:" + followerIDs.getIDs().length); // Filtering for influential user if (followerIDs.getIDs().length > 1000) { System.out.println("User assumed as Influential"); return null; } int from = 0; int to = 99; int limit = checkRateLimit("/users/lookup", twitter); while (from < followerIDs.getIDs().length) { if (to > followerIDs.getIDs().length) to = followerIDs.getIDs().length - 1; if (limit == 0) checkRateLimit("/users/lookup", twitter); ResponseList<User> followers = twitter .lookupUsers(Arrays.copyOfRange(followerIDs.getIDs(), from, to)); System.out.println("Recieved User count:" + followers.size()); for (User user : followers) { DBAccess.insertUser(gson.toJson(user)); if (user.getFollowersCount() < 1000) { // if(user.getStatusesCount()>0 && // user.getStatus()!=null && // sevenDaysAgo.after(user.getStatus().getCreatedAt())) filteredUserListOnFollowerCount.add(user.getId()); getStatuses(user.getScreenName(), twitter); } else System.out.println("User " + user.getScreenName() + " is pruned for Influential or over subscription." + " Follower count:" + user.getFollowersCount() + " Friends Count:" + user.getFriendsCount()); } from += 100; to += 100; limit--; } } catch (TwitterException te) { if (te.getStatusCode() == HttpResponseCode.UNAUTHORIZED || te.getStatusCode() == HttpResponseCode.NOT_FOUND) { System.out.println("Encountered locked profile. Skipping " + twitterUserId); return null; // log something here } te.printStackTrace(); System.out.println("Failed to get followers' Follower: " + te.getMessage()); // System.exit(-1); } return filteredUserListOnFollowerCount; }
From source file:com.cafeform.iumfs.twitterfs.TwitterFactoryAdapter.java
License:Apache License
public static AccessToken getAccessToken(String username) { AccessToken accessToken = null;/*from www. ja va 2 s. c om*/ if (Prefs.get(username + "/accessToken").isEmpty()) { Twitter twitter = factory.getInstance(); twitter.setOAuthConsumer(Prefs.get("OAuthConsumerKey"), Prefs.get("consumerSecret")); RequestToken requestToken; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { requestToken = twitter.getOAuthRequestToken(); 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 ex) { if (401 == ex.getStatusCode()) { System.out.println("Unable to get the access token."); } else { logger.log(Level.SEVERE, "Unable to get the Access Token", ex); } } } } catch (IOException | TwitterException ex) { logger.log(Level.SEVERE, "Unable to get the Access Token", ex); } Prefs.put(username + "/accessToken", accessToken.getToken()); Prefs.put(username + "/accessTokenSecret", accessToken.getTokenSecret()); } logger.finest("Token&Secret: " + Prefs.get(username + "/accessToken") + " " + Prefs.get(username + "/accessTokenSecret")); logger.finest("OauthConsum&Secret: " + Prefs.get("OAuthConsumerKey") + " " + Prefs.get("consumerSecret")); accessToken = new AccessToken(Prefs.get(username + "/accessToken"), Prefs.get(username + "/accessTokenSecret")); return accessToken; }
From source file:com.dwdesign.tweetings.util.Utils.java
License:Open Source License
public static HttpResponse getRedirectedHttpResponse(final HttpClientWrapper client, final String url) throws TwitterException { if (url == null) return null; final ArrayList<String> urls = new ArrayList<String>(); urls.add(url);/* w w w . j a v a 2 s. com*/ HttpResponse resp; try { resp = client.get(url, url); } catch (final TwitterException te) { if (isRedirected(te.getStatusCode())) { resp = te.getHttpResponse(); } else throw te; } while (resp != null && isRedirected(resp.getStatusCode())) { final String request_url = resp.getResponseHeader("Location"); if (request_url == null) return null; if (urls.contains(request_url)) throw new TwitterException("Too many redirects"); urls.add(request_url); try { resp = client.get(request_url, request_url); } catch (final TwitterException te) { if (isRedirected(te.getStatusCode())) { resp = te.getHttpResponse(); } else throw te; } } return resp; }
From source file:com.esz.thaifloodreporter.UpdateStatus.java
License:Apache License
/** * Usage: java twitter4j.examples.tweets.UpdateStatus [text] * * @param args message/*from w w w . j a v a 2s .co m*/ */ public static void main(String[] args) { if (args.length < 1) { System.out.println("Usage: java twitter4j.examples.tweets.UpdateStatus [text]"); System.exit(-1); } try { Twitter twitter = new TwitterFactory().getInstance(); try { // get request token. // this will throw IllegalStateException if access token is already available 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()); 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()); } catch (IllegalStateException ie) { // access token is already available, or consumer key/secret is not set. if (!twitter.getAuthorization().isEnabled()) { System.out.println("OAuth consumer key/secret is not set."); System.exit(-1); } } Status status = twitter.updateStatus(args[0]); System.out.println("Successfully updated the status to [" + status.getText() + "]."); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + te.getMessage()); System.exit(-1); } catch (IOException ioe) { ioe.printStackTrace(); System.out.println("Failed to read the system input."); System.exit(-1); } }