Google launched new reCaptcha for effective detection of robots. Every day hackers decrypting captchas. It became difficult for organizations to get protection from bots. Google has given solution to this problem with new reCaptcha. In this article, I am going to explain the implementation of reCaptcha with Java

How reCaptcha Works

  1. Developer has to register their website for Google recaptcha. Then developer will get application key.
  2. Developer has to integrate reCaptcha with registered website.
  3. Whenever user clicks on "I am not a robot, Google reCaptcha script will generate input value with name g-recaptcha-response
  4. Whenever user submits the form, The website server receives code with parameter recaptcha-response.
  5. Now developer has to verify the code at server side by sending one get request to google recaptcha server with application secret key.

Libraries

Get Google GSON Java Library to handle JSON responses.

Get reCaptcha Key

Click here to register your website and get key for your web application
Get key
Here Site key is open, any one can see. Site key will be used in the script of HTML page. Secret key is for only application developer and it is for contacting google server side validation.

HTML Code

Add google reCaptcha script

<script src='https://www.google.com/recaptcha/api.js'></script>

Add reCaptcha DIV

Google script will add input field to this div
<div class="g-recaptcha" data-sitekey="6Lcsyf4SAAAAABLp3hPq6afXNfsXGxYDjCzwpbbJ"></div>

Observe below HTML code

In this below HTML google reCaptcha DIV was enclosed by form. Whenever user clicks on submit button reCaptcha input field will be submitted along with form input fields.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Google New reCaptcha using Java</title>
</head>
<script src='https://www.google.com/recaptcha/api.js'></script>
<style type='text/css'>
.field {
    padding: 0 0 10px 0;
}

.label {
    padding: 3px 0;
    font-weight: bold;
}
</style>

<body>
    <div style="text-align: center">
        <h1>Google reCaptcha using Java</h1>
    </div>
    <div style="width: 400px; margin: auto">
        <form action="HandleRecaptcha">
            <h3>Registration Form</h3>
            <div class="field">
                <div class="label">Enter Name</div>
                <input value="" name="name" />
            </div>

            <div class="field">
                <div class="label">Enter Email</div>
                <input name="email" />
            </div>

            <div class="g-recaptcha"
                data-sitekey="6Lcsyf4SAAAAABLp3hPq6afXNfsXGxYDjCzwpbbJ"></div>

            <div class="field">
                <input type="submit" value="submit" />
            </div>

        </form>
    </div>
</body>
</html>

Java Code

CaptchaResponse.java

Pojo class to handle JSON Response
public class CaptchaResponse {
    public boolean success;

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }
}

HandleRecaptcha.java

Once user clicks on submit button, form data will be submitted to Server. Now get g-recaptcha-response parameter value. 
String recap = request.getParameter("g-recaptcha-response");
Now verify the g-recaptcha-response with Google server using your application secret key.
URL url = new URL("https://www.google.com/recaptcha/api/siteverify?secret="+secretParameter+"&response="+recap+"&remoteip="+request.getRemoteAddr());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
String line, outputString = "";
BufferedReader reader = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
    outputString += line;
}
System.out.println(outputString);
Now convert the response into Java Object and verify whether the input is from robot or human
CaptchaResponse capRes = new Gson().fromJson(outputString, CaptchaResponse.class);
if(capRes.isSuccess()) {
    // your logic - Human
} else {
    // your logic - Robot
}
Complete servlet code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

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

import com.google.gson.Gson;

