Wednesday, December 11, 2013

Maven based web project runtime error while loading the context -- and resolution

ERROR is given below that is seen in tomcat console:
SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
java.lang.NoClassDefFoundError: org/springframework/context/ApplicationContextException
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
at java.lang.Class.getConstructor0(Class.java:2699)
at java.lang.Class.newInstance0(Class.java:326)
at java.lang.Class.newInstance(Class.java:308)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3916)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4467)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:785)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:519)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:581)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Caused by: java.lang.ClassNotFoundException: org.springframework.context.ApplicationContextException
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:305)
at java.lang.ClassLoader.loadClass(ClassLoader.java:246)
... 20 more
Dec 11, 2013 7:06:04 PM org.apache.catalina.core.StandardContext listenerStart

Reason: The war files that is going to deployed to the configured tomcat server not including the spring and all other dependent jar files.  Specially if your project is built with maven.

Resolution: In the Eclipse managed tomcat can be solved by adding maven dependencies in the project's web deployment assembly.
1) Open the project's properties (e.g., right-click on the project's name in the project explorer and select "Properties")
2) select "Deployment Assembly"
3) Click the "Add..." button on the right margin
4) Select "Java Build Path Entries" from the menu of Directive Type and click "Next"
5) Select "Maven Dependencies" from the Java Build Path Entries menu and click "Finish".
You should see "Maven Dependencies" added to the Web Deployment Assembly definition.

Tuesday, December 10, 2013

Working with TABLE TYPE OBJECTS

Some times its necessary that we get the data from the Oracle PL/SQL procedures as a TABLE type objects.  Retrieving the data from the table type objects is not same as we retrieve the data from ResultSet.  So, here a complete example is given for the benefit of PL/SQL and Java developers. 
       
        1.       Create a table EMPLOYEE
  CREATE TABLE EMPLOYEE_MASTER
   (           EMPID                 NUMBER(10,0) PRIMARY KEY,   
FNAME                                 VARCHAR2(20 BYTE), 
                LNAME                 VARCHAR2(20 BYTE),     
DOB_DATE          DATE, 
                SALARY                 NUMBER(10,0), 
                REMARKS            VARCHAR2(50 BYTE)
 ) ;

2.       Create an object and its body for new object creation.  Body is useful for testing the procedure with in the plsql code.

                              CREATE OR REPLACE TYPE EMP_RECORD_OBJ  AS  OBJECT(
FIRSTNAME        varchar2(20),  
LASTNAME         varchar2(20),
SALARY                 number(10),  
DOB                       DATE,  
REMARKS            varchar2(50),
                STATIC FUNCTION GET_OBJ_FUNCTION   RETURN  EMP_RECORD_OBJ
 );
         
         --//  EMP_RECORD_OBJ  body creation helpful for creating  a new object with null values
               CREATE OR REPLACE TYPE BODY EMP_RECORD_OBJ  
IS
   STATIC FUNCTION GET_OBJ_FUNCTION   RETURN EMP_RECORD_OBJ  
   IS
   BEGIN
      RETURN EMP_RECORD_OBJ  (NULL,  NULL,   NULL,  NULL,  NULL  );
   END;
END;

3.       Create a table type (create under a schema directly to call from   jdbc but not inside the package.)

CREATE OR REPLACE    TYPE   EMP_RECORD_OBJ_ARRAY    IS  TABLE OF   EMP_RECORD_OBJ  ;

4.  Create a procedure to return the table type object from the table

CREATE OR REPLACE  PROCEDURE GET_TABLE_OUTPUT (
            START_EMPID     IN NUMBER,
            END_EMPID       IN NUMBER,
            RECORDS_LIST    OUT  EMP_RECORD_OBJ_ARRAY    )
 AS
 v_emp_array                    EMP_RECORD_OBJ_ARRAY;
 emp_rec                             EMPLOYEE_MASTER%rowType;
 rec_index                           NUMBER;
 CURSOR  EMPLOYEE_CUR  IS    SELECT EMPID , FNAME,  LNAME, DOB_DATE,  SALARY,
