Google Apps Platform

Google Documents List API v2 Developer's Guide: Java

Important: Versions 1 and 2 of the Google Documents List API have been officially deprecated as of April 20, 2012. They will continue to work as per our deprecation policy, but we encourage you to move to the Google Drive API.

In addition to providing some background on the capabilities of the Documents List Data API, this guide provides examples for interacting with the API using the Java client library. For help setting up the client library, see Getting Started with the Google Data Java Client Library. If you're interested in understanding more about the underlying protocol used by the Java client library to interact with the Documents List, please see the protocol guide.

Contents

Audience

This document is intended for developers who want to write client applications using the Google Data Java client library that can interact with Google Documents.

Getting started

Google Documents uses Google Accounts for authentication, so if you have a Google account you are all set. Otherwise, you can create a new account.

Installing the library

For help setting up and installing the client library, see the Getting Started with the Google Data Java Client Library. If you're using Eclipse, that article also explains how to setup your project using the Google Data APIs Eclipse plugin. Here's what you need to get started:

  1. Install Java 1.5 or higher
  2. Download the client library (the latest version of gdata-src.java.zip)
  3. Download the list of dependencies
  4. Download the samples applications (the latest version of gdata-samples.java.zip)

After installing the .jars, you'll find the classes you need to get started in the java/lib/gdata-document-2.0.jar and java/lib/gdata-client-1.0.jar jar files.

Running the sample application

A full working sample application lis ocated in /java/sample/docs subdirectory of the gdata-samples.java.zip download. The source is also available at /trunk/java/sample/docs/DocumentListDemo.java in the SVN repository accessible from the Source tab. The DocumentListDemo.java allows the user to perform a number of operations which demonstrate how to use the Documents List feed.

Starting your own project

Tip: See the article Using Eclipse with Google Data APIs for quick setup with our Eclipse plugin.

Depending on your application's needs, you'll need serveral imports. At a minimum, it's recommend to include the following:

import com.google.gdata.client.*;
import com.google.gdata.client.docs.*;
import com.google.gdata.data.docs.*;
import com.google.gdata.data.acl.*;
import com.google.gdata.util.*;

Next, you will also need to setup a DocsService object, which represents a client connection (with authentication) to the Documents List API:

DocsService client = new DocsService("yourCo-yourAppName-v1");

The applicationName argument should follow the format: company-applicationname-version. This parameter is used for logging purposes.

Note: The rest of the guide assumes you created a DocsService in the variable client.

Authenticating to the Documents List API

The Java client library can be used to work with either public or private feeds. The Documents List Data API provides access to private feeds which require authentication with the documents servers. This can be done via ClientLogin username/password authentication, AuthSub, or OAuth.

Note: The API only offers private feeds at the moment. Your application must perform authentication to issue requests against the Documents List.

Please see the Google Data APIs Authentication Overview for more information on AuthSub, OAuth, and ClientLogin.

AuthSub for web applications

AuthSub Authentication for Web Applications should be used by client applications which need to authenticate their users to Google accounts. The operator does not need access to the username and password for the Google Documents user - only an AuthSub token is required.

View instructions for incorporating AuthSub into your web application Show rest of description Hide rest of description

OAuth for web applications

OAuth can be used as an alternative to AuthSub, and is intended for web applications. OAuth is similar to using the secure and registered mode of AuthSub in that all data requests must be digitally signed and you must register your domain.

View instructions for incorporating OAuth into your installed application Show rest of description Hide rest of description

ClientLogin for installed/mobile applications

ClientLogin should be used by installed or mobile applications which need to authenticate their users to Google accounts. On first run, your application prompts the user for their username/password. On subsequent requests, an authentication token is referenced.

View instructions for incorporating ClientLogin into your installed application Show rest of description Hide rest of description

Specifying a version

Before making requests to the Google Documents List API, clients must specify which version to use. By default, the Java client library uses version 3.0 of the Google Documents List API. Clients wishing to use version 2.0 should use the following Java snippet to set the appropriate version on the DocsService object.

DocsService client = new DocsService("yourCo-yourAppName-v1");
client.setProtocolVersion(DocsService.Versions.V2);
// ...

Retrieving a list of documents

To fetch a feed containing a list of the currently authenticated user's documents, send an authenticated GET request to the following URL:

https://docs.google.com/feeds/documents/private/full