public class HandleRecaptcha extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private String secretParameter="Your Application Secret Code Here";
       
    public HandleRecaptcha() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        // Get input parameter values (form data)
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String recap = request.getParameter("g-recaptcha-response");
        
        // Send get request to Google reCaptcha server with secret key  
        URL url = new URL("https://www.google.com/recaptcha/api/siteverify?secret="+secretParameter+"&response="+recap+"&remoteip="+request.getRemoteAddr());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        String line, outputString = "";
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
        while ((line = reader.readLine()) != null) {
            outputString += line;
        }
        System.out.println(outputString);
        
        // Convert response into Object
        CaptchaResponse capRes = new Gson().fromJson(outputString, CaptchaResponse.class);
        request.setAttribute("name", name);
        request.setAttribute("email", email);
        
        // Verify whether the input from Human or Robot 
        if(capRes.isSuccess()) {
            // Input by Human
            request.setAttribute("verified", "true");   
        } else {
            // Input by Robot
            request.setAttribute("verified", "false");
        }
        request.getRequestDispatcher("/response.jsp").forward(request, response);
    }

}
Read More
In this article, I am going to explain how to search excel sheet using java. To implement this program you need to download Apache POI library and have it in your build path (copy POI jars to lib folder).
There is no direct method to search excel sheet using java. You need to follow the below flow.

Flow of the program


  1. Get Excel files
  2. Get Work Book of the excel files
  3. Get sheets of the workbook 
  4. Iterate rows
  5. Iterate columns
  6. Compare column value based on its type
  7. Return all filtered rows

