How to display response.getBody() in jsp page using scribe - java

Here I want to get all contacts mail id of a person.
This code is redirecting to google site and after getting token and varifier it is returning status code and body which is printing on console.
I want to display response.getBody()(all maial contacts of a person) in jsp page.
How to do this?
public class googleOaoth extends ActionSupport {
private static final String NETWORK_NAME = "Google";
private static final String AUTHORIZE_URL = "https://www.google.com/accounts/OAuthAuthorizeToken?oauth_token=";
private static final String PROTECTED_RESOURCE_URL = "https://www.google.com/m8/feeds/contacts/default/full";
private static final String SCOPE = "https://www.google.com/m8/feeds";
OAuthService service = new ServiceBuilder().provider(GoogleApi.class).apiKey("www.mysite").apiSecret("****").scope(SCOPE).callback("http://mysite/mypage").build();
Token requestToken;
private String url;
private String oauth_verifier;
private String oauth_token;
public String getOauth_verifier() {
return oauth_verifier;
}
public Token getRequestToken() {
return requestToken;
}
public void setRequestToken(Token requestToken) {
this.requestToken = requestToken;
}
public void setOauth_verifier(String oauth_verifier) {
this.oauth_verifier = oauth_verifier;
}
Map session = ActionContext.getContext().getSession();
//method which redirect to google page
public String LoginToGoogle() {
System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ===");
System.out.println();
// Obtain the Request Token
System.out.println("Fetching the Request Token...");
setRequestToken(service.getRequestToken());
System.out.println("Got the Request Token!");
System.out.println("(if your curious it looks like this: " + getRequestToken() + " )");
System.out.println();
session.put("googleAccessToken", getRequestToken());
System.out.println("Now go and authorize Scribe here:");
setUrl(AUTHORIZE_URL + getRequestToken().getToken());
System.out.println(AUTHORIZE_URL + getRequestToken().getToken());
return "redirect";
}
//after getting varification code this method will show body and res_code
public String acceptToken() {
System.out.println("And paste the verifier here");
System.out.print(">>");
Verifier verifier = new Verifier(getOauth_verifier());
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
//System.out.println("varifier : " + getOauth_verifier());
// System.out.println("token :" + getOauth_token());
//requestToken = service.getRequestToken();
setRequestToken((Token) session.get("googleAccessToken"));
System.out.println("token " + getRequestToken());
Token accessToken = service.getAccessToken(getRequestToken(), verifier);//requestToken
System.out.println("Got the Access Token!");
System.out.println("(if your curious it looks like this: " + accessToken + " )");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
request.addHeader("GData-Version", "3.0");
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getCode());
System.out.println(response.getBody());
System.out.println();
System.out.println("Thats it man! Go and build something awesome with Scribe! :)");
return SUCCESS;
}

Inside your action method create variable (e.g. respBody) with public getters/setters and assign response body to it.
respBody = response.getBody();
Then in JSP you can show it using <s:property> tag.
<s:property value="respBody"/>

Related

Magento 1.9 REST API Scribe-Java Request Token Failed

