Inital commit

This commit is contained in:
Tilman
2011-10-26 09:44:02 +02:00
commit 5971f4b417
1813 changed files with 737837 additions and 0 deletions
+251
View File
@@ -0,0 +1,251 @@
/* Copyright (c) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.calendar;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.Link;
import com.google.gdata.data.acl.AclEntry;
import com.google.gdata.data.acl.AclFeed;
import com.google.gdata.data.acl.AclNamespace;
import com.google.gdata.data.acl.AclRole;
import com.google.gdata.data.acl.AclScope;
import com.google.gdata.data.calendar.CalendarAclRole;
import com.google.gdata.data.calendar.CalendarEntry;
import com.google.gdata.data.calendar.CalendarFeed;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Demonstrates basic Calendar Data API operations on the ACL feed using the
* Java client library:
*
* <ul>
* <li>Parsing the metafeed for ACL feed URLs.</li>
* <li>Retrieving access control lists (ACLs) for each calendar.</li>
* <li>Adding users to access control lists.</li>
* <li>Updating users on access control lists.</li>
* <li>Removing users from access control lists.</li>
* </ul>
*/
public class AclFeedDemo {
// The base URL for a user's calendar metafeed (needs a username appended).
private static final String METAFEED_URL_BASE =
"https://www.google.com/calendar/feeds/";
// The string to add to the user's metafeedUrl to access the ACL feed for
// their primary calendar.
private static final String ACL_FEED_URL_SUFFIX = "/acl/full";
// The URL for the metafeed of the specified user.
// (e.g. http://www.google.com/feeds/calendar/jdoe@gmail.com)
private static URL metafeedUrl = null;
// The URL for the ACL feed of the specified user's primary calendar.
// (e.g. http://www.googe.com/feeds/calendar/jdoe@gmail.com/acl/full)
private static URL aclFeedUrl = null;
/**
* Retrieves the calendar metafeed to get the ACL feed URLs for each calendar.
* Then prints the access control lists for each of the user's calendars.
*
* @param service An authenticated CalendarService object.
* @throws ServiceException If the service is unable to handle the request.
* @throws IOException Error communicating with the server.
*/
private static void printAclList(CalendarService service)
throws ServiceException, IOException {
CalendarFeed calendarFeed = service
.getFeed(metafeedUrl, CalendarFeed.class);
// After accessing the meta-feed, get the ACL link for each calendar.
System.out.println("Access control lists for your calendars:");
for (CalendarEntry calEntry : calendarFeed.getEntries()) {
Link link = calEntry.getLink(AclNamespace.LINK_REL_ACCESS_CONTROL_LIST,
Link.Type.ATOM);
// For each calendar that exposes an access control list, retrieve its ACL
// feed. If link is null, then we are not the owner of that calendar
// (e.g., it is a public calendar) and its ACL feed cannot be accessed.
if (link != null) {
AclFeed aclFeed = service.getFeed(new URL(link.getHref()),
AclFeed.class);
System.out.println("\tCalendar \"" + calEntry.getTitle().getPlainText()
+ "\":");
for (AclEntry aclEntry : aclFeed.getEntries()) {
System.out.println("\t\tScope: Type=" + aclEntry.getScope().getType()
+ " (" + aclEntry.getScope().getValue() + ")");
System.out.println("\t\tRole: " + aclEntry.getRole().getValue());
}
}
}
}
/**
* Adds a user in the read-only role to the calendar's access control list.
* Note that this method will not run by default.
*
* @param service An authenticated CalendarService object.
* @param userEmail The email address of the user with whom to share the
* calendar.
* @param role The access privileges to grant this user.
* @throws ServiceException If the service is unable to handle the request.
* @throws IOException Error communicating with the server.
*/
private static void addAccessControl(CalendarService service,
String userEmail, AclRole role) throws ServiceException, IOException {
AclEntry entry = new AclEntry();
entry.setScope(new AclScope(AclScope.Type.USER, userEmail));
entry.setRole(role);
AclEntry insertedEntry = service.insert(aclFeedUrl, entry);
System.out.println("Added user to access control list:");
System.out.println("\tScope: Type=" + insertedEntry.getScope().getType()
+ " (" + insertedEntry.getScope().getValue() + ")");
System.out.println("\tRole: " + insertedEntry.getRole().getValue());
}
/**
* Updates a user to have new access permissions over a calendar. Note that
* this method will not run by default.
*
* @param service An authenticated CalendarService object.
* @param userEmail The email address of the user to update.
* @param newRole The new access privileges to grant this user.
* @throws ServiceException If the service is unable to handle the request.
* @throws IOException Error communicating with the server.
*/
private static void updateAccessControl(CalendarService service,
String userEmail, AclRole newRole) throws ServiceException, IOException {
AclFeed aclFeed = service.getFeed(aclFeedUrl, AclFeed.class);
for (AclEntry aclEntry : aclFeed.getEntries()) {
if (userEmail.equals(aclEntry.getScope().getValue())) {
aclEntry.setRole(newRole);
AclEntry updatedEntry = aclEntry.update();
System.out.println("Updated user's access control:");
System.out.println("\tScope: Type=" + updatedEntry.getScope().getType()
+ " (" + updatedEntry.getScope().getValue() + ")");
System.out.println("\tRole: " + updatedEntry.getRole().getValue());
break;
}
}
}
/**
* Deletes a user from a calendar's access control list, preventing that user
* from accessing the calendar. Note that this method will not run by default.
*
* @param service An authenticated CalendarService object.
* @param userEmail The email address of the user to remove from the ACL.
* @throws ServiceException If the service is unable to handle the request.
* @throws IOException Error communicating with the server.
*/
private static void deleteAccessControl(CalendarService service,
String userEmail) throws ServiceException, IOException {
AclFeed aclFeed = service.getFeed(aclFeedUrl, AclFeed.class);
for (AclEntry aclEntry : aclFeed.getEntries()) {
if (userEmail.equals(aclEntry.getScope().getValue())) {
aclEntry.delete();
System.out.println("Deleted " + userEmail + "'s access control.");
break;
}
}
}
/**
* Instantiates a CalendarService object and uses the command line arguments
* to authenticate. The CalendarService object is used to demonstrate
* interactions with the Calendar data API's ACL feed.
*
* @param args Must be length 2 or 3 and contain a valid username/password
*/
public static void main(String[] args) {
String userToShareWith = null;
// Set username, password and feed URI from command-line arguments.
if (args.length < 2 || args.length > 3) {
usage();
return;
} else if (args.length == 3) {
userToShareWith = args[2];
}
CalendarService myService = new CalendarService("demo-AclFeedDemo-1");
String userName = args[0];
String userPassword = args[1];
// Create necessary URL objects
try {
metafeedUrl = new URL(METAFEED_URL_BASE + userName);
aclFeedUrl = new URL(METAFEED_URL_BASE + userName + ACL_FEED_URL_SUFFIX);
} catch (MalformedURLException e) {
// Bad URL
System.err.println("Uh oh - you've got an invalid URL.");
e.printStackTrace();
return;
}
try {
myService.setUserCredentials(userName, userPassword);
// Demonstrate retrieving access control list feeds.
printAclList(myService);
if (userToShareWith != null) {
// Allow given user to see free/busy information on this calendar.
addAccessControl(myService, userToShareWith, CalendarAclRole.FREEBUSY);
// Allow given user to have full read access on this calendar.
updateAccessControl(myService, userToShareWith, CalendarAclRole.READ);
// Remove given user's access to this calendar.
deleteAccessControl(myService, userToShareWith);
}
} catch (IOException e) {
// Communications error
System.err.println("There was a problem communicating with the service.");
e.printStackTrace();
} catch (ServiceException e) {
// Server side error
System.err.println("The server had a problem handling your request.");
e.printStackTrace();
}
}
/**
* Prints the command line usage of this sample application.
*/
private static void usage() {
System.out.println("Syntax: AclFeedDemo <username> <password>"
+ " [userToShareWith]");
System.out.println("\nThe username and password are used for "
+ "authentication. The 'userToShareWith' is an optional parameter "
+ "that specifies a second user to share the first user's primary "
+ "calendar with. If this parameter is not given then the first "
+ "user's ACL will not be modified.");
}
}
@@ -0,0 +1,304 @@
/* Copyright (c) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.calendar;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.calendar.CalendarEntry;
import com.google.gdata.data.calendar.CalendarFeed;
import com.google.gdata.data.calendar.ColorProperty;
import com.google.gdata.data.calendar.HiddenProperty;
import com.google.gdata.data.calendar.SelectedProperty;
import com.google.gdata.data.calendar.TimeZoneProperty;
import com.google.gdata.data.extensions.Where;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Demonstrates interactions with the Calendar data API's calendar feeds using
* the Java client library:
*
* <ul>
* <li>Retrieving the metafeed list of all the user's calendars</li>
* <li>Retrieving the allcalendars list of calendars</li>
* <li>Retrieving the owncalendars list of calendars</li>
* <li>Creating a new calendar</li>
* <li>Updating an existing calendar</li>
* <li>Deleting a calendar</li>
* <li>Subscribing to an existing calendar</li>
* <li>Updating a subscription</li>
* <li>Deleting a subscription</li>
* </ul>
*/
public class CalendarFeedDemo {
// The base URL for a user's calendar metafeed (needs a username appended).
private static final String METAFEED_URL_BASE =
"https://www.google.com/calendar/feeds/";
// The string to add to the user's metafeedUrl to access the allcalendars
// feed.
private static final String ALLCALENDARS_FEED_URL_SUFFIX =
"/allcalendars/full";
// The string to add to the user's metafeedUrl to access the owncalendars
// feed.
private static final String OWNCALENDARS_FEED_URL_SUFFIX =
"/owncalendars/full";
// The URL for the metafeed of the specified user.
// (e.g. http://www.google.com/feeds/calendar/jdoe@gmail.com)
private static URL metafeedUrl = null;
// The URL for the allcalendars feed of the specified user.
// (e.g. http://www.googe.com/feeds/calendar/jdoe@gmail.com/allcalendars/full)
private static URL allcalendarsFeedUrl = null;
// The URL for the owncalendars feed of the specified user.
// (e.g. http://www.googe.com/feeds/calendar/jdoe@gmail.com/owncalendars/full)
private static URL owncalendarsFeedUrl = null;
// The calendar ID of the public Google Doodles calendar
private static final String DOODLES_CALENDAR_ID =
"c4o4i7m2lbamc4k26sc2vokh5g%40group.calendar.google.com";
// The HEX representation of red, blue and green
private static final String RED = "#A32929";
private static final String BLUE = "#2952A3";
private static final String GREEN = "#0D7813";
/**
* Utility classes should not have a public or default constructor.
*/
protected CalendarFeedDemo() {
}
/**
* Prints the titles of calendars in the feed specified by the given URL.
*
* @param service An authenticated CalendarService object.
* @param feedUrl The URL of a calendar feed to retrieve.
* @throws IOException If there is a problem communicating with the server.
* @throws ServiceException If the service is unable to handle the request.
*/
private static void printUserCalendars(CalendarService service, URL feedUrl)
throws IOException, ServiceException {
// Send the request and receive the response:
CalendarFeed resultFeed = service.getFeed(feedUrl, CalendarFeed.class);
// Print the title of each calendar
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
CalendarEntry entry = resultFeed.getEntries().get(i);
System.out.println("\t" + entry.getTitle().getPlainText());
}
}
/**
* Creates a new secondary calendar using the owncalendars feed.
*
* @param service An authenticated CalendarService object.
* @return The newly created calendar entry.
* @throws IOException If there is a problem communicating with the server.
* @throws ServiceException If the service is unable to handle the request.
*/
private static CalendarEntry createCalendar(CalendarService service)
throws IOException, ServiceException {
System.out.println("Creating a secondary calendar");
// Create the calendar
CalendarEntry calendar = new CalendarEntry();
calendar.setTitle(new PlainTextConstruct("Little League Schedule"));
calendar.setSummary(new PlainTextConstruct(
"This calendar contains the practice schedule and game times."));
calendar.setTimeZone(new TimeZoneProperty("America/Los_Angeles"));
calendar.setHidden(HiddenProperty.FALSE);
calendar.setColor(new ColorProperty(BLUE));
calendar.addLocation(new Where("", "", "Oakland"));
// Insert the calendar
return service.insert(owncalendarsFeedUrl, calendar);
}
/**
* Updates the title, color, and selected properties of the given calendar
* entry using the owncalendars feed. Note that the title can only be updated
* with the owncalendars feed.
*
* @param calendar The calendar entry to update.
* @return The newly updated calendar entry.
* @throws IOException If there is a problem communicating with the server.
* @throws ServiceException If the service is unable to handle the request.
*/
private static CalendarEntry updateCalendar(CalendarEntry calendar)
throws IOException, ServiceException {
System.out.println("Updating the secondary calendar");
calendar.setTitle(new PlainTextConstruct("New title"));
calendar.setColor(new ColorProperty(GREEN));
calendar.setSelected(SelectedProperty.TRUE);
return calendar.update();
}
/**
* Deletes the given calendar entry.
*
* @param calendar The calendar entry to delete.
* @throws IOException If there is a problem communicating with the server.
* @throws ServiceException If the service is unable to handle the request.
*/
private static void deleteCalendar(CalendarEntry calendar)
throws IOException, ServiceException {
System.out.println("Deleting the secondary calendar");
calendar.delete();
}
/**
* Subscribes to the public Google Doodles calendar using the allcalendars
* feed.
*
* @param service An authenticated CalendarService object.
* @return The newly created calendar entry.
* @throws IOException If there is a problem communicating with the server.
* @throws ServiceException If the service is unable to handle the request.
*/
private static CalendarEntry createSubscription(CalendarService service)
throws IOException, ServiceException {
System.out.println("Subscribing to the Google Doodles calendar");
CalendarEntry calendar = new CalendarEntry();
calendar.setId(DOODLES_CALENDAR_ID);
return service.insert(allcalendarsFeedUrl, calendar);
}
/**
* Updated the color property of the given calendar entry.
*
* @param calendar The calendar entry to update.
* @return The newly updated calendar entry.
* @throws IOException If there is a problem communicating with the server.
* @throws ServiceException If the service is unable to handle the request.
*/
private static CalendarEntry updateSubscription(CalendarEntry calendar)
throws IOException, ServiceException {
System.out.println("Updating the display color of the Doodles calendar");
calendar.setColor(new ColorProperty(RED));
return calendar.update();
}
/**
* Deletes the given calendar entry.
*
* @param calendar The calendar entry to delete
* @throws IOException If there is a problem communicating with the server.
* @throws ServiceException If the service is unable to handle the request.
*/
private static void deleteSubscription(CalendarEntry calendar)
throws IOException, ServiceException {
System.out.println("Deleting the subscription to the Doodles calendar");
calendar.delete();
}
/**
* Instantiates a CalendarService object and uses the command line arguments
* to authenticate. The CalendarService object is used to demonstrate
* interactions with the Calendar data API's calendar feeds.
*
* @param args Must be length 2 and contain a valid username/password
*/
public static void main(String[] args) {
// Set username and password from command-line arguments.
if (args.length != 2) {
usage();
return;
}
String userName = args[0];
String userPassword = args[1];
// Create necessary URL objects
try {
metafeedUrl = new URL(METAFEED_URL_BASE + userName);
allcalendarsFeedUrl = new URL(METAFEED_URL_BASE + userName +
ALLCALENDARS_FEED_URL_SUFFIX);
owncalendarsFeedUrl = new URL(METAFEED_URL_BASE + userName +
OWNCALENDARS_FEED_URL_SUFFIX);
} catch (MalformedURLException e) {
// Bad URL
System.err.println("Uh oh - you've got an invalid URL.");
e.printStackTrace();
return;
}
// Create CalendarService and authenticate using ClientLogin
CalendarService service = new CalendarService("demo-CalendarFeedDemo-1");
try {
service.setUserCredentials(userName, userPassword);
} catch (AuthenticationException e) {
// Invalid credentials
e.printStackTrace();
}
// Demonstrate retrieving various calendar feeds.
try {
System.out.println("Calendars in metafeed");
printUserCalendars(service, metafeedUrl);
System.out.println("Calendars in allcalendars feed");
printUserCalendars(service, allcalendarsFeedUrl);
System.out.println("Calendars in owncalendars feed");
printUserCalendars(service, owncalendarsFeedUrl);
// Create a new secondary calendar, update it, then delete it.
CalendarEntry newCalendar = createCalendar(service);
CalendarEntry updatedCalendar = updateCalendar(newCalendar);
deleteCalendar(newCalendar);
// Subscribe to the Google Doodles calendar, update the personalization
// settings, then delete the subscription.
CalendarEntry newSubscription = createSubscription(service);
CalendarEntry updatedSubscription = updateSubscription(newSubscription);
deleteSubscription(newSubscription);
} catch (IOException e) {
// Communications error
System.err.println("There was a problem communicating with the service.");
e.printStackTrace();
} catch (ServiceException e) {
// Server side error
System.err.println("The server had a problem handling your request.");
e.printStackTrace();
}
}
/**
* Prints the command line usage of this sample application.
*/
private static void usage() {
System.out.println("Syntax: CalendarFeedDemo <username> <password>");
System.out.println("\nThe username and password are used for "
+ "authentication. The sample application will modify the specified "
+ "user's calendars so you may want to use a test account.");
}
}
@@ -0,0 +1,550 @@
/* Copyright (c) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.calendar;
import com.google.gdata.client.Query;
import com.google.gdata.client.calendar.CalendarQuery;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.Link;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.batch.BatchOperationType;
import com.google.gdata.data.batch.BatchStatus;
import com.google.gdata.data.batch.BatchUtils;
import com.google.gdata.data.calendar.CalendarEntry;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.CalendarEventFeed;
import com.google.gdata.data.calendar.CalendarFeed;
import com.google.gdata.data.calendar.WebContent;
import com.google.gdata.data.extensions.ExtendedProperty;
import com.google.gdata.data.extensions.Recurrence;
import com.google.gdata.data.extensions.Reminder;
import com.google.gdata.data.extensions.Reminder.Method;
import com.google.gdata.data.extensions.When;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimeZone;
/**
* Demonstrates basic Calendar Data API operations on the event feed using the
* Java client library:
*
* <ul>
* <li>Retrieving the list of all the user's calendars</li>
* <li>Retrieving all events on a single calendar</li>
* <li>Performing a full-text query on a calendar</li>
* <li>Performing a date-range query on a calendar</li>
* <li>Creating a single-occurrence event</li>
* <li>Creating a recurring event</li>
* <li>Creating a quick add event</li>
* <li>Creating a web content event</li>
* <li>Updating events</li>
* <li>Adding reminders and extended properties</li>
* <li>Deleting events via batch request</li>
* </ul>
*/
public class EventFeedDemo {
// The base URL for a user's calendar metafeed (needs a username appended).
private static final String METAFEED_URL_BASE =
"https://www.google.com/calendar/feeds/";
// The string to add to the user's metafeedUrl to access the event feed for
// their primary calendar.
private static final String EVENT_FEED_URL_SUFFIX = "/private/full";
// The URL for the metafeed of the specified user.
// (e.g. http://www.google.com/feeds/calendar/jdoe@gmail.com)
private static URL metafeedUrl = null;
// The URL for the event feed of the specified user's primary calendar.
// (e.g. http://www.googe.com/feeds/calendar/jdoe@gmail.com/private/full)
private static URL eventFeedUrl = null;
/**
* Prints a list of all the user's calendars.
*
* @param service An authenticated CalendarService object.
* @throws ServiceException If the service is unable to handle the request.
* @throws IOException Error communicating with the server
*/
private static void printUserCalendars(CalendarService service)
throws IOException, ServiceException {
// Send the request and receive the response:
CalendarFeed resultFeed = service.getFeed(metafeedUrl, 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());
}
System.out.println();
}
/**
* Prints the titles of all events on the calendar specified by
* {@code feedUri}.
*
* @param service An authenticated CalendarService object.
* @throws ServiceException If the service is unable to handle the request.
* @throws IOException Error communicating with the server.
*/
private static void printAllEvents(CalendarService service)
throws ServiceException, IOException {
// Send the request and receive the response:
CalendarEventFeed resultFeed = service.getFeed(eventFeedUrl,
CalendarEventFeed.class);
System.out.println("All events on your calendar:");
System.out.println();
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
CalendarEventEntry entry = resultFeed.getEntries().get(i);
System.out.println("\t" + entry.getTitle().getPlainText());
}
System.out.println();
}
/**
* Prints the titles of all events matching a full-text query.
*
* @param service An authenticated CalendarService object.
* @param query The text for which to query.
* @throws ServiceException If the service is unable to handle the request.
* @throws IOException Error communicating with the server.
*/
private static void fullTextQuery(CalendarService service, String query)
throws ServiceException, IOException {
Query myQuery = new Query(eventFeedUrl);
myQuery.setFullTextQuery("Tennis");
CalendarEventFeed resultFeed = service.query(myQuery,
CalendarEventFeed.class);
System.out.println("Events matching " + query + ":");
System.out.println();
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
CalendarEventEntry entry = resultFeed.getEntries().get(i);
System.out.println("\t" + entry.getTitle().getPlainText());
}
System.out.println();
}
/**
* Prints the titles of all events in a specified date/time range.
*
* @param service An authenticated CalendarService object.
* @param startTime Start time (inclusive) of events to print.
* @param endTime End time (exclusive) of events to print.
* @throws ServiceException If the service is unable to handle the request.
* @throws IOException Error communicating with the server.
*/
private static void dateRangeQuery(CalendarService service,
DateTime startTime, DateTime endTime) throws ServiceException,
IOException {
CalendarQuery myQuery = new CalendarQuery(eventFeedUrl);
myQuery.setMinimumStartTime(startTime);
myQuery.setMaximumStartTime(endTime);
// Send the request and receive the response:
CalendarEventFeed resultFeed = service.query(myQuery,
CalendarEventFeed.class);
System.out.println("Events from " + startTime.toString() + " to "
+ endTime.toString() + ":");
System.out.println();
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
CalendarEventEntry entry = resultFeed.getEntries().get(i);
System.out.println("\t" + entry.getTitle().getPlainText());
}
System.out.println();
}
/**
* Helper method to create either single-instance or recurring events. For
* simplicity, some values that might normally be passed as parameters (such
* as author name, email, etc.) are hard-coded.
*
* @param service An authenticated CalendarService object.
* @param eventTitle Title of the event to create.
* @param eventContent Text content of the event to create.
* @param recurData Recurrence value for the event, or null for
* single-instance events.
* @param isQuickAdd True if eventContent should be interpreted as the text of
* a quick add event.
* @param wc A WebContent object, or null if this is not a web content event.
* @return The newly-created CalendarEventEntry.
* @throws ServiceException If the service is unable to handle the request.
* @throws IOException Error communicating with the server.
*/
private static CalendarEventEntry createEvent(CalendarService service,
String eventTitle, String eventContent, String recurData,
boolean isQuickAdd, WebContent wc) throws ServiceException, IOException {
CalendarEventEntry myEntry = new CalendarEventEntry();
myEntry.setTitle(new PlainTextConstruct(eventTitle));
myEntry.setContent(new PlainTextConstruct(eventContent));
myEntry.setQuickAdd(isQuickAdd);
myEntry.setWebContent(wc);
// If a recurrence was requested, add it. Otherwise, set the
// time (the current date and time) and duration (30 minutes)
// of the event.
if (recurData == null) {
Calendar calendar = new GregorianCalendar();
DateTime startTime = new DateTime(calendar.getTime(), TimeZone
.getDefault());
calendar.add(Calendar.MINUTE, 30);
DateTime endTime = new DateTime(calendar.getTime(),
TimeZone.getDefault());
When eventTimes = new When();
eventTimes.setStartTime(startTime);
eventTimes.setEndTime(endTime);
myEntry.addTime(eventTimes);
} else {
Recurrence recur = new Recurrence();
recur.setValue(recurData);
myEntry.setRecurrence(recur);
}
// Send the request and receive the response:
return service.insert(eventFeedUrl, myEntry);
}
/**
* Creates a single-occurrence event.
*
* @param service An authenticated CalendarService object.
* @param eventTitle Title of the event to create.
* @param eventContent Text content of the event to create.
* @return The newly-created CalendarEventEntry.
* @throws ServiceException If the service is unable to handle the request.
* @throws IOException Error communicating with the server.
*/
private static CalendarEventEntry createSingleEvent(CalendarService service,
String eventTitle, String eventContent) throws ServiceException,
IOException {
return createEvent(service, eventTitle, eventContent, null, false, null);
}
/**
* Creates a quick add event.
*
* @param service An authenticated CalendarService object.
* @param quickAddContent The quick add text, including the event title, date
* and time.
* @return The newly-created CalendarEventEntry.
* @throws ServiceException If the service is unable to handle the request.
* @throws IOException Error communicating with the server.
*/
private static CalendarEventEntry createQuickAddEvent(
CalendarService service, String quickAddContent) throws ServiceException,
IOException {
return createEvent(service, null, quickAddContent, null, true, null);
}
/**
* Creates a web content event.
*
* @param service An authenticated CalendarService object.
* @param title The title of the web content event.
* @param type The MIME type of the web content event, e.g. "image/gif"
* @param url The URL of the content to display in the web content window.
* @param icon The icon to display in the main Calendar user interface.
* @param width The width of the web content window.
* @param height The height of the web content window.
* @return The newly-created CalendarEventEntry.
* @throws ServiceException If the service is unable to handle the request.
* @throws IOException Error communicating with the server.
*/
private static CalendarEventEntry createWebContentEvent(
CalendarService service, String title, String type, String url,
String icon, String width, String height) throws ServiceException,
IOException {
WebContent wc = new WebContent();
wc.setHeight(height);
wc.setWidth(width);
wc.setTitle(title);
wc.setType(type);
wc.setUrl(url);
wc.setIcon(icon);
return createEvent(service, title, null, null, false, wc);
}
/**
* Creates a new recurring event.
*
* @param service An authenticated CalendarService object.
* @param eventTitle Title of the event to create.
* @param eventContent Text content of the event to create.
* @return The newly-created CalendarEventEntry.
* @throws ServiceException If the service is unable to handle the request.
* @throws IOException Error communicating with the server.
*/
private static CalendarEventEntry createRecurringEvent(
CalendarService service, String eventTitle, String eventContent)
throws ServiceException, IOException {
// Specify a recurring event that occurs every Tuesday from May 1,
// 2007 through September 4, 2007. Note that we are using iCal (RFC 2445)
// syntax; see http://www.ietf.org/rfc/rfc2445.txt for more information.
String recurData = "DTSTART;VALUE=DATE:20070501\r\n"
+ "DTEND;VALUE=DATE:20070502\r\n"
+ "RRULE:FREQ=WEEKLY;BYDAY=Tu;UNTIL=20070904\r\n";
return createEvent(service, eventTitle, eventContent, recurData, false,
null);
}
/**
* Updates the title of an existing calendar event.
*
* @param entry The event to update.
* @param newTitle The new title for this event.
* @return The updated CalendarEventEntry object.
* @throws ServiceException If the service is unable to handle the request.
* @throws IOException Error communicating with the server.
*/
private static CalendarEventEntry updateTitle(CalendarEventEntry entry,
String newTitle) throws ServiceException, IOException {
entry.setTitle(new PlainTextConstruct(newTitle));
return entry.update();
}
/**
* Adds a reminder to a calendar event.
*
* @param entry The event to update.
* @param numMinutes Reminder time, in minutes.
* @param methodType Method of notification (e.g. email, alert, sms).
* @return The updated EventEntry object.
* @throws ServiceException If the service is unable to handle the request.
* @throws IOException Error communicating with the server.
*/
private static CalendarEventEntry addReminder(CalendarEventEntry entry,
int numMinutes, Method methodType) throws ServiceException, IOException {
Reminder reminder = new Reminder();
reminder.setMinutes(numMinutes);
reminder.setMethod(methodType);
entry.getReminder().add(reminder);
return entry.update();
}
/**
* Adds an extended property to a calendar event.
*
* @param entry The event to update.
* @return The updated EventEntry object.
* @throws ServiceException If the service is unable to handle the request.
* @throws IOException Error communicating with the server.
*/
private static CalendarEventEntry addExtendedProperty(
CalendarEventEntry entry) throws ServiceException, IOException {
// Add an extended property "id" with value 1234 to the EventEntry entry.
// We specify the complete schema URL to avoid namespace collisions with
// other applications that use the same property name.
ExtendedProperty property = new ExtendedProperty();
property.setName("http://www.example.com/schemas/2005#mycal.id");
property.setValue("1234");
entry.addExtension(property);
return entry.update();
}
/**
* Makes a batch request to delete all the events in the given list. If any of
* the operations fails, the errors returned from the server are displayed.
* The CalendarEntry objects in the list given as a parameters must be entries
* returned from the server that contain valid edit links (for optimistic
* concurrency to work). Note: You can add entries to a batch request for the
* other operation types (INSERT, QUERY, and UPDATE) in the same manner as
* shown below for DELETE operations.
*
* @param service An authenticated CalendarService object.
* @param eventsToDelete A list of CalendarEventEntry objects to delete.
* @throws ServiceException If the service is unable to handle the request.
* @throws IOException Error communicating with the server.
*/
private static void deleteEvents(CalendarService service,
List<CalendarEventEntry> eventsToDelete) throws ServiceException,
IOException {
// Add each item in eventsToDelete to the batch request.
CalendarEventFeed batchRequest = new CalendarEventFeed();
for (int i = 0; i < eventsToDelete.size(); i++) {
CalendarEventEntry toDelete = eventsToDelete.get(i);
// Modify the entry toDelete with batch ID and operation type.
BatchUtils.setBatchId(toDelete, String.valueOf(i));
BatchUtils.setBatchOperationType(toDelete, BatchOperationType.DELETE);
batchRequest.getEntries().add(toDelete);
}
// Get the URL to make batch requests to
CalendarEventFeed feed = service.getFeed(eventFeedUrl,
CalendarEventFeed.class);
Link batchLink = feed.getLink(Link.Rel.FEED_BATCH, Link.Type.ATOM);
URL batchUrl = new URL(batchLink.getHref());
// Submit the batch request
CalendarEventFeed batchResponse = service.batch(batchUrl, batchRequest);
// Ensure that all the operations were successful.
boolean isSuccess = true;
for (CalendarEventEntry entry : batchResponse.getEntries()) {
String batchId = BatchUtils.getBatchId(entry);
if (!BatchUtils.isSuccess(entry)) {
isSuccess = false;
BatchStatus status = BatchUtils.getBatchStatus(entry);
System.out.println("\n" + batchId + " failed (" + status.getReason()
+ ") " + status.getContent());
}
}
if (isSuccess) {
System.out.println("Successfully deleted all events via batch request.");
}
}
/**
* Instantiates a CalendarService object and uses the command line arguments
* to authenticate. The CalendarService object is used to demonstrate
* interactions with the Calendar data API's event feed.
*
* @param args Must be length 2 and contain a valid username/password
*/
public static void main(String[] args) {
CalendarService myService = new CalendarService("exampleCo-exampleApp-1");
// Set username and password from command-line arguments.
if (args.length != 2) {
usage();
return;
}
String userName = args[0];
String userPassword = args[1];
// Create the necessary URL objects.
try {
metafeedUrl = new URL(METAFEED_URL_BASE + userName);
eventFeedUrl = new URL(METAFEED_URL_BASE + userName
+ EVENT_FEED_URL_SUFFIX);
} catch (MalformedURLException e) {
// Bad URL
System.err.println("Uh oh - you've got an invalid URL.");
e.printStackTrace();
return;
}
try {
myService.setUserCredentials(userName, userPassword);
// Demonstrate retrieving a list of the user's calendars.
printUserCalendars(myService);
// Demonstrate various feed queries.
System.out.println("Printing all events");
printAllEvents(myService);
System.out.println("Full text query");
fullTextQuery(myService, "Tennis");
dateRangeQuery(myService, DateTime.parseDate("2007-01-05"), DateTime
.parseDate("2007-01-07"));
// Demonstrate creating a single-occurrence event.
CalendarEventEntry singleEvent = createSingleEvent(myService,
"Tennis with Mike", "Meet for a quick lesson.");
System.out.println("Successfully created event "
+ singleEvent.getTitle().getPlainText());
// Demonstrate creating a quick add event.
CalendarEventEntry quickAddEvent = createQuickAddEvent(myService,
"Tennis with John April 11 3pm-3:30pm");
System.out.println("Successfully created quick add event "
+ quickAddEvent.getTitle().getPlainText());
// Demonstrate creating a web content event.
CalendarEventEntry webContentEvent = createWebContentEvent(myService,
"World Cup", "image/gif",
"http://www.google.com/logos/worldcup06.gif",
"http://www.google.com/calendar/images/google-holiday.gif", "276",
"120");
System.out.println("Successfully created web content event "
+ webContentEvent.getTitle().getPlainText());
// Demonstrate creating a recurring event.
CalendarEventEntry recurringEvent = createRecurringEvent(myService,
"Tennis with Dan", "Weekly tennis lesson.");
System.out.println("Successfully created recurring event "
+ recurringEvent.getTitle().getPlainText());
// Demonstrate updating the event's text.
singleEvent = updateTitle(singleEvent, "Important meeting");
System.out.println("Event's new title is \""
+ singleEvent.getTitle().getPlainText() + "\".");
// Demonstrate adding a reminder. Note that this will only work on a
// primary calendar.
singleEvent = addReminder(singleEvent, 15, Method.EMAIL);
System.out.println("Set a "
+ singleEvent.getReminder().get(0).getMinutes()
+ " minute " + singleEvent.getReminder().get(0).getMethod()
+ " reminder for the event.");
// Demonstrate adding an extended property.
singleEvent = addExtendedProperty(singleEvent);
// Demonstrate deleting the entries with a batch request.
List<CalendarEventEntry> eventsToDelete =
new ArrayList<CalendarEventEntry>();
eventsToDelete.add(singleEvent);
eventsToDelete.add(quickAddEvent);
eventsToDelete.add(webContentEvent);
eventsToDelete.add(recurringEvent);
deleteEvents(myService, eventsToDelete);
} catch (IOException e) {
// Communications error
System.err.println("There was a problem communicating with the service.");
e.printStackTrace();
} catch (ServiceException e) {
// Server side error
System.err.println("The server had a problem handling your request.");
e.printStackTrace();
}
}
/**
* Prints the command line usage of this sample application.
*/
private static void usage() {
System.out.println("Syntax: EventFeedDemo <username> <password>");
System.out.println("\nThe username and password are used for "
+ "authentication. The sample application will modify the specified "
+ "user's calendars so you may want to use a test account.");
}
}
@@ -0,0 +1,249 @@
/* Copyright (c) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.calendar;
import com.google.gdata.client.Query;
import com.google.gdata.client.calendar.CalendarQuery;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.CalendarEventFeed;
import com.google.gdata.data.extensions.Who;
import com.google.gdata.util.ServiceException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URL;
/**
* Demonstrates partial query and patch capabilities in Calendar Data API by
* <ul>
* <li>Retrieving current attendeeStatus for the authenticated user using partial
* query and
* <li>update the attendeeStatus using partial patch.
* </ul>
*
*
*/
public class EventFeedPartialDemo {
private static final String CALENDAR_FEEDS_PREFIX =
"https://www.google.com/calendar/feeds/";
/** Input stream for reading user input. */
private static final BufferedReader IN
= new BufferedReader(new InputStreamReader(System.in));
/** Output stream to print output. */
private static final PrintStream OUT = System.out;
/** Service instance to talk to calendar server */
private final CalendarService service;
/** Constructor */
private EventFeedPartialDemo(CalendarService service) {
this.service = service;
}
/**
* Displays a menu of the main activities a user can perform.
*/
private void printMenu() {
OUT.println("\n");
OUT.println("Choose one of the following demo options:");
OUT.println("\t1) Retrieve my next week's events");
OUT.println("\t2) Update my attendee status for an event");
OUT.println("\t0) Exit");
OUT.println("\nEnter Number (0-2): ");
}
/**
* Prints user's attendeeStatus for next week's events.
*
* @param uname username whose attendeeStatus is required.
*/
private void printAttendeeStatus(String uname)
throws IOException, ServiceException {
String eventsFeedUrl = CALENDAR_FEEDS_PREFIX
+ uname + "/private/composite";
String fields = "entry(@gd:etag,id,title,gd:who[@email='" + uname + "'])";
CalendarQuery partialQuery = new CalendarQuery(new URL(eventsFeedUrl));
partialQuery.setFields(fields);
DateTime startTime = DateTime.now();
partialQuery.setMinimumStartTime(startTime);
partialQuery.setMaximumStartTime(
new DateTime(startTime.getValue() + 604800000, startTime.getTzShift()));
CalendarEventFeed events = service.query(
partialQuery, CalendarEventFeed.class);
for (CalendarEventEntry event : events.getEntries()) {
String eventId = event.getId()
.substring(event.getId().lastIndexOf("/") + 1);
String attendeeStatus =
event.getParticipants().get(0).getAttendeeStatus();
OUT.println(eventId + ": " + event.getTitle().getPlainText()
+ ": (" + (attendeeStatus != null ? attendeeStatus : "no status")
+ ")");
}
}
/**
* Updates user's response for a specific event using partial patch.
*
* @param uname username whose attendeeStatus need to be updated.
*/
private void updateAttendeeStatus(String uname)
throws IOException, ServiceException {
OUT.println("Enter the id of event to update: ");
String eventId = IN.readLine();
OUT.println("Enter event response (1:Yes, 2:No, 3:Maybe)");
String selection;
switch(readInt()) {
case 1:
selection = Who.AttendeeStatus.EVENT_ACCEPTED;
break;
case 2:
selection = Who.AttendeeStatus.EVENT_DECLINED;
break;
case 3:
selection = Who.AttendeeStatus.EVENT_TENTATIVE;
break;
default:
OUT.println("Invalid selection.");
return;
}
// URL of calendar entry to update.
String eventEntryUrl = CALENDAR_FEEDS_PREFIX + uname
+ "/private/full/" + eventId;
// Selection criteria to fetch only the attendee status of specified user.
String selectAttendee =
"@gd:etag,title,gd:who[@email='" + uname + "']";
Query partialQuery = new Query(new URL(eventEntryUrl));
partialQuery.setFields(selectAttendee);
CalendarEventEntry event = service.getEntry(partialQuery.getUrl(),
CalendarEventEntry.class);
// The participant list will contain exactly one attendee matching
// above partial query selection criteria.
event.getParticipants().get(0).setAttendeeStatus(selection);
// Field selection to update attendeeStatus only.
String toUpdateFields = "gd:who/gd:attendeeStatus";
// Make patch request which returns full representation for the event.
event = service.patch(
new URL(eventEntryUrl), toUpdateFields, event);
// Print the updated attendee status.
OUT.println(event.getTitle().getPlainText() + " updated to: "
+ event.getParticipants().get(0).getAttendeeStatus());
}
/** Program entry point */
public static void main(String args[]) throws IOException, ServiceException {
// Set username and password from command-line arguments.
if (args.length != 2) {
usage();
return;
}
String uname = args[0];
String upassword = args[1];
CalendarService myService = new CalendarService(
"gdata-CalendarPartialDemo");
myService.setUserCredentials(uname, upassword);
EventFeedPartialDemo demo = new EventFeedPartialDemo(myService);
while (true) {
try {
demo.printMenu();
int choice = readInt();
switch (choice) {
case 1:
// Prints out the user's uploaded videos
demo.printAttendeeStatus(uname);
break;
case 2:
demo.updateAttendeeStatus(uname);
break;
case 0:
System.exit(1);
break;
}
} catch (IOException e) {
// Communications error
System.err.println(
"There was a problem communicating with the service.");
e.printStackTrace();
} catch (ServiceException e) {
// Server side error
System.err.println("The server had a problem handling your request.");
e.printStackTrace();
}
}
}
/**
* Prints the command line usage of this sample application.
*/
private static void usage() {
OUT.println("Syntax: EventFeedPartialDemo <username> <password>");
OUT.println("\nThe username and password are used for "
+ "authentication. The sample application will retrieve list of"
+ "user's calendar events and provides option to change event response."
);
}
/**
* Reads a line of text from the standard input.
*
* @throws IOException If unable to read a line from the standard input.
* @return A line of text read from the standard input.
*/
private static String readLine() throws IOException {
return IN.readLine();
}
/**
* Reads a line of text from the standard input and returns the parsed
* integer representation.
*
* @throws IOException If unable to read a line from the standard input.
* @return An integer read from the standard input.
*/
private static int readInt() throws IOException {
String input = readLine();
try {
return Integer.parseInt(input);
} catch (NumberFormatException nfe) {
return 0;
}
}
}
+20
View File
@@ -0,0 +1,20 @@
Google Calendar data API Java Sample - README.txt
-------------------------------------------------
The Java Calendar sample is a simple application that shows sample usage to
create/read/update/delete data on Google Calendar using the GData Java client
library.
The application can be built and run using the provided Ant build file found at
gdata/java/build.xml. The sample can be run in the following manner:
1. Edit gdata/java/build.properties to enter your Google Account username and
password, as well as the feed URI on which you want to test the sample.
2. Invoke the sample using the following commandline:
ant -f gdata/java/build.xml sample.calendar.run
NOTE: This sample will insert, update, and delete events. Thus it will use the
read-write feed. It will clean up after itself.
Binary file not shown.
Binary file not shown.
Binary file not shown.