twitter4j: getting full name, bio, location, url of user (by username) - java

How do I get the full name, bio, location, and url of a user by knowing the username in twitter4j?
Twitter twitter = new TwitterFactory().getInstance();
User user = twitter.showUser(username); // this line
if (user.getStatus() != null) {
System.out.println("#" + user.getScreenName() + " - " + user.getDescription());
} else {
// protected account
System.out.println("#" + user.getScreenName());
}
returns
java.lang.IllegalStateException: Authentication credentials are
missing.
(tokens and so on are defined at the beginning. Tweeting, which also requires authentication of course, works fine with that)

You forget to pass the authentification to the TwitterFactory
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("CONSUMER_KEY");
cb.setOAuthConsumerSecret("CONSUMER_SECRET"));
cb.setOAuthAccessToken("TOKEN");
cb.setOAuthAccessTokenSecret("TOKEN_SECRET");
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
....

Related

PayPal SDK going from payment review page to profilepage

In my current Java/Spring project, I am in the phase of integration with PayPal. After configure a Java class to handle the payment process, following the instructions from here, I run my application and try to checkout an order with paypal.
I am redirected correctly to the PayPal login page, and after the login, to this payment review page:
but then after I click on "Continue", instead of finalizing the payment, I am redirected to my profile page.
Here is my code:
Paypal prop = this.paypalDao.get();
String clientId = prop.getClientID();
String clientSecret = prop.getClientSecret();
APIContext apiContext = new APIContext(clientId, clientSecret, "sandbox");
if(payerId != null) {
if(guid != null) {
Payment payment = new Payment();
payment.setId(map.get(guid));
PaymentExecution paymentExecution = new PaymentExecution();
paymentExecution.setPayerId(payerId);
payment.execute(apiContext, paymentExecution);
String url = request.getContextPath();
return url+"/orders";
}
} else {
List<Produto> lista_de_produtos = this.getListaDeProdutos(clienteId);
Double total = 0.0;
for(Produto produto : lista_de_produtos)
total = total + produto.getPreco();
DecimalFormat df = new DecimalFormat("0.00");
String svalue = df.format(total).replace(',', '.');
Details details = new Details();
details.setSubtotal(svalue);
Amount amount = new Amount();
amount.setCurrency("BRL");
amount.setTotal(svalue);
amount.setDetails(details);
Transaction transaction = new Transaction();
transaction.setAmount(amount);
transaction.setDescription(lista_de_produtos.toString());
List<Transaction> transactions = new ArrayList<Transaction>();
transactions.add(transaction);
Payer payer = new Payer();
payer.setPaymentMethod("paypal");
Payment payment = new Payment();
payment.setIntent("sale");
payment.setPayer(payer);
payment.setTransactions(transactions);
RedirectUrls redirectUrls = new RedirectUrls();
guid = UUID.randomUUID().toString();
String url = request.getContextPath();
redirectUrls.setCancelUrl( url+"/cart" );
redirectUrls.setReturnUrl( url+"/paypal/checkout/"+clientId+"/?guid=" + guid );
payment.setRedirectUrls(redirectUrls);
Payment createdPayment = payment.create(apiContext);
Iterator<Links> links = createdPayment.getLinks().iterator();
while (links.hasNext()) {
Links link = links.next();
if (link.getRel().equalsIgnoreCase("approval_url")) {
map.put("redirectURL", link.getHref());
redirectURL = link.getHref();
}
}
map.put(guid, createdPayment.getId());
payment.setId(map.get(guid));
}
return redirectURL;
Can someone tell me, what am I missing here?
Try printing this value:
System.out.println(url+"/paypal/checkout/"+clientId+"/?guid=" + guid);
The result should be https://www.yoursite.com/paypal/checkout/<number>/?guid=<number>, or a page that would direct there (leaving out https:// to save on bytes could be okay depending on your server configuration).
Additional tests you should try:
Try cancelling on your site.
Try cancelling the payment on paypal's site.
Iff one works but the second does not, then paypal is not redirecting properly, which probably means you're not giving it the right string. Also see comment by #Emile.

Creating a new object