Trying to connect Magento 1.9 using REST API and Scribe-Java 1.3.7
Done creating Web Services Role and Consumer as below:
After that, run the following codes:
public final class MagentoThreeLeggedOAuth extends DefaultApi10a {
private static final String BASE_URL = "http://my.magentoshop.com/";
#Override
public String getAccessTokenEndpoint() {
return BASE_URL + "oauth/token";
}
#Override
public String getAuthorizationUrl(Token requestToken) {
return BASE_URL + "admin/oauth_authorize?oauth_token="
+ requestToken.getToken(); //this implementation is for admin roles only...
}
#Override
public String getRequestTokenEndpoint() {
return BASE_URL + "oauth/token";
}
public static class Main {
public static void main(String[] args) {
final String MAGENTO_API_KEY = "[xxxxxxxxx]";
final String MAGENTO_API_SECRET = "[yyyyyyyyyy]";
final String MAGENTO_REST_API_URL = "http://my.magentoshop.com/api/rest";
// three-legged oauth
OAuthService service = new ServiceBuilder()
.provider(MagentoThreeLeggedOAuth.class)
.apiKey(MAGENTO_API_KEY).apiSecret(MAGENTO_API_SECRET).debug()
.build();
// start
Scanner in = new Scanner(System.in);
System.out.println("Magento's OAuth Workflow");
System.out.println();
// Obtain the Request Token
System.out.println("Fetching the Request Token...");
Token requestToken = service.getRequestToken();
System.out.println("Got the Request Token!");
System.out.println();
// Obtain the Authorization URL
System.out.println("Fetching the Authorization URL...");
String authorizationUrl = service.getAuthorizationUrl(requestToken);
System.out.println("Got the Authorization URL!");
System.out.println("Now go and authorize Main here:");
System.out.println(authorizationUrl);
System.out.println("And paste the authorization code here");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
}
}
}
and below are the errors shown on console:
Magento's OAuth Workflow
Fetching the Request Token...
obtaining request token from http://my.magentoshop.com/oauth/token
setting oauth_callback to oob
generating signature...
using base64 encoder: CommonsCodec
base string is: POST&http%3A%2F%2Fmy.magentosgop.com%2Foauth%2Ftoken&oauth_callback%3Doob%26oauth_consumer_key%3Dxxxxxxxxxxxxxxxx%26oauth_nonce%3D2939370741%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1429517137%26oauth_version%3D1.0
signature is: nINxAFwv6woAAQYbdHn6v2Uc+lw=
appended additional OAuth parameters: { oauth_nonce -> 2939370741 , oauth_signature -> nINxAFwv6woAAQYbdHn6v2Uc+lw= , oauth_callback -> oob , oauth_consumer_key -> 20482d9e12ead3420a4c5aeb6978bf8e , oauth_timestamp -> 1429517137 , oauth_signature_method -> HMAC-SHA1 , oauth_version -> 1.0 }
using Http Header signature
sending request...
response status code: 400
response body: oauth_problem=parameter_absent&oauth_parameters_absent=oauth_token
Exception in thread "main" org.scribe.exceptions.OAuthException: Response body is incorrect. Can't extract token and secret from this: 'oauth_problem=parameter_absent&oauth_parameters_absent=oauth_token'
at org.scribe.extractors.TokenExtractorImpl.extract(TokenExtractorImpl.java:41)
at org.scribe.extractors.TokenExtractorImpl.extract(TokenExtractorImpl.java:27)
at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:64)
at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:40)
at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:45)
at MagentoThreeLeggedOAuth$Main.main(MagentoThreeLeggedOAuth.java:49)
What did I missed or wrongly done?
Thanks
OK, just found out the mistakes was:
Change this:
#Override
public String getRequestTokenEndpoint() {
return BASE_URL + "oauth/token";
}
To this:
#Override
public String getRequestTokenEndpoint() {
return BASE_URL + "oauth/initiate";
}

Aweber Java Api

My goal is to create an aweber app that adds users to an email list I already have.
I currently have code that uses Oauth to get a token but this method also requires an aweber account users
to manually write their credentials in order to grant the app access. I would only ever be using my aweber 'app'
for my own purposes and I want to automate the process of authentication. Look for the comment "//going to the url manually here".
Thanks in advance for the help.
package aweber.test;
import java.util.Scanner;
import org.scribe.builder.ServiceBuilder;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
impo rt org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
public class AweberStuffTest
{
//To get your consumer key/secret, and view API docs, see https://labs.aweber.com/docs
private static final String ACCOUNT_RESOURCE_URL = "https://api.aweber.com/1.0/accounts/";
private static final String CONSUMER_KEY = "AkW******8QO0dMmmF";
private static final String CONSUMER_SECRET = "zfgmPsZkXBam6R***********YD";
public static void main(String[] args)
{
OAuthService service = new ServiceBuilder()
.provider(AWeberApi.class)
.apiKey(CONSUMER_KEY)
.apiSecret(CONSUMER_SECRET)
.build();
Scanner in = new Scanner(System.in);
System.out.println("=== AWeber's OAuth Workflow ===");
System.out.println();
// Obtain the Request Token
System.out.println("Fetching the Request Token...");
Token requestToken = service.getRequestToken();
System.out.println("Got the Request Token!");
System.out.println();
System.out.println("Now go and authorize Scribe here:");
String foo = service.getAuthorizationUrl(requestToken);
System.out.println(foo);
//going to the url manually here
System.out.println("And paste the verifier here");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
Token accessToken = service.getAccessToken(requestToken, verifier);
System.out.println("Got the Access Token!");
System.out.println("(if your curious it looks like this: " + accessToken + " )");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(Verb.GET, ACCOUNT_RESOURCE_URL);
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getBody());
System.out.println();
System.out.println("Thats it man! Go and build something awesome with AWeber and Scribe! :)");
}
}
and
package aweber.test;
import org.scribe.builder.api.DefaultApi10a;
import org.scribe.model.Token;
public class AWeberApi extends DefaultApi10a
{
private static final String AUTHORIZE_URL = "https://auth.aweber.com/1.0/oauth/authorize?oauth_token=%s";
private static final String REQUEST_TOKEN_ENDPOINT = "https://auth.aweber.com/1.0/oauth/request_token";
private static final String ACCESS_TOKEN_ENDPOINT = "https://auth.aweber.com/1.0/oauth/access_token";
#Override
public String getAccessTokenEndpoint()
{
return ACCESS_TOKEN_ENDPOINT;
}
#Override
public String getRequestTokenEndpoint()
{
return REQUEST_TOKEN_ENDPOINT;
}
#Override
public String getAuthorizationUrl(Token requestToken)
{
return String.format(AUTHORIZE_URL, requestToken.getToken());
}
}

