Java Read Facebook Wall - java

I'm building a web portal by using Java; besides other requirements, I'm struggling my mind one one very simple (at least at first view) requirement:
my customer wants on his portal the first N posts of his facebook wall
and he wants to read the first N tweets of his twitter page
Since my java code is based on Spring, I wanted to use spring social, spring social twitter and spring social facebook in order to satisfy the requirement
With twitter I had no problem; in fact I
created an app on twitter
got twitter app id and app secret
prepared code
In a couple of hours, all worked pretty good
Problems were born with facebook and it's a lot of time I'm fighting with it
I passed from spring social to facebook4j (since this last one seems to me stronger).
I did the following
created an app on FB
got the facebook appId and appSecret
told to the code that I need the read_stream permission
prepared the code
But I'm not able in reading posts from my wall
Is there anyone who was able in satisfying this kind of scenario?
here my facebook4j code
private static final Logger log = LoggerFactory.getLogger(FacebookTest.class.getName());
public static void main (String[] a)
{
try
{
ConfigurationBuilder cfgBui = new ConfigurationBuilder();
cfgBui.setDebugEnabled(true);
cfgBui.setOAuthAppId(myAppId);
cfgBui.setOAuthAppSecret(myAppSecret);
cfgBui.setUseSSL(true);
Configuration cfg = cfgBui.build();
FacebookFactory ff = new FacebookFactory(cfg);
OAuthSupport support = new OAuthAuthorization(cfg);
support.setOAuthPermissions("read_stream");
AccessToken appAccessToken = support.getOAuthAppAccessToken();
Facebook face = ff.getInstance(appAccessToken );
ResponseList<Post> posts = face.searchPosts("test");
for (Post post : posts)
{
System.out.println(post.getId());
}
} catch (Exception e)
{
log.error("Errore", e);
}
}
As far as I understood, I should need the user access token, but I don't know how to generate it; should I create a login flow and show to the user the FB login dialog? If so, why should I create app id and app secret? They have no sense in my scenario
Moreover...in my case...the server side should authenticate on FB and read posts from a well know user wall (the wall of my customer...) so....where should I present the login dialog? where should I redirect after the FB login?
Is there any good man :) who can clarify to me the FB read post flow?

You MUST use one of the possibilities to authorize the user (with read_stream) in order to get access to his stream. Here´s the link to all the possibilities: https://developers.facebook.com/docs/facebook-login/v2.2
You can also generate Access Tokens with the Graph API Explorer: https://developers.facebook.com/tools/explorer/
Detailed information about Access Tokens and how to generate them can be found in the following links:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
Keep in mind that an Extended User Token only lasts for 60 days, after that your customer would have to refresh it manually. In general, you are not allowed to use User Profiles for commercial reasons, and it´s very unusual to show a User stream on a website.
Better: Use a Facebook Page. /page-id/feed with an Extended Page Token that lasts forever.

If you use spring-social-facebook, you could let the user login via (front-end login flow) and then you can access the users wall. However, user would need to login and authorize your app to perform the operations.
Here is a spring social sample project that demo's how spring-social-facebook login is done https://github.com/spring-projects/spring-social-samples
Also, within your java code you can use feedoperations to gather information about home feed and also query against it. Checkout the documentation.
facebook.feedOperations().

Related

Spotify logout on android

i have this code to log in to spotify in my app. I using the offical spotify lib.
public void spotifyLoginBtnClicked(View v){
//start the authentication for spotify
AuthenticationRequest.Builder builder = new AuthenticationRequest.Builder(clientID, AuthenticationResponse.Type.TOKEN, redirectURI);
builder.setScopes(new String[]{"user-read-private", "streaming"});
AuthenticationRequest request = builder.build();
// open LoginActivity
AuthenticationClient.openLoginActivity(this, activityIdentification, request);
}
Im wondering now how i can create a logout button. Because once logged in, if i press the login button again, it just returns. So i'am unable to change the user. I havent found anything in the java doc.
I just found this document which looks similar to the code you pasted for logging in.
In there it mentions a few methods for logging the user out but I think the main block of code you will need is:
To log out and clear all stored tokens, use the AuthenticationClient#clearCookies method. Both Spotify and Facebook tokens will be removed.
I would go and check that article I linked above as there is edge cases that might be important for your project.
Happy Coding!

How to make more friendly Facebook application which automatically get access token for user?

I am working on Facebook application using facebook4j API, and it requires access token each time. I want to make this application more friendly with user, and get access token in automatically way.
So user will not have to go graph API explorer,and get access token from there each time. Also I want solution with Java only, no additional programming languages.
import facebook4j.Facebook;
import facebook4j.FacebookFactory;
import facebook4j.auth.AccessToken;
public class Test {
public static void main(String[] args) {
Facebook facebook = new FacebookFactory().getInstance();
facebook.setOAuthAppId("*****", "***********");
facebook.setOAuthPermissions("user_friends,user_groups,user_photos,user_videos,user_birthday,user_status,user_likes,user_activities,user_location");
facebook.setOAuthAccessToken(new AccessToken("*******", null));
//do something
}
}
You have to use the login dialog as explained at https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.3
After you get the access token, You can store it somewhere for accessing Facebook API later on. It's not a one-time token. It might be expired or revoked though. It can be stored in a session for web app or in memory for desktop app. In your case, you probably want to store it in your database and associate it to user's id. More details can be found here: https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.3#token

