Using the Java Client Library

This document describes how to use the Java client library to send Google Data API ("GData") queries and interpret returned responses.

Google provides a set of client libraries, in a variety of programming languages, for interacting with services that have data APIs. Using these libraries, you can construct GData requests, send them to a service, and receive responses.

This document provides some general information about using the Java client library, along with a set of examples of common uses.

To use this client library, you must be running Java 1.5.

Download the Java client library.

This guide's examples refer to the Google Calendar API, but this guide is not an accurate or up-to-date guide to using the Calendar API. For information about using the Java client library with a specific service's Data API, see the service-specific documentation. For example, if you're working with Calendar, read the Calendar Data API Developer's Guide.

Contents

Audience

This document is intended for Java programmers who want to write client applications that can interact with GData services.

This document assumes that you understand the general ideas behind the Google Data APIs protocol. It also assumes that you know how to program in Java.

For reference information about the classes and methods provided by the client library, see the Java client library API reference (in Javadoc format).

This document is designed to be read in order; each example builds on earlier examples.

Data model overview

The Java client library uses a set of classes to represent the elements used by the Google Data APIs. For example, there's a Feed class, which corresponds to the <atom:feed> element; it has methods for creating an entry, getting and setting the values of various sub-elements, and so on. There's also an Entry class, which corresponds to the <atom:entry> element. Not every element defined in the Google Data APIs has its own class; for details, see the reference documentation.

The library can automatically parse Atom content and put the values of the Atom elements into appropriate objects. For example, the getFeed method gets a feed, parses it, and returns a Feed object with the resulting values.

To send a feed or entry to a service, you create a Feed or Entry object, then call a library method (such as the insert method) to automatically translate the object into XML and send it.

You can parse and/or generate XML yourself if you prefer; the easiest way to do that is with an appropriate third-party library such as Rome.

Just as the Google Data API's XML syntax is extensible, the corresponding object model is extensible. For example, the client library provides classes corresponding to the elements defined in the Google Data namespace.

Tutorial and examples

The following examples show how to send various data API requests using the Java client library.

To make them more concrete, these examples show how to interact with a specific service: Google Calendar. We'll point out places where Calendar differs from other Google services, to help you adapt these examples for use with other services. For more information about Calendar, see the Google Calendar Data API documentation.

Building and running your client

To compile the examples in this document, you'll need to use the following import statements:

import com.google.gdata.client.*;
import com.google.gdata.client.calendar.*;
import com.google.gdata.data.*;
import com.google.gdata.data.extensions.*;
import com.google.gdata.util.*;
import java.net.URL;

Requesting a feed

As described in the Google Calendar Data API document, you can request a Calendar feed by sending the following HTTP request to Calendar:

GET http://www.google.com/calendar/feeds/userID/private/full

Of course, you have to replace userID with the user's email address; see the Calendar document for details. You can, instead, use the special default URL for interacting with Calendar (as described in the Calendar document), but in this document we'll use the private full feed URL, which contains the user ID.

You also have to provide appropriate authentication. The main differences between this example and the first example in the Calendar document are that (1) this example includes authentication, and (2) this example uses the more general GoogleService class rather than the Calendar-specific CalendarService class.

Note that the authentication system we're using here (known as "Google Authentication for Installed Applications") is appropriate only for use in installed client applications such as desktop clients, not for use in web applications. For more information about authentication, see the Google Account Authentication documentation.

To request a Calendar feed using the Java client library, for a user with email address "liz@gmail.com" and password "mypassword", use the following code:

// Set up the URL and the object that will handle the connection:
URL feedUrl = new URL("http://www.google.com/calendar/feeds/liz@gmail.com/private/full");
GoogleService myService = new GoogleService("cl", "exampleCo-exampleApp-1");
myService.setUserCredentials("liz@gmail.com", "mypassword");

// Mark the feed as an Event feed:
new EventFeed().declareExtensions(myService.getExtensionProfile());

// Send the request and receive the response:
Feed myFeed = myService.getFeed(feedUrl, Feed.class);

