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:

[groovy] googleDrive{
redirectURL = "Redirect Url"
clientId  = "Client Id"
clientSecret= "Client Secret"
}
[/groovy]

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

[groovy]

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"

[/groovy]

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:

[groovy]

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

[/groovy]

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.

[groovy]

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

[/groovy]

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

[groovy]
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
}

[/groovy]

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.

[groovy]

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

[/groovy]

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

[groovy]

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)}"
}
}
}
[/groovy]

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 Reply

Your email address will not be published. Required fields are marked *