List of usage examples for twitter4j Twitter showUser
User showUser(long userId) throws TwitterException;
From source file:GetTweetsAndSaveToFile.java
License:Apache License
/** * Usage: java twitter4j.examples.user.ShowUser [screen name] * * @param args message/*from ww w . j a v a2s . co m*/ * @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:DestroyFriendship.java
License:Apache License
/** * Usage: java twitter4j.examples.friendship.DestroyFriendship [screen name] * * @param args message/*w w w .j a v a2s.c om*/ */ public void destroyFriendship() { ShowFriendshi df = new ShowFriendshi(); ArrayList<Long> getFilteredtarget = df.showFriendship(); try { Twitter twitter = new TwitterFactory().getInstance(); User user; String get; DefaultListModel m1 = new DefaultListModel(); for (Long target : getFilteredtarget) { user = twitter.showUser(target); get = user.getScreenName(); if (!get.equalsIgnoreCase("prometheanBrain") && !get.equalsIgnoreCase("tweetrackdevs")) { m1.addElement(get); twitter.destroyFriendship(target); } System.out.println("Successfully unfollowed [" + target + "]."); } MainActivity.deletedList.setModel(m1); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to unfollow: " + te.getMessage()); } }
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 . j a va2s . 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 .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:be.ugent.tiwi.sleroux.newsrec.twittertest.App.java
public static void main(String[] args) throws TwitterException { Twitter twitter = TwitterFactory.getSingleton(); AccessToken accessToken = new AccessToken("2369203675-1Pk99eotzhCznmIgr3iXb670DpsEVQCANuoBHRs", "6ua72cabIzcFsBgE15RVzULeKT44TnIrOIaf9chY9dlWe"); twitter.setOAuthConsumer("tQjT8XvB7OPNTl8qdhchDo3J2", "FXWVS3OEW7omiUDSLpET0aRInoUumGPWRxOVyk7GrhiwcfLBnV"); twitter.setOAuthAccessToken(accessToken); User user = twitter.showUser("billclinton"); System.out.println("id=" + user.getId()); StreamReaderService srs = new StreamReaderService(); srs.readTwitterFeed();/*from w w w .j a va 2 s . co m*/ }
From source file:com.arihant15.ActionServlet.java
@RequestMapping("/getFriends.arihant15") public void doFriends(HttpServletRequest req, HttpServletResponse res) throws IOException { try {//from www . j a va 2 s . c o m Twitter twitter = (Twitter) req.getSession().getAttribute("t"); IDs ids = twitter.getFollowersIDs(-1); PagableResponseList<User> users; for (long id : ids.getIDs()) { (res.getWriter()).println("@" + twitter.showUser(id).getName() + "\n"); } } catch (Exception e) { (res.getWriter()).println(e); } }
From source file:com.daiv.android.twitter.ui.profile_viewer.fragments.ProfileFragment.java
License:Apache License
public void getData(final TextView statement, final AsyncListView listView) { Thread getData = new Thread(new Runnable() { @Override// w w w .j a v a 2 s . c o m public void run() { Twitter twitter = Utils.getTwitter(context, settings); try { Log.v("Test_profile", "start of load time: " + Calendar.getInstance().getTimeInMillis()); if (!isMyProfile) { thisUser = twitter.showUser(screenName); } else { if (settings.myId == 0) { try { thisUser = twitter.showUser(settings.myScreenName); } catch (Exception e) { // the user has changed their screen name, so look for the id ((Activity) context).runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(context, context.getResources().getString(R.string.changed_screenname), Toast.LENGTH_LONG).show(); spinner.setVisibility(View.GONE); canRefresh = false; hasMore = false; } }); } return; } else { thisUser = twitter.showUser(settings.myId); } // update the profile picture url and the background url in shared prefs int currentAccount = sharedPrefs.getInt("current_account", 1); SharedPreferences.Editor e = sharedPrefs.edit(); e.putString("twitter_users_name_" + currentAccount, thisUser.getName()).commit(); e.putString("twitter_screen_name_" + currentAccount, thisUser.getScreenName()).commit(); e.putLong("twitter_id_" + currentAccount, thisUser.getId()).commit(); e.putString("profile_pic_url_" + currentAccount, thisUser.getOriginalProfileImageURL()); e.putString("twitter_background_url_" + currentAccount, thisUser.getProfileBannerURL()); e.commit(); } ((Activity) context).runOnUiThread(new Runnable() { @Override public void run() { try { if (thisUser.isVerified()) { if (settings.addonTheme) { verified.setVisibility(View.VISIBLE); verified.setText(getResources().getString(R.string.verified)); } else { verified.setVisibility(View.VISIBLE); verified.setText(getResources().getString(R.string.verified)); } } String state = thisUser.getDescription() + "\n"; String loca = thisUser.getLocation(); if (!loca.equals("")) { state += "\n" + thisUser.getLocation(); } if (state.equals("")) { statement.setText(getResources().getString(R.string.no_description)); } else { statement.setText(state); } if (!settings.addonTheme) { statement.setLinkTextColor(getResources().getColor(R.color.app_color)); } else { statement.setLinkTextColor(settings.accentInt); } tweetsBtn.setText(getResources().getString(R.string.tweets) + "\n" + "(" + thisUser.getStatusesCount() + ")"); followersBtn.setText(getResources().getString(R.string.followers) + "\n" + "(" + thisUser.getFollowersCount() + ")"); followingBtn.setText(getResources().getString(R.string.following) + "\n" + "(" + thisUser.getFriendsCount() + ")"); getURL(statement, thisUser); getTimeline(thisUser, listView); } catch (Exception e) { // Illegal state because the activity is destroyed } } }); } catch (Exception e) { e.printStackTrace(); ((Activity) context).runOnUiThread(new Runnable() { @Override public void run() { try { if (thisUser != null && thisUser.isProtected()) { Toast.makeText(context, getResources().getString(R.string.protected_account), Toast.LENGTH_SHORT).show(); if (settings.roundContactImages) { ImageUtils.loadSizedCircleImage(context, profilePicture, thisUser.getOriginalProfileImageURL(), mCache, 96); } else { ImageUtils.loadImage(context, profilePicture, thisUser.getOriginalProfileImageURL(), mCache); } String url = thisUser.getProfileBannerURL(); ImageUtils.loadImage(context, background, url, mCache); } else { Toast.makeText(context, getResources().getString(R.string.error_loading_timeline), Toast.LENGTH_SHORT).show(); } spinner.setVisibility(View.GONE); } catch (Exception e) { // not attached to activity } canRefresh = false; hasMore = false; } }); } } }); getData.setPriority(Thread.MAX_PRIORITY); getData.start(); }
From source file:com.daiv.android.twitter.utils.text.TouchableSpan.java
License:Apache License
public void longClickMentions() { AlertDialog.Builder builder = getBuilder(); builder.setItems(R.array.long_click_mentions, new DialogInterface.OnClickListener() { @Override//from w w w.ja v a2 s. co m public void onClick(DialogInterface dialogInterface, int i) { final SharedPreferences sharedPrefs = mContext.getSharedPreferences( "com.daiv.android.twitter_world_preferences", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE); switch (i) { case 0: // open profile TouchableSpan.this.onClick(null); break; case 1: // copy handle copy(); break; case 2: // search user search(); break; case 3: // favorite user new Thread(new Runnable() { @Override public void run() { try { Twitter twitter = Utils.getTwitter(mContext, settings); User user = twitter.showUser(full.replace("@", "")); int current = sharedPrefs.getInt("current_account", 1); FavoriteUsersDataSource.getInstance(mContext).createUser(user, current); sharedPrefs.edit() .putString("favorite_user_names_" + current, sharedPrefs.getString("favorite_user_names_" + current, "") + user.getScreenName() + " ") .commit(); } catch (Exception e) { } } }).start(); break; case 4: // mute user String current = sharedPrefs.getString("muted_users", ""); sharedPrefs.edit() .putString("muted_users", current + full.replaceAll(" ", "").replaceAll("@", "") + " ") .commit(); sharedPrefs.edit().putBoolean("refresh_me", true).commit(); sharedPrefs.edit().putBoolean("just_muted", true).commit(); if (mContext instanceof DrawerActivity) { ((Activity) mContext).recreate(); } break; case 5: // mute retweets String muted_rts = sharedPrefs.getString("muted_rts", ""); sharedPrefs.edit() .putString("muted_rts", muted_rts + full.replaceAll(" ", "").replaceAll("@", "") + " ") .commit(); sharedPrefs.edit().putBoolean("refresh_me", true).commit(); sharedPrefs.edit().putBoolean("just_muted", true).commit(); if (mContext instanceof DrawerActivity) { ((Activity) mContext).recreate(); } break; case 6: // share profile share("https://twitter.com/" + full.replace("@", "").replace(" ", "")); break; } } }); builder.create().show(); }
From source file:com.eventattend.portal.bl.TwitterBL.java
License:Open Source License
private List getFollowersProfile(Twitter twitterClient, String screenName, TwitterDTO twitterDTO) throws BaseAppException { //ProfileDTO profileDTO = null; User profile = null;//from www . j ava 2 s. c o m List followersList = null; try { followersList = new ArrayList(); int i = 0; IDs friendsIds = twitterClient.getFollowersIDs(screenName); if (friendsIds != null) { for (int userId : friendsIds.getIDs()) { //if(i<5){ profile = twitterClient.showUser(userId); twitterDTO = fetchProfile(profile, twitterDTO); followersList.add(twitterDTO); } //i++; //} } } catch (TwitterException e) { processTwitterException(e); } return followersList; }
From source file:com.eventattend.portal.bl.TwitterBL.java
License:Open Source License
private List getFriendsProfile(Twitter twitterClient, String screenName, TwitterDTO twitterDTO) throws BaseAppException { //ProfileDTO profileDTO = null; User profile = null;//from w w w . j a v a 2 s . c om List friendsList = null; try { friendsList = new ArrayList(); IDs friendsIds = twitterClient.getFriendsIDs(screenName); int i = 0; if (friendsIds != null) { for (int userId : friendsIds.getIDs()) { //if(i<5){ profile = twitterClient.showUser(userId); twitterDTO = fetchProfile(profile, twitterDTO); friendsList.add(twitterDTO); } //i++; //} } } catch (TwitterException e) { processTwitterException(e); } return friendsList; }