The result is a "meta-feed," a feed that lists all of that user's documents; each entry in the feed represents a document (spreadsheet, presentation, word processor document, pdf, etc.). Again, this feed is only accessible after Authenticating to the Documents List API.

Here is an example of printing out the user's entire document list:

public void showAllDocs() throws IOException, ServiceException {
  URL feedUri = new URL("https://docs.google.com/feeds/documents/private/full/");
  DocumentListFeed feed = client.getFeed(feedUri, DocumentListFeed.class);

  for (DocumentListEntry entry : feed.getEntries()) {
    printDocumentEntry(entry);
  }
}

public void printDocumentEntry(DocumentListEntry doc) {
  String resourceId = doc.getResourceId();
  String docType = resourceId.substring(0, resourceId.lastIndexOf(':'));

  System.out.println("'" + doc.getTitle().getPlainText() + "' (" + docType + ")");
  System.out.println("  link to Google Docs: " + doc.getHtmlLink().getHref());
  System.out.println("  resource id: " + resourceId);

  // print the parent folder the document is in
  if (!doc.getFolders().isEmpty()) {
    System.out.println("  in folder: " +  doc.getFolders());
  }

  // print the timestamp the document was last viewed
  DateTime lastViewed = doc.getLastViewed();
  if (lastViewed != null) {
    System.out.println("  last viewed: " + lastViewed.toString());
  }

  // print who made that modification
  LastModifiedBy lastModifiedBy = doc.getLastModifiedBy();
  if (lastModifiedBy != null) {
    System.out.println("  updated by: " +
        lastModifiedBy.getName() + " - " + lastModifiedBy.getEmail());
  }
  
  // print other useful metadata
  System.out.println("  last updated: " + doc.getUpdated().toString());
  System.out.println("  viewed by user? " + doc.isViewed());
  System.out.println("  writersCanInvite? " + doc.isWritersCanInvite().toString());
  System.out.println("  hidden? " + doc.isHidden());
  System.out.println("  starrred? " + doc.isStarred());
  System.out.println();
}

The resulting DocumentListFeed object feed represents a response from the server. Among other things, this feed contains a list of DocumentListEntry objects (feed.getEntries()), each of which represents a single document. DocumentListEntry encapsulates the information shown in the protocol document.

Back to top

Searching the documents feed

You can search the Document List using some of the standard Google Data API query parameters. Categories are used to restrict the type of document (spreadsheet, folder, etc.) returned. The full-text query string (q parameter) is used to search the content of all the documents. More detailed information on parameters specific to the Documents List can be found in the Documents List Data API Reference Guide.

The following code is used in all of the examples below to print out the feed results to the command line.

public void printDocuments(DocumentListFeed feed) {
  for (DocumentListEntry entry : feed.getEntries()) {
    String resourceId = doc.getResourceId();
    System.out.println(" -- Document(" + resourceId + "/" + doc.getTitle().getPlainText() + ")");
  }
}

Retrieving all word processor documents

A list of only word processor documents can be retrieved by using the document category as follows:

URL feedUri = new URL("https://docs.google.com/feeds/documents/private/full/-/document");
DocumentListFeed feed = client.getFeed(feedUri, DocumentListFeed.class);
printDocuments(feed);

Retrieving all spreadsheets

A list of only spreadsheets can be retrieved by using the spreadsheet category as follows:

URL feedUri = new URL("https://docs.google.com/feeds/documents/private/full/-/spreadsheet");
DocumentListFeed feed = client.getFeed(feedUri, DocumentListFeed.class);
printDocuments(feed);

Retrieving a list of owned presentations

A list of presentations the current logged in user owns can be retrieved by using the presentation and mine categories as follows:

URL feedUri = new URL("https://docs.google.com/feeds/documents/private/full/-/presentation/mine");
DocumentListFeed feed = client.getFeed(feedUri, DocumentListFeed.class);
printDocuments(feed);

Retrieving a list of folders

A list of folders can be retrieved by using the folder category along with the showfolders=true parameter:

URL feedUri = new URL("https://docs.google.com/feeds/documents/private/full/-/folder?showfolders=true");
DocumentListFeed feed = client.getFeed(feedUri, DocumentListFeed.class);
printDocuments(feed);

Tip: Category queries can work for other document types as well. For a list of possible categories, see the reference guide.

Retrieving all documents in a named folder

