List of usage examples for twitter4j User getName
String getName();
From source file:com.michaelfitzmaurice.clocktwerk.TweetResponder.java
License:Apache License
public Collection<Status> getNewMentions() throws TweetException { long sinceId = lastSeenMention(); try {//ww w .j a v a2 s . c o m LOG.info("Checking for new Twitter mentions of {} since Tweet {}", myScreenName, sinceId); Paging paging = new Paging(sinceId); ResponseList<Status> mentions = twitterClient.getMentionsTimeline(paging); int numberOfMentions = mentions.size(); LOG.info("Found {} new mentions", numberOfMentions); for (Status status : mentions) { User user = status.getUser(); String mentionSummary = format("Date:%s, ID:%s, From:%s (%s), Text:'%s'", status.getCreatedAt(), status.getId(), user.getScreenName(), user.getName(), status.getText()); LOG.debug("New mention: [{}]", mentionSummary); } return mentions; } catch (TwitterException e) { throw new TweetException("Error getting Twitter mentions", e); } // TODO handle paging }
From source file:com.michaelstark.twitteroauth.getNameServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//ww w .jav a2s . co m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); HttpSession session = request.getSession(true); User user = (User) session.getAttribute("user"); try (PrintWriter out = response.getWriter()) { out.printf("{\"name\": \"%s\"}", user.getName()); } }
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 * // www .j av a2 s .co 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:com.playcez.twitter.android.TwitterApp.java
License:Apache License
/** * Process token.// ww w. j av a2 s .c o m * * @param callbackUrl the callback url */ public void processToken(String callbackUrl) { mProgressDlg.setMessage("Finalizing ..."); mProgressDlg.show(); final String verifier = getVerifier(callbackUrl); new Thread() { @Override public void run() { int what = 1; try { mHttpOauthprovider.retrieveAccessToken(mHttpOauthConsumer, verifier); mAccessToken = new AccessToken(mHttpOauthConsumer.getToken(), mHttpOauthConsumer.getTokenSecret()); configureToken(); User user = mTwitter.verifyCredentials(); mSession.storeAccessToken(mAccessToken, user.getName()); what = 0; } catch (Exception e) { e.printStackTrace(); } mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0)); } }.start(); }
From source file:com.raythos.sentilexo.twitter.domain.QueryResultItemMapper.java
License:Apache License
public static TwitterQueryResultItemAvro mapItem(String queryOwner, String queryName, String queryString, Status status) {/* w ww . j a v a 2 s.c o m*/ TwitterQueryResultItemAvro result = new TwitterQueryResultItemAvro(); if (queryName != null) queryName = queryName.toLowerCase(); if (queryOwner != null) queryOwner = queryOwner.toLowerCase(); result.setQueryName(queryName); result.setQueryOwner(queryOwner); result.setQuery(queryString); result.setStatusId(status.getId()); result.setText(status.getText()); result.setRelevantQueryTerms(TwitterUtils.relevantQueryTermsFromStatus(queryString, status)); result.setLang(status.getLang()); result.setCreatedAt(status.getCreatedAt().getTime()); User user = status.getUser(); result.setUserId(user.getId()); result.setScreenName(user.getScreenName()); result.setUserLocation(user.getLocation()); result.setUserName(user.getName()); result.setUserDescription(user.getDescription()); result.setUserIsProtected(user.isProtected()); result.setUserFollowersCount(user.getFollowersCount()); result.setUserCreatedAt(user.getCreatedAt().getTime()); result.setUserCreatedAtAsString(DateTimeUtils.getDateAsText(user.getCreatedAt())); result.setCreatedAtAsString(DateTimeUtils.getDateAsText(status.getCreatedAt())); result.setUserFriendsCount(user.getFriendsCount()); result.setUserListedCount(user.getListedCount()); result.setUserStatusesCount(user.getStatusesCount()); result.setUserFavoritesCount(user.getFavouritesCount()); result.setCurrentUserRetweetId(status.getCurrentUserRetweetId()); result.setInReplyToScreenName(status.getInReplyToScreenName()); result.setInReplyToStatusId(status.getInReplyToStatusId()); result.setInReplyToUserId(status.getInReplyToUserId()); if (status.getGeoLocation() != null) { result.setLatitude(status.getGeoLocation().getLatitude()); result.setLongitude(status.getGeoLocation().getLongitude()); } result.setSource(status.getSource()); result.setTrucated(status.isTruncated()); result.setPossiblySensitive(status.isPossiblySensitive()); result.setRetweet(status.getRetweetedStatus() != null); if (result.getRetweet()) { result.setRetweetStatusId(status.getRetweetedStatus().getId()); result.setRetweetedText(status.getRetweetedStatus().getText()); } result.setRetweeted(status.isRetweeted()); result.setRetweetCount(status.getRetweetCount()); result.setRetweetedByMe(status.isRetweetedByMe()); result.setFavoriteCount(status.getFavoriteCount()); result.setFavourited(status.isFavorited()); if (status.getPlace() != null) { result.setPlace(status.getPlace().getFullName()); } Scopes scopesObj = status.getScopes(); if (scopesObj != null) { List scopes = Arrays.asList(scopesObj.getPlaceIds()); result.setScopes(scopes); } return result; }
From source file:com.redhat.ipaas.example.TweetToContactMapper.java
License:Apache License
@Override public void process(Exchange exchange) throws Exception { Message in = exchange.getIn();/*ww w . j av a 2s .co m*/ Status status = exchange.getIn().getBody(Status.class); User user = status.getUser(); String name = user.getName(); String screenName = user.getScreenName(); Contact contact = new Contact(); contact.setLastName(name); contact.setTwitterScreenName__c(screenName); in.setBody(contact); }
From source file:com.revolucion.secretwit.twitter.TwitterClient.java
License:Open Source License
public User authorize(String pin) throws TwitterException { AccessToken accessToken = null;/*from w w w.j a v a 2s. c o m*/ if (pin != null && !pin.isEmpty()) { accessToken = twitter.getOAuthAccessToken(requestToken, pin); logger.debug("Requested access token for pin {}.", pin); } else accessToken = twitter.getOAuthAccessToken(); User user = twitter.verifyCredentials(); if (user != null) { logger.info("Authorized user {}.", user.getName()); // signedIn = true; this.user = user; storeAccessToken(accessToken); } return user; }
From source file:com.soomla.profile.social.twitter.SoomlaTwitter.java
License:Apache License
private UserProfile createUserProfile(User user, boolean withExtraFields) { String fullName = user.getName(); String firstName = ""; String lastName = ""; if (!TextUtils.isEmpty(fullName)) { String[] splitName = fullName.split(" "); if (splitName.length > 0) { firstName = splitName[0];//from w ww . j ava 2 s . com if (splitName.length > 1) { lastName = splitName[1]; } } } Map<String, Object> extraDict = Collections.<String, Object>emptyMap(); if (withExtraFields) { extraDict = new HashMap<String, Object>(); // TwitterException will throws when Twitter service or network is unavailable, or the user has not authorized try { extraDict.put("access_token", twitter.getOAuthAccessToken().getToken()); } catch (TwitterException twitterExc) { SoomlaUtils.LogError(TAG, twitterExc.getErrorMessage()); } } //Twitter does not supply email access: https://dev.twitter.com/faq#26 UserProfile result = new UserProfile(RefProvider, String.valueOf(user.getId()), user.getScreenName(), "", firstName, lastName, extraDict); // No gender information on Twitter: // https://twittercommunity.com/t/how-to-find-male-female-accounts-in-following-list/7367 result.setGender(""); // No birthday on Twitter: // https://twittercommunity.com/t/how-can-i-get-email-of-user-if-i-use-api/7019/16 result.setBirthday(""); result.setLanguage(user.getLang()); result.setLocation(user.getLocation()); result.setAvatarLink(user.getBiggerProfileImageURL()); return result; }
From source file:com.speed.traquer.app.TraqComplaintTaxi.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_traq_complaint_taxi); easyTracker = EasyTracker.getInstance(TraqComplaintTaxi.this); //onCreateView(savedInstanceState); //InitialSetupUI(); //Added UIHelper uiHelper = new UiLifecycleHelper(this, null); uiHelper.onCreate(savedInstanceState); inputTaxi = (EditText) findViewById(R.id.taxi_id); taxiDriver = (EditText) findViewById(R.id.taxi_driver); taxiLic = (EditText) findViewById(R.id.taxi_license); geoLat = (TextView) findViewById(R.id.geoLat); geoLong = (TextView) findViewById(R.id.geoLong); editDate = (EditText) findViewById(R.id.editDate); editTime = (EditText) findViewById(R.id.editTime); editCurrTime = (EditText) findViewById(R.id.editCurrTime); complainSend = (Button) findViewById(R.id.complain_send); ProgressBar barProgress = (ProgressBar) findViewById(R.id.progressLoading); ProgressBar barProgressFrom = (ProgressBar) findViewById(R.id.progressLoadingFrom); ProgressBar barProgressTo = (ProgressBar) findViewById(R.id.progressLoadingTo); actv_comp_taxi = (AutoCompleteTextView) findViewById(R.id.search_taxi_comp); SuggestionAdapter sa = new SuggestionAdapter(this, actv_comp_taxi.getText().toString(), taxiUrl, "compcode"); sa.setLoadingIndicator(barProgress); actv_comp_taxi.setAdapter(sa);/*from w w w. j a v a 2 s. co m*/ actv_from = (AutoCompleteTextView) findViewById(R.id.search_from); SuggestionAdapter saFrom = new SuggestionAdapter(this, actv_from.getText().toString(), locUrl, "location"); saFrom.setLoadingIndicator(barProgressFrom); actv_from.setAdapter(saFrom); actv_to = (AutoCompleteTextView) findViewById(R.id.search_to); SuggestionAdapter saTo = new SuggestionAdapter(this, actv_to.getText().toString(), locUrl, "location"); saTo.setLoadingIndicator(barProgressTo); actv_to.setAdapter(saTo); /*if(isNetworkConnected()) { new getTaxiComp().execute(new ApiConnector()); }*/ //Setting Fonts String fontPath = "fonts/segoeuil.ttf"; Typeface tf = Typeface.createFromAsset(getAssets(), fontPath); complainSend.setTypeface(tf); inputTaxi.setTypeface(tf); editDate.setTypeface(tf); editTime.setTypeface(tf); actv_comp_taxi.setTypeface(tf); actv_to.setTypeface(tf); actv_from.setTypeface(tf); taxiDriver.setTypeface(tf); taxiLic.setTypeface(tf); TextView txtComp = (TextView) findViewById(R.id.taxi_comp); txtComp.setTypeface(tf); TextView txtTaxiDriver = (TextView) findViewById(R.id.txt_taxi_driver); txtTaxiDriver.setTypeface(tf); TextView txtTaxiLic = (TextView) findViewById(R.id.txt_taxi_license); txtTaxiLic.setTypeface(tf); TextView txtNumber = (TextView) findViewById(R.id.taxi_number); txtNumber.setTypeface(tf); TextView txtTo = (TextView) findViewById(R.id.to); txtTo.setTypeface(tf); TextView txtDate = (TextView) findViewById(R.id.date); txtDate.setTypeface(tf); TextView txtTime = (TextView) findViewById(R.id.time); txtTime.setTypeface(tf); gLongitude = this.getIntent().getExtras().getDouble("Longitude"); gLatitude = this.getIntent().getExtras().getDouble("Latitude"); speedTaxiExceed = this.getIntent().getExtras().getDouble("SpeedTaxiExceed"); isTwitterSelected = false; isFacebookSelected = false; isDefaultSelected = false; isSmsSelected = false; geoLat.setText(Double.toString(gLatitude)); geoLong.setText(Double.toString(gLongitude)); rateBtnBus = (ImageButton) findViewById(R.id.btn_rate_bus); rateBtnBus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (actv_comp_taxi.length() != 0) { final AlertDialog.Builder alertBox = new AlertDialog.Builder(TraqComplaintTaxi.this); alertBox.setIcon(R.drawable.info_icon); alertBox.setCancelable(false); alertBox.setTitle("Do you want to cancel complaint?"); alertBox.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { // finish used for destroyed activity easyTracker.send(MapBuilder .createEvent("Complaint", "Cancel Complaint (Yes)", "Complaint event", null) .build()); finish(); } }); alertBox.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int arg1) { easyTracker.send(MapBuilder .createEvent("Complaint", "Cancel Complaint (No)", "Complaint event", null) .build()); dialog.cancel(); } }); alertBox.show(); } else { Intent intent = new Intent(getApplicationContext(), TraqComplaint.class); intent.putExtra("Latitude", gLatitude); intent.putExtra("Longitude", gLongitude); intent.putExtra("SpeedBusExceed", speedTaxiExceed); startActivity(intent); } } }); complainSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String taxi_id = inputTaxi.getText().toString().toUpperCase(); String taxi_comp = actv_comp_taxi.getText().toString(); /*if(taxi_comp.length() == 0){ Toast.makeText(TraqComplaintTaxi.this, "Taxi Company is required!", Toast.LENGTH_SHORT).show(); }else */ if (taxi_comp.length() < 2) { Toast.makeText(TraqComplaintTaxi.this, "Invalid Taxi Company.", Toast.LENGTH_SHORT).show(); } else if (taxi_id.length() == 0) { Toast.makeText(TraqComplaintTaxi.this, "Taxi Plate Number is required!", Toast.LENGTH_SHORT) .show(); } else if (taxi_id.length() < 7) { Toast.makeText(TraqComplaintTaxi.this, "Invalid Taxi Number.", Toast.LENGTH_SHORT).show(); } else { easyTracker.send( MapBuilder.createEvent("Complaint", "Dialog Prompt", "Complaint event", null).build()); PromptCustomDialog(); } } }); setCurrentDateOnView(); getCurrentTime(); //Shi Chuan's Code StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); cd = new ConnectionDetector(getApplicationContext()); // Check if Internet present if (!cd.isConnectingToInternet()) { // Internet Connection is not present alert.showAlertDialog(TraqComplaintTaxi.this, "Internet Connection Error", "Please connect to working Internet connection", false); // stop executing code by return return; } // Check if twitter keys are set if (TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0) { // Internet Connection is not present alert.showAlertDialog(TraqComplaintTaxi.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false); // stop executing code by return return; } // Shared Preferences mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0); /** This if conditions is tested once is * redirected from twitter page. Parse the uri to get oAuth * Verifier * */ if (!isTwitterLoggedInAlready()) { Uri uri = getIntent().getData(); if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) { // oAuth verifier String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER); try { // Get the access token AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); // Shared Preferences SharedPreferences.Editor e = mSharedPreferences.edit(); // After getting access token, access token secret // store them in application preferences e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken()); e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret()); // Store login status - true e.putBoolean(PREF_KEY_TWITTER_LOGIN, true); e.commit(); // save changes Log.e("Twitter OAuth Token", "> " + accessToken.getToken()); // Getting user details from twitter // For now i am getting his name only long userID = accessToken.getUserId(); User user = twitter.showUser(userID); String username = user.getName(); String description = user.getDescription(); // Displaying in xml ui //lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>" + description)); } catch (Exception e) { // Check log for login errors Log.e("Twitter Login Error", "> " + e.getMessage()); } } } //LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); //LocationListener ll = new passengerLocationListener(); //lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll); }
From source file:com.speed.traquer.app.TraqComplaintTaxi.java
private void checkTwitterID() { /* Get Access Token after login*/ try {// w ww.ja v a 2 s . c o m 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); // Getting user details from twitter // For now i am getting his name only twitterID = accessToken.getUserId(); User user = twitter.showUser(twitterID); userName = user.getName(); //Toast.makeText(TraqComplaintTaxi.this, Long.toString(twitterID) + userName, Toast.LENGTH_SHORT).show(); // Displaying in xml ui //lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>" + description)); } catch (TwitterException e) { // Error in updating status Log.d("Twitter Update Error", e.getMessage()); } catch (Exception e) { // Error in updating status Log.d("error!", e.getMessage()); } }