Fetch contacts from google contact api java - java

I am able to get access token for google contact API. Now I am not able to figure out how to use that token to fetch contacts. The method available in Google Contact API documentation does not involve access token. Also I don't know how to call that method in Java.
If Anyone can help me with that, it will be highly appreciable.
ContactsService service = new ContactsService("Test");
service.setHeader("Authorization", "Bearer " + access_token);
URL feedUrl = new URL("google.com/m8/feeds/contacts/default/full");
ContactFeed resultFeed = service.getFeed(feedUrl, ContactFeed.class);
System.out.println(resultFeed.getTitle().getPlainText());
This is how I am trying to fetch contacts but I am getting:
com.google.gdata.util.ParseException: Feature: xml.org/sax/features/external-general-entities

Related

Google authentication from server

I am need to upload video to youtube to specific youtube account. So I need to authenticate I am using java google lib. Code looks like this:
Credential credential = new GoogleCredential.Builder()
.setTransport(new ApacheHttpTransport())
.setJsonFactory(new JacksonFactory())
.setServiceAccountId("xxx#xx-app.iam.gserviceaccount.com")
.setClientSecrets("xx#gmail.com", "xx")
.setServiceAccountPrivateKeyFromP12File(new File("xx.p12"))
.setServiceAccountScopes(scopes)
.setServiceAccountUser("xx#gmail.com")
.build();
youtube = new YouTube.Builder(credential.getTransport(), credential.getJsonFactory(), credential).setApplicationName(
"tellews-app").build();
Video returnedVideo = videoInsert.execute();
YouTube.Videos.Insert videoInsert = youtube.videos()
.insert("snippet,statistics,status", videoObjectDefiningMetadata, mediaContent);
Video returnedVideo = videoInsert.execute();
And getting error:
IOException: 401 Unauthorized
{
"error" : "unauthorized_client",
"error_description" : "Client is unauthorized to retrieve access tokens using this method."
}
Maybe someone sees what I am doing wrong
Simple.
Do not use a Service Account - that's not what they're there for.
You need to obtain an Access Token for the target YouTube account. The simples way to do that is to get yourself a Refresh Token for that account from the Oauth Playground, and use it to fetch an Access Token whenever you need one. The steps to do this are enumerated at How do I authorise an app (web or installed) without user intervention? (canonical ?) . In the comments there is a link to a YouTube video which also explains the steps.

jInstagram - How to establish connection?

I want to build an app in Java based on live showing certain photos of Instagram tagged with a particular hashtag. I'm currently trying to use jInstagram, but I can't understand the flow of the API Instagram. It's not like the Twitter API. Instagram API seems to call for a server in the middle of my app and their servers, while Twitter API gave me access to the gardenhose without a lot of work. And, overall, thanks to the nice samples on Twitter4J.org
I'd be grateful if somebody can help me to start with. I just want to get live photos with certain hashtag of Instagram but I don't know if I'd should set up a server or where they give me an access token.
First you need to register your app to instagram's website and get your apiKey and apiSecret. Then you can choose a callback URL and a scope.
InstagramService service = new InstagramAuthService()
.apiKey("e607b7XXXce54e729bXXXXf40162")
.apiSecret("651cXXX2ab348a3XXXXa7ae90c6d")
.callback("http://www.cagdasalagoz.com")
.scope("basic public_content likes comments follower_list relationships")
.build();
After this, you can get the authorization like this.
String authorizationUrl = service.getAuthorizationUrl();
System.out.println(authorizationUrl); //paste in browser
Scanner sc = new Scanner(System.in);
System.out.println("Paste the code gotten in the browser (at the end of the URL): ");
String verCode = sc.nextLine(); //SCAN VERIFIER CODE
Verifier verifier = new Verifier(verCode);
Token accessToken = service.getAccessToken(verifier); //Token successfully gotten
//** RUNS OK UP TO THIS LINE INCLUDED **//
Instagram instagram = new Instagram(accessToken); //Ok
About getting the posts by a tag can be achived by this method I guess.
String tag="seaside";
instagram.getRecentMediaFeedTags(tag);
You can learn more about jInstagram from this page.

'AuthSub token has wrong scope' when trying to retrieve google spreadsheet

My code is: (sensitive info removed)
SpreadsheetService service = new SpreadsheetService("MySpreadsheetIntegration-v1");
// service.setUserCredentials(<email>, <pw>);
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey("xxx.yyy.no");
oauthParameters.setOAuthConsumerSecret("XXX");
oauthParameters.setOAuthToken("YYYY");
oauthParameters.setOAuthTokenSecret("ZZZZ");
oauthParameters.setScope("https://docs.google.com/feeds/ https://docs.googleusercontent.com/ https://spreadsheets.google.com/feeds/");
service.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer());
// Define the URL to request. This should never change.
URL SPREADSHEET_FEED_URL = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
// Make a request to the API and get all spreadsheets.
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
// Iterate through all of the spreadsheets returned
for (SpreadsheetEntry spreadsheet : spreadsheets) {
// Print the title of this spreadsheet to the screen
System.out.println(spreadsheet.getTitle().getPlainText());
}
Issue:
WARNING: Authentication error: Unable to respond to any of these challenges: {authsub=WWW-Authenticate: AuthSub realm="https://www.google.com/accounts//AuthSubRequest"}
and
com.google.gdata.util.AuthenticationException: Token invalid - AuthSub token has wrong scope
I tried clientLogin method (setUserCredentials(, )) and that works fine.
I also know my OAuthConsumerKey, OAuthConsumerSecret, OAuthToken and OAuthTokenSecret work, cos I access a different feed using them (picasa)
I have tried setting different combinations of the above 3 scopes, but no luck.
I have seen this and this, but again, no luck.
Any help would be greatly appreciated.
Take a look at this answer.
Try to delete the following directory:
$HOME/.credentials
After what run the program again, it's gonna make a callback and ask you to grant permissions for your application in Google Console and now it's gonna work properly.