You can use a category query which includes the folders name to find the documents in that folder:

URL feedUri = new URL("https://docs.google.com/feeds/documents/private/full/-/MyFolder");
DocumentListFeed feed = client.getFeed(feedUri, DocumentListFeed.class);
printDocuments(feed);

Retrieving a document by an exact title match

It is possible to retrieve documents by matching on their title instead of their entire contents. To do this, you can also use the DocumentQuery class to construct complex queries for the Documents List feed.

This example uses the title parameter and title-exact parameter to indicate a full, explicit title match. Since this parameter is case-insensitive or multiple docs could have the same title, a feed is returned.

The following examples searches for the first 10 documents matching the title "Test", and orders the results alphabetically:

URL feedUri = new URL("https://docs.google.com/feeds/documents/private/full/");
DocumentQuery query = new DocumentQuery(feedUri);
query.setSortMode("title");
query.setTitleQuery("Test");
query.setTitleExact(true);
query.setMaxResults(10);
DocumentListFeed feed = client.getFeed(query, DocumentListFeed.class);
printDocuments(feed);

Note: title-exact queries are case-insenstive. For example, the sample above will print documents that match "Test", "test", and "TeSt", but not "Test title".

Performing a text query

You can search the contents of documents by using the q parameter or the setFullTextQuery() method of the DocumentQuery object.

URL feedUri = new URL("https://docs.google.com/feeds/documents/private/full/");
DocumentQuery query = new DocumentQuery(feedUri);
query.setFullTextQuery("Something to search for");
DocumentListFeed feed = client.getFeed(query, DocumentListFeed.class);
printDocuments(feed);

This snippet searches the entire contents of every document for the string "Something to search for" and returns all documents where this string is found. This is different than searching just the title of every document, which can be done as described in the section Retrieving a document by an exact title match.

Back to top

Uploading documents

Creating an empty document

This example creates a new word processor document in the Documents List feed by creating a DocumentListEntry object containining metadata for the document.

DocumentListEntry createdEntry = null;

// Create an empty word processor document
createdEntry = createNewDocument("NewDocTitle", "document");
System.out.println("Document now online @ :" + createdEntry.getHtmlLink().getHref());

// Create an empty presentation
createdEntry = createNewDocument("NewPresentationTitle", "presentation");
System.out.println("Presentation now online @ :" + createdEntry.getHtmlLink().getHref());

// Create an empty spreadsheet
createdEntry = createNewDocument("NewSpreadsheetTitle", "spreadsheet");
System.out.println("Spreadsheet now online @ :" + createdEntry.getHtmlLink().getHref());

public DocumentListEntry createNewDocument(String title, String type)
    throws IOException, ServiceException {
  DocumentListEntry newEntry = null;
  if (type.equals("document")) {
    newEntry = new DocumentEntry();
  } else if (type.equals("presentation")) {
    newEntry = new PresentationEntry();
  } else if (type.equals("spreadsheet")) {
    newEntry = new SpreadsheetEntry();
  }
  newEntry.setTitle(new PlainTextConstruct(title));
  return client.insert(new URL("https://docs.google.com/feeds/documents/private/full/"), newEntry);
}

Uploading documents with content

To upload a document to the server you can attach the file to the new DocumentListEntry using the setFile() method. Once the file is associated with this entry, it's contents will be sent to the server when you insert the DocumentListEntry.

The example below shows how to upload a file when given the absolute path of a file. Note that the mime-type sent to the server is inferred from the file's extension.

DocumentListEntry uploadedEntry = uploadFile("/path/to/your/file.doc", "TitleToUse");
System.out.println("Document now online @ :" + uploadedEntry.getHtmlLink().getHref());
        
public DocumentListEntry uploadFile(String filepath, String title)
    throws IOException, ServiceException  {
  File file = new File(filepath);
  DocumentListEntry newDocument = new DocumentListEntry();
  String mimeType = DocumentListEntry.MediaType.fromFileName(file.getName()).getMimeType();
  newDocument.setFile(new File(filepath), mimeType);
  newDocument.setTitle(new PlainTextConstruct(title));

  return client.insert(new URL("https://docs.google.com/feeds/documents/private/full/"), newDocument);
}

Note: that the above sample sets the name of the document to "TitleToUse", but you are free to choose a different name by passing in a string to the PlainTextConstruct constructor.

