List of usage examples for twitter4j TwitterException getStatusCode
public int getStatusCode()
From source file:twitterGateway_v2_06.java
License:Creative Commons License
public void GetAccessToken() { //AccessToken accessToken = null; while (null == accessToken) { //}/*from w w w .jav a 2 s.c om*/ //catch (TwitterException ex) { // println(ex); //} println("requestToken " + requestToken); println("pin " + pin); try { if (pin.length() > 0) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(); } TwitterAccessToken = accessToken.getToken(); TwitterAccessTokenSecret = accessToken.getTokenSecret(); } catch (TwitterException te) { if (401 == te.getStatusCode()) { println("Unable to get the access token."); } else { te.printStackTrace(); } } } }
From source file: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 void getToken() throws TwitterException, IOException { File file = new File("twitter4j.properties"); Properties prop = new Properties(); InputStream is = null; OutputStream os = null; MainActivity m = new MainActivity(); Twitter twitter = new TwitterFactory().getInstance(); try { try { if (file.exists()) { is = new FileInputStream(file); prop.load(is); } if (true) { 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); } } } 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 { 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 { System.out.println("fdfgghd"); 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() + "."); m.setTwitter(twitter); m.setVisible(true); //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); } } catch (java.lang.IllegalStateException jli) { System.out.println("Already registered"); m.setTwitter(twitter); m.setVisible(true); } }
From source file:Register.java
License:Open Source License
/** * Usage: java twitter4j.examples.tweets.UpdateStatus [text] * * @param args message//from w ww .j av a2 s.co m */ public static void main(String[] args) { try { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("wIb1qVNc0CNXQJxduYIXw") .setOAuthConsumerSecret("vTES3U9862wYaxFRdMyD1LRatkq2R42mDyOjXLHIdk"); Twitter twitter = new TwitterFactory(cb.build()).getInstance(); AccessToken accessToken = null; try { // get request token. // this will throw IllegalStateException if access token is already available RequestToken requestToken = twitter.getOAuthRequestToken(); 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("Access granted to Twitter."); 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); } } twitter.updateStatus("Minecraft server successfully registered at " + (new Date()).toString()); System.out.println("Successfully connected to Twitter."); // Write the properties file PrintWriter pw = new PrintWriter(new FileWriter("../TwitterEvents.properties")); pw.println("accessToken=" + accessToken.getToken()); pw.println("accessTokenSecret=" + accessToken.getTokenSecret()); pw.close(); System.out.println("Your TwitterEvents.properties file has been created with your access tokens."); System.out.println("Start Minecraft server to load the remaining default values."); System.out.println("Then reload TwitterEvents if you make any changes."); System.exit(0); } catch (TwitterException te) { System.out.println("Failed to get timeline: " + te.getMessage()); System.out .println("Try revoking access to the hModEvents application from your Twitter settings page."); System.exit(-1); } catch (IOException ioe) { System.out.println("Failed to read the system input."); System.exit(-1); } }
From source file:ac.simons.tweetarchive.Application.java
License:Apache License
static void createTwitterOauthTokens(final String consumerKey, final String consumerSecret) throws Exception { final Twitter twitter = TwitterFactory.getSingleton(); twitter.setOAuthConsumer(consumerKey, consumerSecret); final RequestToken requestToken = twitter.getOAuthRequestToken(); AccessToken accessToken = null;//from ww w.j a va 2 s . com final 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 { throw te; } } } final Properties properties = new Properties(); properties.put("twitter4j.oauth.consumerKey", consumerKey); properties.put("twitter4j.oauth.consumerSecret", consumerSecret); properties.put("twitter4j.oauth.accessToken", accessToken.getToken()); properties.put("twitter4j.oauth.accessTokenSecret", accessToken.getTokenSecret()); try (final FileOutputStream out = new FileOutputStream("application.properties", true)) { properties.store(out, null); } }
From source file:au.edu.anu.portal.portlets.tweetal.servlet.TweetalServlet.java
License:Apache License
public void deleteTweets(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userToken = request.getParameter("u"); String userSecret = request.getParameter("s"); long statusID = Long.parseLong(request.getParameter("d")); log.debug("Deleting tweet " + statusID); Twitter twitter = twitterLogic.getTwitterAuthForUser(userToken, userSecret); if (twitter == null) { // no connection response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return;/*w w w. j a v a 2s.c om*/ } try { Status s = twitter.destroyStatus(statusID); if (s != null) { // success response.setStatus(HttpServletResponse.SC_OK); // remove tweets from cache String cacheKey = userToken; tweetsCache.remove(cacheKey); } else { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } } catch (TwitterException e) { // problem in deleting the tweet log.error("Delete Tweet: " + e.getStatusCode() + ": " + e.getClass() + e.getMessage()); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } }
From source file:au.edu.anu.portal.portlets.tweetal.servlet.TweetalServlet.java
License:Apache License
public void updateUserStatus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); PrintWriter out = response.getWriter(); String userToken = request.getParameter("u"); String userSecret = request.getParameter("s"); String userStatus = request.getParameter("t"); String statusId = request.getParameter("d"); log.debug("userStatus: " + userStatus); log.debug("statusId: " + statusId); Twitter twitter = twitterLogic.getTwitterAuthForUser(userToken, userSecret); if (twitter == null) { // no connection response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return;//w w w . jav a 2s .c o m } try { Status status = null; // update user status if (StringUtils.isNotBlank(statusId)) { status = twitter.updateStatus(userStatus, Long.parseLong(statusId)); } else { status = twitter.updateStatus(userStatus); } if (status == null) { log.error("Status is null."); // general error response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } JSONObject json = new JSONObject(); JSONObject statusJSON = getStatusJSON(twitter, status); User currentUser = twitter.showUser(twitter.getId()); Status lastUserStatus = currentUser.getStatus(); // return as an array even though only it contains only one element, // so we can reuse the same Trimpath template (Denny) JSONArray statusList = new JSONArray(); statusList.add(statusJSON); json.put("statusList", statusList); lastRefreshed = Calendar.getInstance().getTime().toString(); if (lastRefreshed == null) { json.element("lastRefreshed", "unable to retrieve last refreshed"); } else { json.element("lastRefreshed", lastRefreshed.toString()); } if (lastUserStatus == null) { json.element("lastStatusUpdate", "unable to retrieve last status"); } else { Date lastStatusUpdate = lastUserStatus.getCreatedAt(); json.element("lastStatusUpdate", lastStatusUpdate.toString()); } if (log.isDebugEnabled()) { log.debug(json.toString(2)); } out.print(json.toString()); } catch (TwitterException e) { log.error("GetTweets: " + e.getStatusCode() + ": " + e.getClass() + e.getMessage()); if (e.getStatusCode() == 401) { //invalid credentials response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } else if (e.getStatusCode() == -1) { //no connection response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { //general error response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } }
From source file:au.edu.anu.portal.portlets.tweetal.servlet.TweetalServlet.java
License:Apache License
public void retweet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); PrintWriter out = response.getWriter(); String userToken = request.getParameter("u"); String userSecret = request.getParameter("s"); long statusId = Long.parseLong(request.getParameter("d")); log.debug("statusId: " + statusId); Twitter twitter = twitterLogic.getTwitterAuthForUser(userToken, userSecret); if (twitter == null) { // no connection response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return;//w ww. j ava 2 s.c o m } try { Status status = null; // update user status status = twitter.retweetStatus(statusId); if (status == null) { log.error("Status is null."); // general error response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } JSONObject json = new JSONObject(); JSONObject statusJSON = getStatusJSON(twitter, status); // return as an array even though only it contains only one element, // so we can reuse the same Trimpath template (Denny) JSONArray statusList = new JSONArray(); statusList.add(statusJSON); json.put("statusList", statusList); if (log.isDebugEnabled()) { log.debug(json.toString(2)); } out.print(json.toString()); } catch (TwitterException e) { log.error("GetTweets: " + e.getStatusCode() + ": " + e.getClass() + e.getMessage()); if (e.getStatusCode() == 401) { // invalid credentials response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } else if (e.getStatusCode() == -1) { // no connection response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { // general error response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } }
From source file:au.edu.anu.portal.portlets.tweetal.servlet.TweetalServlet.java
License:Apache License
public void getTweets(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); PrintWriter out = response.getWriter(); String userToken = request.getParameter("u"); String userSecret = request.getParameter("s"); Twitter twitter = twitterLogic.getTwitterAuthForUser(userToken, userSecret); if (twitter == null) { // no connection response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return;// w ww . j a v a 2s . c o m } String cacheKey = userToken; Element element = null; // force refresh boolean force = Boolean.parseBoolean(request.getParameter("force")); if (force) { log.debug("force refresh for " + userToken); // remove tweets cache tweetsCache.remove(cacheKey); } else { element = tweetsCache.get(cacheKey); } if (element == null) { synchronized (tweetsCache) { // if it is still null after acquiring lock element = tweetsCache.get(cacheKey); if (element == null) { log.debug("cache miss: getting tweets for " + userToken); System.out.println("Last refreshed: " + Calendar.getInstance().getTime()); try { ResponseList<Status> friendStatus = twitter.getFriendsTimeline(); long maxId = Long.MIN_VALUE; JSONObject json = new JSONObject(); lastRefreshed = Calendar.getInstance().getTime().toString(); if (lastRefreshed == null) { json.element("lastRefreshed", "unable to retrieve last refreshed"); } else { json.element("lastRefreshed", lastRefreshed.toString()); } User currentUser = twitter.showUser(twitter.getId()); Status lastUserStatus = currentUser.getStatus(); if (lastUserStatus == null) { json.element("lastStatusUpdate", "unable to retrieve last status"); } else { Date lastStatusUpdate = lastUserStatus.getCreatedAt(); json.element("lastStatusUpdate", lastStatusUpdate.toString()); } for (Status status : friendStatus) { maxId = Math.max(maxId, status.getId()); json.accumulate("statusList", getStatusJSON(twitter, status)); } if (log.isDebugEnabled()) { log.debug(json.toString(2)); } out.print(json.toString()); element = new Element(cacheKey, new TweetsCacheElement(System.currentTimeMillis(), maxId, json)); tweetsCache.put(element); return; } catch (TwitterException e) { log.error("GetTweets: " + e.getStatusCode() + ": " + e.getClass() + e.getMessage()); if (e.getStatusCode() == 401) { // invalid credentials response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } else if (e.getStatusCode() == -1) { // no connection response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { // general error response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } return; } } } } // tweets available in cache log.debug("cache hit: getting tweets for " + userToken); TweetsCacheElement tweets = (TweetsCacheElement) element.getObjectValue(); // if just refreshed too quickly, don't request update, just use // whatever in cache long period = System.currentTimeMillis() - tweets.getLastRefresh(); System.out.println("Already refreshed: " + (period / 1000) + " second(s) ago"); if (period < 2 * 60 * 1000) { log.debug("refreshed too quickly: " + (period / 1000) + " seconds"); JSONObject json = tweets.getResult(); lastRefreshed = Calendar.getInstance().getTime().toString(); json.element("lastRefreshed", lastRefreshed.toString()); out.print(json.toString()); return; } // get new updates since the last id long maxId = tweets.lastId; try { JSONObject json = tweets.getResult(); ResponseList<Status> friendStatus = twitter.getFriendsTimeline(new Paging(maxId)); tweets.setLastRefresh(System.currentTimeMillis()); log.debug(String.format("Got %d new tweets", friendStatus.size())); if (friendStatus.size() > 0) { JSONArray newTweets = new JSONArray(); lastRefreshed = Calendar.getInstance().getTime().toString(); json.element("lastRefreshed", lastRefreshed.toString()); for (Status status : friendStatus) { maxId = Math.max(maxId, status.getId()); newTweets.add(getStatusJSON(twitter, status)); } if (log.isDebugEnabled()) { log.debug("new tweets:\n" + newTweets.toString(2)); } json.getJSONArray("statusList").addAll(0, newTweets); tweets.setLastId(maxId); User currentUser = twitter.showUser(twitter.getId()); Status lastUserStatus = currentUser.getStatus(); if (lastUserStatus == null) { json.element("lastStatusUpdate", "unable to retrieve last status"); } else { Date lastStatusUpdate = lastUserStatus.getCreatedAt(); json.element("lastStatusUpdate", lastStatusUpdate.toString()); } } out.print(json.toString()); } catch (TwitterException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { log.error(e); } }
From source file:au.net.moon.tGetMissingUsers.ReadTwitter.java
License:Open Source License
/** * Get the user by getting a tweet with the user embedded in it. * /* www . j a va2s . c o m*/ * @param tweetId * the tweet to retrieve * @return Twitter user object */ public TUser getUserFromTweet(long tweetId) { TUser user = null; try { Status tweet = twitter.showStatus(tweetId); user = new TUser(tweet.getUser()); } catch (TwitterException e) { if (e.getStatusCode() == 404 || e.getStatusCode() == 403) { // 404 = tweet not found // 403 = tweet protected or user account suspended // just return the null user } else { e.printStackTrace(); } } return user; }
From source file:au.net.moon.tStreamingArchiver.Archiver.java
License:Open Source License
public void onException(Exception ex) { String errorMessageText = ""; boolean errorExit = true; System.out.println("Error: " + ex.toString()); if (ex.toString().contains("TwitterException")) { TwitterException tex = (TwitterException) ex; if (tex.getStatusCode() == 401) { errorMessageText = "ERROR: Invalid userid or password for Twitter"; } else if (tex.getStatusCode() == 404) { errorMessageText = "ERROR: Parameter not allowed for resource"; } else if (tex.getStatusCode() == 406) { errorMessageText = "ERROR: Parameter not allowed for resource"; } else if (tex.getStatusCode() == 413) { errorMessageText = "ERROR: Parameter too long"; } else if (tex.getStatusCode() == 416) { errorMessageText = "ERROR: Parameter range unacceptable"; } else if (tex.getStatusCode() == 500) { errorMessageText = "ERROR: Server Internal Error - contact Twitter API team"; errorExit = false;// w w w. ja v a2 s. c o m } else if (tex.getStatusCode() == 503) { System.err.println("ERROR: Service Overloaded - contact Twitter API team"); errorExit = false; } else if (tex.getStatusCode() == -1) { errorMessageText = "ERROR: status code -1 - maybe a dropped stream?"; errorExit = false; } // System.out.println("rateLimit: " + tex.getRateLimitStatus()); if (!errorExit) { System.err.println(errorMessageText); sendMail.sendMessage("TwitterStreamingArchiver: Twitter Exception", errorMessageText); } else { // give up System.err.println(errorMessageText); ex.printStackTrace(); sendMail.sendMessage("TwitterStreamingArchiver: Twitter Exception", "Error Exit:\n" + errorMessageText + "\n" + ex.toString()); System.exit(-1); } } else { ex.printStackTrace(); sendMail.sendMessage("TwitterStreamingArchiver: Other Error", "Other Error:\n" + ex.toString()); } }