Unrecognized temporary token when attempting to complete authorization: FITBIT4J - java

I am trying to create a app for fitbit using fitbit4j . I found their sample code
at
https://github.com/apakulov/fitbit4j/blob/master/fitbit4j-example-client/src/main/java/com/fitbit/web/FitbitApiAuthExampleServlet.java
When i tried to implement it I am getting many errors.
below is their doGet function()
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
FitbitAPIClientService<FitbitApiClientAgent> apiClientService = new FitbitAPIClientService<FitbitApiClientAgent>(
new FitbitApiClientAgent(apiBaseUrl, fitbitSiteBaseUrl, credentialsCache),
clientConsumerKey,
clientSecret,
credentialsCache,
entityCache,
subscriptionStore
);
if (request.getParameter("completeAuthorization") != null) {
String tempTokenReceived = request.getParameter(OAUTH_TOKEN);
String tempTokenVerifier = request.getParameter(OAUTH_VERIFIER);
APIResourceCredentials resourceCredentials = apiClientService.getResourceCredentialsByTempToken(tempTokenReceived);
if (resourceCredentials == null) {
throw new ServletException("Unrecognized temporary token when attempting to complete authorization: " + tempTokenReceived);
}
// Get token credentials only if necessary:
if (!resourceCredentials.isAuthorized()) {
// The verifier is required in the request to get token credentials:
resourceCredentials.setTempTokenVerifier(tempTokenVerifier);
try {
// Get token credentials for user:
apiClientService.getTokenCredentials(new LocalUserDetail(resourceCredentials.getLocalUserId()));
} catch (FitbitAPIException e) {
throw new ServletException("Unable to finish authorization with Fitbit.", e);
}
}
try {
UserInfo userInfo = apiClientService.getClient().getUserInfo(new LocalUserDetail(resourceCredentials.getLocalUserId()));
request.setAttribute("userInfo", userInfo);
request.getRequestDispatcher("/fitbitApiAuthExample.jsp").forward(request, response);
} catch (FitbitAPIException e) {
throw new ServletException("Exception during getting user info", e);
}
} else {
try {
response.sendRedirect(apiClientService.getResourceOwnerAuthorizationURL(new LocalUserDetail("-"), exampleBaseUrl + "/fitbitApiAuthExample?completeAuthorization="));
} catch (FitbitAPIException e) {
throw new ServletException("Exception during performing authorization", e);
}
}
}
When i run the code it goes into the 'else' part first and i get the URL with
localhost:8080/fitbitApiAuthExample?completeAuthorization=&oauth_token=5bccadXXXXXXXXXXXXXXXXXXXXXXXXXX&oauth_verifier=h35kXXXXXXXXXXXXXXXXX, and i get the fitbit login screen and when i log in
and since the
'completeAuthorization==null',
it is executing the else part again.So i manually added a value so that it will enter the 'if' section .
So the new URL became
localhost:8080/fitbitApiAuthExample?completeAuthorization=Success&oauth_token=5bccadXXXXXXXXXXXXXXXXXXXXXXXXXX&oauth_verifier=h35kXXXXXXXXXXXXXXXXX and entered the 'if' section.
Now am getting the exception
'Unrecognized temporary token when attempting to complete authorization:'I tried many workarounds but still cant understand the error.
Please Help.

Solved the problem. the 'apiClientService' was going null when i reload the servlet. Made it member variable and everything started working.

