Reading Google Drive Spreadsheet in Grails Application

13 / May / 2013 by paridhi 0 comments

OAuth is a secure mechanism to access google drive. In order to access google drive in your application you need to register your application at the google API console at Google API Console. Read the blog  Integrating Google plus in grails application by Vishal Sahu to see how to get client ID, client secret and redirect URL but in order to read google drive spreadsheets select Drive API in the services pane while registering your project.

Now to access your Google drive in your grails application you may save the client ID, client secret and redirect URL in Config.groovy like this:

 googleDrive{
  redirectURL = "Redirect Url"
  clientId  = "Client Id"
  clientSecret= "Client Secret"
}

Add following  dependencies in BuildConfig.groovy to import jars for accessing google documents and OAuth authorization:


compile "com.google.gdata:core:1.47.1"
compile "com.google.apis:google-api-services-drive:v2-rev72-1.14.2-beta"
compile "com.google.http-client:google-http-client-jackson:1.14.1-beta"

To access authorized user’s google drive, you need to get an authorization URL. User of the application must access this URL to authorize the application with Google and generate the authorization code. Following sample action generates the required authorization URL:


def index = {
   String clientId = grailsApplication.config.googleDrive.clientId
   String redirectURL = grailsApplication.config.googleDrive.redirectURL
   //List of scopes for which to request access
   List scopes =["https://spreadsheets.google.com/feeds", "https://docs.google.com/feeds"];
   String authorizationUrl =
   new GoogleAuthorizationCodeRequestUrl(clientId , redirectURL, scopes).build();
   redirect(url: authorizationUrl)
 }

The browser will redirect to the URL you specified in the redirectUrl parameter with the authorization code. Here is a sample redirect action which sets the authorization code in session.


def callback(String code) {
  HttpSession session = request.getSession();
  session.code = code;
  setCredential()
}

The setCredential() method generates the access token and sets its value in the session.

def setCredential() {
  HttpTransport transport = new NetHttpTransport()
  JacksonFactory jsonFactory = new JacksonFactory()
  String clientId = grailsApplication.config.googleDrive.clientId
  String clientSecret = grailsApplication.config.googleDrive.clientSecret
  String redirectUrl = grailsApplication.config.googleDrive.redirectURL
  GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest
  (transport, jsonFactory, clientId, clientSecret,session.code, redirectUrl).execute();
  GoogleCredential accessToken = new GoogleCredential.Builder()
  .setClientSecrets(clientId, clientSecret)
  .setJsonFactory(jsonFactory).setTransport(transport).build()
  .setAccessToken(response.getAccessToken()).setRefreshToken(response.getRefreshToken());
  session.accessToken = accessToken
}

Once you have the access token you may access google drive. Following code snippet returns a list of all spreadsheets. Now you can view, edit, delete and manipulate your spreadsheets using Google Spreadsheet API.


SpreadsheetService service = new SpreadsheetService("MySpreadsheetService");
service.setOAuth2Credentials(session.accessToken)
URL sheetFeedUrl = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full")
SpreadsheetFeed feed = service.getFeed(sheetFeedUrl,SpreadsheetFeed.class);
List spreadsheets = feed.getEntries()

Following is the code for reading data from first spreadsheet from the list retrieved above:


List worksheets = spreadsheets.get(0).getWorksheets();
worksheets.each{worksheet->
URL listFeedUrl = worksheet.getListFeedUrl();
ListFeed listFeed = service.getFeed(listFeedUrl, ListFeed.class);
listFeed.entries.each{row->
row.customElements.tags.each{tag->
   println "Column: ${tag} -- Value: ${row.getCustomElements().getValue(tag)}"
  }
 }
}

Helpful links:

https://code.google.com/apis/console/

https://developers.google.com/google-apps/spreadsheets/

Hope it helps!!
Paridhi Goel
paridhi@intelligrape.com

FOUND THIS USEFUL? SHARE IT

Leave a comment -