Creating/uploading documents folders

Creating an empty document in a folder

To create an empty document, presentation, or spreadsheet in an existing folder, you need to make a POST request to the folder's Atom content src URL. One way to do this is to overload our createNewDocument() method to accept a URL object. It assumed that folderEntry is to destination folder as DocumentListEntry object.

URL destFolderUrl = new URL("https://docs.google.com/feeds/folders/private/full/" + folderEntry.getResourceId());
DocumentListEntry createdEntry = createNewDocument("NewDocument", "document", destFolderUrl);
System.out.println("Document now online in folder '" +
    folderEntry.getTitle().getPlainText() + "' @ :" + createdEntry.getHtmlLink().getHref());

public DocumentListEntry createNewDocument(String title, String type, URL uri)
    throws IOException, ServiceException {
  DocumentListEntry newEntry = null;
  if (type.equals("document")) {
    newEntry = new DocumentEntry();
  } else if (type.equals("presentation")) {
    newEntry = new PresentationEntry();
  } else if (type.equals("spreadsheet")) {
    newEntry = new SpreadsheetEntry();
  }
  newEntry.setTitle(new PlainTextConstruct(title));
  return client.insert(uri, newEntry);
}

public DocumentListEntry createNewDocument(String title, String type)
    throws MalformedURLException, IOException, ServiceException {
  return createNewDocument(title, type, new URL("https://docs.google.com/feeds/documents/private/full/"));
}

Uploading a document to a folder

Similar to creating a document inside a folder, you can upload an existing document, presentation, or spreadsheet into a folder by overloading the uploadFile() method (defined above) to accept the URL of the destination folder. It assumed that folderEntry is a valid DocumentListEntry object representing the folder you wish to upload to.

URL destFolderUri = new URL("https://docs.google.com/feeds/folders/private/full/" + folderEntry.getResourceId());
DocumentListEntry uploadedEntry = uploadFile("/path/to/your/file.doc", "TitleToUse", destFolderUri);
System.out.println("Document now online in folder '" +
    folderEntry.getTitle().getPlainText() + "' @ :" + uploadedEntry.getHtmlLink().getHref());

// Uploads a file to a particular folder specified by the URL argument
public DocumentListEntry uploadFile(String filepath, String title, URL uri)
    throws IOException, ServiceException  {
  File file = new File(filepath);
  DocumentListEntry newDocument = new DocumentListEntry();
  String mimeType = DocumentListEntry.MediaType.fromFileName(file.getName()).getMimeType();
  newDocument.setFile(new File(filepath), mimeType);
  newDocument.setTitle(new PlainTextConstruct(title));

  return client.insert(uri, newDocument);
}

// Uploads a file to the root documents list
public DocumentListEntry uploadFile(String filepath, String title)
    throws IOException, ServiceException  {
  return uploadFile(filepath, title, new URL("https://docs.google.com/feeds/documents/private/full/"));
}

Back to top

Downloading and exporting documents

To export documents from the Documents List feed, you need the Atom entry of the document or the document, spreadsheet, or presentation's resource id (e.g. spreadsheet:12345). Note, each type of document has a valid set of export formats.

Exporting word processor documents

The following example exports a word processor document contained in documentEntry, a DocumentListEntry object as a .doc file:

String resourceId = documentEntry.getResourceId();  // resourceId is of the form "document:dfrkj84g_9128gtvh8nt"
downloadDocument(resourceId, "/path/to/export/to/myDoc.doc", "doc");

public void downloadDocument(String resourceId, String filepath, String format)
    throws IOException, MalformedURLException, ServiceException {
  downloadFile(resourceId, filepath, format);
}

public void downloadFile(String resourceId, String filepath, String format)
    throws IOException, MalformedURLException, ServiceException {

  String docType = resourceId.substring(0, resourceId.lastIndexOf(':'));
  String docId = resourceId.substring(resourceId.lastIndexOf(':') + 1);

  URL exportUrl = new URL("https://docs.google.com/feeds/download/" + docType +
      "s/Export?docID=" + docId + "&exportFormat=" + format);

  System.out.println("Exporting document from: " + exportUrl);

  MediaContent mc = new MediaContent();
  mc.setUri(exportUrl.toString());
  MediaSource ms = client.getMedia(mc);

  InputStream inStream = null;
  FileOutputStream outStream = null;

  try {
    inStream = ms.getInputStream();
    outStream = new FileOutputStream(filepath);

    int c;
    while ((c = inStream.read()) != -1) {
      outStream.write(c);
    }
  } finally {
    if (inStream != null) {
      inStream.close();
    }
    if (outStream != null) {
      outStream.flush();
      outStream.close();
    }
  }
}