Invalid grant_type parameter or parameter missing on Box OAuth2 API with scribe library

I'm trying to write a simple Jenkins plug-in with integration with Box, but I always get this error:
=== Box's OAuth Workflow ===
Fetching the Authorization URL...
Got the Authorization URL!
Now go and authorize Scribe here:
https://www.box.com/api/oauth2/authorize?client_id=abc123&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fjenkins%2Fconfigure&response_type=code&state=authenticated
And paste the authorization code here
>>xyz9876543
Trading the Request Token for an Access Token...
Exception in thread "main" org.scribe.exceptions.OAuthException: Cannot extract an acces token. Response was: {"error":"invalid_request","error_description":"Invalid grant_type parameter or parameter missing"}
at org.scribe.extractors.JsonTokenExtractor.extract(JsonTokenExtractor.java:23)
at org.scribe.oauth.OAuth20ServiceImpl.getAccessToken(OAuth20ServiceImpl.java:37)
at com.example.box.oauth2.Box2.main(Box2.java:40)
Box2 class (for testing) :
public class Box2 {
private static final Token EMPTY_TOKEN = null;
public static void main(String[] args) {
// Replace these with your own api key and secret
String apiKey = "abc123";
String apiSecret = "xyz987";
OAuthService service = new ServiceBuilder().provider(BoxApi.class)
.apiKey(apiKey).apiSecret(apiSecret)
.callback("http://localhost:8080/jenkins/configure")
.build();
Scanner in = new Scanner(System.in);
System.out.println("=== Box's OAuth Workflow ===");
System.out.println();
// Obtain the Authorization URL
System.out.println("Fetching the Authorization URL...");
String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN);
System.out.println("Got the Authorization URL!");
System.out.println("Now go and authorize Scribe here:");
System.out.println(authorizationUrl);
System.out.println("And paste the authorization code here");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);
System.out.println("Got the Access Token!");
System.out.println("(if your curious it looks like this: "
+ accessToken + " )");
System.out.println();
}
}
BoxApi class:
public class BoxApi extends DefaultApi20 {
private static final String AUTHORIZATION_URL =
"https://www.box.com/api/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code&state=authenticated";
#Override
public String getAccessTokenEndpoint() {
return "https://www.box.com/api/oauth2/token?grant_type=authorization_code";
}
#Override
public String getAuthorizationUrl(OAuthConfig config) {
return String.format(AUTHORIZATION_URL, config.getApiKey(),
OAuthEncoder.encode(config.getCallback()));
}
#Override
public Verb getAccessTokenVerb(){
return Verb.POST;
}
#Override
public AccessTokenExtractor getAccessTokenExtractor() {
return new JsonTokenExtractor();
}
}
I'm not sure how I get these exceptions. Can anyone who knows the Box API tell me if I've done anything wrong with it?
The request for the access token needs to be in the form of a POST request, with the parameters included in the body of the request–it looks like you're sending a GET with the parameters as URL parameters.

RestFB: Using a facebook app to get the users Access Token

