Contents

Audience

This document is intended for Apex Developers who want to write Force.com Apps that can interact with Google's Calendar.

This document assumes that you understand the general ideas behind the Google Data APIs protocol.

For additional Google Calendar Data API reference information, see the Google Calendar Data API Reference Guide.

Getting started

Set up your Force.com Development environment.

The Force.com platform is the most scalable, secure and popular on-demand platform in the world today. You can develop and instantaneously deploy applications without any infrastructure - 100% on-demand

Install the latest version of the Force.com IDE

The Force.com IDE allows developers a full-featured, Eclipse-based coding environment, with capabilities like code completion, version control,collaborative development, and project sharing.

Create a Google Account

Google Contacts are associated with Google Accounts, so a Google Account will be required in order to proceed. To view your contacts without using the Contacts Data API, you can log in to Gmail and click the Contacts link.

Check out the source code

Check out the Force.com Toolkit for Google Data APIs from the Google repository.

Apex Code Examples

The following examples show how to send Google Calendar Data API requests from Apex Code.

Authenticating to the Calendar service

Create the Apex object that will handle the connection to Google Calendars. This via AuthSub proxy authentication.

CalendarService service = new CalendarService();  
service.setAuthSubToken(sessionAuthToken); 

Retrieving calendar lists

The Calendar data API provides several ways to access the list of calendars that appear in the Google Calendar web application. There are three types of calendars in this list: primary, secondary, and imported calendars. A primary calendar is created for a user when they sign up for a Google Calendar account. All other calendars created by that user are called secondary calendars. Imported calendars are calendars that a user subscribes to that someone else has created.

Retrieving all calendars

The result of this request is a feed that includes all primary, secondary, and imported calendars.

GoogleData feed = service.getAllCalendarsFeed();

Retrieving only calendars that a user owns

You can get use the "owncalendars" feed to retrieve the list of calendars that the authenticated user has owner access to.

GoogleData feed = service.getFeed( CalendarService.ownCalendars );       
list<GoogleData.Calendar> cals = GoogleData.calendarFactory(feed.entries); 

Querying this feed will return a list of calendars that includes the user's primary and secondary calendars, as well as any imported calendars for which the user has been granted ownership.


Managing calendars

The owncalendars feed can also be used to create, update, and delete calendars. Calendars created through the owncalendars feed will be secondary calendars.

Creating new calendars

To create a new calendar, first instantiate a CalendarEntry object and set the appropriate values. Then call the CalendarService.insert method, specifying the owncalendars feed.

 	GoogleData.Calendar cal = 
               GoogleData.createCalendarEntry('test cal','summary for cal');
 	// here you can set the gCal:timezone, gd:where etc.. 
 		
 	xmldom.element newcal = service.insertCalendar( cal );
 	newcal.dumpall();  

Updating existing calendars

You can update most information about a user's calendar via the owncalendars feed. The following example updates the title and color of the first calendar retrieved from the owncalendars feed.

 	GoogleData.Calendar gcal = service.getCalendarByTitle('test');
 	gcal.dump();
 		
 	gcal.entry.getElementByTagName('gCal:color').attributes.put('value','#0D7813');
     	gcal.entry.getElementByTagName('gCal:selected').attributes.put('value','true');
    
    	system.debug( gcal.toXmlString() );
     	service.makePutRequest(gcal.edit, gcal.toXmlString()); 

Deleting calendars

To delete a calendar, simply call the remove method. The following example creates a new calendar, then deletes the calendar just created:


	xmldom.element newcal = service.insertCalendar( cal );
 	newcal.dumpall();  
 	// now delete it
 	service.remove(newcal);


Retrieving events

Retrieving events without query parameters

To view all events on your calendar, use the following Apex code. Note: May return a large list!

GoogleData.Calendar cal = service.getCalendarByTitle('MyCalendar');
GoogleData evs = service.getFeed( cal.alternate ); 

Retrieving events for a specified date range

To view events on your calendar that overlap a particular date range, use the following Apex code.

GoogleData.Calendar cal = service.getCalendarByTitle('MyCalendar');
GoogleData evs_range = service.getEventsRange( cal,
                        system.now().addDays(-1), 
                        system.now().addDays(+1) );

Retrieving events matching a full text query

To retrieve the first match in a full-text search, use the following code: Note: query string matches anywhere in the calendar entry

GoogleData.Calendar cal = service.getCalendarByTitle('MyCalendar');
string query = EncodingUtil.urlEncode('Tour de Force','UTF-8' ); 
GoogleData cal = service.getFeed( CalendarService.defaultFeed + '?q=' + query );  

Creating events

The Calendar data API allows you to create two types of events: single-occurrence events and recurring events, which are set up to repeat on a predetermined schedule.

Creating single-occurrence events

To insert a single-occurrence event into a Calendar feed, you might use the following code:

GoogleData.Calendar cal = service.getCalendarByTitle('MyCalendar');
event newEvent = new Event(
subject = 'Tennis with Beth',
description = 'Meet for a quick lesson.',
ActivityDateTime = system.now(),
DurationInMinutes = 60
);

Now insert the new event using the GoogleData.Calendar service:

xmldom.element entry = service.insertEvent( cal, newEvent );  
entry.dumpAll();  

Updating events

To update an existing item, use the following code.

GoogleData.Calendar cal = service.getCalendarByTitle('MyCalendar');
system.debug(cal);
GoogleData evs_range = service.getEventsRange( cal,
system.now().addDays(-1), system.now().addDays(+1) 
    ); 
if ( evs_range.entries.size() > 0 ) { 
	  xmldom.element upd = evs_range.entries[0]; // just update one
	  upd.getElementByTagName('title').nodeValue = 'Tennis with Bill';
	  service.updateEvent( upd ); 
     } 
      else { 
      System.debug(' no events found to update ');
     }
}

Deleting events

This example lists entries for yesterday, then delete the first entry found:

GoogleData.Calendar cal = service.getCalendarByTitle('MyCalendar');
GoogleData evs_range = service.getEventsRange( cal,
system.now().addDays(-1), system.now() ); 
    
// remove(0) takes the first entry off the apex array 
xmldom.element del = evs_range.entries.remove(0);

// removeEvent() tells Google to remove this event
service.removeEvent( del );

Performing multiple operations with a batch request

If you're performing a lot of operations, the time it takes to send and and receive all those requests can really add up, making your app slow and unresponsive. With batch requests you can have the server perform multiple operations with a single request. The basic idea is that you create a CalendarEventFeed object and add an entry for each operation you want to perform. The following code snippet builds and submits a batch request that inserts two events with one call to google data api, passing a list of Events:

list<Event> evtList = new list<Event>();
 		
evtList.add(  new Event(
	subject = 'Tennis with Jill',
	description = 'Meet for a quick lesson.',
	ActivityDateTime = system.now(),
	DurationInMinutes = 60
	) );
evtList.add(  new Event(
	subject = 'Tennis with Debbie',
	description = 'Meet for a quick lesson.',
	ActivityDateTime = system.now().addHours(1),
	DurationInMinutes = 60
	) );

// insert events and dump the response 
xmldom.element entry = service.insertEvents( cal, evtList );  
entry.dumpAll();  

The dumpAll() method will print out the tree of an xmldom Entry, the output goes to the system log window.

When working with batch requests, the size of the request must be under a 100K and it's best to limit batches to ~ 25 events at a time.

You can find more information about batch operations in the Google Data Batch Processing documentation.

Related Content