Exporting presentations

The same downloadFile can be used to export presentations. The following example exports a presentation contained in documentEntry, a DocumentListEntry object as a .pdf:

String resourceId = documentEntry.getResourceId();  // resourceId is of the form "presentation:dfrkj84g_9128gtvh8nt"
downloadPresentation(resourceId, "/path/to/export/to/preso.pdf", "pdf");

public void downloadPresentation(String resourceId, String filepath, String format)
    throws IOException, MalformedURLException, ServiceException {
  downloadFile(resourceId, filepath, format);
}

Exporting spreadsheets

To export spreadsheets, change the original downloadFile() method to support the modified export URL and query parameters.

String resourceId = documentEntry.getResourceId();  // resourceId is of the form "spreadsheet:dfrkj84g_9128gtvh8nt"
downloadSpreadsheet(resourceId, "/path/to/export/to/spreadsheet.xls", "xls");

public static void downloadSpreadsheet(String resourceId, String filepath, String format)
    throws IOException, MalformedURLException, ServiceException {

  // Valid spreadsheet export formats
  HashMap SPREADSHEET_FORMATS = new HashMap();
  SPREADSHEET_FORMATS.put("xls", "4");
  SPREADSHEET_FORMATS.put("ods", "13");
  SPREADSHEET_FORMATS.put("pdf", "12");
  SPREADSHEET_FORMATS.put("csv", "5");
  SPREADSHEET_FORMATS.put("tsv", "23");
  SPREADSHEET_FORMATS.put("html", "102");

  String key = resourceId.substring(resourceId.lastIndexOf(':') + 1);

  String exportUrl = "https://spreadsheets.google.com/feeds/download/spreadsheets" +
      "/Export?key=" + key + "&fmcmd=" + SPREADSHEET_FORMATS.get(format);

  // If exporting to .csv or .tsv, add the gid parameter to specify which sheet to export
  if (format.equals("csv") || format.equals("tsv")) {
    exportUrl += "&gid=0";  // gid=0 will download only the first sheet
  }

  System.out.println("Exporting document from: " + exportUrl);

  MediaContent mc = new MediaContent();
  mc.setUri(exportUrl.toString());
  MediaSource ms = client.getMedia(mc);

  InputStream inStream = null;
  FileOutputStream outStream = null;

  try {
    inStream = ms.getInputStream();
    outStream = new FileOutputStream(filepath);

    int c;
    while ((c = inStream.read()) != -1) {
      outStream.write(c);
    }
  } finally {
    if (inStream != null) {
      inStream.close();
    }

    if (outStream != null) {
      outStream.flush();
      outStream.close();
    }
  }
}

Important: In order to download spreadsheets, your client needs a valid token for the Spreadsheets API service. See downloading spreadsheets section of the protocol guide for more details.

If you're using AuthSub, the solution to the above warning is to request a multi-scoped token, good for both the Documents List API and the Spreadsheets API. Pass in String scope = "https://docs.google.com/feeds/%20https://spreadsheets.google.com/feeds/" to AuthSubUtil.getRequestUrl().

For ClientLogin, the process is somewhat more involved. First create a SpreadsheetsService object (to obtain a spreadsheets token), and then swap that token into your DocsService object. This example demonstrates that process:

import com.google.gdata.client.spreadsheet.SpreadsheetService;

// Authenticate against the Spreadsheets API to obtain an auth token
SpreadsheetService spread_client = new SpreadsheetService("yourCo-yourAppName-v1");
spread_client.setUserCredentials("example@gmail.com", "pa$$word");

// Substitute the spreadsheets token for the docs token
UserToken docsToken = (UserToken) client.getAuthTokenFactory().getAuthToken();
UserToken spreadsheetsToken = (UserToken) spread_client.getAuthTokenFactory().getAuthToken();
client.setUserToken(spreadsheetsToken.getValue());

String resourceId = documentEntry.getResourceId();  // resourceId is of the form "spreadsheet:dfrkj84g_9128gtvh8nt"
downloadSpreadsheet(resourceId, "/path/to/export/to/spreadsheet.xls", "xls");

