List of usage examples for twitter4j User getStatus
Status getStatus();
From source file:GetTweetsAndSaveToFile.java
License:Apache License
/** * Usage: java twitter4j.examples.user.ShowUser [screen name] * * @param args message//from ww w . j a va 2 s . com * @throws IOException */ public static void main(String[] args) throws IOException { if (args.length < 1) { System.out.println("Usage: java twitter4j.examples.user.ShowUser [screen name]"); System.exit(-1); } try { Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer("men2JyLEaAsxcbfmgzOAwUnTp", "2AGN0ie9TfCDJyWeH8qhTLtMhqRvRlNBtQU3lAP2M8k3Xk1KWl"); RequestToken requestToken = twitter.getOAuthRequestToken(); System.out.println("Authorization URL: \n" + requestToken.getAuthorizationURL()); AccessToken accessToken = new AccessToken("2811255124-zigkuv8MwDQbr5s9HdjLRSbg8aCOyxeD2gYGMfH", "D7jFABWHQa8QkTWwgYj1ISUbWP8twdfbzNgYkXI3jwySR"); twitter.setOAuthAccessToken(accessToken); /* 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()); User user = twitter.showUser(args[0]); if (user.getStatus() != null) { System.out.println("@" + user.getScreenName() + " - " + user.getStatus().getText()); } else { // the user is protected System.out.println("@" + user.getScreenName()); } FileWriter file = new FileWriter("./" + user.getScreenName() + "_Tweets.txt"); List<Status> list = twitter.getHomeTimeline(); for (Status each : list) { file.write("Sent by: @" + each.getUser().getScreenName() + " - " + each.getUser().getName() + "---" + each.getText() + "\n"); } file.close(); System.exit(0); } catch (Exception te) { te.printStackTrace(); System.exit(-1); } }
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 ww .ja va 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 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 . ja v a 2s . co 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:com.anshul.HomeServlet.java
License:Open Source License
private void statusCheck(Twitter twitter, HttpServletRequest req, HttpServletResponse resp) throws IOException, TwitterException { User user = twitter.verifyCredentials(); String username = user.getName(); String latestTweet = user.getStatus().getText(); TweetWrapper tweetWrapper = TweetWrapper.feel(latestTweet); String emotion = tweetWrapper.getStrongestEmotion(); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Query query = new Query("Station"); query.setFilter(FilterOperator.EQUAL.of("mood", emotion)); List<Entity> stations = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)); Entity station = stations.get(0); req.getSession().setAttribute("user", username); req.getSession().setAttribute("userId", user.getId()); req.getSession().setAttribute("latestTweet", latestTweet); req.getSession().setAttribute("emotion", emotion); req.getSession().setAttribute("stationName", station.getProperty("name")); req.getSession().setAttribute("url", station.getProperty("url")); req.getSession().setAttribute("profileImage", user.getBiggerProfileImageURL()); req.removeAttribute("oauth_token"); req.removeAttribute("oauth_verifier"); resp.sendRedirect("login.jsp"); }
From source file:com.github.gorbin.asne.twitter.TwitterSocialNetwork.java
License:Open Source License
private TwitterPerson getDetailedSocialPerson(TwitterPerson twitterPerson, User user) { getSocialPerson(twitterPerson, user); twitterPerson.createdDate = user.getCreatedAt().getTime(); twitterPerson.description = user.getDescription(); twitterPerson.favoritesCount = user.getFavouritesCount(); twitterPerson.followersCount = user.getFollowersCount(); twitterPerson.friendsCount = user.getFriendsCount(); twitterPerson.lang = user.getLang(); twitterPerson.location = user.getLocation(); twitterPerson.screenName = user.getScreenName(); if (user.getStatus() != null) { twitterPerson.status = user.getStatus().getText(); } else {//from w w w . j av a 2s. co m twitterPerson.status = null; } twitterPerson.timezone = user.getTimeZone(); twitterPerson.isTranslator = user.isTranslator(); twitterPerson.isVerified = user.isVerified(); return twitterPerson; }
From source file:com.javielinux.infos.InfoTweet.java
License:Apache License
public InfoTweet(User user) { urls = new ArrayList<URLContent>(); mTypeFrom = FROM_USER;//from w w w. j a v a2 s .c om urlAvatar = user.getProfileImageURL().toString(); userId = user.getId(); username = user.getScreenName(); fullname = user.getName(); try { id = user.getStatus().getId(); text = user.getStatus().getText(); source = user.getStatus().getSource(); toUsername = user.getStatus().getInReplyToScreenName(); toUserId = user.getStatus().getInReplyToUserId(); createAt = user.getStatus().getCreatedAt(); toReplyId = user.getStatus().getInReplyToStatusId(); if (user.getStatus().getGeoLocation() != null) { latitude = user.getStatus().getGeoLocation().getLatitude(); longitude = user.getStatus().getGeoLocation().getLongitude(); } } catch (Exception e) { } calculateLinks(); }
From source file:com.javielinux.infos.InfoUsers.java
License:Apache License
public InfoUsers(User user) { setId(user.getId());//from w ww . ja v a2 s .c om setName(user.getScreenName()); setFullname(user.getName()); setCreated(user.getCreatedAt()); setLocation(user.getLocation()); if (user.getURL() != null) setUrl(user.getURL().toString()); setFollowers(user.getFollowersCount()); setFollowing(user.getFriendsCount()); setTweets(user.getStatusesCount()); setBio(user.getDescription()); if (user.getStatus() != null) setTextTweet(user.getStatus().getText()); setUrlAvatar(user.getProfileImageURL().toString()); ArrayList<Entity> ents = DataFramework.getInstance().getEntityList("users", "service is null or service = \"twitter.com\""); for (Entity ent : ents) { friendly.put(ent.getString("name"), new Friend(ent.getString("name"))); } }
From source file:com.oldterns.vilebot.handlers.user.UrlTweetAnnouncer.java
License:Open Source License
/** * Accesses the source of a HTML page and looks for a title element * //from w w w. ja v a 2 s .c o m * @param url http tweet String * @return String of text which represents the tweet. Empty if error. */ private String scrapeURLHTMLTitle(String url) { String text = ""; URL page; try { page = new URL(url); } catch (MalformedURLException x) { // System.err.format("scrapeURLHTMLTitle new URL error: %s%n", x); return text; } //split the url into pieces, change the request based on what we have String parts[] = url.split("/"); int userPosition = 0; long tweetID = 0; for (int i = 0; i < parts.length; i++) { if (parts[i].toString().equals("twitter.com")) userPosition = i + 1; if (parts[i].toString().equals("status") || parts[i].toString().equals("statuses")) tweetID = Long.valueOf(parts[i + 1].toString()).longValue(); } if (userPosition == 0) return text; else { try { String consumerKey = ""; //may be known as 'API key' String consumerSecret = ""; //may be known as 'API secret' String accessToken = ""; //may be known as 'Access token' String accessTokenSecret = ""; //may be known as 'Access token secret' ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret) .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); if (tweetID != 0) //tweet of the twitter.com/USERID/status/TWEETID variety { Status status = twitter.showStatus(tweetID); return (status.getUser().getName() + ": " + status.getText()); } else //just the user is given, ie, twitter.com/USERID { User user = twitter.showUser(parts[userPosition].toString()); if (!user.getDescription().isEmpty()) //the user has a description return ("Name: " + user.getName() + " | " + user.getDescription() + "\'\nLast Tweet: \'" + user.getStatus().getText()); else //the user doesn't have a description, don't print it return ("Name: " + user.getName() + "\'\nLast Tweet: \'" + user.getStatus().getText()); } } catch (TwitterException x) { return text; } } }
From source file:de.binfalse.jatter.processors.JabberMessageProcessor.java
License:Open Source License
/** * Translate user.// w w w.j av a2s . c om * * @param user the user * @param profile the profile * @return the string */ public static String translateUser(User user, String profile) { String ret = "profile of *" + profile + "*\n" + "name: " + user.getName() + "\n" + "screen name: " + user.getScreenName() + "\n" + "id: " + user.getId() + "\n"; if (user.getDescription() != null) ret += "description: " + user.getDescription() + "\n"; if (user.getURL() != null) ret += "url: " + JatterTools.expandUrl(user.getURL()) + "\n"; if (user.getLang() != null) ret += "language: " + user.getLang() + "\n"; if (user.getLocation() != null) ret += "location: " + user.getLocation() + "\n"; if (user.getTimeZone() != null) ret += "time zone: " + user.getTimeZone() + "\n"; ret += "tweets: " + user.getStatusesCount() + "\n"; ret += "favourites: " + user.getFavouritesCount() + "\n"; ret += "followers: " + user.getFollowersCount() + "\n"; ret += "friends: " + user.getFriendsCount() + "\n"; if (user.getStatus() != null) ret += "last status: " + TwitterStatusProcessor.translateTwitterStatus(user.getStatus()); return ret; }
From source file:de.jetsli.twitter.TwitterSearch.java
License:Apache License
/** * API COSTS: 1/*from w ww .j a va 2 s . com*/ * * @param users should be maximal 100 users * @return the latest tweets of the users */ public Collection<? extends Status> updateUserInfo(List<? extends User> users) { int counter = 0; String arr[] = new String[users.size()]; // responseList of twitter.lookup has not the same order as arr has!! Map<String, User> userMap = new LinkedHashMap<String, User>(); for (User u : users) { arr[counter++] = u.getScreenName(); userMap.put(u.getScreenName(), u); } int maxRetries = 5; for (int retry = 0; retry < maxRetries; retry++) { try { ResponseList<User> res = twitter.lookupUsers(arr); rateLimit--; List<Status> tweets = new ArrayList<Status>(); for (int ii = 0; ii < res.size(); ii++) { User user = res.get(ii); User yUser = userMap.get(user.getScreenName().toLowerCase()); if (yUser == null) continue; // Status stat = yUser.updateFieldsBy(user); // if (stat == null) // continue; // Status tw = toTweet(stat, res.get(ii)); tweets.add(user.getStatus()); } return tweets; } catch (TwitterException ex) { logger.warn("Couldn't lookup users. Retry:" + retry + " of " + maxRetries, ex); if (retry < 1) continue; else break; } } return Collections.EMPTY_LIST; }