Getting Started with the Google Data Java Client LibraryStay organized with collectionsSave and categorize content based on your preferences.
Page Summary
This article provides step-by-step instructions for downloading and installing the Google Data APIs (GData) Java Client Library.
It details the necessary external dependencies, including JDK, Apache Ant, JavaMail API, JavaBeans Activation Framework, and Servlet API, and how to install them on Windows, Mac OS X, and Linux.
Instructions are provided for installing the GData Java Client Library, including downloading the library and samples and configuring the build properties file.
The article explains how to run the included sample applications using Ant and provides a basic "Hello, World!" equivalent program to demonstrate building your own applications with the library.
Troubleshooting tips and links to additional resources like developer guides and forums are included to assist with the development process.
Stephanie Liu, Google Data APIs Team September 2007
It's never easy to start developing with an unfamiliar API, so this article has step-by-step instructions on how to download and install the Google Data APIs ("GData") Java Client Library. I'll go through getting all of the dependencies and setting the environment variables you'll need. You'll be mashing up different GData services in no time!
The GData Java Client Library has the following external dependencies. The following sections will describe how to install these dependencies on your favorite operating system (or the OS that you're stuck with at work).
JDK (Java Development Kit) version 1.5+
Apache Ant version 1.7+
mail.jar in Sun's JavaMail API 1.4+
activation.jar in Sun's JavaBeansActivationFramework. This is only required for media specific APIs including Document List Data API, Picasa Web Album API, and YouTube Data API.
servlet.jar in Sun's Servlet API version 2.3+. This is required only if executing code samples in 'sample.authsub' or 'sample.gbase.recipe' packages.
A few of the.jardependencies are only required for specific samples, but to avoid build errors, it's best just to get everything. Choose your operating system of choice to continue:Windows,Mac OS X, orLinux.
On Windows
Instructions for the Windows operating system.
Installing Java
The Java development package is available from Sun in the form of the JDK (Java Development Kit). The JRE (Java Runtime Environment) and everything else you need to write, compile, test, and debug Java applications are contained within. If you already have Java installed, skip ahead toinstalling Ant.
Note:You need to have administrative permissions to install the JDK.
Edit thePathenvironment variable to easily run JDK executables likejavac. The path you'll want to add will look something likeC:\jdk\bin\. See theAppendixfor instructions on how to edit thePathvariable in Windows.
Apache Antis a build tool for Java similar tomake(but better). You'll be using it to build the library and execute samples. If you already have Ant installed, check that it's version 1.7 or higher.
Click the "Start" menu, and then "Run."
Typecmdinto the text field.
Typeant -versioninto the prompt to see which version you have.
If you have 1.7+, skip ahead togettingmail.jar. If your version of Ant is lower than 1.7 or you don't have it installed, follow the steps below.
Click the link for the.zipfile containing the Activation Framework.
Extract the files to your computer and note the location.activation.jarwill be under the root directory,jaf-(version)
Getting servlet.jar
servlet.jar(it may be calledservlet-api.jar) can be found in your servlet container (J2EE, Tomcat, WebLogic, etc.). It is used for the AuthSub and Google Base samples. The following instructions go through getting Tomcat 6.x.
If you're running Mac OS X, you have less work to do! Apple has included a fully configured and ready-to-use JDK (Java Development Kit) with every instance. Check out Apple'sJava sitefor more information.
Installing Ant
Apache Antis a build tool for Java similar tomake(but better). You'll be using it to build the library and execute samples. You probably already have Ant installed as well, but check that you have version 1.7+.
Open a terminal window. (Command + Space bar, then type 'Terminal' to find the application)
At the command prompt, type:
ant -version
If the version of ant you are running is less than 1.7, follow the steps below to get the latest version.
You can finddetailed installation instructionsat Ant's website if you run into any issues. Thisblog postalso has a detailed explanation of what the above shell commands mean.
Click the link for the.zipfile containing the Activation Framework.
Extract the files to your computer and note the location.activation.jarwill be under the root directory,jaf-(version)
Getting servlet.jar
servlet.jar(it may be calledservlet-api.jar) can be found in your servlet container (J2EE, Tomcat, WebLogic, etc.). It is used for the AuthSub and Google Base samples. The following instructions go through getting Tomcat 6.x.
This tutorial will use Sun's JDK (Java Development Kit). If you have root access, please follow the instructions below. If not, you can just install the JDK in your home directory by followingthese instructions. If you already have the JDK 1.5+ installed, skip ahead toInstalling Ant.
Click and download the self extracting build (not RPM) under "Linux Platform."
Open a terminal window, change to the directory where you downloaded the file, and type the following commands:
chmod +x jdk-6(version)-linux-i586-rpm.bin
Change to the directory where you want to file to be installed.
Run the self extracting binary. If you're installing it in the current directory, then you would just type./jdk-6(version)-linux-i586-rpm.bin
Agree to the license agreement.
If you run into trouble, more detailed installation instructions can be foundhere.
Installing Ant
The GData Java Client Library requires Ant 1.7 or above. If you already have Ant installed, check the version by typingant -versionat a command prompt. If you need to get the latest version, or if you don't have it installed, follow the instructions below. Skip ahead togettingmail.jarif your Java and Ant installations are already set up.
Click the link for the.zipfile containing the Activation Framework.
unzipthe files to your computer and note the location.activation.jarwill be under the root directory,jaf-(version)
Getting servlet.jar
servlet.jar(it may be calledservlet-api.jar) can be found in your servlet container (J2EE, Tomcat, WebLogic, etc.). It is used for the AuthSub and Google Base samples. The following instructions go through getting Tomcat 6.x.
All of the available samples are located undergdata/java/samplefrom thegdata-samples.java-1.x.x.java.ziparchive. Thegdata/java/build-samples/build.propertiesfile contains all the input values for the samples contained in the library. Setsample.credentials.usernameandsample.credentials.passwordto a valid username and password. We can use Ant to build as well as execute the samples.
Test to see if you've installed everything correctly by opening a command prompt, changing to thegdata/javadirectory, and typing:
ant -f build-samples.xml sample.calendar.run
You may receive some info or warning messages, but just look for theBUILD SUCCESSFULmessage at the end! See thetroubleshooting sectionif you don't get a success message.
Try out a more interactive sample by typing:
ant -f build-samples.xml sample.spreadsheet.guidemo.run
To find out how to run a particular sample, go togdata/java/build-samplesand check the build file for that sample. Look for thesamples runsection.
Troubleshooting
If your build fails with an error message like,
BUILD FAILED
Target 'core.sample.core.util.build' does not exist in this project. It is used from target 'sample.calendar.build'.
Total time: 0 seconds
or a similar error message about an essential file missing from the project, you may be running an older version of Ant. Typeant -versionto make sure you're running 1.7 or higher. Refer to thedependencyinstructions above to get the latest version of Ant.
Building Your Own Applications
The next question is how to build your own application. I'll go through a "Hello, World!" equivalent program using the Calendar service to exhibit basic functionality. More detailed information can be found in the Java Client Library'sdeveloper guide, as well as the individual productdeveloper guides.
Create a file called CalendarTest.java. Start by including the following import statements.
Here is the whole program (without any exception handling).
public class CalendarTest {
public static void main(String[] args) {
CalendarService myService = new CalendarService("exampleCo-exampleApp-1.0");
myService.setUserCredentials("root@gmail.com", "pa$$word");
URL feedUrl = new URL("http://www.google.com/calendar/feeds/default/allcalendars/full");
CalendarFeed resultFeed = myService.getFeed(feedUrl, CalendarFeed.class);
System.out.println("Your calendars:");
System.out.println();
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
CalendarEntry entry = resultFeed.getEntries().get(i);
System.out.println("\t" + entry.getTitle().getPlainText());
}
}
}
This little program will request all the calendars you own and display all the titles. It's a little longer than the canonical "Hello, World!" example, but it's very simple once we break it down. The first couple of lines creates a service object and sets the user credentials.
CalendarService myService = new CalendarService("exampleCo-exampleApp-1.0");
myService.setUserCredentials("root@gmail.com", "pa$$word");
Then, the URL of the resource is set. In this case, this is where you can request the list of all calendars from the authenticated user.
URL feedUrl = new URL("http://www.google.com/calendar/feeds/default/allcalendars/full");
The line below will execute the actualGETcommand on the URL and put the resultant feed into a tidy object.
Theforloop below will iterate through each entry and print the title. Note that the title is stored as aTextConstruct, so an extra function call is required to get the plain text.
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
CalendarEntry entry = resultFeed.getEntries().get(i);
System.out.println("\t" + entry.getTitle().getPlainText());
}
That was pretty basic - let's go through a few other common things. The following snippet will show you how to create an object and insert it. For our example, it will be a new calendar event entry.
URL postURL = new URL("http://www.google.com/calendar/feeds/root@gmail.com/private/full");
CalendarEventEntry myEvent = new CalendarEventEntry();
//Set the title and description
myEvent.setTitle(new PlainTextConstruct("Pi Day Party"));
myEvent.setContent(new PlainTextConstruct("I am throwing a Pi Day Party!"));
//Create DateTime events and create a When object to hold them, then add
//the When event to the event
DateTime startTime = DateTime.parseDateTime("2007-03-14T15:00:00-08:00");
DateTime endTime = DateTime.parseDateTime("2007-03-14T17:00:00-08:00");
When eventTimes = new When();
eventTimes.setStartTime(startTime);
eventTimes.setEndTime(endTime);
myEvent.addTime(eventTimes);
// POST the request and receive the response:
CalendarEventEntry insertedEntry = myService.insert(postURL, myEvent);
Another common operation is building a query.
//Create a new query object and set the parameters
Query myQuery = new Query(feedURL);
myQuery.setFullTextQuery("Pi");
//Send the request with the built query URL
CalendarEventFeed myResultsFeed = myService.query(myQuery, CalendarEventFeed.class);
//Take the first match and print the title
if (myResultsFeed.getEntries().size() > 0) {
CalendarEventEntry firstMatchEntry = new CalendarEventEntry();
myResultsFeed.getEntries().get(0);
System.out.println(firstMatchEntry.getTitle().getPlainText());
}
While debugging, another useful operation is dumping out the raw XML. There's a handy utility that you can use to do this in the library. Make suresamples.util.*is imported. Then, dump the feed or entry.
This should give you a feel for what building apps using the client library is like. For more detailed information, see theconclusion sectionfor a list
of available developer guides for each Google Data API.
Conclusion
Hopefully, you're now able to build and run applications using the GData Java Client Library! I didn't go into any of the popular IDEs that you can use, but you may want to look into popular tools likeEclipseorNetBeans. Here are some additional links that may be helpful:
If you have any questions on using Java Client Library with any API, you can let us know by posting in the API specificforums.
Appendix: Setting Environment Variables
Instructions for setting your environment variables on Windows or Linux. You should not have to set anything for Mac OS X.
Windows
System variables will apply to all users on the computer. If you can't edit system variables because you don't have administrative privileges, follow the instructionshere.
If you have administrative privileges:
Right click "My Computer" and select "Properties."
Click the "Advanced" tab.
Click on "Environment Variables."
"Add" or "Edit" system variables: (substitute the location on your local machine)
Add or EditANT_HOMEand set the value toC:\ant
Add or EditJAVA_HOMEand set the value toC:\jdk
Add or EditPathand append;C:\ant\bin;C:\jdk\binto the end (the semicolon separates directory paths)
Add or EditCLASSPATHand append the.jarfiles you'll need, depending on which services you want to work with. Make sure the "." is included &mhash; this indicates the current directory..;C:\gdata\java\lib\gdata-core-1.0.jar;C:\gdata\java\lib\gdata-calendar-1.0.jar, etc.
Reboot to make sure they take effect.
Note:Ensure that the variables do not have quotes (either ' or ") and do not end with \ or /.
If you don't have administrative privileges:
Right click "My Computer" and select "Properties."
Click the "Advanced" tab.
Click on "Environment Variables."
"Add" or "Edit" user variables: (substitute the location on your local machine)
Add or EditANT_HOMEand set the value toC:\ant
Add or EditJAVA_HOMEand set the value toC:\jdk
Add or EditPathand append;C:\ant\bin;C:\jdk\binto the end (the semicolon separates directory paths)
Add or EditCLASSPATHand append the.jarfiles you'll need, depending on which services you want to work with. Make sure the "." is included &mhash; this indicates the current directory..;C:\gdata\java\lib\gdata-core-1.0.jar;C:\gdata\java\lib\gdata-calendar-1.0.jar, etc.
Reboot to make sure they take effect.
Note:Ensure that the variables do not have quotes (either ' or ") and do not end with \ or /.
The user variables you have just edited will only apply to your user profile.
Linux
Open your.bash_profilefile in your editor of choice, located in your home directory.
Add the following to your.bash_profile, substituting the actual locations of the files on your machine:
export ANT_HOME=/usr/local/ant
export JAVA_HOME=/usr/local/jdk
export PATH=${PATH}:${ANT_HOME}/bin
You'll need to add the.jarfiles for the services you'll be using. For example,export CLASSPATH=${CLASSPATH}:/home/username/gdata/java/lib/gdata-core-1.0.jar:/home/username/gdata/java/lib/gdata-calendar-1.0.jar:/home/username/gdata/java/sample/util/lib/sample-util.jar
source .bash_profileto establish the variables
Note:Ensure that the variables do not have quotes (either ' or ") and do not end with \ or /.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2023-11-03 UTC."],[],[]]