List of usage examples for twitter4j TwitterException getMessage
@Override
public String getMessage()
From source file:au.edu.anu.portal.portlets.tweetal.logic.TwitterLogic.java
License:Apache License
public boolean verifyCredentials(String userToken, String userSecret) { Twitter twitter = getTwitterAuthForUser(userToken, userSecret); try {// w w w . jav a 2 s .c om twitter.verifyCredentials(); return true; } catch (TwitterException e) { log.error("Error: Credentials are invalid.\n" + e.getClass() + ":\n" + e.getMessage()); } return false; }
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;/* ww w . j a v a 2 s . co m*/ } 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;/*from www. j a v a 2 s . 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 w w .j a va2 s. com } 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 w w. j av a 2 s. 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:blg.bhdrkn.wicket.twitter.TwitterPanel.java
License:Apache License
private void addFormSubmit(Form<Void> twitterForm) { twitterForm.add(new AjaxButton("button") { private static final long serialVersionUID = 1L; @Override/*w ww.j a v a 2s. co m*/ protected void onSubmit(AjaxRequestTarget target, Form<?> form) { try { accessToken = twitter.getOAuthAccessToken(requestToken, twitterPinModel); setResponsePage(new TwitterPage(accessToken)); } catch (TwitterException e) { logger.error("Error While Getting AccessToken: " + e.getMessage()); e.printStackTrace(); } } @Override protected void onError(AjaxRequestTarget target, Form<?> form) { logger.error("Error"); } }); }
From source file:bluevia.OAuth.java
License:Apache License
private String oAuthTwitter(HttpServletRequest req, String step) { String oAuthUrl = "/index.jsp"; Properties prop = new Properties(); prop.setProperty("oauth.consumerKey", TwitterOAuth.consumer_key); prop.setProperty("oauth.consumerSecret", TwitterOAuth.consumer_secret); Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(TwitterOAuth.consumer_key, TwitterOAuth.consumer_secret); try {/*from w w w. j av a2s .c om*/ if (step.compareTo("1") == 0) { RequestToken requestToken = twitter .getOAuthRequestToken(Util.getCallbackDomain() + "/oauth?network=twitter&step=2"); req.getSession().setAttribute("request_key", requestToken.getToken()); req.getSession().setAttribute("request_secret", requestToken.getTokenSecret()); oAuthUrl = requestToken.getAuthenticationURL(); } else { String request_key = (String) req.getSession().getAttribute("request_key"); String request_secret = (String) req.getSession().getAttribute("request_secret"); String oauth_verifier = req.getParameter("oauth_verifier"); RequestToken requestToken = new RequestToken(request_key, request_secret); AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, oauth_verifier); UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); Util.addNetworkAccount(user.getEmail(), "TwitterAccount", Util.TwitterOAuth.consumer_key, Util.TwitterOAuth.consumer_secret, accessToken.getToken(), accessToken.getTokenSecret()); req.getSession().removeAttribute("request_key"); req.getSession().removeAttribute("request_secret"); oAuthUrl = "/settings.jsp"; } } catch (TwitterException e) { // TODO Auto-generated catch block e.printStackTrace(); logger.severe(e.getMessage()); } catch (Exception e) { e.printStackTrace(); logger.severe(e.getMessage()); } return oAuthUrl; }
From source file:bluevia.SendSMS.java
License:Apache License
public static void setTwitterStatus(String userEmail, String tweet) { if (tweet != null) { try {/*from w ww .jav a 2 s.co m*/ Properties twitterAccount = Util.getNetworkAccount(userEmail, "TwitterAccount"); if (twitterAccount != null) { String consumer_key = twitterAccount.getProperty("TwitterAccount.consumer_key"); String consumer_secret = twitterAccount.getProperty("TwitterAccount.consumer_secret"); String access_key = twitterAccount.getProperty("TwitterAccount.access_key"); String access_secret = twitterAccount.getProperty("TwitterAccount.access_secret"); Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(consumer_key, consumer_secret); twitter.setOAuthAccessToken(new AccessToken(access_key, access_secret)); StatusUpdate status = new StatusUpdate(tweet); twitter.updateStatus(status); } } catch (TwitterException te) { te.printStackTrace(); log.severe(te.getMessage()); } catch (Exception e) { log.severe(String.format("Error sending SMS: %s", e.getMessage())); } } }
From source file:br.unisal.twitter.bean.TwitterBean.java
public void consultarTweets() { TwitterFactory TwitterFactory = new TwitterFactory(); Twitter twitter = TwitterFactory.getSingleton(); List<Status> tweets = new ArrayList<>(); Query query = new Query(getTwittQuery()); try {/*from ww w . j ava2 s .co m*/ QueryResult result = twitter.search(query); tweets.addAll(result.getTweets()); StringBuilder builder = new StringBuilder(); double lon = 0; double lat = 0; for (Status s : tweets) { if ((s.getGeoLocation() != null)) { lon = s.getGeoLocation().getLongitude(); lat = s.getGeoLocation().getLatitude(); } Tweet t = new Tweet(s.getUser().getName(), s.getUser().getLocation(), s.getText(), s.getCreatedAt(), lat, lon); dao.insert(t); builder.append(t.toString()); } this.getUiResultQuery().setSubmittedValue(builder.toString()); } catch (TwitterException te) { System.out.println("Failed to search tweets: " + te.getMessage()); } }
From source file:co.uk.socialticker.ticker.TickerActivity.java
License:Open Source License
/** * Test code to try and retrieve some data from twitter in a search! * @throws TwitterException /*from w ww. ja v a 2 s .c o m*/ * */ public JSONArray doSearch(View v) throws TwitterException { if (mApiClient != null || debugOn) { // The factory instance is re-useable and thread safe. //get the hashtag - check to make sure if returned value is set to something with a length JSONArray jsA = new JSONArray(); String qHash = p.getString(KEY_CAST_HASHTAG, ""); Log.d(TAG, "Hash to search: " + qHash); if (qHash.length() == 0) { Toast.makeText(this, "The hashtag looks like it is not setup. May want to fix that", Toast.LENGTH_LONG).show(); } else { try { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY); builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET); // Access Token String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, ""); // Access Token Secret String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, ""); AccessToken accessToken = new AccessToken(access_token, access_token_secret); Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken); //Query query = new Query("#MOTD2014"); Query query = new Query(qHash); query.count(TWEET_COUNT); QueryResult result = twitter.search(query); for (twitter4j.Status status : result.getTweets()) { MediaEntity[] me = status.getMediaEntities(); String meUrl = ""; if (me.length > 0) { Log.d(TAG, "me[0] : " + me[0].getMediaURL()); //meUrl = me[0].getDisplayURL(); //sjort URl = useless. meUrl = me[0].getMediaURL(); } JSONObject jso = tweetJSON(status.getUser().getScreenName(), status.getUser().getName() // , status.getUser().getOriginalProfileImageURL() //Whatever the size was it was uploaded in // , status.getUser().getProfileImageURL() // 48x48 , status.getUser().getBiggerProfileImageURL() // 73x73 , status.getText(), status.getCreatedAt().toString(), status.getFavoriteCount(), status.getRetweetCount(), meUrl); jsA.put(jso); } } catch (TwitterException e) { // Error in updating status Log.d("Twitter Search Error", e.getMessage()); Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show(); } } ; return jsA; } else { Toast.makeText(this, "You do not seem to be connected to a cast device...", Toast.LENGTH_LONG).show(); return null; } }