OAuth2.0 Implementation for Google API in JAVA or PHP

Using OAuth2.0 authenticating your web application with Google API is now very easy. This will help your applications to maintain sing user repository from Google logging, and no need to maintain any password at your application side.  Here the idea is to give an idea of complete Web Server flow (Oauth2 web server side dance) and understand it completely with complete open source technologies. Steps involved for this process are given below:

First step is go to Google API Console and register a project then create a Web Application userid and secret key.  (Make sure that the registering URL will have your application’s context path).

Note: Modify the userid/secretkeys as per your settings.

Create a web project ( say TestProject) and then create a servlet as shown below:

package com.test.oauth;

import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.io.IOUtils;

public class OAuthTwoCallBackServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

private static String client_id = “895498929378-4uohdps8sb5v6jp8saf0rea73c0h87nr.apps.googleusercontent.com”;
private static String client_secret = “LsIy_r4-S22jGwGJkbNeYQ1H”;
private static String redirectURL = “http://localhost:8080/TestProject/callback”;
private String auth_code = null;

public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {

System.out.println(“Callback to URI that is configured in Google API Console”);
resp.setContentType(“text/html”);
resp.getWriter().println(” “);
resp.getWriter().println(” “);
resp.getWriter().println(”
Top of Form

“);

Bottom of Form

if (req.getParameter(“code”) == null) {

if (req.getParameter(“error”) != null) {
resp.getWriter().println(“Hello, ” + req.getParameter(“error”));
} else {

resp.getWriter().println(“”);
resp.getWriter().println(“”);
resp.getWriter().println(”

“);    resp.getWriter().println(“”);
resp.getWriter().println(”

Hello

“);
resp.getWriter().println(“To login with Google Account click here “);
resp.getWriter().println(“”);
resp.getWriter().println(”    resp.getWriter().println(” alt=’Powered by Google App Engine’ />”);
resp.getWriter().println(”
“);    resp.getWriter().println(”
“);       }
} else {
resp.getWriter().println(”

Code

“);
resp.getWriter().println(“Authentication Code = ” + req.getParameter(“code”));
this.auth_code = req.getParameter(“code”);

// Exchange the code for token
HttpClient httpclient = new HttpClient();
BufferedReader bufferedreader = null;
PostMethod postmethod = new PostMethod(
“https://accounts.google.com/o/oauth2/token”);
postmethod.addParameter(“code”, auth_code);
postmethod.addParameter(“client_id”, client_id);
postmethod.addParameter(“client_secret”, client_secret);
postmethod.addParameter(“redirect_uri”, redirectURL);
postmethod.addParameter(“grant_type”, “authorization_code”);
String access_token = null;
String token_type = null;
int expires_in = 0;
String id_token = null;
try {

int rCode = httpclient.executeMethod(postmethod);
System.out.println(“HTTP POST for Token rCode is” + rCode);

if (rCode == HttpStatus.SC_NOT_IMPLEMENTED) {
System.err.println(“The Post postmethod is not implemented by this URI”);
postmethod.getResponseBodyAsString();
} else if (rCode == HttpStatus.SC_NOT_ACCEPTABLE) {
System.out.println(postmethod.getResponseBodyAsString());
} else {

String jsonTxt = IOUtils.toString(postmethod
.getResponseBodyAsStream());

JSONObject json = (JSONObject) JSONSerializer
.toJSON(jsonTxt);

access_token = json.getString(“access_token”);
token_type = json.getString(“token_type”);
expires_in = json.getInt(“expires_in”);
id_token = json.getString(“id_token”);
System.out.println(“======== TOKEN INFO ========”);
System.out.println(“access_token: ” + access_token);
System.out.println(“token_type: ” + token_type);
System.out.println(“expires_in: ” + expires_in);
System.out.println(“id_token: ” + id_token);
System.out.println(“=========================”);
resp.getWriter().println(”

Token & Refresh

“);
resp.getWriter().println(“Access Token = ” + access_token);
resp.getWriter().println(“Refresh Token = ” + id_token);
resp.getWriter().println(“Expire Time (Seconds) = ” + expires_in);
resp.getWriter().println(“Token Type = ” + token_type);
}
} catch (Exception e) {
System.err.println(e);
} finally {
postmethod.releaseConnection();
if (bufferedreader != null)
try {
bufferedreader.close();
} catch (Exception fe) {
fe.printStackTrace();
}
}

//Calling Google account info API
User user = null;
httpclient = new HttpClient();
bufferedreader = null;
GetMethod getmethod = new GetMethod(“https://www.googleapis.com/oauth2/v1/userinfo?access_token=” + access_token);
try {
int rCode = httpclient.executeMethod(getmethod);
System.out.println(“HTTP GET for User rCode is” + rCode);

if (rCode == HttpStatus.SC_NOT_IMPLEMENTED) {
System.err
.println(“The Get method is not implemented by this URI”);
getmethod.getResponseBodyAsString();
} else if (rCode == HttpStatus.SC_NOT_ACCEPTABLE) {
System.out.println(getmethod.getResponseBodyAsString());
} else {

String jsonTxt = IOUtils.toString(getmethod
.getResponseBodyAsStream());
JSONObject json = (JSONObject) JSONSerializer
.toJSON(jsonTxt);

user = new User();
user.id = json.getString(“id”);
user.name = json.getString(“name”);
user.email = json.getString(“email”);
user.picture = json.getString(“picture”);
user.gender = json.getString(“gender”);
user.locale = json.getString(“locale”);

System.out.println(“============ TOKEN INFO ===============”);
System.out.println(“id: ” + user.id);
System.out.println(“name: ” + user.name);
System.out.println(“Gender: ” + user.gender);
System.out.println(“email: ” + user.email);
System.out.println(“pictureURL: ” + user.picture);
System.out.println(“Locale: ” + user.locale);
System.out.println(“====================================”);
}
} catch (Exception e) {
System.err.println(e);
} finally {
postmethod.releaseConnection();
if (bufferedreader != null)
try {
bufferedreader.close();
} catch (Exception fe) {
fe.printStackTrace();
}
}

// Get User Information
//resp.setContentType(“text/html”);
resp.getWriter().println(”

User Information

“);
resp.getWriter().println(”
“);

Property Data

resp.getWriter().println(”
Id
” + user.getId()+ ”
“);
resp.getWriter().println(”
Name
” + user.getName()+ ”
“);
resp.getWriter().println(”
Email
” + user.getEmail()+ ”
“);
resp.getWriter().println(”
Gender
” + user.getGender()+ ”
“);
resp.getWriter().println(”
Image

“);
resp.getWriter().println(”
Locale
” + user.getLocale()+ ”
“);
resp.getWriter().println(”
“);
}
}

public class User {
public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPicture() {
return picture;
}

public void setPicture(String picture) {
this.picture = picture;
}

public String getGender() {
return gender;
}

public void setGender(String gender) {
this.gender = gender;
}

public String getLocale() {
return locale;
}

public void setLocale(String locale) {
this.locale = locale;
}

String id;
String email;
String name;
String picture;
String gender;
String locale;

@Override
public String toString() {
return String.format(“id:%s,name:%s,email:%s,gender:%d,locale:%s”,
id, name, email, gender, locale);
}
}

public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
System.out.println(“This is never called”);
}
}

The web.xml file should have the following as well.

TestProject

ServletName:  OAuth2Callback

Servlet calssname: com.test.oauth.OAuthTwoCallBackServlet

Servlet Mapping:  OAuth2Callback

Servlet Mapping Name  /callback
Similarly for PHP I have create a Test project and Home.php file where nothing else is required.
The Home.php:

if(!isset($_GET[“code”]) || $_GET[“code”] ==””){

?>

Please click on Login button to lonon Google Apps using OAuth2.0 and get the Google Aaacount Details

}else{

$userProfile = array(
‘id’ => ”,
‘name’ => ”,
‘gender’ => ”,
’email’ => ”,
‘picture’ => ”,
‘locale’ => ”
);

$userProfile = authValidateUser($_GET[“code”]);

if(isset($userProfile[“email”]) && $userProfile[“email”] != “”){
?>

User Property Data

Name
Email
Gender
ID
Picture
Locale

}else{

?>

Unable to get User Data, Please try Again !!!

}

}

function authValidateUser($code)
{
$OAuth = array(
‘oauth_uri’ => ‘https://accounts.google.com/o/oauth2/auth’,
‘client_id’ => ‘284443344502-do31sm7eo7nogdcn5m0dmlgb0841r8j2.apps.googleusercontent.com’,
‘client_secret’ => ‘abUpKB-rqoBOx0DJv2fhJ44S’,
‘redirect_uri’ => ‘http://localhost/Test/Home.php’,
‘oauth_token_uri’ => ‘https://accounts.google.com/o/oauth2/token’
);

$token = array(
‘access_token’ => ”,
‘token_type’ => ”,
‘expires_in’ => ”,
‘refresh_token’ => ”
);

$userinfo = array(
‘id’ => ”,
‘name’ => ”,
‘gender’ => ”,
’email’ => ”,
‘picture’ => ”,
‘locale’ => ”
);

if(isset($code) && $code != “”){

// now exchange Authorization code for access token and refresh token
$token_response = _get_auth_token($OAuth, $code);
$json_obj = json_decode($token_response);
$token[“access_token”] = $json_obj->access_token;
$token[“token_type”] = $json_obj->token_type;
$token[“expires_in”] = $json_obj->expires_in;
$token[“refresh_token”] = $json_obj->refresh_token;
}

if(isset($token[“access_token”]) && $token[“access_token”] != “”){
//Exchange Authorization code for access token and refresh token
$userinfo_response = _get_user_info($token[“access_token”]);
$json_obj = json_decode($userinfo_response);
$userinfo[“id”] = $json_obj->id;
$userinfo[“name”] = $json_obj->name;
$userinfo[“gender”] = $json_obj->gender;
$userinfo[“email”] = $json_obj->email;
$userinfo[“picture”] = $json_obj->picture;
$userinfo[“locale”] = $json_obj->locale;
}

return $userinfo;
}

function _get_auth_token($params, $code)
{
$url = $params[‘oauth_token_uri’];

$fields = array(
‘code’ => $code,
‘client_id’ => $params[‘client_id’],
‘client_secret’ => $params[‘client_secret’],
‘redirect_uri’ => $params[‘redirect_uri’],
‘grant_type’ => ‘authorization_code’
);

$response = _do_post($url, $fields);
return $response;
}

function _get_refresh_token($params, $code)
{
$url = $params[‘oauth_token_uri’];

$fields = array(
‘code’ => $code,
‘client_id’ => $params[‘client_id’],
‘client_secret’ => $params[‘client_secret’],
‘refresh_token’ => $token[‘refresh_token’],
‘grant_type’ => ‘refresh_token’
);

$response = _do_post($url, $fields);
return $response;
}

function _do_post($url, $fields)
{
$fields_string = “”;

foreach ($fields as $key => $value)
{
$fields_string .= $key . “=” . $value . “&”;
}
$fields_string = rtrim($fields_string, “&”);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$response = curl_exec($ch);
curl_close($ch);

return $response;
}

function _get_user_info($AuthToken){
$url = “https://www.googleapis.com/oauth2/v1/userinfo”;
$fields = array(‘access_token’ => $AuthToken );
$response = _do_get($url, $fields);

//$response = logoutOauthTwoUser($AuthToken);
return $response;
}

function _do_get($url, $fields)
{
$fields_string = “”;

foreach ($fields as $key => $value)
{
$fields_string .= $key . “=” . $value . “&”;
}
$fields_string = rtrim($fields_string, “&”);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url.”?”.$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPGET, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$response = curl_exec($ch);
curl_close($ch);

return $response;
}

?>

— END —

Author: Khaleel Shaik, JAVA Practice Head & Technical Architect at Bodhtree. He specializes in JAVA/J2EE Technologies; Applications Integration using the SOA web services technologies with more focus on Oracle Fusion Middleware (BPEL/ OSB/ BAM/ B2B/ Oracle Application Adapter/ etc.)

Read More

Is Social Mining already deciding your forecasting and Pricing?



big data analytic services

A recent study conducted by Oracle Corporation in the retail sector revealed that customers are more social media savvy and the reason behind selecting a particular brand as the best brand is customer service (post sale). If you have visited Japan, Australia or India you may have seen an “Oxygen Bar.” These are establishments that sell oxygen for recreational and consumer usage…seriously. Visit www.o2bar.com.au or Google it. When I first saw the statistics below, I felt that maybe what I really need is a “free air” bar, as in free of Social Media. But this seems impossible in today’s digital world. Social Media has not only played a major role in connecting people, it has also brought a paradigm shift in the way enterprises conduct business.

Here are some quick facts about the ever-present role social media now plays in our relationships and buying decisions:

– How demand is influenced (Forecast)

– 20% of time on PCs is spent on social media. On mobile devices, people are on social media 30% of the time (Nielson)

– Consumers are 71% more likely to make a purchase based on social media referrals (Hubspot)

– Social networks influence nearly 50% of all IT decision makers (LinkedIn – learn more at TechConnect ’12)

– 74% of consumers rely on social networks to guide purchase decisions (SproutSocial)

– Facebook is the most effective platform to get consumers talking about products (SproutSocial)

– 44% of automotive consumers conduct research on forums (Mashable)

– 81% of US respondents indicated that friends’ social media posts directly influenced their purchase decision (Forbes)

– 78% of respondents said that companies’ social media posts impact their purchases (Forbes)

It is not enough for a company to say, “I am mining social data and using Big Data technologies.” Instead companies need to clearly state and understand “What are you mining?”;”Do you understand the ROI?”; ”Do you know how it integrates with demand and pricing management?” If the answers to these questions are not clear, you may not be there yet; but should any sense of complacency arise, just ask, “Is my competitor ahead of me with social mining?”

Read More

Why data of all sizes and complexities including “Big Data” should be “Happy”

My blog is centered on the theme of making a conscious decision to begin to view data as if it was “alive” with all the complexities and mysteries of a human being. By taking this approach I hope to provide a journey and a platform to spark a conversation on how this perspective can then begin to change on how we act towards data and how our decisions around data might then change. Yet, if I do take this premise then it is in my personal opinion that at the end of the day that my data or data that I personally interact with it or have responsibility of will be “Happy Data”.

When I studied biopsychology (combo of psychology + neuroscience) at UCSD we would often look at how biological processes interact with emotions and cognition. As I was earning my degree too often the common debate of nature vs. nurture would be highlighted in this branch of psychology. Over the years, I truly believe that the difference of nature vs. nurture is very important but there is strong importance the relationship between both of them. By nature you carry the traits that might define you but you are nurtured to become the human being that you become as an adult by your interactions. Those interaction can start with your family environment (data in your organization), your extended family (data loosely related) , peer experience (how data interacts with other data), and extending to influences in socio-economic status(will you make different decision around your data in you are economical sound). So if my goal is to make sure that at the end of the day my data is happy what can I do to make sure this happens? What should I consider in the DNA of my data? What things should I consider to provide a positive environment as my data is maturing in my ecosystem?

Nurture: In the beginning there was “Little Data”

I have a strong passion for Analytics so a lot my examples going forward would probably gravitate towards that subject. (Yet, I will try to change around in future postings)Lets then look at my first example on when an organization has decided to launch existing product line in a different channel. Let’s say that this organization has traditionally provided this product only via direct to consumer over the web and print channel (catalog). Now they want to have physical presence were can have a more intimate relationship with the customer and have begun to roll their products via kiosk in a mall. It is anticipated that mix % of these new distribution channel might increase to 15% in 12 month period so they are being cautious not to tarnish the brand but also cognizant that there is certain opportunity cost if they do not move fast enough. Both the folks in marketing and product development might have decided that it was more important to the launch the product quickly then to see if the proper process of capturing the entire 360 degree touch points of the customer. In this example, the organization rolled out the product and did not think about the various components that the transactions with the customer might be different that on the web. Thus, it is treating the data with a limited view. So the data is small and young at the beginning of this process. If the data was alive like a human being would you wait until the data grows or would you try to deal data at a different cycle of the process? It is best to think about it, listen to it, analyze it, interpret it, treat it, nurture it, and protect it (we will talk about security in detail in later blogs) at a stage that it is not as complex and the size is manageable. You also have a stronger chance to nurture it along the process and can influence the outcome of this data by beginning a relationship with it earlier on. You are able to change some the environment and process when you begin to understand the importance of this data in the future.

I will try to get into more details on different examples on different stages in maturity and complexities of data going forward on other postings. I did not get into too much detail given that I wanted to introduce this subject first. I am excited to see in other discussion what we should consider in your organization if the data might be unstructured and rebellious, how then you would then need to act around it. Also, if you have old enterprise data that has been there a long time what are different ways to deal with historical and older data. Regardless, your data should be happy and you should consider how to get there. Can you provide an example in your organization that if you had taken this approach the outcome would be different? Did I miss something or angle that I should have considered? Thank you and please share your comments.

Kain A Sosa VP, Analytics at Bodhtree with expertise on various big data technologies, like Hadoop, Big query, Passionate leader in Data Analytics, Business Intelligence, and Big Data services.

Read More

Why are so many customers failing in their Big Data initiatives?


I strongly believe that companies with a successful Big Data strategy have an information-centric culture where all employees are fully aware of the possibilities of well-analyzed and visualized information. Better data visualization can help you make better decisions

As a matter of fact, Gartner’s top predictions for 2012 and beyond included this prediction about Big Data: “Through 2015, more than 85 percent of Fortune 500 organizations will fail to effectively exploit Big Data for competitive advantage.” This leads to the question “Why are so many customers failing in their Big Data initiatives?”

The success of a Big Data implementation is directly proportional to the maturity model of the organization.

Remembering the Big Data project implementation experience I would like to share the approach that includes three assessment steps as mentioned below. I thought it would be insightful if I also mention here the recommendations which lead to a successful Big Data implementation.

I. APPROACH

II. RECOMMENDATION

Recommend a model, which will demonstrate the real value of Big Data as it is applicable to an organization. The final recommendations and roadmap, based on our learning’s yield one of two possible outcomes:

• If an organization already has all the necessary tools, processes, systems, and solution to solve the existing problems, then we will recommend through a business case that they are not a good contender to adopt Big Data technologies but can resolve their problems with existing ecosystem

• If an organization demonstrates the potential value of a Big Data investment, then we would recommend moving forward with next steps: take the executable roadmap and blueprint to engage in a Big Data proof of concept (POC)

III. METHODOLOGY

Organizations that approach big data from a value perspective with partnership between the business and IT are much more likely to be successful than those which adopt a pure technology approach. For this reason, making appropriate investments in both technology and organizational skill sets to ensure enterprise capability in extracting value from big data is essential.

Don’t wait, start now

Start collecting massive amounts of data and store it centralized with Hadoop, hire or train your data scientists and change your culture to an information-centric organization. This will help to drive innovation and stay ahead. Don’t wait, as Big Data is the only way forward.

Phani Kumar Reddy is a Manager Analytics at Bodhtree, Managing presales of BI with expertise on various big data technologies, like Hadoop, Big query , Passionate leader in Data Analytics, Business Intelligence, and Big Data services

Read More