REMARKS FROM EMPLOYEE_MASTER;
 BEGIN
  IF  v_emp_array.EXISTS(1)         THEN    v_emp_array.DELETE();   END IF;
  v_emp_array       :=      EMP_RECORD_OBJ_ARRAY();
  rec_index         :=      0;

  OPEN   EMPLOYEE_CUR;
   LOOP
     FETCH EMPLOYEE_CUR INTO emp_rec;
     EXIT WHEN EMPLOYEE_CUR%NOTFOUND;
     IF emp_rec.empid >= start_empid and  emp_rec.empid <= end_empid THEN
      v_emp_array.EXTEND();
      rec_index := rec_index+1;
      v_emp_array(rec_index) := EMP_RECORD_OBJ.GET_OBJ_FUNCTION();
      v_emp_array(rec_index).FIRSTNAME      := emp_rec.fname;
      v_emp_array(rec_index).LASTNAME       := emp_rec.lname;
      v_emp_array(rec_index).SALARY := emp_rec.salary;
      v_emp_array(rec_index).DOB            := emp_rec.dob_date;
      v_emp_array(rec_index).REMARKS        := emp_rec.remarks;
     -- DBMS_OUTPUT.PUT_LINE(emp_rec.fname || 'is -->> ' || emp_rec.remarks);
     END IF;
   END LOOP;
   CLOSE EMPLOYEE_CUR;
                RECORDS_LIST    := v_emp_array;
  EXCEPTION WHEN OTHERS THEN
                RECORDS_LIST    := NULL;
END;

5.       Now enter some master records for testing
INSERT INTO EMPLOYEE_MASTER VALUES (1, 'KHALEEL','SHAIK', SYSDATE-9000, 10000, 'PRACTICE HEAD');
INSERT INTO EMPLOYEE_MASTER VALUES (2, 'RAJA','RAO', SYSDATE-8000, 99000, 'MANAGER');
INSERT INTO EMPLOYEE_MASTER VALUES (3, 'RANGA','RAJU', SYSDATE-9200, 9000, 'LEAD');
INSERT INTO EMPLOYEE_MASTER VALUES (4, 'RAMANA','REDDY', SYSDATE-9100, 11000, 'MANAGER PROJECTS');
INSERT INTO EMPLOYEE_MASTER VALUES (5, 'MOHAN','RAO', SYSDATE-9100, 20000, 'SOLARIS ADMIN');
INSERT INTO EMPLOYEE_MASTER VALUES (6, 'PRANEETH','M', SYSDATE-6000, 8000, 'PROGRAMMER');
INSERT INTO EMPLOYEE_MASTER VALUES (7, 'SHIVA','REDDY', SYSDATE-8500, 11000, 'PROGRAMMER');
INSERT INTO EMPLOYEE_MASTER VALUES (8, 'SURENDER','KUMAR', SYSDATE-9000, 10000, 'LEAD PROGRAMMER');
INSERT INTO EMPLOYEE_MASTER VALUES (9, 'MUNNA','BHAI', SYSDATE-10000, 20000, 'BHAI');
INSERT INTO EMPLOYEE_MASTER VALUES (10, 'RANI','RARU', SYSDATE-3000, 10000, 'HR');
 COMMIT;

6.       Testing the procedure from PL/SQL

SET serveroutput on;

DECLARE
TEST_emp_array              EMP_RECORD_OBJ_ARRAY;
                BEGIN
                                GET_TABLE_OUTPUT (1, 4,   TEST_emp_array);
FOR index  IN 1 .. TEST_emp_array.COUNT
LOOP
DBMS_OUTPUT.PUT_LINE('Here is a last name: '|| TEST_emp_array (index).LASTNAME);
END LOOP;
                END;

                Note: Now you should be able to see the below output:
                        Here is a last name: SHAIK
Here is a last name: RAO
Here is a last name: RAJU
Here is a last name: REDDY


         7.       Testing the procedure from java through JDBC call.


import java.sql.Array;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSetMetaData;
import java.sql.Struct;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.Date;

import oracle.sql.StructDescriptor;