Java Code to Search Excel Sheet

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class SearchExcel {
    public static void main(String[] args) {
        try {
            // excel files
            FileInputStream excellFile = new FileInputStream(new File(
                    "C:\\excel1.xlsx"));
            
            // Create Workbook instance holding reference to .xlsx file
            XSSFWorkbook workbook = new XSSFWorkbook(excellFile);
            
            // Get first/desired sheet from the workbook
            XSSFSheet sheet = workbook.getSheetAt(0);
            
            // add sheet2 to sheet1
            ArrayList<Row> rows = searchSheet("Srinivas", sheet);
            System.out.println("filtered rows : \n"+rows);
            excellFile.close();

            System.out
                    .println("Files were searched successfulyy ");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
        
    public static ArrayList<Row> searchSheet(String searchText, XSSFSheet sheet) {
        // This parameter is for appending sheet rows to mergedSheet in the end
        
        Double doubleValue = null;
        Boolean booleanValue = null;
        ArrayList<Row> filteredRows = new ArrayList<Row>();

        //Get double value if searchText is double
        try {
            doubleValue = Double.parseDouble(searchText);
        } catch(Exception e) {  
        }
        
        //Get boolean value if searchText is boolean
        try {
            booleanValue = Boolean.parseBoolean(searchText);
        } catch(Exception e) {  
        }
        
        //Iterate rows
        for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {

            XSSFRow row = sheet.getRow(j);
           
            //Iterate columns
            for (int k = row.getFirstCellNum(); k < row.getLastCellNum(); k++) {
                XSSFCell cell = row.getCell(k);
            
               //Search value based on cell type
               switch (cell.getCellType()) {
                case HSSFCell.CELL_TYPE_NUMERIC:
                    if(doubleValue != null && doubleValue.doubleValue() == cell.getNumericCellValue()) {
                        filteredRows.add(row);
                    }
                    break;
                case HSSFCell.CELL_TYPE_STRING:
                    if(searchText != null && searchText.equals(cell.getStringCellValue())) {
                        filteredRows.add(row);
                    }
                    break;
                case HSSFCell.CELL_TYPE_BOOLEAN:
                    if(booleanValue != null && booleanValue.booleanValue() == cell.getBooleanCellValue()) {
                        filteredRows.add(row);
                    }
                    break;
                default:
                    if(searchText != null && searchText.equals(cell.getStringCellValue())) {
                        filteredRows.add(row);
                    }
                    break;
                }
            }
        }
        return filteredRows;
    }

}
Read More
In this article, I am going explain the simple way to make GUI with Eclipse editor. Eclipse have some wonderful plugins to decrease GUI coders effort. You need to install WindowBuilder plugin with some toolkits.

Install plugin

Goto Menu > Help > Install New Software > Click on 'Work with' drop down and select appropriate URL based on your eclipse version

example :

Helios - http://download.eclipse.org/releases/helios
Indigo - http://download.eclipse.org/releases/indigo
Juno - http://download.eclipse.org/releases/juno
Kepler - http://download.eclipse.org/releases/kepler

Now Eclipse will filter all plugins under this release. Expand 'General Purpose Tools'. Select all WindowBuilder items and Swing Designer and SWT items. Cick on finish.

These plugins will be installed.

Create New Application Window java  class file

Create new project and create new package.
Right click on that package > New Other > Select Application Window under Swing Designer > Click Next and give some name > Click Finish

Working with GUI components

Open the created Java file
Switch it to design view
There you can see lot of GUI components ready to use. If you want to add any component, just select that and add it to present panel.
You can generated event handlers functions by right clicking on components >Add Event Handler > required action

Read More
In this article, I am going to explain how to merge two excel files. Some time we may need to do excel merging programmitically. If you want to do any modification by logic in merging, you can do using this program easily. To implement this program you need to download Apache POI library and have it in your build path (copy POI jars to lib folder).
There is no direct method to merge excel files using java. You have need to follow the below flow.

Flow of the program

  1. Get Excel files
  2. Get Work Books of those excel files
  3. Get sheets to be merged in those excel files
  4. Read every row and add it to other sheet
  5. Read every cell and add it to the row
  6. Write merged workbook to output file

Java Code

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class MergeExcel {

    public static void main(String[] args) {
        try {
            // excel files
            FileInputStream excellFile1 = new FileInputStream(new File(
                    "C:\\excel1.xlsx"));
            FileInputStream excellFile2 = new FileInputStream(new File(
                    "C:\\excel2.xlsx"));

            // Create Workbook instance holding reference to .xlsx file
            XSSFWorkbook workbook1 = new XSSFWorkbook(excellFile1);
            XSSFWorkbook workbook2 = new XSSFWorkbook(excellFile2);

            // Get first/desired sheet from the workbook
            XSSFSheet sheet1 = workbook1.getSheetAt(0);
            XSSFSheet sheet2 = workbook2.getSheetAt(0);

            // add sheet2 to sheet1
            addSheet(sheet1, sheet2);
            excellFile1.close();

            // save merged file
            File mergedFile = new File(
                    "C:\\merged.xlsx");
            if (!mergedFile.exists()) {
                mergedFile.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(mergedFile);
            workbook1.write(out);
            out.close();
            System.out
                    .println("Files were merged succussfully");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void addSheet(XSSFSheet mergedSheet, XSSFSheet sheet) {
        // map for cell styles
        Map<Integer, XSSFCellStyle> styleMap = new HashMap<Integer, XSSFCellStyle>();
        
        // This parameter is for appending sheet rows to mergedSheet in the end
        int len = mergedSheet.getLastRowNum();
        for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {

            XSSFRow row = sheet.getRow(j);
            XSSFRow mrow = mergedSheet.createRow(len + j);

            for (int k = row.getFirstCellNum(); k < row.getLastCellNum(); k++) {
                XSSFCell cell = row.getCell(k);
                XSSFCell mcell = mrow.createCell(k);

                if (cell.getSheet().getWorkbook() == mcell.getSheet()
                        .getWorkbook()) {
                    mcell.setCellStyle(cell.getCellStyle());
                } else {
                    int stHashCode = cell.getCellStyle().hashCode();
                    XSSFCellStyle newCellStyle = styleMap.get(stHashCode);
                    if (newCellStyle == null) {
                        newCellStyle = mcell.getSheet().getWorkbook()
                                .createCellStyle();
                        newCellStyle.cloneStyleFrom(cell.getCellStyle());
                        styleMap.put(stHashCode, newCellStyle);
                    }
                    mcell.setCellStyle(newCellStyle);
                }

                switch (cell.getCellType()) {
                case HSSFCell.CELL_TYPE_FORMULA:
                    mcell.setCellFormula(cell.getCellFormula());
                    break;
                case HSSFCell.CELL_TYPE_NUMERIC:
                    mcell.setCellValue(cell.getNumericCellValue());
                    break;
                case HSSFCell.CELL_TYPE_STRING:
                    mcell.setCellValue(cell.getStringCellValue());
                    break;
                case HSSFCell.CELL_TYPE_BLANK:
                    mcell.setCellType(HSSFCell.CELL_TYPE_BLANK);
                    break;
                case HSSFCell.CELL_TYPE_BOOLEAN:
                    mcell.setCellValue(cell.getBooleanCellValue());
                    break;
                case HSSFCell.CELL_TYPE_ERROR:
                    mcell.setCellErrorValue(cell.getErrorCellValue());
                    break;
                default:
                    mcell.setCellValue(cell.getStringCellValue());
                    break;
                }
            }
        }
    }
}
Read More
Facebook is providing OAuth Service. You can implement Facebook Login on your website so that user doesn't need to remember another password for your website. You will also get worthy email addresses to connect with users. Get Google GSON Java Library to handle JSON responses.

OAuth 2.0 Flow

  1. User will click on Auth login link
  2. Facebook Auth server will show permission screen to user
  3. Once user accepts to the scope, It will send code to App Server ( Redirect URI)
  4. Once we got code, get access token by using client secret id
  5. Access User's Information using that access token 

Get OAuth 2.0  Credentials from Facebook App Dashboard

  1. Go to Facebook Developer's Page.
  2. Go to Apps > Add New App
  3. Enter Site URL and Mobile Site URL. You need to enter your Site URL here. for example "http://demo.sodhanalibrary.com/". After processing User permissions screen, facebook will redirect the code value to this URL 
  4. Goto Dashboard of the above created app, There you can see your app client id and secret id.
  5. If you want to make your app available to public, You need to enter lot of app details. Be patience and complete them.

Form the URL

Now we need to create a button with Auth URL. Syntax of the URL is
https://www.facebook.com/dialog/oauth?[parameters]

Some important Query Paramenters

  1. client_id: Which you got at Facebook developer's app dashboard
  2. redirect_uri: Redirect URI to which code has to be redirected
  3. scope: to get profile info give profile as scope, to get email address give email as scope

The Auth URL get Users Email Address

 https://www.facebook.com/dialog/oauth?
 client_id= client id
 &redirect_uri= redirect URI
 &scope=email
 &scope=user_friends

Get Access Token 

Once user click on above link, It will ask for User's permission to provide information to your site. Once user click on accept it will redirect to Your APP Redirect URI?code=[some code here]. Here you will get code value at server side. So you need to access this from Java or PHP or any other server side language.

Get Code value and format URL

String code = request.getParameter("code");
URL url = new URL("https://graph.facebook.com/oauth/access_token?client_id="
        + clientID + "&redirect_uri=" + redirectURI
        + "&client_secret=" + clientSecret
        + "&code=" + code);

Send request for Access Token

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
String line, outputString = "";
BufferedReader reader = new BufferedReader(
        new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
    outputString += line;
}
System.out.println(outputString);
String accessToken = null;
if(outputString.indexOf("access_token")!=-1) {
    int k=outputString.length();
    accessToken = outputString.substring(k+1,outputString.indexOf("&"));
}

Get User Info

url = new URL("https://graph.facebook.com/me?access_token="+ accessToken);
System.out.println(url);
URLConnection conn1 = url.openConnection();
outputString = "";
reader = new BufferedReader(new InputStreamReader(conn1.getInputStream()));
while ((line = reader.readLine()) != null) {
    outputString += line;
}
reader.close();
System.out.println(outputString);
FaceBookPojo fbp = new Gson().fromJson(outputString, FaceBookPojo.class);

User Info in JSON Format

{
    "id":"user id here",
    "first_name":"name here",
    "last_name":"given name here", 
    "link":"family name here",
    "user_name":"your name here"  
    "email":"your email here"
}

Pojo class to handle response

public class FaceBookPojo {
    String id;
    String name;
    String first_name;
    String last_name;
    String link;
    String user_name;
    String email;
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getFirst_name() {
        return first_name;
    }
    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }
    public String getLast_name() {
        return last_name;
    }
    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }
    public String getLink() {
        return link;
    }
    public void setLink(String link) {
        this.link = link;
    }
    public String getUser_name() {
        return user_name;
    }
    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}

Whole Servlet code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import demo.factory.GlobalCons;
import demo.pojo.FaceBookPojo;

/**
 * Servlet implementation class Oauh2fb
 */
public class OAuth2fb extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    // Set Facebook App details here 
    private static final String clientID = "your app client id here";
    private static final String clientSecret = "your app secret id here";
    private static final String redirectURI = "redirect uri here";

    /**
     * @see HttpServlet#HttpServlet()
     */
    public OAuth2fb() {
        super();

    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        try {
            String rid = request.getParameter("request_ids");
            if (rid != null) {
                response.sendRedirect("https://www.facebook.com/dialog/oauth?client_id="
                        + clientID + "&redirect_uri=" + redirectURI);
            } else {
                // Get code
                String code = request.getParameter("code");
                if (code != null) {
                    
                    // Format parameters
                    URL url = new URL(
                            "https://graph.facebook.com/oauth/access_token?client_id="
                                    + clientID + "&redirect_uri=" + redirectURI
                                    + "&client_secret=" + clientSecret
                                    + "&code=" + code);
                    
                    // request for Access Token
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.setRequestMethod("GET");
                    String line, outputString = "";
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(conn.getInputStream()));
                    while ((line = reader.readLine()) != null) {
                        outputString += line;
                    }
                    System.out.println(outputString);
                    
                    // extract access token from response
                    String accessToken = null;
                    if(outputString.indexOf("access_token")!=-1) {
                        int k=outputString.length();
                        accessToken = outputString.substring(k+1,outputString.indexOf("&"));
                    }
                    
                    // request for user info
                    url = new URL("https://graph.facebook.com/me?access_token="
                            + accessToken);
                    System.out.println(url);
                    URLConnection conn1 = url.openConnection();
                    outputString = "";
                    reader = new BufferedReader(new InputStreamReader(
                            conn1.getInputStream()));
                    while ((line = reader.readLine()) != null) {
                        outputString += line;
                    }
                    reader.close();
                    System.out.println(outputString);
                    
                    // convert response JSON to Pojo class
                    FaceBookPojo fbp = new Gson().fromJson(outputString,
                            FaceBookPojo.class);
                    System.out.println(fbp);
                                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
Read More
Google is providing OAuth Service. You can implement Google Login on your website so that user doesn't need to remember another password for your website. You will also get worthy email addresses to connect with users. Get Google GSON Java Library to handle JSON responses.

OAuth 2.0 Flow

  1. User will click on Auth login link
  2. Google Auth server will show permission screen to user
  3. Once user accepts to the scope, It will send code to App Server ( Redirect URI)
  4. Once we got code, get access token by using client secret id
  5. Access User's Information using that access token 

Get OAuth 2.0  Credentials from Google developer console 

  1. Go to Google Developer Console
  2. Create Project and Open that project
  3. Go to API & Auth > Credentials > Create New Client ID. Here one new dialog box will open and show some options. Now select web application, Give you website URL (example: http://demo.sodhanalibrary.com) in JavaScript origins and Give redirect URL (example: http://demo.sodhanalibrary.com/oauth2callback). Now click on Create Client ID button.
  4. Now you can see your client id and client secret id.

Form the URL

Now we need to create a button with Auth URL. Syntax of the URL is
https://accounts.google.com/o/oauth2/auth?[parameters]

Some important Query Paramenters

  1. client_id: Which you got at Google developer console
  2. response_id: For web application response_id is code
  3. redirect_uri: Redirect URI which you given at Google developer console
  4. scope: to get profile info give profile as scope, to get email address give email as scope
  5. approval_prompt: (force or auto) If it is force, user must accept to your scope or else it will be optional.

The Auth URL get Users Email Address

 https://accounts.google.com/o/oauth2/auth?
 scope=email&
 redirect_uri=http://demo.sodhanalibrary.com/oauth2callback&
 response_type=code&
 client_id=your application client id&
 approval_prompt=force

Get Access Token 

Once user click on above link, It will ask for User's permission to provide information to your site. Once user click on accept it will redirect to Your APP Redirect URI?code=[some code here]. Here you will get code value at server side. So you need to access this from Java or PHP or any other server side language. 

Get Code Value and format Parameters

String code = request.getParameter("code");
String urlParameters = "code="
                    + code
                    + "&client_id=Your app client id"
                    + "&client_secret=Your app secret id"
                    + "&redirect_uri=http://demo.sodhanalibrary.com/oauth2callback"
                    + "&grant_type=authorization_code";
Now we have to send that code with client id and secret id to https://accounts.google.com/o/oauth2/token

Java code to post parameters

URL url = new URL("https://accounts.google.com/o/oauth2/token");
URLConnection urlConn = url.openConnection();
urlConn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(
urlConn.getOutputStream());
writer.write(urlParameters);
writer.flush();

Extract Access Token

After posting above parameters to Google Auth URL, we will get response which contains Access Token. Now extract that access token from that response.
JsonObject json = (JsonObject)new JsonParser().parse(line1);
String access_token = json.get("access_token").getAsString();

Get User Info

Now we have access token so we can get user info.
url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token="+ access_token);
urlConn = url.openConnection();
outputString = "";
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
        outputString += line;
}
In the above code outputString contains the User Info

User info in JSON format

  {
    "id":"user id here",
    "email":"email here",
    "name":"name here",
    "given_name":"given name here", 
    "family_name":"family name here"  
  }

POJO Class to handle JSON rensponse

public class GooglePojo {
    String id;
    String email;
    boolean verified_email;
    String name;
    String given_name;
    String family_name;

    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 boolean isVerified_email() {
        return verified_email;
    }

    public void setVerified_email(boolean verified_email) {
        this.verified_email = verified_email;
    }

    public String getName() {
        return name;
    }

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

    public String getGiven_name() {
        return given_name;
    }

    public void setGiven_name(String given_name) {
        this.given_name = given_name;
    }

    public String getFamily_name() {
        return family_name;
    }

    public void setFamily_name(String family_name) {
        this.family_name = family_name;
    }

    @Override
    public String toString() {
        return "GooglePojo [id=" + id + ", email=" + email
                + ", verified_email=" + verified_email + ", name=" + name
                + ", given_name=" + given_name + ", family_name=" + family_name
                + "]";
    }
}

Whole Servlet Code 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

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

    public Oauth2callback() {
        super();
        
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        
        System.out.println("entering doGet");
        try {
            // get code
            String code = request.getParameter("code");
            // format parameters to post
            String urlParameters = "code="
                    + code
                    + "&client_id=Your App Client ID"
                    + "&client_secret=Your App secret client ID"
                    + "&redirect_uri=Your App Redirect URL"
                    + "&grant_type=authorization_code";
            
            //post parameters
            URL url = new URL("https://accounts.google.com/o/oauth2/token");
            URLConnection urlConn = url.openConnection();
            urlConn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(
                    urlConn.getOutputStream());
            writer.write(urlParameters);
            writer.flush();
            
            //get output in outputString 
            String line, outputString = "";
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    urlConn.getInputStream()));
            while ((line = reader.readLine()) != null) {
                outputString += line;
            }
            System.out.println(outputString);
            
            //get Access Token 
            JsonObject json = (JsonObject)new JsonParser().parse(outputString);
            String access_token = json.get("access_token").getAsString();
            System.out.println(access_token);

            //get User Info 
            url = new URL(
                    "https://www.googleapis.com/oauth2/v1/userinfo?access_token="
                            + access_token);
            urlConn = url.openConnection();
            outputString = "";
            reader = new BufferedReader(new InputStreamReader(
                    urlConn.getInputStream()));
            while ((line = reader.readLine()) != null) {
                outputString += line;
            }
            System.out.println(outputString);
            
            // Convert JSON response into Pojo class
            GooglePojo data = new Gson().fromJson(outputString, GooglePojo.class);
            System.out.println(data);
            writer.close();
            reader.close();
            
        } catch (MalformedURLException e) {
            System.out.println( e);
        } catch (ProtocolException e) {
            System.out.println( e);
        } catch (IOException e) {
            System.out.println( e);
        }
        System.out.println("leaving doGet");
    }

}
Read More

Search This Blog

Loading...

Blogroll

Srinivas Dasari
find me on facebook
follow me on twitter

Follow this blog by Email

Popular Posts