public class NewServlet extends HttpServlet {
public String apiBaseUrl = "api.fitbit.com";
public String webBaseUrl = "https://www.fitbit.com";
public String consumerKey = "your key";
public String consumerSecret = "your secret";
public String callbackUrl = "*****/run?Controller=Verifier";
public FitbitAPIClientService<FitbitApiClientAgent> apiClientService = null;
public String oauth_token = null;
public String oauth_verifier = null;
public String token = null;
public String tokenSecret = null;
public String userId = null;
public APIResourceCredentials resourceCredentials=null;
public FitbitApiClientAgent agent =null;
public LocalUserDetail user=null;
public Gson gson =null;
public UserInfo userInfo=null;
private static Properties getParameters(String url) {
Properties params = new Properties();
String query_string = url.substring(url.indexOf('?') + 1);
String[] pairs = query_string.split("&");
for (String pair : pairs) {
String[] kv = pair.split("=");
params.setProperty(kv[0], kv[1]);
}
return params;
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ParserConfigurationException, SAXException, Exception {
PrintWriter out = response.getWriter();
response.addHeader("Access-Control-Allow-Origin", "*");
// out.println(" ----- process Request Called-----");
String controllerValue = request.getParameter("Controller");
// out.println(" Controller Request : "+param);
if (controllerValue == null) {
// out.println(" inside if part ");
FitbitAPIEntityCache entityCache = new FitbitApiEntityCacheMapImpl();
FitbitApiCredentialsCache credentialsCache = new FitbitApiCredentialsCacheMapImpl();
FitbitApiSubscriptionStorage subscriptionStore = new FitbitApiSubscriptionStorageInMemoryImpl();
FitbitApiClientAgent apiClientAgent = new FitbitApiClientAgent(apiBaseUrl, webBaseUrl, credentialsCache);
out.println("testing2");
apiClientService
= new FitbitAPIClientService<FitbitApiClientAgent>(
apiClientAgent,
consumerKey,
consumerSecret,
credentialsCache,
entityCache,
subscriptionStore
);
// out.println("<script>localStorage.setItem('api',apiClientService);</script>");
LocalUserDetail userDetail = new LocalUserDetail("-");
try {
// out.println("testing4");
String authorizationURL = apiClientService.getResourceOwnerAuthorizationURL(userDetail, callbackUrl);
out.println("access by web browser: " + authorizationURL);
out.println("Your web browser shows redirected URL.");
out.println("Input the redirected URL and push Enter key.");
response.sendRedirect(authorizationURL);
} catch (FitbitAPIException ex) {
out.println("exception : " + ex);
//Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (controllerValue.equalsIgnoreCase("Verifier")) {
oauth_token = request.getParameter("oauth_token");
oauth_verifier = request.getParameter("oauth_verifier");
resourceCredentials = apiClientService.getResourceCredentialsByTempToken(oauth_token);
if (resourceCredentials == null) {
out.println(" resourceCredentials = null ");
throw new Exception("Unrecognized temporary token when attempting to complete authorization: " + oauth_token);
}
if (!resourceCredentials.isAuthorized()) {
resourceCredentials.setTempTokenVerifier(oauth_verifier);
apiClientService.getTokenCredentials(new LocalUserDetail(resourceCredentials.getLocalUserId()));
}
userId = resourceCredentials.getLocalUserId();
token = resourceCredentials.getAccessToken();
tokenSecret = resourceCredentials.getAccessTokenSecret();
user = new LocalUserDetail(userId);
userInfo = apiClientService.getClient().getUserInfo(new LocalUserDetail(resourceCredentials.getLocalUserId()));
user = new LocalUserDetail(userId);
agent = apiClientService.getClient();
response.sendRedirect("http://localhost:8084/FitbitClientCheck/");
}

Related

First time login Null pointer exception (singleton pattern) [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have a problem. Please take a look at these codes. When I click to login button first time it throws null pointer exception even I am typing correct username and password. But second time everything goes fine. How can I solve this issue?
I have attached OracleDBConnection and Login servlet. Null pointer exception happens in OracleDBConnection file.
Thanks for reading.
OracleDBConnection.java
public class OracleDBConnection {
private static volatile OracleDataSource instance = null;
private static final DBPropertyController DB_PROPERTY = new DBPropertyController();
private static final String URL = DB_PROPERTY.getProperty("url");
private static final String USERNAME = DB_PROPERTY.getProperty("username");
private static final String PASSWORD = DB_PROPERTY.getProperty("password");
private static final String PORT = DB_PROPERTY.getProperty("port");
private OracleDBConnection(){
}
private static void initialize() {
try {
instance = new OracleDataSource();
instance.setURL(URL);
instance.setUser(USERNAME);
instance.setPassword(PASSWORD);
instance.setPortNumber(Integer.parseInt(PORT));
} catch (SQLException ex) {
Logger.getLogger(OracleDBConnection.class.getName()).log(Level.ERROR, ex);
}
}
public static OracleDataSource getInstance() {
OracleDataSource ods = OracleDBConnection.instance;
if(ods == null) {
synchronized(OracleDataSource.class){
ods = OracleDBConnection.instance;
if(ods == null) {
initialize();
}
}
}
return ods;
}
}
Login.java
#WebServlet(name = "Login", urlPatterns = {"/login"})
public class Login extends HttpServlet {
private final LogController logger = new LogController();
private final JWTController jwt_controller = new JWTController();
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
LoginController login_controller = new LoginController();
HttpSession session = request.getSession(true);
String username = request.getParameter("username");
String password = request.getParameter("password");
int role = 0;
try {
role = Integer.parseInt(request.getParameter("userrole"));
} catch(NumberFormatException ex) {
Logger.getLogger(Login.class.getName()).log(Level.ERROR, null, ex);
role=0;
}
if(username!=null && password!=null && !username.equals("") && !password.equals("") && isRoleValid(role)){
if(login_controller.validateLogin(username, password, role)) {
// get manager object
Manager manager = login_controller.getManager(username, password, role);
long currentEpochTime = LocalDateTime.now().atZone(ZoneId.systemDefault()).toEpochSecond();
// set manager object to session
session.setAttribute("manager", manager);
//generate token
String token = jwt_controller.generateToken(username, MD5.generate(password), role);
// set token to cookie
Cookie cookie = new Cookie("token", token);
// add cookie to response
response.addCookie(cookie);
// check password expire date
if(manager.getPaswd_edate() > currentEpochTime) {
// signed in
response.getWriter().write("Signed in");
} else {
// expired
response.getWriter().write("Expired");
}
// add log
logger.addLog(username, "Signed in.", request.getRemoteHost(), request.getHeader("user-agent"));
} else {
response.getWriter().write("Error");
}
} else {
response.getWriter().write("Error");
}
}
private boolean isRoleValid(int role) {
return role==0 || role==1 || role==2 || role==3;
}
}
You haven't mentioned where is your NPE, but I guess it is because your OracleDBConnection.getInstance() returns null object first time it is called.
Change your lines
synchronized(OracleDataSource.class){
ods = OracleDBConnection.instance;
if(ods == null) {
initialize();
}
}
to
synchronized(OracleDataSource.class){
if(ods == null) {
initialize();
}
ods = OracleDBConnection.instance;
}

application deployed in server works in chrome but not in firefox and IE

We've recently deployed an application in our tomcat server. It's working properly when we used Chrome, but when we've tried it in Firefox, it's not. The same goes for IE.
We've checked and found that when in Chrome, the status is 200.
But in Firefox or IE, the status alternates from 302 to 200.
Also, there are times when it works in those two browsers.
Here's some code snippets which might help :
private SecurityContext processSession(final HttpSession session) {
LOG.info("SESSION ID: {}", session.getId());
final int maxAppSessionTimeout = 28800;
final String ssc = "SPRING_SECURITY_CONTEXT";
// set context
SecurityContext context = (SecurityContext) session.getAttribute(ssc);
// set session timeout in seconds
session.setMaxInactiveInterval(maxAppSessionTimeout);
return context;
}
We suspect that it is being caused by the method above since it sometimes returns null when in Firefox or IE. This method is being called by the code below :
public final void doFilter(final ServletRequest request,
final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
User user = getUser();
String userId = "";
String uname = "";
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpSession session = httpRequest.getSession(false);
SecurityContext context = null;
String logURL = httpRequest.getRequestURI();
String logParams = httpRequest.getQueryString();
LOG.info("lOG URI: {}", logURL);
LOG.info("lOG URI PARAMS: {}", logParams);
if (session != null) {
// validate and add new parameters in session
context = processSession(session);
// sanitize cookies
processCookies(httpRequest, httpResponse);
// commit
}
// anti x-frame
// httpresponse.addHeader("X-FRAME-OPTIONS", "SAMEORIGIN");
httpResponse.addHeader("X-Content-Type-Options", "nosniff");
httpResponse.addHeader("X-XSS-Protection", "1; mode=block");
try {
if (user != null) {
userId = user.getUid();
uname = user.getUsername();
if (StringUtils.isNotBlank(userId)
&& StringUtils.isNotBlank(uname)) {
if (session.getAttribute("fullname") == null) {
// add user name in session
session.setAttribute("fullname", uname);
}
if (session.getAttribute("userId") == null) {
// add user nadme in session
session.setAttribute("userId", userId);
}
}
initiateLogger(session, userId, request.getRemoteAddr(),
"userLogged");
}
} catch (Exception e) {
LOG.error("Exception while getting employee information.", e);
}
System.out.println("context " + context);
if ("/MTBBR/".equalsIgnoreCase(logURL) || context != null) {
try {
chain.doFilter(request, response);
} catch (Exception e) {
throw new ServletException(e);
}
} else {
httpResponse.setStatus(HttpURLConnection.HTTP_MOVED_TEMP);
}
}
Could you guys help us figure this out?
Thanks a lot!

AWS EC2 Instances: Launch Multiple Instance

I want to create ec2 instances when ever the new user arrive. I created a servlet class to do this. When User arrive i check DB that is user new or not if new then create the instance and send back his/her IP. When i send http request to this servlet one by one for users i get the IP correctly. But when i send HTTP Call in parallel (for user1 send request in tab1, for user2 send request in tab2 simultaneously before getting response from user1 HTTP call). When i do this i got error. Sometimes user1 said
"The instance ID 'i-0b79495934c3b5459' does not exist (Service:
AmazonEC2; Status Code: 400; Error Code: InvalidInstanceID.NotFound;
Request ID: e18a9eaa-cb1b-4130-a3ee-bf1b19fa184c) "
And user2 send IP in response. Kindly help me What is the issue and how to resolve this.
This is the Servlet Class which i created.
public class GateKeeperController extends HttpServlet {
private static final long serialVersionUID = 1L;
BasicAWSCredentials awsCreds = new BasicAWSCredentials(credentials);
AmazonEC2Client ec2Client = new AmazonEC2Client(awsCreds);
RunInstancesRequest runInstancesRequest;
RunInstancesResult runInstancesResult;
Reservation reservation;
Instance intstance;
DescribeInstancesRequest describeInstanceRequest;
DescribeInstancesResult describeInstanceResult;
GatekeeperModal gateKeepermodal;
String sourceAMI = null;
String destinationAMI = null;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession s = request.getSession();
String userID = (String) request.getParameter("userID");
Double lattitude = Double.parseDouble((String) request.getParameter("lat"));
Double lonitude = Double.parseDouble((String) request.getParameter("long"));
if (userID != null) {
Pair coordinates = new Pair(lattitude, lonitude);
RegionSelection targetRegion = new RegionSelection();
String regionResult = targetRegion.getRegion(coordinates);
String instanceIP = null;
gateKeepermodal = new GatekeeperModal();
try {
if (gateKeepermodal.checkUserIsNew(userID)) {
instanceIP = startInstance(userID, regionResult);
if (instanceIP != null) {
response.getWriter().write(instanceIP);
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
}
}
private String startInstance(String userID, String region) {
String ami_id = new AMI().getAMI_ID(region);
ec2Client.setEndpoint(region);
runInstancesRequest = new RunInstancesRequest();
runInstancesRequest.withImageId(ami_id).withInstanceType("t2.micro").withMinCount(1).withMaxCount(1)
.withKeyName("GateKeeper_User").withSecurityGroups("GateKeeper User");
runInstancesResult = ec2Client.runInstances(runInstancesRequest);
reservation = runInstancesResult.getReservation();
intstance = reservation.getInstances().get(0);
String s1 = intstance.getState().getName();
String s2 = InstanceStateName.Running.name();
while (!s1.toLowerCase().equals(s2.toLowerCase())) {
describeInstanceRequest = new DescribeInstancesRequest();
describeInstanceRequest.withInstanceIds(intstance.getInstanceId());
ec2Client.setEndpoint(region);
describeInstanceResult = ec2Client.describeInstances(describeInstanceRequest);
reservation = describeInstanceResult.getReservations().get(0);
intstance = reservation.getInstances().get(0);
s1 = intstance.getState().getName();
s2 = InstanceStateName.Running.name();
}
GateKeeperUser user = new GateKeeperUser(userID, intstance.getInstanceId(), intstance.getPublicIpAddress(),
region);
Boolean result;
try {
result = gateKeepermodal.createUser(user);
if (result) {
return intstance.getPublicIpAddress();
} else {
return null;
}
} catch (SQLException e) {
}
return null;
}
}
According to the documentation:
"If you successfully run the RunInstances command, and then
immediately run another command using the instance ID that was
provided in the response of RunInstances, it may return an
InvalidInstanceID.NotFound error. This does not mean the instance does
not exist. Some specific commands that may be affected are:
DescribeInstances: To confirm the actual state of the instance, run
this command using an exponential backoff algorithm.
TerminateInstances: To confirm the state of the instance, first run
the DescribeInstances command using an exponential backoff algorithm."

GAE OAuth Java: No authentication header information

I have this error:
WARNING: Authentication error: Unable to respond to any of these challenges: {}
Exception : No authentication header information
I am using GWT with eclipse.
I really don't know what's wrong in my code.
Any help would be appreciated.
Thanks in advance.
Client side EntryPoint class:
private static final String GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/auth";
private static final String GOOGLE_CLIENT_ID = "xxxxxxx.apps.googleusercontent.com";
private static final String CONTACTS_SCOPE = "https://www.google.com/m8/feeds";
private static final Auth AUTH = Auth.get();
public void onModuleLoad() {
final AuthRequest req = new AuthRequest(GOOGLE_AUTH_URL, GOOGLE_CLIENT_ID).withScopes(CONTACTS_SCOPE);
AUTH.login(req, new Callback<String, Throwable>() {
public void onSuccess(String token) {
ABASession.setToken(token);
}
public void onFailure(Throwable caught) {
Window.alert("Error:\n" + caught.getMessage());
}
});
}
I store the token in a class that I will use later.
Server side: ContactServiceImpl (RPC GAE procedure)
//The token stored previously is then passed through RPC
public List printAllContacts(String token) {
try {
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey("My consumer key");
oauthParameters.setOAuthConsumerSecret("My consumer secret");
PrivateKey privKey = getPrivateKey("certificate/akyosPrivateKey.key");
OAuthRsaSha1Signer signer = new OAuthRsaSha1Signer(privKey);
ContactsService service = new ContactsService("XXX");
service.setProtocolVersion(ContactsService.Versions.V3);
oauthParameters.setOAuthToken(token);
service.setOAuthCredentials(oauthParameters, signer);
// Request the feed
URL feedUrl = new URL("http://www.google.com/m8/feeds/contacts/default/full?xoauth_requestor_id=xxx.yyy#gmail.com");
ContactFeed resultFeed = service.getFeed(feedUrl, ContactFeed.class);
for (ContactEntry entry : resultFeed.getEntries()) {
for (Email email : entry.getEmailAddresses()) {
contactNames.add(email.getAddress());
}
}
return contactNames;
} catch (Exception e) {
System.err.println("Exception : " + e.getMessage());
}
return null;
}
set the scope
oauthParameters.setScope("http://www.google.com/m8/feeds/contacts/default/full");

help needed in importing yahoo contacts to my page through play framework

I am working in Play framework and I am trying to import yahoo contacts.
I have cleared the yahoo authentication api's to get the access_token and guid.
With that, when I try to import the contacts using http://social.yahooapis.com/v1/user/{guid}/contacts with the auth parameters, I am getting the connection timeout exception in my page and log.
When I paste the same contact url being generated through the code in the browser, I am getting as signature_invalid
I hope I have followed all the stuffs mentioned in the yahoo api dev notes to create the oauth_signature, but still I am not getting it.
Can anyone help me on this please?
Controller code for generating signature -
public class Yahoo {
private static String token = "";
private static String currentUrl = "";
private static String verifier = "";
private static String tokenSecret = "";
private static String accessToken = "";
private static String yahooGuid = "";
public Yahoo(){
}
/**
* Requests access to the Yahoo API for request token.
* #return True if the request is successful, false if not.
*/
public static Yahoo authorize() {
Session session = Session.current();
if(session.contains("authorized") && session.get("authorized").equals("0")){
session.put("authorized", "1");
String url = getRequestTokenUrl();
WS.WSRequest request = WS.url(url);
Logger.info("Yahoo: Create request to get request token'%s'", request.url);
WS.HttpResponse response = request.get();
Logger.info("Yahoo: Token response status is %d", response.getStatus());
if (response.getStatus() == 200){
String[] pairs = response.getString().split("&");
String[] tokenSecret = pairs[1].split("=");
Yahoo.tokenSecret = tokenSecret[1];
for (String pair : pairs) {
String[] kv = pair.split("=");
if (kv.length != 2) {
break;
} else {
if (kv[0].equals("oauth_token")) {
Yahoo.token = kv[1];
}
}
}
Logger.info("level 1 - yahoo token = %s, secret = %s",Yahoo.token, Yahoo.tokenSecret);
}
}
return null;
}
/**
* Requests access to the Yahoo API for access token.
* #return True if the request is successful, false if not.
*/
public static Yahoo getAccessToken(){
String url = getAccessTokenUrl();
WS.WSRequest request = WS.url(url);
Logger.info("Yahoo: Create request to get Access token'%s'", request.url);
WS.HttpResponse response = request.get();
Logger.info("Yahoo: Token response status is %d", response.getStatus());
if (response.getStatus() == 200){
String[] pairs = response.getString().split("&");
String[] guidPair = pairs[5].split("=");
String[] tokenSecret = pairs[1].split("=");
Yahoo.tokenSecret = tokenSecret[1];
yahooGuid = guidPair[1];
for (String pair : pairs) {
String[] kv = pair.split("=");
if (kv.length != 2) {
break;
} else {
if (kv[0].equals("oauth_token")) {
Yahoo.accessToken = kv[1];
}
}
}
Logger.info("level 3 - yahoo token = %s, secret = %s, guid = %s",Yahoo.accessToken, Yahoo.tokenSecret, Yahoo.yahooGuid);
}
return null;
}
/**
* Requests Signature
* #return String
*/
public static String getBaseSignature(){
String signature = "";
String data = generateBaseString();
String key = keyString();
Logger.info("key : %s",key);
try {
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(data.getBytes());
signature = new String(Base64.encode(rawHmac));
signature = java.net.URLEncoder.encode(signature, "ISO-8859-1");
Logger.info("Signature=%s", signature);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return signature;
}
/**
* Requests access to the Yahoo API for getting contacts.
*
*/
public static void getContacts(){
String url = getContactUrl();
WS.WSRequest request = WS.url(url);
Logger.info("Yahoo: Create request to get Contacts '%s'", request.url);
WS.HttpResponse response = request.get();
Logger.info("Yahoo: Token response status is %d", response.getStatus());
if (response.getStatus() == 200){
String[] pairs = response.getString().split("&");
for(int i=0;i<pairs.length;i++){
Logger.info("%s", pairs[i]);
}
}else {
//errors contains a JSON response
JsonParser parser = new JsonParser();
JsonObject message = parser.parse(response.getString()).getAsJsonObject();
Logger.error("Yahoo: Could not get token (status %d): %s", response.getStatus(), message.get("message").getAsString());
}
}
public static String generateBaseString(){
String baseString = getBaseUrl();
Logger.info("token secret : %s",tokenSecret);
Logger.info("base url : %s",baseString);
Logger.info("callback url : %s",getCallBackUrl().toString().split("oauth_token")[0].replace('?', '\0'));
String returnString = "";
try {
returnString = java.net.URLEncoder.encode("GET", "ISO-8859-1") + "&" + java.net.URLEncoder.encode("http://social.yahooapis.com/v1/user/"+yahooGuid+"/contacts", "ISO-8859-1") + "&" + java.net.URLEncoder.encode(baseString, "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Logger.info("Yahoo: Base string: %s",returnString);
return returnString;
}
public static String keyString(){
String consumerSecret = encodeString(getConsumerSecret());
String tokenSec = encodeString(tokenSecret);
String keyString = consumerSecret + encodeString("&") + tokenSec;
return keyString;
}
public static String encodeString(String msgString){
String msg = "";
try {
msg = java.net.URLEncoder.encode(msgString.toString(), "ISO-8859-1");
Logger.info("encode=%s", msg);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return msg;
}
You are getting invalid signature when you copy and paste on the browser because you are not passing the oauth headers.
I strongly suggest you using a lib to do that, I have done the exact same thing with linkedin:
http://geeks.aretotally.in/projects/play-framework-linkedin-module
You will find explanation and link to the source code.
Hope it helps.
Thank you,
Felipe
http://geeks.aretotally.in
http://playframework.info
http://mashup.fm

Categories

Resources