Signing in via Twitter OAuth doesn't remember authorization

I am writing a web application and have just implemented that a user can sign in via Twitter, using spring-social-(core/twitter).
However, Twitter behaves strangely. After the initial authentication/authorization, every time I'm sending a user to Twitter for authentication, Twitter prompts to authorize my application again. I've looked into the connected Twitter profile. My app is there and authorized correctly (in my case for read access).
I don't have a case of requesting additional permissions. All my application needs is read access (the authorization dialog confirms this).
I am using the OAuth1Operations (returned by the TwitterConnectionFactory) to do the OAuth dance and save the resulting connection in a database. My front-end is written with Wicket 1.5.
I can work around this behavior by just re-authorizing my app again and again when I want to sign in via Twitter, but this is a big nuisance. Anyone knows what I'm missing here?
Here is my code:
TwitterConnectionFactory connectionFactory = (TwitterConnectionFactory) connectionFactoryLocator.getConnectionFactory(Twitter.class);
String callbackUrl = [...];
if (pageParameters.get("oauth_token").isNull() || pageParameters.get("oauth_verifier").isNull()) {
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("x_auth_access_type", "read");
OAuthToken token = connectionFactory.getOAuthOperations().fetchRequestToken(callbackUrl, params);
String url = connectionFactory.getOAuthOperations().buildAuthorizeUrl(token.getValue(), OAuth1Parameters.NONE);
getSession().setAttribute("twitter_token", token);
setResponsePage(new RedirectPage(url));
} else {
String token = pageParameters.get("oauth_token").toString();
String verifier = pageParameters.get("oauth_verifier").toString();
OAuthToken previousToken = (OAuthToken) getSession().getAttribute("twitter_token");
if (previousToken.getValue().equals(token)) {
AuthorizedRequestToken authorizedRequestToken = new AuthorizedRequestToken(previousToken, verifier);
OAuthToken accessToken = connectionFactory.getOAuthOperations().exchangeForAccessToken(authorizedRequestToken, null);
Connection<Twitter> connection = connectionFactory.createConnection(accessToken);
}
}
I've found the solution! It is also detailed here: Simple Twitter Oauth authorization asking for credentials every time
The problem was that I specifically requested Twitter to authorize my app every time. Replacing:
String url = connectionFactory.getOAuthOperations().buildAuthorizeUrl(token.getValue(), OAuth1Parameters.NONE);
with
String url = connectionFactory.getOAuthOperations().buildAuthenticateUrl(token.getValue(), OAuth1Parameters.NONE);
solves the issue!
Calling the URL for authentication does only ask for authorization if the app hasn't been authorized yet.

Invalid parameter exception on client.auth_getSession() in Facebook java API

I want to connect to a my facebook application using the facebook java api 2.1.1(http://code.google.com/p/facebook-java-api/). My application is in "Desktop" mode so I should be able to access it outside of a web application. I have not defined any callback url for it as well. My code looks something like this.
FacebookJsonRestClient client = new FacebookJsonRestClient( FB_APP_API_KEY, FB_APP_SECRET );
String token = client.auth_createToken();
HttpClient http = new HttpClient();
http.setParams(new HttpClientParams());
http.setState(new HttpState());
final String LOGIN = "https://login.facebook.com/login.php";
GetMethod get = new GetMethod(LOGIN + "?api_key=" + FB_APP_API_KEY + "&v=1.0&auth_token=" + token );
http.executeMethod(get);
PostMethod post = new PostMethod(LOGIN);
post.addParameter(new NameValuePair("api_key", FB_APP_API_KEY));
post.addParameter(new NameValuePair("v", "1.0"));
post.addParameter(new NameValuePair("auth_token", token));
post.addParameter(new NameValuePair("email", "my-email"));
post.addParameter(new NameValuePair("pass", "my-password"));
http.executeMethod(post);
String session = client.auth_getSession(token);
However instead of returning the session the API throws an exception:
com.google.code.facebookapi.FacebookException: Invalid parameter
at com.google.code.facebookapi.FacebookJsonRestClient.parseCallResult(FacebookJsonRestClient.java:354)
at com.google.code.facebookapi.ExtensibleClient.callMethod(ExtensibleClient.java:535)
at com.google.code.facebookapi.ExtensibleClient.callMethod(ExtensibleClient.java:472)
at com.google.code.facebookapi.FacebookJsonRestClient.auth_getSession(FacebookJsonRestClient.java:278)
Can anyone please tell me whats wrong with this code? And what is the correct way to access a facebook application in desktop mode using the java api (v. 2.1.1).
Thanks for your help.
Regards
Nabeel Mukhtar
As far as I understand FB's API, you're not supposed to provide username and password manually but instead let the user input them manually and then allow the Facebook Login to redirect the user back to your application. This means that instead of providing "email" and "pass" you provide "next" and "cancel" URL:s instead.
This is purely a security feature of FB API and while the theory behind it is alright, the execution is far from optimal.
See this discussion thread on the Google Code site. There's a link in the that thread to a wiki page which explains how to do desktop auth.

Categories