This is what i have:
static AccessToken accessToken = new DefaultFacebookClient().obtainExtendedAccessToken("<my app id>", "<my app secret>");
static FacebookClient client = new DefaultFacebookClient();
public static void main(String args[]) {
System.out.print("Enter Your Status: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String status= null;
try {
userName = br.readLine();
System.out.println("..........");
} catch (IOException ioe) {
System.out.println("!");
System.exit(1);
}
FacebookType publishMessageResponse =
client.publish("me/feed", FacebookType.class,
Parameter.with("message", status));
So first line gets the token and stores it as type AccessToken but what good does that do to me because next line i need to provide the access token as a string and i can't convert it. Any Help?
First of all don't confuse app token with user token (more info)
To get user token you have to
Provide a way for user to authenticate against Facebook (more info) and receive "code" - an encrypted string unique to each login request.
Get the user token using this code.
You can get user token with pure RestFB the following way:
private FacebookClient.AccessToken getFacebookUserToken(String code, String redirectUrl) throws IOException {
String appId = "YOUR_APP_ID";
String secretKey = "YOUR_SECRET_KEY";
WebRequestor wr = new DefaultWebRequestor();
WebRequestor.Response accessTokenResponse = wr.executeGet(
"https://graph.facebook.com/oauth/access_token?client_id=" + appId + "&redirect_uri=" + redirectUrl
+ "&client_secret=" + secretKey + "&code=" + code);
return DefaultFacebookClient.AccessToken.fromQueryString(accessTokenResponse.getBody());
}
The call is simple:
FacebookClient.AccessToken token = getFacebookUserToken(code, redirectUrl);
String accessToken = token.getAccessToken();
Date expires = token.getExpires();
In addition to what Jack said about AccessToken.getAccessToken() returning the string value of accessToken, you can avoid instantiating DefaultFacebookClient twice by extending DefaultFacebookClient like this:
import com.restfb.DefaultFacebookClient;
public class LoggedInFacebookClient extends DefaultFacebookClient {
public LoggedInFacebookClient(String appId, String appSecret) {
AccessToken accessToken = this.obtainAppAccessToken(appId, appSecret);
this.accessToken = accessToken.getAccessToken();
}
}
Try the following code:
AccessToken accessToken = new DefaultFacebookClient().obtainAppAccessToken(appid,appsecret);
String token=accessToken.getAccessToken();
Per restfb.FacebookClient.AccessToken, you should be able to call accessToken.getAccessToken() -- that should return the String you are looking for.
This will work
AccessToken accessToken = new DefaultFacebookClient().obtainAppAccessToken("XXXX", "XXXX");
String token=accessToken.getAccessToken();
DefaultFacebookClient facebookClient = new DefaultFacebookClient(token);

GWT Facebook Integration

I am trying to write a server side Facebook Notification service in my GWT app. The idea is that I will run this as a timertask or cron job sort of.
With the code below, I get a login URL, I want to be able to Login programmatically as this is intended to be automated (Headless sort of way). I was gonna try do a submit with HTMLunit but I thought the FB API should cater for this.
Please advice.
public class NotificationServiceImpl extends RemoteServiceServlet implements NotificationService {
/**serialVersionUID*/
private static final long serialVersionUID = 6893572879522128833L;
private static final String FACEBOOK_USER_CLIENT = "facebook.user.client";
long facebookUserID;
public String sendMessage(Notification notification) throws IOException {
String api_key = notification.getApi_key();
String secret = notification.getSecret_key();
try {
// MDC.put(ipAddress, req.getRemoteAddr());
HttpServletRequest request = getThreadLocalRequest();
HttpServletResponse response = getThreadLocalResponse();
HttpSession session = getThreadLocalRequest().getSession(true);
// session.setAttribute("api_key", api_key);
IFacebookRestClient<Document> userClient = getUserClient(session);
if(userClient == null) {
System.out.println("User session doesn't have a Facebook API client setup yet. Creating one and storing it in the user's session.");
userClient = new FacebookXmlRestClient(api_key, secret);
session.setAttribute(FACEBOOK_USER_CLIENT, userClient);
}
System.out.println("Creating a FacebookWebappHelper, which copies fb_ request param data into the userClient");
FacebookWebappHelper<Document> facebook = new FacebookWebappHelper<Document>(request, response, api_key, secret, userClient);
String nextPage = request.getRequestURI();
nextPage = nextPage.substring(nextPage.indexOf("/", 1) + 1); //cut out the first /, the context path and the 2nd /
System.out.println(nextPage);
boolean redirectOccurred = facebook.requireLogin(nextPage);
if(redirectOccurred) {
return null;
}
redirectOccurred = facebook.requireFrame(nextPage);
if(redirectOccurred) {
return null;
}
try {
facebookUserID = userClient.users_getLoggedInUser();
if (userClient.users_hasAppPermission(Permission.STATUS_UPDATE)) {
userClient.users_setStatus("Im testing Facebook With Java! This status is written using my Java code! Can you see it? Cool :D", false);
}
} catch(FacebookException ex) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error while fetching user's facebook ID");
System.out.println("Error while getting cached (supplied by request params) value " +
"of the user's facebook ID or while fetching it from the Facebook service " +
"if the cached value was not present for some reason. Cached value = {}" + userClient.getCacheUserId());
return null;
}
// MDC.put(facebookUserId, String.valueOf(facebookUserID));
// chain.doFilter(request, response);
} finally {
// MDC.remove(ipAddress);
// MDC.remove(facebookUserId);
}
return String.valueOf(facebookUserID);
}
public static FacebookXmlRestClient getUserClient(HttpSession session) {
return (FacebookXmlRestClient)session.getAttribute(FACEBOOK_USER_CLIENT);
}
}
Error message:
[ERROR] com.google.gwt.user.client.rpc.InvocationException: <script type="text/javascript">
[ERROR] top.location.href = "http://www.facebook.com/login.php?v=1.0&api_key=MY_KEY&next=notification";
[ERROR] </script>

Categories