// Restore docs token for our DocList client
client.setUserToken(docsToken.getValue());

Back to top

Trashing documents

To delete a document, call the delete() method on the retrieved DocumentListEntry:

documentEntry.delete()

Updating existing documents

Updating metadata

Updating documents requires the use of ETags to make sure you are not overwriting another client's changes. In the following examples, the If-Match header is set to overwrite any changes we don't know about. However, in pratice, you should use the entry's Etag by calling documentEntry.getEtag() and referencing it in the If-Match header.

Here is an example of updating a document's metadata, but leaving its content unchanged. The document's name will be changed to 'Updated Title'. It is assumed you have already fetched the documentEntry.

// Simple example, we don't care about nuking someone else's changes
client.getRequestFactory().setHeader("If-Match", "*");

documentEntry.setTitle(new PlainTextConstruct("Updated Title"));
DocumentListEntry updatedEntry = documentEntry.update();

System.out.println(updatedEntry.getTitle().getPlainText());

Alternatively, you can use the client's update() method if you don't have the full documentEntry handy.

Replacing a document's content

To update a document's content, use the DocumentListEntry's updateMediaupdateMedia() method. The following example replaces the document's content with "updated content". It is assumed you have already fetched the documentEntry.

// Simple example, we don't care about nuking someone else's changes
client.getRequestFactory().setHeader("If-Match", "*");

documentEntry.setMediaSource(new MediaByteArraySource("updated content".getBytes(), "text/plain"));
documentEntry.updateMedia(false);

Back to top

Folder management

Creating folders

Creating a folder is similar to creating an empty document. Use the insert method as follows:

DocumentListEntry folderEntry = createFolder("New Folder");

public DocumentListEntry createFolder(String title) throws IOException, ServiceException {
  DocumentListEntry newEntry = new FolderEntry();
  newEntry.setTitle(new PlainTextConstruct(title));
  return client.insert(url, newEntry);
}

Tip: To create a folder inside of a parent folder, modify the createNewDocument() method (above) to accept a FolderEntry.

Trashing folders

Deleting a folder is the same as deleting a document. Use the DocumentListEntry's or service's delete(). This example uses the entry's delete():

folderEntry.delete()

Moving documents/folders in and out folders

Moving a document into a folder requires that you have a DocumentListEntry object for the document, and another for the folder in which the document should be moved to. Ultimately, a new entry is created with its Atom <id> set to the source document/folder's ID. An HTTP POST is then sent to the folder entry's content src link. Here is an example:

Moving a word processor document into a folder:
DocumentListEntry movedDocumentEntry = moveDocumentToFolder(documentEntry, destFolderEntry);

public DocumentListEntry moveDocumentToFolder(DocumentListEntry documentEntry, DocumentListEntry destFolderEntry)
    throws IOException, MalformedURLException, ServiceException {
  DocumentEntry newEntry = new DocumentEntry();
  URL url = new URL("https://docs.google.com/feeds/folders/private/full/" + destFolderEntry.getResourceId());
  newEntry.setId(documentEntry.getId());
  return client.insert(url, newEntry);
}
Moving a presentation into a folder:

The process is the same for moving presentations except for this time, a PresentationEntry is created.

DocumentListEntry movedPresentationEntry = movePresentationToFolder(presentationEntry, destFolderEntry);

public DocumentListEntry movePresentationToFolder(DocumentListEntry presentationEntry, DocumentListEntry destFolderEntry)
    throws IOException, MalformedURLException, ServiceException {
  PresentationEntry newEntry = new PresentationEntry();
  URL url = new URL("https://docs.google.com/feeds/folders/private/full/" + destFolderEntry.getResourceId());
  newEntry.setId(presentationEntry.getId());
  return client.insert(url, newEntry);
}
Moving a spreadsheet into a folder:

The process is the same for moving spreadsheet. Instead create a SpreadsheetEntry is created.

DocumentListEntry movedSpreadsheetEntry = moveSpreadsheetToFolder(spreadsheetEntry, destFolderEntry);

public DocumentListEntry moveSpreadsheetToFolder(DocumentListEntry spreadsheetEntry, DocumentListEntry destFolderEntry)
    throws IOException, MalformedURLException, ServiceException {
  SpreadsheetEntry newEntry = new SpreadsheetEntry();
  URL url = new URL("https://docs.google.com/feeds/folders/private/full/" + destFolderEntry.getResourceId());
  newEntry.setId(spreadsheetEntry.getId());
  return client.insert(url, newEntry);
}
Moving a folder into another folder:

The process is the same for moving a folder inside another folder. Instead create a FolderEntry is created.

DocumentListEntry movedFolderEntry = moveFolderToFolder(srcFolderEntry, destFolderEntry);

public DocumentListEntry moveFolderToFolder(DocumentListEntry srcFolderEntry, DocumentListEntry destFolderEntry)
    throws IOException, MalformedURLException, ServiceException {
  FolderEntry newEntry = new FolderEntry();
  URL url = new URL("https://docs.google.com/feeds/folders/private/full/" + destFolderEntry.getResourceId());
  newEntry.setId(srcFolderEntry.getId());
  return client.insert(url, newEntry);
}
Moving a document/folder out of a folder:

Moving a folder or document out of its parent folder can be done be executing a delete() to the folder content's edit link:

// Simple example, we don't care about nuking someone else's changes
client.getRequestFactory().setHeader("If-Match", "*");

moveOutOfFolder(documentEntry, parentFolderEntry);

public void moveOutOfFolder(DocumentListEntry documentEntry, DocumentListEntry parentFolderEntry)
    throws IOException, MalformedURLException, ServiceException {
  URL url = new URL("https://docs.google.com/feeds/folders/private/full/" +
      parentFolderEntry.getResourceId() + "/" + documentEntry.getResourceId());
  client.delete(url);
}

Back to top

Modifying Document Sharing Permissions

Retrieving the ACL feed for a document

To retrieve the ACL permissions for a document, you need the entry's <gd:feedLink> from the Atom entry. The DocumentListEntry has a getAclFeedLink() method for finding this value.

The following example fetches the first document the authenticated user owns, queries its ACL feed, and prints out the permission entries:

DocumentQuery query = new DocumentQuery(new URL("https://docs.google.com/feeds/documents/private/full/-/mine"));
DocumentListFeed resultFeed = client.getFeed(query, DocumentListFeed.class);
DocumentListEntry documentEntry = resultFeed.getEntries().get(0);

AclFeed aclFeed = client.getFeed(new URL(documentEntry.getAclFeedLink().getHref()), AclFeed.class);
for (AclEntry entry : aclFeed.getEntries()) {
  System.out.println(
      entry.getScope().getValue() + " (" + entry.getScope().getType() + ") : " + entry.getRole().getValue());
}

Modifying the ACL feed for a document

Adding a new permission

To add a new permission to a document, your client needs to create a new AclEntry and POST it to the server.

Here's an example that adds 'user@example.com' as a reader to the document represented by documentEntry:

AclRole role = new AclRole("reader");
AclScope scope = new AclScope(AclScope.Type.USER, "user@example.com");
AclEntry aclEntry = addAclRole(role, scope, documentEntry);

public AclEntry addAclRole(AclRole role, AclScope scope, DocumentListEntry documentEntry)
    throws IOException, MalformedURLException, ServiceException  {
  AclEntry entry = new AclEntry();
  entry.setRole(role);
  entry.setScope(scope);

  URL url = new URL("https://docs.google.com/feeds/acl/private/full/" + documentEntry.getResourceId());
  return client.insert(url, entry);
}

Possible values for the AclRole are reader, writer, and owner.

Updating a permission

You can update an existing ACL permission by sending a PUT request (with the updated content payload) to the edit link of the acl entry in question.

This example modifies the previous aclEntry by updating 'user@example.com' to be a writer (collaborator):

// Simple example, we don't care about nuking someone else's changes
client.getRequestFactory().setHeader("If-Match", "*");

aclEntry.setRole(new AclRole("writer"));
AclEntry updatedAclEntry = aclEntry.update();

// Could also use the client's update method
// client.update(new URL(aclEntry.getEditLink().getHref()), aclEntry);

Deleting a permission

Deleting a permission invovles sending a DELETE to the ACL entry's edit link.

// Simple example, we don't care about nuking someone else's changes
client.getRequestFactory().setHeader("If-Match", "*");

aclEntry.delete();

// Could also use the client's delete method
// client.delete(new URL(aclEntry.getEditLink().getHref()), aclEntry);

Back to top

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.