public class TestOracleTableOfResult {

public static void main(String...a) throws Exception {
Class.forName("oracle.jdbc.OracleDriver");
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:scott/tiger@localhost:1521:XE");

final String typeName = "EMP_RECORD_OBJ";
final String typeTableName = "EMP_RECORD_OBJ_ARRAY";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");

// Get a description of your type (Oracle specific)
final StructDescriptor structDescriptor = StructDescriptor.createDescriptor(typeName.toUpperCase(), connection);
final ResultSetMetaData metaData = structDescriptor.getMetaData();

// Call the procedure (or whatever else) that returns the table of a custom type
CallableStatement cs = connection.prepareCall("{call GET_TABLE_OUTPUT(?, ?, ?)}");
cs.setInt(1, 1);
cs.setInt(2, 5);
// Result is an java.sql.Array...
cs.registerOutParameter(3, Types.ARRAY, typeTableName);
cs.execute();

// Now who's elements are java.sql.Structs
Object[] data = (Object[]) ((Array) cs.getObject(3)).getArray();
for(Object tmp : data) {
Struct row = (Struct) tmp;
// Attributes are index 1 based...
int idx = 1;
for(Object attribute : row.getAttributes()) {
System.out.print(metaData.getColumnName(idx) + " = " + attribute);

//Use the below switch block to populate into a POJO object.
switch (idx){
case 1 : System.out.println(" <<===>> as Column FirstName index = " + idx + " , value = " + attribute.toString()); break;
case 2 : System.out.println(" <<===>> as Column LastName index = " + idx + " , value = " + attribute.toString()); break;
case 3 : System.out.println(" <<===>> as Column Salary index = " + idx + " , value = " + Integer.parseInt(""+attribute.toString())); break;
case 4 : System.out.println(" <<===>> as Column Date Of Birth index = " + idx + " , value = " + df.parse(attribute.toString())); break;
case 5 : System.out.println(" <<===>> as Column Remarks index = " + idx + " , value = " + attribute.toString()); break;
}

++idx;

}
System.out.println("----------------------------");
}
cs.close();
connection.close();
}
}

The output of the Java program will be:

FIRSTNAME = KHALEEL <<===>> as FirstName index = 1 , => KHALEEL
LASTNAME = SHAIK <<===>> as LastName index = 2 , => SHAIK
SALARY = 10000 <<===>> as Salary index = 3 , => 10000
DOB = 1989-04-20 15:44:36.0 <<===>> as DOB index = 4 , => Thu Apr 20 15:44:36 IST 1989
REMARKS = PRACTICE HEAD <<===>> as Remarks index = 5 , => PRACTICE HEAD
----------------------------
FIRSTNAME = RAJA <<===>> as FirstName index = 1 , => RAJA
LASTNAME = RAO <<===>> as LastName index = 2 , => RAO
SALARY = 99000 <<===>> as Salary index = 3 , => 99000
DOB = 1992-01-15 15:44:36.0 <<===>> as DOB index = 4 , => Wed Jan 15 15:44:36 IST 1992
REMARKS = MANAGER <<===>> as Remarks index = 5 , => MANAGER
----------------------------
FIRSTNAME = RANGA <<===>> as FirstName index = 1 , => RANGA
LASTNAME = RAJU <<===>> as LastName index = 2 , => RAJU
SALARY = 9000 <<===>> as Salary index = 3 , => 9000
DOB = 1988-10-02 15:44:36.0 <<===>> as DOB index = 4 , => Sun Oct 02 15:44:36 IST 1988
REMARKS = LEAD <<===>> as Remarks index = 5 , => LEAD
----------------------------
FIRSTNAME = RAMANA <<===>> as FirstName index = 1 , => RAMANA
LASTNAME = REDDY <<===>> as LastName index = 2 , => REDDY
SALARY = 11000 <<===>> as Salary index = 3 , => 11000
DOB = 1989-01-10 15:44:36.0 <<===>> as DOB index = 4 , => Tue Jan 10 15:44:36 IST 1989
REMARKS = MANAGER PROJECTS <<===>> as Remarks index = 5 , => MANAGER PROJECTS
----------------------------
FIRSTNAME = MOHAN <<===>> as FirstName index = 1 , => MOHAN
LASTNAME = RAO <<===>> as LastName index = 2 , => RAO
SALARY = 20000 <<===>> as Salary index = 3 , => 20000
DOB = 1989-01-10 15:44:36.0 <<===>> as DOB index = 4 , => Tue Jan 10 15:44:36 IST 1989
REMARKS = SOLARIS ADMIN <<===>> as Remarks index = 5 , => SOLARIS ADMIN
----------------------------



                ==  END ==

Wednesday, November 27, 2013

SOA Vs API Management



API management is concerned with managing external APIs where consumers are unknown. SOA Governance, on the other hand, is about managing services with known consumers.
SOA and API management are the same but different approach.  SOA has its reusability and loose coupling, web based access values, but it may not suitable for every enterprise.  SOA work will maintain its worth because it is always amenable to use in the newer Web technologies, for both development and integration.  API Management is about connecting different parts of a hybrid IT infrastructure including social, mobile and cloud.