The GoogleService class represents a client connection (with authentication) to a GData service. The general procedure for sending a query to a service using the client library consists of the following steps:

  1. Obtain or construct the appropriate URL.
  2. If you're sending data to a service (for example, if you're inserting a new entry), then transform the raw data into objects using the client library classes. (This step doesn't apply if you're just requesting a feed, as we're doing in this example.)
  3. Create a new GoogleService instance, setting the service name (such as "cl" for Calendar) and your application's name (in the form companyName-applicationName-versionID).
  4. Set the appropriate credentials.
  5. Indicate to the client library what extensions the feed will use, so that the library can parse returned feeds correctly.
  6. Call a method to send the request and receive any results.

The setUserCredentials method specifies the ID and password of the user on whose behalf your client is sending the query. The examples in this document use the "Authentication for Installed Applications" authentication system; for more information about authentication systems, see the Google Account Authentication documentation.

After setting credentials, you indicate which extensions the feed will use by calling the declareExtensions method. In this case, we're saying that the feed is an Event feed, and thus that it will use the extensions defined by the Event kind.

To request an entire feed, you call the getFeed method, which takes a URL and returns the entire feed found at that URL. We'll show how to send more specific queries later in this document.

Like other methods of the GoogleService class, getFeed handles authentication and redirects as necessary.

Inserting a new item

To create a new calendar event, you might use the following code:

URL postUrl =
  new URL("http://www.google.com/calendar/feeds/liz@gmail.com/private/full");
EventEntry myEntry = new EventEntry();

myEntry.setTitle(new PlainTextConstruct("Tennis with Darcy"));
myEntry.setContent(new PlainTextConstruct("Meet for a quick lesson."));

Person author = new Person("Elizabeth Bennet", null, "liz@gmail.com");
myEntry.getAuthors().add(author);

DateTime startTime = DateTime.parseDateTime("2006-04-17T15:00:00-08:00");
DateTime endTime = DateTime.parseDateTime("2006-04-17T17:00:00-08:00");
When eventTimes = new When();
eventTimes.setStartTime(startTime);
eventTimes.setEndTime(endTime);
myEntry.addTime(eventTimes);

// Send the request and receive the response:
EventEntry insertedEntry = myService.insert(postUrl, myEntry);

After setting the URL, we construct an EventEntry object; EventEntry is derived from the abstract base class BaseEntry, which is also the parent class for the Entry class, which represents an <atom:entry> element.

The EventEntry class represents an Event kind; for more information, see the Kinds document. For services other than Calendar, you might assign the returned entry to an Entry object rather than an EventEntry object.

The entry title is a TextConstruct, a class that holds text in various forms (plain text, HTML, or XHTML). The entry content is represented by a Content object, a class that can hold either plain text or other forms of content, including XML and binary data. (But the setContent method can also accept a TextConstruct.)

Each author is represented as a name, a URI, and an email address. (In this example, we're leaving out the URI.) You add an author to an entry by calling the entry's getAuthors().add method.

We're using the same GoogleService object that we created in the previous example. In this case, the method to call is insert, which sends an item to the specified insertion URL.

The service returns the newly created entry, which may contain additional server-generated elements, such as an edit URL for the entry.

HTTP status codes are returned as exceptions.

The above code is equivalent to sending POST http://www.google.com/calendar/feeds/liz@gmail.com/private/full (with proper authentication) and providing an entry in the form of an Event kind.

Requesting a specific entry

The following code lets you request the specific entry that you inserted in the previous example.

In the context of this series of examples, retrieving that entry isn't really necessary, because Calendar already returned the inserted entry; but the same technique can be applied whenever you know the URI for an entry.

URL entryUrl = new URL(insertedEntry.getSelfLink().getHref());
EventEntry retrievedEntry = myService.getEntry(entryUrl, EventEntry.class);

The inserted entry has a method, getSelfLink, that returns a Link object that includes the entry's URL. The Link class has a getHref method that returns the URL as a String, from which we can create a URL object.

Then we just have to call the service's getEntry method to get the entry.

Note that we give EventEntry.class as a parameter to getEntry, indicating that we're specifically expecting the service to return an Event rather than just a plain entry. For services other than Calendar, you might just pass Entry.class instead.

The above code is equivalent to sending GET http://www.google.com/calendar/feeds/liz@gmail.com/private/full/entryID to Calendar, with proper authentication.

Searching entries

To retrieve the first match from a full-text search, use the following code:

Query myQuery = new Query(feedUrl);
myQuery.setFullTextQuery("Tennis");
Feed myResultsFeed = myService.query(myQuery, Feed.class);
if (myResultsFeed.getEntries().size() > 0) {
  Entry firstMatchEntry = myResultsFeed.getEntries().get(0);
  String myEntryTitle = firstMatchEntry.getTitle().getPlainText();
}

This example starts by constructing a Query object, which consists mostly of a URL plus associated query parameters. Each of the standard GData query parameters has a setter method. You can also set custom query parameters for a particular service, using the addCustomParameter method.

After constructing the Query, we pass it to the service's query method, which returns a feed containing the query results. An alternative approach would be to construct a URL yourself (by appending query parameters to the feed URL) and then call the getFeed method, but the query method provides a useful layer of abstraction so that you don't have to construct the URL yourself.

The feed's getEntries method returns a list of the entries in the feed; getEntries().size returns the number of entries in the feed.

In this case, if the query returned any results, we assign the first matching result to an Entry object. Then we use the Entry class's getTitle().getPlainText method to retrieve the entry's title and convert it to text.

The above code is equivalent to sending GET http://www.google.com/calendar/feeds/liz@gmail.com/private/full?q=Tennis to Calendar.

Querying by category

Note: Google Calendar doesn't associate labels with events, so this example doesn't work with Calendar.

To retrieve a feed consisting of all the entries that match the earlier full-text search and that are in a particular category or have a particular label, use the following code:

Category myCategory = new Category("by_liz");
CategoryFilter myCategoryFilter = new CategoryFilter(myCategory);
myQuery.addCategoryFilter(myCategoryFilter);
Feed myCategoryResultsFeed = myService.query(myQuery, Feed.class);

The Category class, of course, represents a category to be used in a category filter. The Query.CategoryFilter class can contain multiple categories, but in this case we're constructing a filter with only one category.

Then we add that filter to the existing query, which still contains the full-text query string from the previous example.

We again use the query method to send the query to the service.

If Calendar allowed a category search, the above code would be equivalent to sending GET http://www.google.com/calendar/feeds/liz@gmail.com/private/full/-/by_liz?q=Tennis to Calendar.

Updating an item

To update an existing item, use the following code. In this example, we're changing the title of the previously retrieved entry from its old text ("Tennis with Darcy") to "Important meeting."

retrievedEntry.setTitle(new PlainTextConstruct("Important meeting"));
URL editUrl = new URL(retrievedEntry.getEditLink().getHref());
EventEntry updatedEntry = myService.update(editUrl, myEntry);

First we set a new title for the entry we fetched earlier. Then we get the edit URL for the entry, using the getEditLink method. Then we call the service's update method to send the updated entry.

The service returns the updated entry, including a new URL for this entry's new version. (For more information on entry versions, see the Optimistic concurrency section of the protocol reference document.)

The above code is roughly equivalent to sending PUT http://www.google.com/calendar/feeds/liz@gmail.com/private/full/entryID to the service, along with the new entry (in Atom format) to replace the original entry.

Deleting an item

To delete the updated entry, use the following code:

URL deleteUrl = new URL(updatedEntry.getEditLink().getHref());
myService.delete(deleteUrl);

The URL to use for deletion is the same as the edit URL, so this example is very similar to the previous one, except of course that we're calling the delete method instead of update.

The above code is roughly equivalent to sending DELETE http://www.google.com/calendar/feeds/liz@gmail.com/private/full/entryID to the service.

Reference

For reference information about the classes and methods provided by the client library, see the Java client library API reference (in Javadoc format).

Back to top