Grails and Google Calendar

I wanted to integrate Google Calendar into our project to allow our users to sync the appointments they make in our system with their Google Calendar.  Doing this will allow us to focus on creating the core of our site while allowing Google to make our more useful to our users.

The biggest obstacle in connecting to Google with Grails was the lack of a good resource.  I even struggled to find a good Java resource, so I knew there was no way Grails had one.

There are two parts essential to connecting to Google Calendar.  First, you need to create a connection to google using one of their APIs.  The two available are OAuth and AuthSub.  Because of the nature of how we want users connecting to Google, I choose to use AuthSub (and because it seemed to have more reasources).   The second part of the integration is using the CalendarService API.  This is fairly straight forward after getting the authentication piece working.

Getting Started

With grails, the easiest way to get any of Google’s data services is to install the google-data plugin

grails install-plugin google-data

This installs several jars that are the Java adaptation of the Google Data API.  The JavaDocs can be found here.

AuthSub

The AuthSub is pretty well documented.  I’m just going to throw out some code, and if you can’t understand it, ask.

First the Imports:

import com.google.gdata.client.*;
import com.google.gdata.client.calendar.*;
import com.google.gdata.data.*;
import com.google.gdata.data.acl.*;
import com.google.gdata.data.calendar.*;
import com.google.gdata.data.extensions.*;
import com.google.gdata.util.*;
import com.google.gdata.client.http.AuthSubUtil;

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

Now some AuthSub Code:

    //This will return a URL.  The user will have to be redirect()ed to it to get the security token
     def sendRequestURL() {
        //we don't have access for one reason or another. So re-up with google.
	String nextUrl = "http://localhost:8080/returnHandler";
	String scope = "http://www.google.com/calendar/feeds/";
	boolean secure = false;  // set secure=true to request AuthSub tokens
	boolean session = true;

	String authSubUrl = AuthSubUtil.getRequestUrl(nextUrl, scope, secure, session);
	return authSubUrl;
    }

    def returnHandler = {
    	if (params.token){
    		session['googleToken'] = getSessionToken(params.token)
	}
	redirect(action:"weHaveApproval")
    }

    //getting a session token will allow us to interact for a while
    def getSessionToken(token) {
    	return AuthSubUtil.exchangeForSessionToken(token, null);
    }

Basically, installing the plugin did all the legwork of us. We just have to assemble how to handle our situation.

Google Services

Again, the installed plugin will handle most of the work, and it is well documented.  I again will just give code, and let you experiment.

Here are couple of methods for creating a calendar and creating events for that calendar:

    def calendarUser = {
	//create the service
    	CalendarService service = new CalendarService("evodox-appointmentsDemo-v1.0");
	service.setAuthSubToken(googleToken, null);

	//Find the proper calendar
	CalendarFeed resultFeed = service.getFeed(owncalendarsFeedUrl, CalendarFeed.class);
	def calendar;
	resultFeed.getEntries().each {
		println it.getTitle().getPlainText()
		if (it.getTitle().getPlainText() == calName){
			println "matched calName"
			calendar = it;
		}
	}
	//see if we found the calendar. if not, make it.
	if (!calendar){
		calendar = createCalendar(service, calName);
	}
	//Add an event to that calendar
	jobList.each{
		if (it.nextContact > new Date()){
	  			calendar = addJobAppointment(calendar,service,it);
		}
	}
    }

    private static CalendarEntry createCalendar(CalendarService service, String title) throws IOException, ServiceException {
      // Create the calendar
      CalendarEntry calendar = new CalendarEntry();
      calendar.setTitle(new PlainTextConstruct(title));
      calendar.setSummary(new PlainTextConstruct("This calendar contains you appointments made in Evodox."));
      calendar.setHidden(HiddenProperty.FALSE);
      calendar.setColor(new ColorProperty(GREEN));

      // Insert the calendar
      return service.insert(owncalendarsFeedUrl, calendar);
    }

    private static CalendarEntry addJobAppointment(CalendarEntry calendar,CalendarService service, job) throws IOException, ServiceException {
      def list = calendar.getEditLink().getHref().split("/")
      URL postURL = new URL("http://www.google.com/calendar/feeds/" + list[list.length-1].replace("%40","@") + "/private/full");

      CalendarEventEntry myEvent = new CalendarEventEntry();
      myEvent.setTitle(new PlainTextConstruct(job.contact.toString() + " - " + job.nextAction));
      myEvent.setContent(new PlainTextConstruct("Event in evodox:n" + job.contact.toString() + " - " + job.nextAction));
      def googleFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
      DateTime startTime = DateTime.parseDateTime(googleFormat.format(job.nextContact)+ "-05:00")//DateTime.parseDateTime("2009-05-19T15:00:00-08:00");
      DateTime endTime = DateTime.parseDateTime(googleFormat.format(job.nextContact)+ "-05:00") //DateTime.parseDateTime("2009-05-19T17:00:00-08:00");
      When eventTimes = new When();
      eventTimes.setStartTime(startTime);
      eventTimes.setEndTime(endTime);
      myEvent.addTime(eventTimes);

      CalendarEventEntry insertedEntry = service.insert(postURL, myEvent);
      return calendar.update();

}

Of course , these aren’t perfect solutions, but they wil help you get started with interacting with Google Calendar, and probably some other services.

Resources:



Tags: , , , , ,
This entry was posted on Thursday, May 28th, 2009 at 7:50 am and is filed under Coding, Grails. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 Responses to “Grails and Google Calendar”

  1. TOMMY


    Pillspot.org. Canadian Health&Care.Best quality drugs.Special Internet Prices.No prescription online pharmacy. Low price pills. Order drugs online

    Buy:Valtrex.Prednisolone.Lumigan.Arimidex.Retin-A.Accutane.Petcam (Metacam) Oral Suspension.Zyban.Nexium.Prevacid.Human Growth Hormone.100% Pure Okinawan Coral Calcium.Mega Hoodia.Actos.Zovirax.Synthroid….

  2. Artificial

Leave a Reply

Your comment