o   API Management solution needs to integrate with SOA (at least Enterprise Service Bus) for sharing the metadata about the available enterprise data.
o   APIs are created as business approach to reach new markets with BYOD model, where are SOA is to reach web customers.
o   APIs provide SOA with a way to reach beyond the controlled environment of the enterprise, while SOA provides APIs with acceleration and proven design principles.
o   Defining a strategy for how to merge SOA and API management will be important(long term) to the enterprises.
o   So, we can say that both have close relation and both help customers for business agility. 

Comparisons

API Management
SOA Services
API Management is natural extension of SOA.  All API are services, but not all APIs are good services.
A set of components which can be invoked, and whose interface descriptions can be published and discovered.
API management is concerned with managing external APIs where consumers are unknown
SOA Governance, on the other hand, is about managing services with known consumers.
Web APIs more truly reflect the nature of the Web
SOA reflects the nature of  Web services
More suitable for cloud, mobile, big data platforms to involve external world to innovate new ideas.
More suitable within the enterprise integration
API management enables enterprise services through channels and new forms of innovative products and services.
A business centric architectural approach.
The API security model says ‘good old SSL is good enough.
Security is handles with high standards at the message lever in a complex way.
Its more on REST and JSON services
Its standards based and mostly on SAOP
In a lot of ways, you can think of it as the web for machine-to-machine communication
Its machine-to-machine and machine-to-people as well
Doesn’t require you to sit down and install special infrastructure or libraries to do machine-to-machine communication
Needs special software
Designed for reuse by many apps platforms.  API provides
Designed to reuse in standards basis over the web/connectors

Thursday, November 14, 2013

Enabling SOA Integration with ISG

Oracle E-Business Suite Integrated SOA Gateway (ISG) provides a customer-focused robust communication and integration infrastructure between an external system and ISG for inbound and outbound communication that does not require a special class of middleware software.  This will not only save license costs but also reduce maintenance costs as the existing EBS system support team can maintain the infrastructure easily. This infrastructure not only enables greater and effective business integration with standard SOA concept between heterogeneous applications, but also facilitates the development and execution of complex business processes into highly flexible and reusable Web services. With this standardized and interoperable Web service platform, ISG provides a powerful framework that accelerates publishing of custom PL/SQL procedures as web services over the Web.

Inbound and Outbound with ISG


Integration Architecture

ISG Integrations require some configurations and customizations to enable the functionality in the ISG module.  The functionality would be written in PL/SQL procedures and then enabled as a web service.  The Outbound calls are made using the Service Invocation Framework (SIF) of EBS, which internally uses built-in Business Events for initiating the transaction or web service call.  Organizations would not need to hire new resources to develop this functionality as Apps technical resources possessing PL/SQL skills can easily deploy this functionality. This helps the firm in saving recruitment and resource management costs.  This cross-industry integration can be performed on EBS versions R12.1 and above. 

Implementation Steps
Here is a detailed illustration of web services implementation and calling web services from EBS.  Oracle E-Business Suite (R12.1.3) must be installed and ready to use for Integrated SOA Gateway (ISG) setup and implementation.  This implementation requires some setup configuration and development of several components for Inbound and Outbound as given below:
Inbound
1.    ISG Setup
a.    Enable ASADMIN user
b.    Create ISGUSER
2.    Write a Custom PL/SQL procedure
3.    Write the annotation into Procedure
4.    Generate and Upload the ILDT file
5.    View the Published Custom Web Service developed
6.    Monitoring SOA Requests

Outbound
1.    Run SQL script for Security Parameters to Support UsernameToken based WS-Security WSSE password   (If the external services are WSSE enabled only)
2.    Creating Business Events
3.    Creating Invoke Web Service Subscriptions
4.    Creating Error Notification Subscriptions
5.    Creating Call back event Subscriptions in PL/SQL
6.    Testing the Setup (Don’t DO in the production environments)

7.    Resubmitting Failed Business Events

Note: For detailed implementations details contact me.

Friday, February 15, 2013

How to get the element name in BPEL of a XML using the XPath


Use the expression as follows will work out to get the element name from the variable of message type.

local-name(bpws:getVariableData('Receive_InputVariable',   'body',   '/ns2:OrderElement/*[$VariableIndex]'))   will returns the element name.

Here  "VariableIndex"  is an integer variable which tell the array index of the element you need get the name.



Wednesday, August 29, 2012

OAuth2.0 Implementation for Google API in JAVA or PHP

Using OAuth2.0 authenticating your web application with Google API is 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.

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(" OAuth2.0 example in Web Server Flow");
resp.getWriter().println(" ");
resp.getWriter().println("
");


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 nothing else is required.
The Home.php :




OAuth2.0 Implementatin in PHP by Khaleel



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 ---