At the moment my program has a Jpanel with about 15 different inputs. These inputs are created to one long string called "searchInput".
"searchInput" is then put into a query named which then gets metadata about the tweet result one at a time, such as createdAt, user and text. These results are printed to a textArea named tweetsResult.
createdAt, user and text are only some of the metadata behind each tweet, more being favouriteCount and retweetCount.
Because Twitter has a maximum amount of Tweets it can deliver to you using the API, I feel it would be best if I created a new class which uses searchInput, and then get the desired amount of Tweets with all of the metadata into an object. And then from the main class, I would only call the results with the specific meta data that I would like.
Is this the right way to do it? If so how would I create this new object, presumably using getters and setters?
I hope this is clear to you, and many thanks for the help!
List<Status> tweets = new ArrayList<Status>();
//Standard Twitter and Twitter4j authentication
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
Configuration configuration = builder.build();
TwitterFactory twitterFactory = new TwitterFactory(configuration);
Twitter twitter = twitterFactory.getInstance();
twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));
//The query is split up into 5 sections
//All the text boxes are read in the seperate methods
String searchWordInput = getWordSearchQuery();
String searchPeopleInput = getPeopleSearchQuery();
String filtersSearchInput = getFiltersSearchQuery();
String dateAndLocationSearchInput = getDateAndLocationSearchQuery();
String radiusAndLocationSearchInput = getRadiusAndLocationSearchQuery();
String searchInput = searchWordInput + searchPeopleInput + filtersSearchInput + dateAndLocationSearchInput + radiusAndLocationSearchInput;
//One big search String called "searchInput" is taken to be sent to Twitter
//Increases maximum amount of tweets in one search
int wantedTweets = 100; //CHANGE THIS FOR DIFFERENT AMOUNT OF TWEETS
long lastSearchID = Long.MAX_VALUE;
int remainingTweets = wantedTweets;
Query query = new Query(searchInput);
tweetsResultInput.append(searchInput);
try {
while (remainingTweets > 0) {
remainingTweets = wantedTweets - tweets.size();
if (remainingTweets > 100) {
query.count(100);
} else {
query.count(remainingTweets);
}
QueryResult result = twitter.search(query);
tweets.addAll(result.getTweets());
Status s = tweets.get(tweets.size() - 1);
lastSearchID = s.getId();
query.setMaxId(lastSearchID);
remainingTweets = wantedTweets - tweets.size();
}
//Increases maximum amount of tweets in ones search
tweetsResult.append(searchInput);
tweetsResult.append("\n");
//For the query tweets, using "searchInput", get every tweet in the format; when Tweet was sent, who it was sent by, and the Tweets text and write to tweetsResults
for (Status tweet : tweets) {
tweetsResult.append(tweet.getCreatedAt() + ":\t#" + tweet.getUser().getScreenName() + " - " + tweet.getText());
tweetsResult.append("\n");
}
} catch (TwitterException te) {
System.out.println("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}

How to check if a user is in an LDAP group

Problem
I want to see if user "john" is in group "Calltaker". I can't seem to get the syntax right on my search filter to check for a specific user in a specific group. I can list all users in a group to verify the desired user is there.
Questions
What is the right syntax for a ldap search filter to determine if a specific user is in a specific group(in Tivoli Access Manager)?
What should I check on the returned LDAPEntry object given by that search string to see that the user is, or isn't, in the group?
Info
john is defined in "cn=users,dc=ldap,dc=net"
Calltaker is defined in "cn=groups,dc=ldap,dc=net"
I'm querying against TAM's ldap, from java
Using the searchfilter to be "cn=Calltaker" I can print out the search results such that calling nextEntry.toString contains the list of users. See Example 1 below
Here's a few searchfilters I've tried that don't work (aka searchResults.next() throws an error):
(&(objectclass=groupOfUniqueName)(uniquemember=uid="+ username + ",cn=groups,dc=ldap,dc=net))
(&(objectclass=groupOfUniqueName)(uniquemember=uid="+ username + ",cn=users,dc=ldap,dc=net))
(uniquemember=uid="+ username + ",cn=users,dc=ldap,dc=net)
Example 1) only search group, using searchFilter="cn=Calltaker", verify it contains users:
System.out.println(nextEntry.toString()); //added newlines for readability
nextEntry:
LDAPEntry:
cn=Calltaker,cn=groups,dc=ldap,dc=net;
LDAPAttributeSet:
LDAPAttribute: {type='objectclass', values='groupOfUniqueNames','top'}
LDAPAttribute: {type='uniquemember',
values=
'uid=placeholder,cn=users,dc=ldap,dc=net',
'secAuthority=default',
'uid=john,cn=users,dc=ldap,dc=net',
'uid=sally,cn=users,dc=ldap,dc=net', ....etc
Code:
public boolean isUserInGroup(username){
boolean userInGroup = false;
String loginDN = "uid=" + admin_username + "," + "cn=users,dc=ldap,dc=net";
String searchBase = "cn=groups,dc=ldap,dc=net";
int searchScope = LDAPConnection.SCOPE_SUB;
searchFilter = "(&(objectclass=ePerson)(uniquemember=uid="+ username + ",cn=users,dc=ldap,dc=net))";
//Connect
LDAPConnection lc = connect(hosts);
lc.bind(LDAPConnection.LDAP_V3, loginDN, admin_password.getBytes("UTF8"));
lc.getAuthenticationDN();
LDAPSearchResults searchResults = lc.search(searchBase,
searchScope,
searchFilter,
null, // return all attributes
false); // return attrs and values
while (searchResults.hasMore()) {
LDAPEntry nextEntry = null;
try {
nextEntry = searchResults.next();
} catch (LDAPException e) {
// Exception is thrown, go for next entry
if (e.getResultCode() == LDAPException.LDAP_TIMEOUT || e.getResultCode() == LDAPException.CONNECT_ERROR)
break;
else
continue;
}
//TODO some check to verify nextEntry shows the user in the group
userInGroup = true;
LDAPAttributeSet attributeSet = nextEntry.getAttributeSet();
Iterator<LDAPAttribute> allAttributes = attributeSet.iterator();
while (allAttributes.hasNext()) {
LDAPAttribute attribute = (LDAPAttribute) allAttributes.next();
String attributeName = attribute.getName();
System.out.println("found attribute '" + attributeName + "' with value '" + attribute.getStringValue() + "'");
}
}
lc.disconnect();
return userInGroup;
}
** EDIT **
Implemented answer from EJP, changed searchBase to include group
Code that works:
private static final String admin_username = "foo";
private static final String[] hosts = new String[]{"foohost.net"};
public boolean isUserInGroup(String username, String group){
boolean userInGroup = false;
String loginDN = "uid=" + admin_username + "," + "cn=users,dc=ldap,dc=net";
String searchBase = "cn=" + group + "," + "cn=groups,dc=ldap,dc=net";
int searchScope = LDAPConnection.SCOPE_SUB;
searchFilter = "(&(objectclass=groupOfUniqueNames)(uniquemember=uid="+ username + ",cn=users,dc=ldap,dc=net))";
//Connect
LDAPConnection lc = connect(hosts);
lc.bind(LDAPConnection.LDAP_V3, loginDN, admin_password.getBytes("UTF8"));
lc.getAuthenticationDN();
LDAPSearchResults searchResults = lc.search(searchBase,
searchScope,
searchFilter,
null, // return all attributes
false); // return attrs and values
while (searchResults.hasMore()) {
LDAPEntry nextEntry = null;
try {
nextEntry = searchResults.next();
} catch (LDAPException e) {
// Exception is thrown, go for next entry
if (e.getResultCode() == LDAPException.LDAP_TIMEOUT || e.getResultCode() == LDAPException.CONNECT_ERROR)
break;
else
continue;
}
//A result was found, therefore the user is in the group
userInGroup = true;
}
lc.disconnect();
return userInGroup;
}
What is the right syntax for a ldap search filter to determine if a specific user is in a specific group(in Tivoli Access Manager)?
Either of the filters you used, but the objectClass to search on is groupofUniqueNames (plural).
What should I check on the returned LDAPEntry object given by that search string to see that the user is, or isn't, in the group?
Nothing. He will be, otherwise the group won't be returned in the search. All you need to do is check that the search result is non-empty.
Here's a few searchfilters I've tried that don't work (aka searchResults.next() throws an error):
Throws what error?
(&(objectclass=groupOfUniqueName)(uniquemember=uid="+ username + ",cn=groups,dc=ldap,dc=net))
Nothing wrong with this except for groupOfUniqueName. You should use search filter arguments like {0} rather than building them into the search string.
(&(objectclass=groupOfUniqueName)(uniquemember=uid="+ username + ",cn=users,dc=ldap,dc=net))
This one will search the cn=users subtree for a group. It won't work unless you have groups under cn=users, which doesn't seem likely.
(uniquemember=uid="+ username + ",cn=users,dc=ldap,dc=net)
This will select non-groups. You don't want that: you need the objectClass part.

Not able to fetch all data from facebook access token in java servlet

I am trying to fetch fb user's "friend list" and his/her "about" but when i do i am getting null value of certain field like i comment below.
System.out.println(loginUser.getId()); //show id
System.out.println(loginUser.getName()); //Show Name
System.out.println(loginUser.getFirstName()); //show null
System.out.println(loginUser.getGender()); //show null
System.out.println(loginUser.getAbout()); //show null
I've been trying the graph-api explorer to see what I'm getting for gender
Its shows here
Code:
String code = request.getParameter("code");
String URLEncodedRedirectURI = URLEncoder.encode("http://localhost:8080/bitspedia-fetchfbfriends/FriendsListServlet");
String MY_ACCESS_TOKEN = "";
String authURL = "https://graph.facebook.com/oauth/access_token?" +
"client_id=" + FriendsListServlet.APP_ID + "&" +
"redirect_uri=" + URLEncodedRedirectURI + "&" +
"client_secret=" + FriendsListServlet.APP_SECRET + "&" +
"code=" + code;
URL url = new URL(authURL);
String result = readURL(url);
String[] pairs = result.split("&");
for (String pair : pairs) {
String[] kv = pair.split("=");
if (kv[0].equals("access_token")) {
MY_ACCESS_TOKEN = kv[1];
}
}
FacebookClient facebookClient = new DefaultFacebookClient(MY_ACCESS_TOKEN, FriendsListServlet.APP_SECRET);
Connection<User> friends = null;
try {
User loginUser = facebookClient.fetchObject("me", User.class);
request.setAttribute("loginUser", loginUser);
friends = facebookClient.fetchConnection("/me/friends", User.class);
System.out.println(loginUser.getId()); //shows id
System.out.println(loginUser.getName()); //Shows name
System.out.println(loginUser.getFirstName()); //shows null
System.out.println(loginUser.getWebsite()); //shows null
System.out.println(loginUser.getAbout()); //shows null
} catch (FacebookException e) {
e.printStackTrace();
}
List<User> friendsList = friends.getData();
It has very small issue, you didn't provide parameter of null showing value so doing small changes it works fine.
User loginUser = facebookClient.fetchObject("me", `Parameter.with("fields","first_name,last_name,posts")););`

Java code to fetch the twitter followers of any user using twitter screen name

I tried to get the twitter followers using the screen name. But i am able to get only my followers screen names where as i am expecting the followers of my followers. But i didn't found any supported method for this.
My code is as follows.
TwitterFactory factory = new TwitterFactory();
Twitter twitter = factory.getInstance();
twitter.setOAuthConsumer(consumerKey, consumerSecret);
AccessToken accessToken = new AccessToken(twitterToken, twitterSecret);
twitter.setOAuthAccessToken(accessToken);
String twitterScreenName = twitter.getScreenName();
IDs followerIDs = twitter.getFollowersIDs(twitterScreenName, -1);
long[] ids = followerIDs.getIDs();
for (long id : ids) {
twitter4j.User user = twitter.showUser(id);
//here i am trying to fetch the followers of each id
System.out.println("Name: " + user.getScreenName());
System.out.println("Location:" + user.getLocation());
}
Can anyone please help me in this.
You will need to do the nesting over here. You are just getting the list of current users followers. But you need to get the list of followers of your followers.
Sample code is as below:
TwitterFactory factory = new TwitterFactory();
Twitter twitter = factory.getInstance();
String twitterScreenName;
try {
twitterScreenName = twitter.getScreenName();
IDs followerIDs = twitter.getFollowersIDs(twitterScreenName, -1);
long[] ids = followerIDs.getIDs();
for (long id : ids) {
twitter4j.User user = twitter.showUser(id);
//here i am trying to fetch the followers of each id
String userScreenName = user.getScreenName();
System.out.println("Name: " + user.getScreenName());
System.out.println("Location:" + user.getLocation());
IDs followerIDsOfFollowers = twitter.getFollowersIDs(user.getScreenName(), -1);
long[]fofIDs = followerIDsOfFollowers.getIDs();
for(long subId : fofIDs) {
twitter4j.User user1 = twitter.showUser(subId);
System.out.println("Follower Master:" + userScreenName +" Follower of Follower Name: " + user1.getScreenName());
System.out.println("Location:" + user1.getLocation());
}

Categories

Resources