Skip to main content

Google Spreadsheet API Connecting with OAuth2 JAVA Example

What is OAuth2 and things you should know before writing your source code?

OAuth, is an open protocol that aims to standardize the way desktop and web applications access a user's private data. OAuth provides a means of performing API authentication in a standard and secure fashion. As programmers, we're taught to reuse code wherever possible. OAuth will help developers reduce the amount of duplicate code they write and make it easier to create tools that work with multiple services from a variety of different providers.

Here are the terms we are using in the OAuth world.



  • OAuth dance - Unofficial term to describe the full OAuth authentication/authorization process.


  • (OAuth) Request token - An initial token that lets Google know your application is requesting access to one of the Google Data APIs. The second step of the OAuth dance is for the user to manually grant access to their data. If this step is successful, the request token becomes authorized.


  • (OAuth) Access token - The last step of the dance is to exchange the authorized request token for an access token. Once your application has this token, a user won't need to go through the OAuth dance again, unless the token is revoked.



  • (OAuth) Endpoints - These are URIs required to authenticate an application and obtain an access token. 

  •  There are three total - one for each step of the OAuth process. Google's OAuth endpoints are:
    Obtain a request token:https://www.google.com/accounts/OAuthGetRequestToken
    Authorize the request token:https://www.google.com/accounts/OAuthAuthorizeToken
    Upgrade to an access token:https://www.google.com/accounts/OAuthGetAccessToken


  • (OAuth) Service Provider In the case of the Google Data APIs, this provider is Google. In general, the service provider is used to describe the website or web service that provides the OAuth endpoints. Another example of an OAuth service provider is MySpace.



  • (OAuth) Consumer The program requesting permission to access a user's data (i.e. your application). The OAuth protocol is flexible in that it allows for a wide variety of different types of clients (web, installed, desktop, mobile).


  • How to get the required token's from google (OAuth provider) ?

    1. First you need to register your application with google api console at this url
    https://code.google.com/apis/console

    2. Create a new project for your application

    3. Create a new OAuth2 Client ID by clicking the button and giving the required information.

    4. Then click the create client ID button and that will create a Client ID and Client Secret for your application


    How to access google spreadsheet api with a JAVA program?

    Here is the complete JAVA source code with comments inside for accessing the google spreadsheet api with the token's you have received from the above step.

    package org.samples.oauth2;

    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;

    import com.google.gdata.client.GoogleService;
    import com.google.gdata.client.authn.oauth.GoogleOAuthHelper;
    import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
    import com.google.gdata.client.authn.oauth.OAuthException;
    import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;
    import com.google.gdata.client.authn.oauth.OAuthRsaSha1Signer;
    import com.google.gdata.client.authn.oauth.OAuthSigner;
    import com.google.gdata.client.spreadsheet.SpreadsheetService;
    import com.google.gdata.data.BaseEntry;
    import com.google.gdata.data.BaseFeed;
    import com.google.gdata.data.Feed;
    import com.google.gdata.util.AuthenticationException;
    import com.google.gdata.util.ServiceException;


    /**
     * 
     * @author Chanaka Fernando
     * 
     * Class implemented for accessing google spreadsheet application programming interface (API) features related to authentication
     *
     */

    public class OAuth2Sample {
      

     /**
      * Log in to Google, with the OAuth2 authentication
      * 
      * @param clientID client ID received from registering the application with Google
               * @param clientSecret client Secret received from registering the application with Google
      * @throws AuthenticationException if the service is unable to validate the
      *         oauth2 parameters.
      */
     public void loginOAuth2(String clientID, String clientSecret)
         throws AuthenticationException {

       String SCOPES = "https://docs.google.com/feeds https://spreadsheets.google.com/feeds";
       
       // STEP 1: Set up the OAuth objects

       // You first need to initialize a few OAuth-related objects.
       // GoogleOAuthParameters holds all the parameters related to OAuth.
       // OAuthSigner is responsible for signing the OAuth base string.
       GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();

       // Set your OAuth Consumer Key (which you can register at
       // https://www.google.com/accounts/ManageDomains).
       oauthParameters.setOAuthConsumerKey(clientID);

       // Initialize the OAuth Signer.  
       OAuthSigner signer = null;
       oauthParameters.setOAuthConsumerSecret(clientSecret);
       signer = new OAuthHmacSha1Signer();

       // Finally create a new GoogleOAuthHelperObject.  This is the object you
       // will use for all OAuth-related interaction.
       GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(signer);


       // STEP 2: Get the Authorization URL

       // Set the scope for this particular service.
       oauthParameters.setScope(SCOPES);

       // This method also makes a request to get the unauthorized request token,
       // and adds it to the oauthParameters object, along with the token secret
       // (if it is present).
       try {
    oauthHelper.getUnauthorizedRequestToken(oauthParameters);
    } catch (OAuthException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

       // Get the authorization url.  The user of your application must visit
       // this url in order to authorize with Google.  If you are building a
       // browser-based application, you can redirect the user to the authorization
       // url.
       String requestUrl = oauthHelper.createUserAuthorizationUrl(oauthParameters);
       System.out.println(requestUrl);
       System.out.println("Please visit the URL above to authorize your OAuth "
           + "request token.  Once that is complete, press any key to "
           + "continue...");
       try {
    System.in.read();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }


       // STEP 3: Get the Access Token

       // Once the user authorizes with Google, the request token can be exchanged
       // for a long-lived access token.  If you are building a browser-based
       // application, you should parse the incoming request token from the url and
       // set it in GoogleOAuthParameters before calling getAccessToken().
       String token = null;
    try {
    token = oauthHelper.getAccessToken(oauthParameters);
    } catch (OAuthException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
       System.out.println("OAuth Access Token: " + token);
       System.out.println();


       // STEP 4: Make an OAuth authorized request to Google

       // Initialize the variables needed to make the request
       URL feedUrl = null;
    try {
    feedUrl = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");

    } catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
       System.out.println("Sending request to " + feedUrl.toString());
       System.out.println();
       SpreadsheetService googleService =
           new SpreadsheetService("oauth-sample-app");

       // Set the OAuth credentials which were obtained from the step above.
       try {
    googleService.setOAuthCredentials(oauthParameters, signer);
    } catch (OAuthException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

       // Make the request to Google

       
       // Make a request to the API and get all spreadsheets.
       SpreadsheetFeed feed = googleService.getFeed(feedUrl, SpreadsheetFeed.class);
       List<SpreadsheetEntry> spreadsheets = feed.getEntries();
       
       System.out.println("Response Data:");
       System.out.println("=====================================================");
       if(spreadsheets != null) {
       
        // Iterate through all of the spreadsheets returned
        for (SpreadsheetEntry spreadsheet : spreadsheets) {
    //Print the name of each spreadshet
        System.out.println(spreadsheet.getTitle().getPlainText());
        }
       }

         System.out.println("=====================================================");
       System.out.println();

      


       ////////////////////////////////////////////////////////////////////////////
       // STEP 5: Revoke the OAuth token
       ////////////////////////////////////////////////////////////////////////////

       System.out.println("Revoking OAuth Token...");
       try {
    oauthHelper.revokeToken(oauthParameters);
    } catch (OAuthException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
       System.out.println("OAuth Token revoked...");
     }


    }


    With the above code you can access the Google Spreadsheet API with OAuth2 authentication mechanism with your JAVA program.

    Cheers !!!!












    Comments

    1. hey buddy does ur program executed successfully ???????

      ReplyDelete
    2. when I registered my android app (installed application) in the google console, google provides only client ID (no cient secret). how should I use this example with no client secret?

      ReplyDelete
    3. Hey dude, I have tried with your code and I am running into issues.
      What all I did is simply taken your above code and added my client ID and client secret and ran the program. I didn't change anything in the code as I really don't have any idea on connecting to Google drive through Java and also about OAuth authentication..
      Issue I am getting when I am running your code is below
      I am not able get "oauth_token" as I am getting "com.google.gdata.client.authn.oauth.OAuthException: Error getting HTTP response (response code is 400 I am getting)" exception at "oauthHelper.getUnauthorizedRequestToken(oauthParameters);"..

      Help is really appreciated.. :) :)

      ReplyDelete
      Replies
      1. hey buddy, did you find a solution as i'm having the same problem.

        Delete
      2. This comment has been removed by the author.

        Delete
    4. Replies
      1. Have you got anything that allows you to connect to Google spreadsheets using Java? (Basically same as the above but is a working solution?)

        Many thanks in advance.

        Delete
    5. Hi, the code is unable to generate a authentication url, can you please explain with example what is "scope". Thanks in advance!

      ReplyDelete
    6. This blog is so informative for providing a valuable information about send sms api java.

      ReplyDelete
    7. This comment has been removed by the author.

      ReplyDelete
    8. I can't help but express how much I adore your post! It's truly remarkable and captures my attention every time, If you're in need of a Debris removal service in Johnstown CO, Bull Elk Junk Removal LLC is here to help.

      ReplyDelete

    Post a Comment

    Popular posts from this blog

    Understanding Threads created in WSO2 ESB

    WSO2 ESB is an asynchronous high performing messaging engine which uses Java NIO technology for its internal implementations. You can find more information about the implementation details about the WSO2 ESB’s high performing http transport known as Pass-Through Transport (PTT) from the links given below. [1] http://soatutorials.blogspot.com/2015/05/understanding-wso2-esb-pass-through.html [2] http://wso2.com/library/articles/2013/12/demystifying-wso2-esb-pass-through-transport-part-i/ From this tutorial, I am going to discuss about various threads created when you start the ESB and start processing requests with that. This would help you to troubleshoot critical ESB server issues with the usage of a thread dump. You can monitor the threads created by using a monitoring tool like Jconsole or java mission control (java 1.7.40 upwards). Given below is a list of important threads and their stack traces from an active ESB server.  PassThroughHTTPSSender ( 1 Thread )

    How to configure timeouts in WSO2 ESB to get rid of client timeout errors

    WSO2 ESB has defined some configuration parameters which controls the timeout of a particular request which is going out of ESB. In a particular  scneario, your client sends a request to ESB, and then ESB sends a request to another endpoint to serve the request. CLIENT->WSO2 ESB->BACKEND The reason for clients getting timeout is that ESB timeout is larger than client's timeout. This can be solved by either increasing the timeout at client side or by decreasing the timeout in ESB side. In any of the case, you can control the timeout in ESB using the below properties. 1) Global timeout defined in synapse.properties (ESB_HOME\repository\conf\) file. This will decide the maximum time that a callback is waiting in the ESB for a response for a particular request. If ESB does not get any response from Back End, it will drop the message and clears out the call back. This is a global level parameter which affects all the endpoints configured in ESB. synapse.global_timeout_inte

    WSO2 ESB tuning performance with threads

    I have written several blog posts explaining the internal behavior of the ESB and the threads created inside ESB. With this post, I am talking about the effect of threads in the WSO2 ESB and how to tune up threads for optimal performance. You can refer [1] and [2] to understand the threads created within the ESB. [1] http://soatutorials.blogspot.com/2015/05/understanding-threads-created-in-wso2.html [2] http://wso2.com/library/articles/2012/03/importance-performance-wso2-esb-handles-nonobvious/ Within this blog post, I am discussing about the "worker threads" which are used for processing the data within the WSO2 ESB. There are 2 types of worker threads created when you start sending the requests to the server 1) Server Worker/Client Worker Threads 2) Mediator Worker (Synapse-Worker) Threads Server Worker/Client Worker Threads These set of threads will be used to process all the requests/responses coming to the ESB server. ServerWorker Threads will be used to pr