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

Data Integration for Salesforce.com is no more a challenging task

Enterprises implement SalesForces so that teams can focus on customers and revenue, leaving the rest to automation.  But when companies try to extend that automation by integrating SalesForce with an ERP, the result too often is more headache than focus.  MIDAS an ETLE Tool (Extraction, Transformation, Loading and Enrichment) resolves the challenge by seamlessly integrating capabilities from Saleforce to and from SAP, EBS and other ERPs. Midas seamlessly integrates Saleforce.com with SAP, Oracle E-Business Suite and other ERPs.

Feature set

• Cloud based solution for invoking transformations and jobs remotely
• Broad connectivity and data delivery
• Hosting a Cloud solution with multi-tenancy capability
• Social connectors – Facebook, Twitter and LinkedIn
• Custom Connectors – SAP, Oracle E-Business Suite and Salesforce.com
• Analytics integration with Pentaho Reports, OBIEE and SAP BusinessObjects
• Powerful administration and management
• Data profiling and data quality
• Single interface to manage all the integration projects
• Flexible deployment options
• Bi-directional CRM-ERP integration

Key Benefits

• Designed for seamlessly integrating Salesforce.com with ERPs and other applications
• 300 plus Open – source connectors out of the box
• Transparent diagrammatic depiction of data transfer steps
• Removes custom coding for quick turn around
• Reduces integration and maintenance costs
• Improves data quality
• Shortens implementation time
• Easy installation and configuration
• Business continuity and application availability management

Read More

You know it’s possible when iPads from China are being shipped to customers in the US!

Service Oriented Architecture (SOA) is often associated with XML and Web Services. But in my opinion it is a business driven approach that can greatly help in promoting agility between Business and IT. I started thinking about this more seriously as I saw iPads from China being directly shipped to customers in the US.

My recent experience in managing a SOA implementation using Oracle Fusion Middleware has transformed this opinion into a belief.

One of our customers – the no.1 brand in the air coolers industry worldwide had an immediate business need – to work with their B2B partners to drop ship orders directly to their end customers. In more technical terms, they wanted to be able to process customer orders through Oracle ERP and send Warehouse Shipment Orders via EDI to the 3PL provider.

Thanks to the functionality offered by SOA Suite 11g and B2B adapter, we were able to successfully automate this process. Our solution enables them to process complex multi-record structured, position based files and seamlessly integrate them with Oracle E-Business Suite.

Our solution not only compliments their new business model, but also empowers their team to generate business performance reports from real time transactional data using Oracle Business Activity Monitoring (BAM).

At the end of this pilot our customer was delighted to see his new business model coming live and has now decided to work with us to institutionalize this further in their organization.

Khaleel Shaik is a Technical Architect and heads SOA and Java Practice at Bodhtree. He specializes in JAVA/J2EE Technologies, Applications Integration using the SOA technologies with more focus on Oracle Fusion Middleware (BPEL/ OSB/ BAM/ B2B/ Oracle Application Adapter/ etc.).

Read More

Big Data – How does it impact an Organization?

Business Intelligence

“Data will grow to several petabytes and zeta bytes in the next few years;” “Corporations will be overwhelmed by the sheer volume of data;” “By 2015 databases will grow so large that companies will have to rent space on the moon to store them.” These are just a few common quotes we hear from renowned industry analysts, experts and CIOs surrounding the topic of Big Data.

But for many observers, there’s still a lot of gray area surrounding when to apply Big Data solutions.  How is Big Data different from traditional analysis tools?  How does it impact an organization? Just because there are several terabytes of data, does that make it Big Data? Does it really matter?

We can make a generic bold statement here: Data is everywhere! When you pause to think, you’ll see it’s true. The cars we drive, stores we shop at, the phone we use, the websites we read, the social media we so closely embrace, the TV programs we watch, the election polls that we follow – everything generates data and it is all stored somewhere.

When it comes to Big Data, people commonly mention the 4 Vs, but this only scratches the surface.  Traditionally, any large organization that implements ERP services has all these Vs associated with their everyday line of business.  Admittedly, this is primarily “structured” data, and it can be handled by a traditional RDBMS or an MPP database.  But in light of the other Vs, it technically has volume because everything is recorded in an ERP system; the incorrect and the correct entries alike form the millions and billions of rows.  It undoubtedly has value; otherwise corporations would not bother to collect it. It clearly is volatile because data does not come at regular intervals. It also has variety; data comes in from multiple sources, such as CRM systems, HR systems and modules that are implemented within the organization.

Even if you add unstructured data, can you really derive strategic value for your business? What is this unstructured data comprised of? What kind of metrics can we extract from this unstructured data?

More often than not, Big Data buzz induces a cool factor akin to what was once associated with owning an iPhone/iPad or, back in the day, having a free Facebook account. Sometimes a personal agenda is associated with Big Data implementations. Several managers and CIOs have vested interests in showing off a ‘cutting edge’ Big Data implementation.  We recommend organizations take a breather to make sure that the data problem they have qualifies as a Big Data problem.

…Stay tuned for a model CIOs can use to evaluate whether Big Data is the solution to their challenge…

Ajay Narayan is a presales solution architect for Bodhtree, a leader in data analytics and product engineering.  Bodhtree partners with SAP and Informatica to assist companies in leveraging enterprise data to gain a competitive edge in the market.  Bodhtree also offers the MIDAS product suite, which migrates, cleanses and integrates data between SalesForce, SAP and legacy platforms.

Read More