How to use the twitter4j library?

I was overwhelmed by the amount of information on https://dev.twitter.com/docs and then I went to twitter4j and downloaded the library. I got a consumer key and secret by registering on their website. What are these for?
What I am trying to is get tweet text from certain twitter account( not my personal one but public one) and other information( account user, time and other stuff).
I couldn't find useful tutorial online. So please help me. Thank you very much!
The keys are so that your application can authenticate to the Twitter API. I put them in a properties file and made them available on the classpath. Once your application has authenticated, you will be able to use the API to get the account information you need. I don't know any good tutorials, but you could use an open source project I wrote as a reference if you like: https://github.com/rossh/gift-findr.
This is an example of how to get hold of a org.twitter4j.Twitter object. Once you have that, you can do a great many operations - just inspect the interface for org.twitter4j.Twitter.
Twitter twitter = new TwitterFactory().getInstance(twitter4JConfiguration);
twitter.setOAuthConsumer(consumerKey, consumerSecret);
twitter.setOAuthAccessToken(new AccessToken(oauthToken, oauthTokenSecret));
String screenName = twitter.getScreenName(); // Returns authenticating user's screen name.
User stephenfry = twitter.showUser("stephenfry"); // Returns extended information of a given user ...
List<User> friends = twitter.getFriendsList("stephenfry", -1L); // Returns a cursored collection of user objects ...
This is a link to the javadoc for the org.twitter4j.Twitter interface

java :direct gmail url

I am completely new to this site. I was searching for an answer for my problem. But I saw the same problem asked by someone in this website. The question is here
I am using windows 7. I didn't not get answer there in that link..so I am asking the same question again. I want to open a gmail account link in a browser from a java application. Yes I do know about browse() method in Desktop class. The thing is that I can open the gmail website but I need to open directly the specified gmail account while username and password are provided. Any ideas?
Okay, so take this with a couple of caveats: 1. the last time I played with Google APIs was in an older version, so this may be quite different now, 2. this code isn't tested, I'm just writing it up partially from memory and partially from an old project of mine. Think of it more like pseudo-code, and 3. if this does by chance work, this is a pretty dirty solution. Hopefully this can set you on the track of finding a better way to do this with the API.
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey( [insert consumer key here] );
oauthParameters.setOAuthConsumerSecret( [insert consumer secret here] );
OAuthSigner signer = new OAuthHmacSha1Signer();
GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(signer);
oauthParameters.setScope("https://mail.google.com/mail"); //no clue if this is a valid scope or not
oauthHelper.getUnauthorizedRequestToken(oauthParameters);
String requestUrl = oauthHelper.createUserAuthorizationUrl(oauthParameters);
Desktop desktop = Desktop.getDesktop();
URI url;
url = new URI(requestUrl);
//this will make the user log in to authorize your app
desktop.browse(url);
//auth token response from Google, you can use this to authenticate your app if there are other requests you want to make against the user account
String token = oauthHelper.getAccessToken(oauthParameters);
//since you made sure the user is logged into their account to authorize your app, their gmail can now just be opened. Yes, very dirty. I know. (if it all works)
desktop.browse("https://www.gmail.com/");

TwitterException {statusCode=403, retryAfter=0, rateLimitStatus=null}

I have recently noticed that I keep getting a 403 error while doing twitter search. My application was working until couple of days back when i noticed the error.
I checked with Twitter & they say my IP is not blocked, I am also within the rate limit = about 60 search requests/per hour.
Here's how i was initializing the Twitter object -
private static Twitter TWITTER_CLIENT = new TwitterFactory().getInstance();
After i noticed the error, i tried the following & still no success -
private static Twitter TWITTER_CLIENT = new TwitterFactory().getInstance("user", "password");
Here's how i am searching -
TWITTER_CLIENT.search(new Query("#keyword1 OR #keyword2"));
I tried this URL (curl http://search.twitter.com/search.json?q=ipad) from my server & it works alright.
Following is the exception. I am on java6 + Twitter4j v2.1.2. Would really appreciate any help. Thanks.
TwitterException{statusCode=403, retryAfter=0, rateLimitStatus=null}
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:301)
at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:68)
at twitter4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:82)
at twitter4j.Twitter.search(Twitter.java:193)
Most likely the reason is basic auth shutdown by Twitter (aka OAuthcalypse):
Basic Auth Shutdown
You need to switch to using OAuth.
Recently i got the same error while executing similar code.
To fix it, please go to
https://apps.twitter.com/app/your_app_id
Click on Keys and access token
In Access Level, click modify app permission and choose the 3rd option: Read, Write and Access direct messages
Click on update. ( Note: you might have to add your mobile no and verify with otp to get this access if you dont have your no added in twitter)
Regenerate both Consumer key & secretand Access token & secret using the clickable button
Us e the new keys in your program
And you are done! Your program will start working.

Categories