Access google plus profile information in Java

3 views
Skip to first unread message

Hemant via StackOverflow

unread,
Oct 5, 2014, 5:08:36 PM10/5/14
to google-appengin...@googlegroups.com

I am new to Google App Engine programming but know Java well. I have been trying to access calendar list of a user. I have to go though OAuth 2.0. I tried following the documentation available on Google but stuck at one point for some days. Here are number of steps that I followed : 1. I created index.html which includes all javasripts required for OAuth 2.0. Here is my index.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
  </script>
<script type="text/javascript">
    (function () {
      var po = document.createElement('script');
      po.type = 'text/javascript';
      po.async = true;
      po.src = 'https://plus.google.com/js/client:plusone.js?onload=start';
      var s = document.getElementsByTagName('script')[0];
      s.parentNode.insertBefore(po, s);
    })();
  </script>

<script type="text/javascript">
function signInCallback(authResult) {
    alert("inside signInCallback");
  if (authResult['code']) {
    alert("authorized " + authResult['code']);
    // Hide the sign-in button now that the user is authorized, for example:
    $('#signinButton').attr('style', 'display: none');

    gapi.client.load('plus','v1', function(){ 
        // once we get this call back, gapi.client.plus.* will exist
        });
    // Send the code to the server
    $.ajax({
      type: 'POST',
      url: '/oauth2callback',
      contentType: 'application/octet-stream; charset=utf-8',
      success: function(result) {
        // Handle or verify the server response if necessary.
        // Prints the list of people that the user has allowed the app to know
        // to the console.
        console.log(result);
        if (result['profile'] && result['people']){
          $('#results').html('Hello ' + result['profile']['displayName'] + '. You successfully made a server side call to people.get and people.list');
        } else {
          $('#results').html('Failed to make a server-side call. Check your configuration and console.');
        }
      },
      processData: false,
      data: authResult['code']
    });
  } else if (authResult['error']) {
    // There was an error.
    // Possible error codes:
    //   "access_denied" - User denied access to your app
    //   "immediate_failed" - Could not automatially log in the user
     console.log('There was an error: ' + authResult['error']);
  }
}
</script>

<title>Hello App Engine</title>
</head>

<body>
    <h1>Hello App Engine!</h1>

    <table>
        <tr>
            <td colspan="2" style="font-weight: bold;">Available Servlets:</td>
        </tr>
        <tr>
            <td><li><a href="googlecalenderapiofc2">GoogleCalenderApiOfc2</a></li></td>
        </tr>
        <tr>
            <td><li><a href="googlecalenderapiservlet">GoogleCalenderApiServlet</a></li></td>
        </tr>
        <tr>
            <td><li><a href="plussampleservlet">OAuth2 Example (Two Servlets)</a></li></td>
        </tr>

        <tr>
            <!-- Add where you want your sign-in button to render -->
            <div id="signinButton">
                <span class="g-signin"
                    data-scope="https://www.googleapis.com/auth/plus.login"
                    data-clientid="323051610551-gfdn6puahf69f2vad9cpfjdfp9k3l8a7.apps.googleusercontent.com"
                    data-redirecturi="postmessage" data-accesstype="offline"
                    data-cookiepolicy="single_host_origin"
                    data-callback="signInCallback"> </span>
            </div>
            <div id="result"></div>
        </tr>
    </table>
</body>
</html>

My Java File:

package com.max.google.calender;

import java.io.IOException;
import java.io.Writer;
import java.util.logging.Logger;

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

import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.appengine.auth.oauth2.AbstractAppEngineAuthorizationCodeCallbackServlet;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * HTTP servlet to process access granted from user.
 * 
 */
public class OAuth2Callback extends AbstractAppEngineAuthorizationCodeCallbackServlet {

  private static final long serialVersionUID = 1L;
  private static final Logger logger = Logger.getLogger(OAuth2Callback.class.getName().toString());

  @Override
  protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException ,ServletException {
      logger.info("Hemant in service method.");
      super.service(req, resp);
  }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException, ServletException {
        logger.info("HEmant doPost().");
         String gPlusId = req.getParameter("gplus_id");

        resp.setContentType("text/html");
        resp.setStatus(200);
        Writer writer = resp.getWriter();
        writer.write("<ul>");
        writer.write("Hemant");
        writer.write("</ul>");
//      resp.sendRedirect("http://www.maxsolution.pro/");
    }

  @Override
  protected void onSuccess(HttpServletRequest req, HttpServletResponse resp, Credential credential)
      throws ServletException, IOException {
      logger.info("HEmant success.");
      resp.sendRedirect("/");
  }

  @Override
  protected void onError(
      HttpServletRequest req, HttpServletResponse resp, AuthorizationCodeResponseUrl errorResponse)
      throws ServletException, IOException {
      logger.info("HEmant in error");
    String nickname = UserServiceFactory.getUserService().getCurrentUser().getNickname();
    resp.getWriter().print("<h3>" + nickname + ", why don't you want to play with me?</h1>");
    resp.setStatus(200);
    resp.addHeader("Content-Type", "text/html");
  }

  @Override
  protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException {
      logger.info("HEmant in getRedirectUri()");
    return Utils.getRedirectUri(req);
  }

  @Override
  protected AuthorizationCodeFlow initializeFlow() throws IOException {
      logger.info("HEmant in initializeFlow()");
    return Utils.newFlow();
  }
}

Web.xml

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
    <servlet>
        <servlet-name>GoogleCalenderApiOfc2</servlet-name>
        <servlet-class>com.max.google.calender.GoogleCalenderApiOfc2Servlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>GoogleCalenderApiOfc2</servlet-name>
        <url-pattern>/googlecalenderapiofc2</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>GoogleCalenderApiServlet</servlet-name>
        <servlet-class>com.max.google.calender.GoogleCalenderApiServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>GoogleCalenderApiServlet</servlet-name>
        <url-pattern>/googlecalenderapiservlet</url-pattern>
    </servlet-mapping>


      <servlet>
    <servlet-name>PlusSampleServlet</servlet-name>
    <servlet-class>com.max.google.calender.PlusSampleServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>PlusSampleServlet</servlet-name>
    <url-pattern>/plussampleservlet</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>OAuth2Callback</servlet-name>
    <servlet-class>com.max.google.calender.OAuth2Callback</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>OAuth2Callback</servlet-name>
    <url-pattern>/oauth2callback</url-pattern>
  </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>
  1. I get the authResult back and then i call /oauth2callback to exchange this code with token. Now, I need java side code to convert this code to token. Secondly, how am i supposed to send this token back to index.html ? Third, shall i then submit this page again to show Calendar list or is there any good way of doing it ?

Any help is deeply appreciated ..

Thanks,
Hemant



Please DO NOT REPLY directly to this email but go to StackOverflow:
http://stackoverflow.com/questions/26207190/access-google-plus-profile-information-in-java
Reply all
Reply to author
Forward
0 new messages