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
+951
View File
@@ -0,0 +1,951 @@
/* 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.docs;
import com.google.gdata.client.GoogleAuthTokenFactory.UserToken;
import com.google.gdata.client.GoogleService;
import com.google.gdata.client.Query;
import com.google.gdata.client.docs.DocsService;
import com.google.gdata.data.MediaContent;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.acl.AclEntry;
import com.google.gdata.data.acl.AclFeed;
import com.google.gdata.data.acl.AclRole;
import com.google.gdata.data.acl.AclScope;
import com.google.gdata.data.docs.DocumentEntry;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
import com.google.gdata.data.docs.FolderEntry;
import com.google.gdata.data.docs.PresentationEntry;
import com.google.gdata.data.docs.RevisionFeed;
import com.google.gdata.data.docs.SpreadsheetEntry;
import com.google.gdata.data.media.MediaSource;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* An application that serves as a sample to show how the Documents List Service
* can be used to search your documents, upload and download files, change
* sharing permission, file documents in folders, and view revisions history.
*
*
*
*/
public class DocumentList {
public DocsService service;
public GoogleService spreadsheetsService;
public static final String DEFAULT_HOST = "docs.google.com";
public static final String SPREADSHEETS_SERVICE_NAME = "wise";
public static final String SPREADSHEETS_HOST = "spreadsheets.google.com";
private final String URL_FEED = "/feeds";
private final String URL_DOWNLOAD = "/download";
private final String URL_DOCLIST_FEED = "/private/full";
private final String URL_DEFAULT = "/default";
private final String URL_FOLDERS = "/contents";
private final String URL_ACL = "/acl";
private final String URL_REVISIONS = "/revisions";
private final String URL_CATEGORY_DOCUMENT = "/-/document";
private final String URL_CATEGORY_SPREADSHEET = "/-/spreadsheet";
private final String URL_CATEGORY_PDF = "/-/pdf";
private final String URL_CATEGORY_PRESENTATION = "/-/presentation";
private final String URL_CATEGORY_STARRED = "/-/starred";
private final String URL_CATEGORY_TRASHED = "/-/trashed";
private final String URL_CATEGORY_FOLDER = "/-/folder";
private final String URL_CATEGORY_EXPORT = "/Export";
private final String PARAMETER_SHOW_FOLDERS = "showfolders=true";
private String host;
private final Map<String, String> DOWNLOAD_DOCUMENT_FORMATS;
{
DOWNLOAD_DOCUMENT_FORMATS = new HashMap<String, String>();
DOWNLOAD_DOCUMENT_FORMATS.put("doc", "doc");
DOWNLOAD_DOCUMENT_FORMATS.put("txt", "txt");
DOWNLOAD_DOCUMENT_FORMATS.put("odt", "odt");
DOWNLOAD_DOCUMENT_FORMATS.put("pdf", "pdf");
DOWNLOAD_DOCUMENT_FORMATS.put("png", "png");
DOWNLOAD_DOCUMENT_FORMATS.put("rtf", "rtf");
DOWNLOAD_DOCUMENT_FORMATS.put("html", "html");
DOWNLOAD_DOCUMENT_FORMATS.put("zip", "zip");
}
private final Map<String, String> DOWNLOAD_PRESENTATION_FORMATS;
{
DOWNLOAD_PRESENTATION_FORMATS = new HashMap<String, String>();
DOWNLOAD_PRESENTATION_FORMATS.put("pdf", "pdf");
DOWNLOAD_PRESENTATION_FORMATS.put("png", "png");
DOWNLOAD_PRESENTATION_FORMATS.put("ppt", "ppt");
DOWNLOAD_PRESENTATION_FORMATS.put("swf", "swf");
DOWNLOAD_PRESENTATION_FORMATS.put("txt", "txt");
}
private final Map<String, String> DOWNLOAD_SPREADSHEET_FORMATS;
{
DOWNLOAD_SPREADSHEET_FORMATS = new HashMap<String, String>();
DOWNLOAD_SPREADSHEET_FORMATS.put("xls", "xls");
DOWNLOAD_SPREADSHEET_FORMATS.put("ods", "ods");
DOWNLOAD_SPREADSHEET_FORMATS.put("pdf", "pdf");
DOWNLOAD_SPREADSHEET_FORMATS.put("csv", "csv");
DOWNLOAD_SPREADSHEET_FORMATS.put("tsv", "tsv");
DOWNLOAD_SPREADSHEET_FORMATS.put("html", "html");
}
/**
* Constructor.
*
* @param applicationName name of the application.
*
* @throws DocumentListException
*/
public DocumentList(String applicationName) throws DocumentListException {
this(applicationName, DEFAULT_HOST);
}
/**
* Constructor
*
* @param applicationName name of the application
* @param host the host that contains the feeds
*
* @throws DocumentListException
*/
public DocumentList(String applicationName, String host) throws DocumentListException {
if (host == null) {
throw new DocumentListException("null passed in required parameters");
}
service = new DocsService(applicationName);
// Creating a spreadsheets service is necessary for downloading spreadsheets
spreadsheetsService = new GoogleService(SPREADSHEETS_SERVICE_NAME, applicationName);
this.host = host;
}
/**
* Set user credentials based on a username and password.
*
* @param user username to log in with.
* @param pass password for the user logging in.
*
* @throws AuthenticationException
* @throws DocumentListException
*/
public void login(String user, String pass) throws AuthenticationException,
DocumentListException {
if (user == null || pass == null) {
throw new DocumentListException("null login credentials");
}
service.setUserCredentials(user, pass);
spreadsheetsService.setUserCredentials(user, pass);
}
/**
* Allow a user to login using an AuthSub token.
*
* @param token the token to be used when logging in.
*
* @throws AuthenticationException
* @throws DocumentListException
*/
public void loginWithAuthSubToken(String token) throws AuthenticationException,
DocumentListException {
if (token == null) {
throw new DocumentListException("null login credentials");
}
service.setAuthSubToken(token);
spreadsheetsService.setAuthSubToken(token);
}
/**
* Create a new item in the DocList.
*
* @param title the title of the document to be created.
* @param type the type of the document to be created. One of "spreadsheet",
* "presentation", or "document".
*
* @throws DocumentListException
* @throws ServiceException
* @throws IOException
* @throws MalformedURLException
*/
public DocumentListEntry createNew(String title, String type) throws MalformedURLException,
IOException, ServiceException,
DocumentListException {
if (title == null || type == null) {
throw new DocumentListException("null title or type");
}
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();
} else if (type.equals("folder")) {
newEntry = new FolderEntry();
}
newEntry.setTitle(new PlainTextConstruct(title));
return service.insert(buildUrl(URL_DEFAULT + URL_DOCLIST_FEED), newEntry);
}
/**
* Gets a feed containing the documents.
*
* @param category what types of documents to list:
* "all": lists all the doc objects (documents, spreadsheets, presentations)
* "folders": lists all doc objects including folders.
* "documents": lists only documents.
* "spreadsheets": lists only spreadsheets.
* "pdfs": lists only pdfs.
* "presentations": lists only presentations.
* "starred": lists only starred objects.
* "trashed": lists trashed objects.
*
* @throws IOException
* @throws MalformedURLException
* @throws ServiceException
* @throws DocumentListException
*/
public DocumentListFeed getDocsListFeed(String category) throws IOException,
MalformedURLException, ServiceException, DocumentListException {
if (category == null) {
throw new DocumentListException("null category");
}
URL url;
if (category.equals("all")) {
url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED);
} else if (category.equals("folders")) {
String[] parameters = {PARAMETER_SHOW_FOLDERS};
url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_FOLDER, parameters);
} else if (category.equals("documents")) {
url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_DOCUMENT);
} else if (category.equals("spreadsheets")) {
url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_SPREADSHEET);
} else if (category.equals("pdfs")) {
url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_PDF);
} else if (category.equals("presentations")) {
url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_PRESENTATION);
} else if (category.equals("starred")) {
url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_STARRED);
} else if (category.equals("trashed")) {
url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_TRASHED);
} else {
return null;
}
return service.getFeed(url, DocumentListFeed.class);
}
/**
* Gets the entry for the provided object id.
*
* @param resourceId the resource id of the object to fetch an entry for.
*
* @throws IOException
* @throws MalformedURLException
* @throws ServiceException
* @throws DocumentListException
*/
public DocumentListEntry getDocsListEntry(String resourceId) throws IOException,
MalformedURLException, ServiceException, DocumentListException {
if (resourceId == null) {
throw new DocumentListException("null resourceId");
}
URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + resourceId);
return service.getEntry(url, DocumentListEntry.class);
}
/**
* Gets the feed for all the objects contained in a folder.
*
* @param folderResourceId the resource id of the folder to return the feed
* for the contents.
*
* @throws IOException
* @throws MalformedURLException
* @throws ServiceException
* @throws DocumentListException
*/
public DocumentListFeed getFolderDocsListFeed(String folderResourceId) throws IOException,
MalformedURLException, ServiceException, DocumentListException {
if (folderResourceId == null) {
throw new DocumentListException("null folderResourceId");
}
URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + folderResourceId
+ URL_FOLDERS);
return service.getFeed(url, DocumentListFeed.class);
}
/**
* Gets a feed containing the documents.
*
* @param resourceId the resource id of the object to fetch revisions for.
*
* @throws IOException
* @throws MalformedURLException
* @throws ServiceException
* @throws DocumentListException
*/
public RevisionFeed getRevisionsFeed(String resourceId) throws IOException,
MalformedURLException, ServiceException, DocumentListException {
if (resourceId == null) {
throw new DocumentListException("null resourceId");
}
URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + resourceId
+ URL_REVISIONS);
return service.getFeed(url, RevisionFeed.class);
}
/**
* Search the documents, and return a feed of docs that match.
*
* @param searchParameters parameters to be used in searching criteria.
*
* @throws IOException
* @throws MalformedURLException
* @throws ServiceException
* @throws DocumentListException
*/
public DocumentListFeed search(Map<String, String> searchParameters) throws IOException,
MalformedURLException, ServiceException, DocumentListException {
return search(searchParameters, null);
}
/**
* Search the documents, and return a feed of docs that match.
*
* @param searchParameters parameters to be used in searching criteria.
* accepted parameters are:
* "q": Typical search query
* "alt":
* "author":
* "updated-min": Lower bound on the last time a document' content was changed.
* "updated-max": Upper bound on the last time a document' content was changed.
* "edited-min": Lower bound on the last time a document was edited by the
* current user. This value corresponds to the app:edited value in the
* Atom entry, which represents changes to the document's content or metadata.
* "edited-max": Upper bound on the last time a document was edited by the
* current user. This value corresponds to the app:edited value in the
* Atom entry, which represents changes to the document's content or metadata.
* "title": Specifies the search terms for the title of a document.
* This parameter used without title-exact will only submit partial queries, not exact
* queries.
* "title-exact": Specifies whether the title query should be taken as an exact string.
* Meaningless without title. Possible values are true and false.
* "opened-min": Bounds on the last time a document was opened by the current user.
* Use the RFC 3339 timestamp format. For example: 2005-08-09T10:57:00-08:00
* "opened-max": Bounds on the last time a document was opened by the current user.
* Use the RFC 3339 timestamp format. For example: 2005-08-09T10:57:00-08:00
* "owner": Searches for documents with a specific owner.
* Use the email address of the owner.
* "writer": Searches for documents which can be written to by specific users.
* Use a single email address or a comma separated list of email addresses.
* "reader": Searches for documents which can be read by specific users.
* Use a single email address or a comma separated list of email addresses.
* "showfolders": Specifies whether the query should return folders as well as documents.
* Possible values are true and false.
* @param category define the category to search. (documents, spreadsheets, presentations,
* starred, trashed, folders)
*
* @throws IOException
* @throws MalformedURLException
* @throws ServiceException
* @throws DocumentListException
*/
public DocumentListFeed search(Map<String, String> searchParameters, String category)
throws IOException, MalformedURLException, ServiceException, DocumentListException {
if (searchParameters == null) {
throw new DocumentListException("searchParameters null");
}
URL url;
if (category == null || category.equals("")) {
url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED);
} else if (category.equals("documents")) {
url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_DOCUMENT);
} else if (category.equals("spreadsheets")) {
url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_SPREADSHEET);
} else if (category.equals("presentations")) {
url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_PRESENTATION);
} else if (category.equals("starred")) {
url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_STARRED);
} else if (category.equals("trashed")) {
url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_TRASHED);
} else if (category.equals("folders")) {
url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_FOLDER);
} else {
throw new DocumentListException("invaild category");
}
Query qry = new Query(url);
for (String key : searchParameters.keySet()) {
qry.setStringCustomParameter(key, searchParameters.get(key));
}
return service.query(qry, DocumentListFeed.class);
}
/**
* Upload a file.
*
* @param filepath path to uploaded file.
* @param title title to use for uploaded file.
*
* @throws ServiceException when the request causes an error in the Doclist
* service.
* @throws IOException when an error occurs in communication with the Doclist
* service.
* @throws DocumentListException
*/
public DocumentListEntry uploadFile(String filepath, String title)
throws IOException, ServiceException, DocumentListException {
if (filepath == null || title == null) {
throw new DocumentListException("null passed in for required parameters");
}
File file = new File(filepath);
String mimeType = DocumentListEntry.MediaType.fromFileName(file.getName())
.getMimeType();
DocumentEntry newDocument = new DocumentEntry();
newDocument.setFile(file, mimeType);
newDocument.setTitle(new PlainTextConstruct(title));
return service
.insert(buildUrl(URL_DEFAULT + URL_DOCLIST_FEED), newDocument);
}
/**
* Trash an object.
*
* @param resourceId the resource id of object to be trashed.
* @param delete true to delete the permanently, false to move it to the
* trash.
*
* @throws IOException
* @throws MalformedURLException
* @throws ServiceException
* @throws DocumentListException
*/
public void trashObject(String resourceId, boolean delete) throws IOException,
MalformedURLException, ServiceException, DocumentListException {
if (resourceId == null) {
throw new DocumentListException("null resourceId");
}
String feedUrl = URL_DEFAULT + URL_DOCLIST_FEED + "/" + resourceId;
if (delete) {
feedUrl += "?delete=true";
}
service.delete(buildUrl(feedUrl), getDocsListEntry(resourceId).getEtag());
}
/**
* Remove an object from a folder.
*
* @param resourceId the resource id of an object to be removed from the
* folder.
* @param folderResourceId the resource id of the folder to remove the object
* from.
*
* @throws IOException
* @throws MalformedURLException
* @throws ServiceException
* @throws DocumentListException
*/
public void removeFromFolder(String resourceId, String folderResourceId)
throws IOException, MalformedURLException, ServiceException,
DocumentListException {
if (resourceId == null || folderResourceId == null) {
throw new DocumentListException("null passed in for required parameters");
}
URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + folderResourceId
+ URL_FOLDERS + "/" + resourceId);
service.delete(url, getDocsListEntry(resourceId).getEtag());
}
/**
* Downloads a file.
*
* @param exportUrl the full url of the export link to download the file from.
* @param filepath path and name of the object to be saved as.
*
* @throws IOException
* @throws MalformedURLException
* @throws ServiceException
* @throws DocumentListException
*/
public void downloadFile(URL exportUrl, String filepath) throws IOException,
MalformedURLException, ServiceException, DocumentListException {
if (exportUrl == null || filepath == null) {
throw new DocumentListException("null passed in for required parameters");
}
MediaContent mc = new MediaContent();
mc.setUri(exportUrl.toString());
MediaSource ms = service.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();
}
}
}
/**
* Downloads a spreadsheet file.
*
* @param filepath path and name of the object to be saved as.
* @param resourceId the resource id of the object to be downloaded.
* @param format format to download the file to. The following file types are
* supported: spreadsheets: "ods", "pdf", "xls", "csv", "html", "tsv"
*
* @throws IOException
* @throws MalformedURLException
* @throws ServiceException
* @throws DocumentListException
*/
public void downloadSpreadsheet(String resourceId, String filepath,
String format) throws IOException, MalformedURLException,
ServiceException, DocumentListException {
if (resourceId == null || filepath == null || format == null) {
throw new DocumentListException("null passed in for required parameters");
}
UserToken docsToken = (UserToken) service.getAuthTokenFactory()
.getAuthToken();
UserToken spreadsheetsToken = (UserToken) spreadsheetsService
.getAuthTokenFactory().getAuthToken();
service.setUserToken(spreadsheetsToken.getValue());
HashMap<String, String> parameters = new HashMap<String, String>();
parameters
.put("key", resourceId.substring(resourceId.lastIndexOf(':') + 1));
parameters.put("exportFormat", format);
// If exporting to .csv or .tsv, add the gid parameter to specify which
// sheet to export
if (format.equals(DOWNLOAD_SPREADSHEET_FORMATS.get("csv"))
|| format.equals(DOWNLOAD_SPREADSHEET_FORMATS.get("tsv"))) {
parameters.put("gid", "0"); // download only the first sheet
}
URL url = buildUrl(SPREADSHEETS_HOST, URL_DOWNLOAD + "/spreadsheets"
+ URL_CATEGORY_EXPORT, parameters);
downloadFile(url, filepath);
// Restore docs token for our DocList client
service.setUserToken(docsToken.getValue());
}
/**
* Downloads a document.
*
* @param filepath path and name of the object to be saved as.
* @param resourceId the resource id of the object to be downloaded.
* @param format format to download the file to. The following file types are
* supported: documents: "doc", "txt", "odt", "png", "pdf", "rtf",
* "html"
*
* @throws IOException
* @throws MalformedURLException
* @throws ServiceException
* @throws DocumentListException
*/
public void downloadDocument(String resourceId, String filepath, String format)
throws IOException, MalformedURLException, ServiceException,
DocumentListException {
if (resourceId == null || filepath == null || format == null) {
throw new DocumentListException("null passed in for required parameters");
}
String[] parameters = {"docID=" + resourceId, "exportFormat=" + format};
URL url = buildUrl(URL_DOWNLOAD + "/documents" + URL_CATEGORY_EXPORT,
parameters);
downloadFile(url, filepath);
}
/**
* Downloads a presentation.
*
* @param filepath path and name of the object to be saved as.
* @param resourceId the resource id of the object to be downloaded.
* @param format format to download the file to. The following file types are
* supported: presentations: "pdf", "ppt", "png", "swf", "txt"
*
* @throws IOException
* @throws MalformedURLException
* @throws ServiceException
* @throws DocumentListException
*/
public void downloadPresentation(String resourceId, String filepath,
String format) throws IOException, MalformedURLException,
ServiceException, DocumentListException {
if (resourceId == null || filepath == null || format == null) {
throw new DocumentListException("null passed in for required parameters");
}
String[] parameters = {"docID=" + resourceId, "exportFormat=" + format};
URL url = buildUrl(URL_DOWNLOAD + "/presentations" + URL_CATEGORY_EXPORT,
parameters);
downloadFile(url, filepath);
}
/**
* Moves a object to a folder.
*
* @param resourceId the resource id of the object to be moved to the folder.
* @param folderId the id of the folder to move the object to.
*
* @throws IOException
* @throws MalformedURLException
* @throws ServiceException
* @throws DocumentListException
*/
public DocumentListEntry moveObjectToFolder(String resourceId, String folderId)
throws IOException, MalformedURLException, ServiceException, DocumentListException {
if (resourceId == null || folderId == null) {
throw new DocumentListException("null passed in for required parameters");
}
DocumentListEntry doc = new DocumentListEntry();
doc.setId(buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + resourceId).toString());
URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + folderId + URL_FOLDERS);
return service.insert(url, doc);
}
/**
* Gets the access control list for a object.
*
* @param resourceId the resource id of the object to retrieve the ACL for.
*
* @throws IOException
* @throws MalformedURLException
* @throws ServiceException
* @throws DocumentListException
*/
public AclFeed getAclFeed(String resourceId) throws IOException,
MalformedURLException, ServiceException, DocumentListException {
if (resourceId == null) {
throw new DocumentListException("null resourceId");
}
URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + resourceId
+ URL_ACL);
return service.getFeed(url, AclFeed.class);
}
/**
* Add an ACL role to an object.
*
* @param role the role of the ACL to be added to the object.
* @param scope the scope for the ACL.
* @param resourceId the resource id of the object to set the ACL for.
*
* @throws IOException
* @throws MalformedURLException
* @throws ServiceException
* @throws DocumentListException
*/
public AclEntry addAclRole(AclRole role, AclScope scope, String resourceId)
throws IOException, MalformedURLException, ServiceException,
DocumentListException {
if (role == null || scope == null || resourceId == null) {
throw new DocumentListException("null passed in for required parameters");
}
AclEntry entry = new AclEntry();
entry.setRole(role);
entry.setScope(scope);
URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + resourceId + URL_ACL);
return service.insert(url, entry);
}
/**
* Change the ACL role of a file.
*
* @param role the new role of the ACL to be updated.
* @param scope the new scope for the ACL.
* @param resourceId the resource id of the object to be updated.
*
* @throws IOException
* @throws MalformedURLException
* @throws ServiceException
* @throws DocumentListException
*/
public AclEntry changeAclRole(AclRole role, AclScope scope, String resourceId)
throws IOException, ServiceException, DocumentListException {
if (role == null || scope == null || resourceId == null) {
throw new DocumentListException("null passed in for required parameters");
}
URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + resourceId
+ URL_ACL);
return service.update(url, scope, role);
}
/**
* Remove an ACL role from a object.
*
* @param scope scope of the ACL to be removed.
* @param email email address to remove the role of.
* @param resourceId the resource id of the object to remove the role from.
*
* @throws IOException
* @throws MalformedURLException
* @throws ServiceException
* @throws DocumentListException
*/
public void removeAclRole(String scope, String email, String resourceId) throws IOException,
MalformedURLException, ServiceException, DocumentListException {
if (scope == null || email == null || resourceId == null) {
throw new DocumentListException("null passed in for required parameters");
}
URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + resourceId
+ URL_ACL + "/" + scope + "%3A" + email);
service.delete(url);
}
/**
* Returns the format code based on a file extension, and object id.
*
* @param resourceId the resource id of the object you want the format for.
* @param ext extension of the file you want the format for.
*
* @throws DocumentListException
*/
public String getDownloadFormat(String resourceId, String ext) throws DocumentListException {
if (resourceId == null || ext == null) {
throw new DocumentListException("null passed in for required parameters");
}
if (resourceId.indexOf("document") == 0) {
if (DOWNLOAD_DOCUMENT_FORMATS.containsKey(ext)) {
return DOWNLOAD_DOCUMENT_FORMATS.get(ext);
}
} else if (resourceId.indexOf("presentation") == 0) {
if (DOWNLOAD_PRESENTATION_FORMATS.containsKey(ext)) {
return DOWNLOAD_PRESENTATION_FORMATS.get(ext);
}
} else if (resourceId.indexOf("spreadsheet") == 0) {
if (DOWNLOAD_SPREADSHEET_FORMATS.containsKey(ext)) {
return DOWNLOAD_SPREADSHEET_FORMATS.get(ext);
}
}
throw new DocumentListException("invalid document type");
}
/**
* Gets the suffix of the resourceId. If the resourceId is
* "document:dh3bw3j_0f7xmjhd8", "dh3bw3j_0f7xmjhd8" will be returned.
*
* @param resourceId the resource id to extract the suffix from.
*
* @throws DocumentListException
*/
public String getResourceIdSuffix(String resourceId) throws DocumentListException {
if (resourceId == null) {
throw new DocumentListException("null resourceId");
}
if (resourceId.indexOf("%3A") != -1) {
return resourceId.substring(resourceId.lastIndexOf("%3A") + 3);
} else if (resourceId.indexOf(":") != -1) {
return resourceId.substring(resourceId.lastIndexOf(":") + 1);
}
throw new DocumentListException("Bad resourceId");
}
/**
* Gets the prefix of the resourceId. If the resourceId is
* "document:dh3bw3j_0f7xmjhd8", "document" will be returned.
*
* @param resourceId the resource id to extract the suffix from.
*
* @throws DocumentListException
*/
public String getResourceIdPrefix(String resourceId) throws DocumentListException {
if (resourceId == null) {
throw new DocumentListException("null resourceId");
}
if (resourceId.indexOf("%3A") != -1) {
return resourceId.substring(0, resourceId.indexOf("%3A"));
} else if (resourceId.indexOf(":") != -1) {
return resourceId.substring(0, resourceId.indexOf(":"));
} else {
throw new DocumentListException("Bad resourceId");
}
}
/**
* Builds a URL from a patch.
*
* @param path the path to add to the protocol/host
*
* @throws MalformedURLException
* @throws DocumentListException
*/
private URL buildUrl(String path) throws MalformedURLException, DocumentListException {
if (path == null) {
throw new DocumentListException("null path");
}
return buildUrl(path, null);
}
/**
* Builds a URL with parameters.
*
* @param path the path to add to the protocol/host
* @param parameters parameters to be added to the URL.
*
* @throws MalformedURLException
* @throws DocumentListException
*/
private URL buildUrl(String path, String[] parameters)
throws MalformedURLException, DocumentListException {
if (path == null) {
throw new DocumentListException("null path");
}
return buildUrl(host, path, parameters);
}
/**
* Builds a URL with parameters.
*
* @param domain the domain of the server
* @param path the path to add to the protocol/host
* @param parameters parameters to be added to the URL.
*
* @throws MalformedURLException
* @throws DocumentListException
*/
private URL buildUrl(String domain, String path, String[] parameters)
throws MalformedURLException, DocumentListException {
if (path == null) {
throw new DocumentListException("null path");
}
StringBuffer url = new StringBuffer();
url.append("https://" + domain + URL_FEED + path);
if (parameters != null && parameters.length > 0) {
url.append("?");
for (int i = 0; i < parameters.length; i++) {
url.append(parameters[i]);
if (i != (parameters.length - 1)) {
url.append("&");
}
}
}
return new URL(url.toString());
}
/**
* Builds a URL with parameters.
*
* @param domain the domain of the server
* @param path the path to add to the protocol/host
* @param parameters parameters to be added to the URL as key value pairs.
*
* @throws MalformedURLException
* @throws DocumentListException
*/
private URL buildUrl(String domain, String path, Map<String, String> parameters)
throws MalformedURLException, DocumentListException {
if (path == null) {
throw new DocumentListException("null path");
}
StringBuffer url = new StringBuffer();
url.append("https://" + domain + URL_FEED + path);
if (parameters != null && parameters.size() > 0) {
Set<Map.Entry<String, String>> params = parameters.entrySet();
Iterator<Map.Entry<String, String>> itr = params.iterator();
url.append("?");
while (itr.hasNext()) {
Map.Entry<String, String> entry = itr.next();
url.append(entry.getKey() + "=" + entry.getValue());
if (itr.hasNext()) {
url.append("&");
}
}
}
return new URL(url.toString());
}
}
@@ -0,0 +1,846 @@
/* 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.docs;
import sample.util.SimpleCommandLineParser;
import com.google.gdata.data.Link;
import com.google.gdata.data.MediaContent;
import com.google.gdata.data.acl.AclEntry;
import com.google.gdata.data.acl.AclFeed;
import com.google.gdata.data.acl.AclRole;
import com.google.gdata.data.acl.AclScope;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
import com.google.gdata.data.docs.RevisionEntry;
import com.google.gdata.data.docs.RevisionFeed;
import com.google.gdata.util.AuthenticationException;
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.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* An application that serves as a sample to show how the Documents List
* Service can be used to search your documents and upload files.
*
*
*
*
*/
public class DocumentListDemo {
private DocumentList documentList;
private PrintStream out;
private static final String APPLICATION_NAME = "JavaGDataClientSampleAppV3.0";
/**
* The message for displaying the usage parameters.
*/
private static final String[] USAGE_MESSAGE = {
"Usage: java DocumentListDemo.jar --username <user> --password <pass>",
"Usage: java DocumentListDemo.jar --authSub <token>",
" [--host <host:port>] Where is the feed (default = docs.google.com)",
" [--log] Enable logging of requests",
""};
/**
* Welcome message, introducing the program.
*/
private final String[] WELCOME_MESSAGE = {
"", "This is a demo of the document list feed!",
"Using this interface, you can read and upload your documents.",
"Type 'help' for a list of commands.", ""};
/**
* Help on all available commands.
*/
private final String[] COMMAND_HELP_MESSAGE = {
"Commands:",
" create <object_type> <name> [[create an object]]",
" trash <resource_id> [delete] [[puts the object into the trash]]",
" download <resource_id> <file_path> [[downloads the object to the folder"
+ " specified by file_path]]",
" list [object_type] [...] [[lists objects]]",
" move <resource_id> <folder_id> [[moves an object into a folder]]",
" perms <operation> [...] [[lists or modifies file permissions]]",
" remove <resource_id> <folder_resource_id> [[removes an object from a folder]]",
" search <search_text> [[search documents for text strings]]",
" asearch <search_option> [[advanced search]]",
" upload <file_path> <title> [[uploads a object]]",
" revisions <resource_id> [[lists revisions of a document]]",
"",
" help [command] [[display this message, or info about"
+ " the specified command]]",
" exit [[exit the program]]"};
private final String[] COMMAND_HELP_CREATE = {
"create <object_type> <name>",
" object_type: document, spreadsheet, folder.",
" name: the name for the new object"};
private final String[] COMMAND_HELP_TRASH = {
"trash <resource_id> [delete]",
" resource_id: the resource id of the object to be deleted",
" \"delete\": Specify to permanently delete the document instead of just trashing it."};
private final String[] COMMAND_HELP_DOWNLOAD = {
"download <resource_id> <file_path>",
" resource_id: the resource id of the file you wish to download",
" file_path: the path to the directory to save the file in"};
private final String[] COMMAND_HELP_LIST = {
"list [object_type]",
" object_type: all, starred, documents, spreadsheets, pdfs, presentations, folders.\n"
+ " (defaults to 'all')", "list folder <folder_id>",
" folder_id: The id of the folder you want the contents list for."};
private final String[] COMMAND_HELP_MOVE = {
"move <resource_id> <folder_id>",
" resource_id: the resource id of the object to be moved",
" folder_id: the folder to move the document into"};
private final String[] COMMAND_HELP_PERMS = {
"perms list <resource_id>",
" resource_id: the resource id of the object you wish to add/list permissions for",
"perms add <role> <scope> <email> <object_id>",
" role: \"reader\", \"writer\", \"owner\"",
" scope: \"user\", \"domain\"",
" email: The user's email address or domain name (\"user@gmail.com\", \"domain.com\")",
" resource_id: The resource id of the object to change permissions for.",
"perms change <role> <scope> <email> <object_id>",
" role: \"reader\", \"writer\", \"owner\"",
" scope: \"user\", \"domain\"",
" email: The user's email address or domain name (\"user@gmail.com\", \"domain.com\")",
" object_id: The id of the object to change permissions for.",
"perms remove <scope> <email> <object_id>",
" role: \"reader\", \"writer\", \"owner\"",
" scope: \"user\", \"domain\"",
" email: The user's email address or domain name (\"user@gmail.com\", \"domain.com\")",
" object_id: The id of the object to change permissions for."};
private final String[] COMMAND_HELP_REMOVE = {
"remove <object_id> <folder_id>",
" object_id: the id of the object to remove from the folder",
" folder_id: the id of the folder to remove the object from"};
private final String[] COMMAND_HELP_SEARCH = {
"search <search_text>",
" search_text: A string to be used for a full text query"};
private final String[] COMMAND_HELP_ASEARCH = {
"asearch [<query_param>=<value>] [<query_param2>=<value2>] ...",
" query_param: title, title-exact, opened-min, opened-max, owner, writer, reader, "
+ "showfolders, etc.", " value: The value of the parameter"};
private final String[] COMMAND_HELP_UPLOAD = {
"upload <file_path> <title>", " file_path: file to upload",
" title: A title to call the document"};
private final String[] COMMAND_HELP_REVISIONS = {
"revisions <resource_id>", " resource_id: document resource id"};
private final String[] COMMAND_HELP_HELP = {
"help [command]", " Weeeeeeeeeeeeee..."};
private final String[] COMMAND_HELP_EXIT = {
"exit", " Exit the program."};
private final String[] COMMAND_HELP_ERROR = {"unknown command"};
private final Map<String, String[]> HELP_MESSAGES;
{
HELP_MESSAGES = new HashMap<String, String[]>();
HELP_MESSAGES.put("create", COMMAND_HELP_CREATE);
HELP_MESSAGES.put("trash", COMMAND_HELP_TRASH);
HELP_MESSAGES.put("download", COMMAND_HELP_DOWNLOAD);
HELP_MESSAGES.put("list", COMMAND_HELP_LIST);
HELP_MESSAGES.put("move", COMMAND_HELP_MOVE);
HELP_MESSAGES.put("perms", COMMAND_HELP_PERMS);
HELP_MESSAGES.put("remove", COMMAND_HELP_REMOVE);
HELP_MESSAGES.put("search", COMMAND_HELP_SEARCH);
HELP_MESSAGES.put("asearch", COMMAND_HELP_ASEARCH);
HELP_MESSAGES.put("upload", COMMAND_HELP_UPLOAD);
HELP_MESSAGES.put("revisions", COMMAND_HELP_REVISIONS);
HELP_MESSAGES.put("help", COMMAND_HELP_HELP);
HELP_MESSAGES.put("exit", COMMAND_HELP_EXIT);
HELP_MESSAGES.put("error", COMMAND_HELP_ERROR);
}
/**
* Constructor
*
* @param outputStream Stream to print output to.
* @throws DocumentListException
*/
public DocumentListDemo(PrintStream outputStream, String appName, String host)
throws DocumentListException {
out = outputStream;
documentList = new DocumentList(appName, host);
}
/**
* Authenticates the client using ClientLogin
*
* @param username User's email address
* @param password User's password
* @throws DocumentListException
* @throws AuthenticationException
*/
public void login(String username, String password) throws AuthenticationException,
DocumentListException {
documentList.login(username, password);
}
/**
* Authenticates the client using AuthSub
*
* @param authSubToken authsub authorization token.
* @throws DocumentListException
* @throws AuthenticationException
*/
public void login(String authSubToken)
throws AuthenticationException, DocumentListException {
documentList.loginWithAuthSubToken(authSubToken);
}
/**
* Prints out the specified document entry.
*
* @param doc the document entry to print.
*/
public void printDocumentEntry(DocumentListEntry doc) {
StringBuffer output = new StringBuffer();
output.append(" -- " + doc.getTitle().getPlainText() + " ");
if (!doc.getParentLinks().isEmpty()) {
for (Link link : doc.getParentLinks()) {
output.append("[" + link.getTitle() + "] ");
}
}
output.append(doc.getResourceId());
out.println(output);
}
/**
* Prints out the specified revision entry.
*
* @param doc the revision entry to print.
*/
public void printRevisionEntry(RevisionEntry entry) {
StringBuffer output = new StringBuffer();
output.append(" -- " + entry.getTitle().getPlainText());
output.append(", created on " + entry.getUpdated().toUiString() + " ");
output.append(" by " + entry.getModifyingUser().getName() + " - "
+ entry.getModifyingUser().getEmail() + "\n");
output.append(" " + entry.getHtmlLink().getHref());
out.println(output);
}
/**
* Prints out the specified ACL entry.
*
* @param entry the ACL entry to print.
*/
public void printAclEntry(AclEntry entry) {
out.println(" -- " + entry.getScope().getValue() + ": " + entry.getRole().getValue());
}
/**
* Executes the "create" command.
*
* @param args arguments for the "create" command.
* args[0] = "create" args[1] = object_type ("folder", "document", "spreadsheet")
* args[2] = title (what to name the document/folder)
*
* @throws IOException when an error occurs in communication with the Doclist
* service.
* @throws MalformedURLException when an malformed URL is used.
* @throws ServiceException when the request causes an error in the Doclist
* service.
* @throws DocumentListException
*/
private void executeCreate(String[] args) throws IOException,
MalformedURLException, ServiceException, DocumentListException {
if (args.length == 3) {
printDocumentEntry(documentList.createNew(args[2], args[1]));
} else {
printMessage(COMMAND_HELP_CREATE);
}
}
/**
* Executes the "trash" command.
*
* @param args arguments for the "trash" command.
* args[0] = "trash"
* args[1] = resourceid (the resource id of the object to be trashed)
* args[2] = delete (where to delete permanently or not)
*
* @throws IOException when an error occurs in communication with the Doclist
* service.
* @throws MalformedURLException when an malformed URL is used.
* @throws ServiceException when the request causes an error in the Doclist
* service.
* @throws DocumentListException
*/
private void executeTrash(String[] args) throws IOException,
ServiceException, DocumentListException {
if (args.length == 3) {
documentList.trashObject(args[1], true);
} else if (args.length == 2) {
documentList.trashObject(args[1], false);
} else {
printMessage(COMMAND_HELP_TRASH);
}
}
/**
* Executes the "download" command.
*
* @param args arguments for the "download" command.
* args[0] = "download"
* args[1] = resourceId (the resource id of the object to be downloaded)
* args[2] = filepath (the path and filename to save the object as)
*
* @throws IOException when an error occurs in communication with the Doclist
* service.
* @throws MalformedURLException when an malformed URL is used.
* @throws ServiceException when the request causes an error in the Doclist
* service.
* @throws DocumentListException
*/
private void executeDownload(String[] args) throws IOException,
ServiceException, DocumentListException {
if (args.length == 3) {
String docType = documentList.getResourceIdPrefix(args[1]);
if (docType.equals("spreadsheet")) {
String format = documentList.getDownloadFormat(args[1],
getTypeFromFilename(args[2]));
documentList.downloadSpreadsheet(args[1], args[2], format);
} else if (docType.equals("presentation")) {
String format = documentList.getDownloadFormat(args[1],
getTypeFromFilename(args[2]));
documentList.downloadPresentation(args[1], args[2], format);
} else if (docType.equals("document")) {
String format = documentList.getDownloadFormat(args[1],
getTypeFromFilename(args[2]));
documentList.downloadDocument(args[1], args[2], format);
} else {
MediaContent mc = (MediaContent) documentList.getDocsListEntry(args[1]).getContent();
String fileExtension = mc.getMimeType().getSubType();
URL exportUrl = new URL(mc.getUri());
// PDF file cannot be exported in different formats.
String requestedFormat = args[2]
.substring(args[2].lastIndexOf(".") + 1);
if (!requestedFormat.equals(fileExtension)) {
String[] formatWarning = {"Warning: "
+ mc.getMimeType().getMediaType() + " cannot be downloaded as a "
+ requestedFormat + ". Using ." + fileExtension + " instead."};
printMessage(formatWarning);
}
String newFilePath = args[2].substring(0, args[2].lastIndexOf(".") + 1) + fileExtension;
documentList.downloadFile(exportUrl, newFilePath);
}
} else {
printMessage(COMMAND_HELP_DOWNLOAD);
}
}
/**
* Execute the "list" command.
*
* @param args arguments for the "list" command.
* args[0] = "list"
* args[1] = category ("all", "folders", "documents", "spreadsheets", "pdfs",
* "presentations", "starred", "trashed")
* args[2] = folderId (required if args[1] is "folder")
*
* @throws IOException when an error occurs in communication with the Doclist
* service.
* @throws MalformedURLException when an malformed URL is used.
* @throws ServiceException when the request causes an error in the Doclist
* service.
* @throws DocumentListException
*/
private void executeList(String[] args) throws IOException,
ServiceException, DocumentListException {
DocumentListFeed feed = null;
String msg = "";
switch (args.length) {
case 1:
msg = "List of docs: ";
feed = documentList.getDocsListFeed("all");
break;
case 2:
msg = "List of all " + args[1] + ": ";
feed = documentList.getDocsListFeed(args[1]);
break;
case 3:
if (args[1].equals("folder")) {
msg = "Contents of folder_id '" + args[2] + "': ";
feed = documentList.getFolderDocsListFeed(args[2]);
}
break;
}
if (feed != null) {
out.println(msg);
for (DocumentListEntry entry : feed.getEntries()) {
printDocumentEntry(entry);
}
} else {
printMessage(COMMAND_HELP_LIST);
}
}
/**
* Execute the "move" command.
*
* @param args arguments for the "move" command.
* args[0] = "move" args[1] = resourceid (the resourceid of the object to move)
* args[2] = folderResourceId (the resource id of the folder to move the object to)
*
* @throws IOException when an error occurs in communication with the Doclist
* service.
* @throws MalformedURLException when an malformed URL is used.
* @throws ServiceException when the request causes an error in the Doclist
* service.
* @throws DocumentListException
*/
private void executeMove(String[] args) throws IOException,
ServiceException, DocumentListException {
if (args.length == 3) {
printDocumentEntry(documentList.moveObjectToFolder(args[1], args[2]));
} else {
printMessage(COMMAND_HELP_MOVE);
}
}
/**
* Execute the "perms" command.
*
* @param args arguments for the "perms" command.
* args[0] = "perms"
* args[1] = "list"
* args[2] = resourceId
* args[1] = "add", "change"
* args[2] = role
* args[3] = scope
* args[4] = email
* args[5] = resourceId
* args[1] = "remove"
* args[2] = scope
* args[3] = email
* args[4] = resourceId
*
* @throws IOException when an error occurs in communication with the Doclist
* service.
* @throws MalformedURLException when an malformed URL is used.
* @throws ServiceException when the request causes an error in the Doclist
* service.
* @throws DocumentListException
*/
private void executePerms(String[] args) throws IOException,
ServiceException, DocumentListException {
if (args.length < 3) {
printMessage(COMMAND_HELP_PERMS);
return;
}
if (args[1].equals("list") && args.length == 3) {
AclFeed feed = documentList.getAclFeed(args[2]);
if (feed != null) {
for (AclEntry entry : feed.getEntries()) {
printAclEntry(entry);
}
}
} else if (args[1].equals("add") && args.length == 6) {
AclRole role = new AclRole(args[2]);
AclScope scope;
if (args[3].equals("user")) {
scope = new AclScope(AclScope.Type.USER, args[4]);
} else if (args[3].equals("domain")) {
scope = new AclScope(AclScope.Type.DOMAIN, args[4]);
} else {
printMessage(COMMAND_HELP_PERMS);
return;
}
printAclEntry(documentList.addAclRole(role, scope, args[5]));
} else if (args[1].equals("change") && args.length == 6) {
AclRole role = new AclRole(args[2]);
AclScope scope;
if (args[3].equals("user")) {
scope = new AclScope(AclScope.Type.USER, args[4]);
} else if (args[3].equals("domain")) {
scope = new AclScope(AclScope.Type.DOMAIN, args[4]);
} else {
printMessage(COMMAND_HELP_PERMS);
return;
}
printAclEntry(documentList.changeAclRole(role, scope, args[5]));
} else if (args[1].equals("remove") && args.length == 5) {
documentList.removeAclRole(args[2], args[3], args[4]);
} else {
printMessage(COMMAND_HELP_PERMS);
}
}
/**
* Execute the "remove" command.
*
* @param args arguments for the "remove" command.
* args[0] = "remove"
* args[1] = resourceId
* args[2] = folderReourceId
*
* @throws IOException when an error occurs in communication with the Doclist
* service.
* @throws MalformedURLException when an malformed URL is used.
* @throws ServiceException when the request causes an error in the Doclist
* service.
* @throws DocumentListException
*/
private void executeRemove(String[] args) throws IOException,
ServiceException, DocumentListException {
if (args.length == 3) {
documentList.removeFromFolder(args[1], args[2]);
} else {
printMessage(COMMAND_HELP_REMOVE);
}
}
/**
* Execute the "search" command.
*
* @param args arguments for the "search" command.
* args[0] = "search"
* args[1] = searchString
*
* @throws IOException when an error occurs in communication with the Doclist
* service.
* @throws MalformedURLException when an malformed URL is used.
* @throws ServiceException when the request causes an error in the Doclist
* service.
* @throws DocumentListException
*/
private void executeSearch(String[] args) throws IOException,
ServiceException, DocumentListException {
if (args.length == 2) {
HashMap<String, String> searchParameters = new HashMap<String, String>();
searchParameters.put("q", args[1]);
DocumentListFeed feed = documentList.search(searchParameters);
out.println("Results for [" + args[1] + "]");
for (DocumentListEntry entry : feed.getEntries()) {
printDocumentEntry(entry);
}
} else {
printMessage(COMMAND_HELP_SEARCH);
}
}
/**
* Execute the "asearch" (advanced search) command.
*
* @param args arguments for the "asearch" command.
* args[0] = "asearch"
*
* @throws IOException when an error occurs in communication with the Doclist
* service.
* @throws MalformedURLException when an malformed URL is used.
* @throws ServiceException when the request causes an error in the Doclist
* service.
* @throws DocumentListException
*/
private void executeAdvancedSearch(String[] args) throws IOException,
ServiceException, DocumentListException {
if (args.length <= 1) {
printMessage(COMMAND_HELP_ASEARCH);
return;
}
HashMap<String, String> searchParameters = new HashMap<String, String>();
for (int i = 1; i < args.length; ++i) {
searchParameters.put(args[i].substring(0, args[i].indexOf("=")), args[i]
.substring(args[i].indexOf("=") + 1));
}
DocumentListFeed feed = documentList.search(searchParameters);
out.println("Results for advanced search:");
for (DocumentListEntry entry : feed.getEntries()) {
printDocumentEntry(entry);
}
}
/**
* Execute the "upload" command.
*
* @param args arguments for the "upload" command.
* args[0] = "upload"
* args[1] = filepath (path and filename of the file to be uploaded)
* args[2] = title (title to be used for the uploaded file)
*
* @throws IOException when an error occurs in communication with the Doclist
* service.
* @throws MalformedURLException when an malformed URL is used.
* @throws ServiceException when the request causes an error in the Doclist
* service.
* @throws DocumentListException
*/
private void executeUpload(String[] args) throws IOException,
ServiceException, DocumentListException, InterruptedException {
if (args.length == 3) {
DocumentListEntry entry = documentList.uploadFile(args[1], args[2]);
printDocumentEntry(entry);
} else {
printMessage(COMMAND_HELP_UPLOAD);
}
}
/**
* Execute the "revisions" command.
*
* @param args arguments for the "upload" command.
* args[0] = "revisions"
* args[1] = resourceId (the resource id of the object to fetch revisions for)
*
* @throws IOException when an error occurs in communication with the Doclist
* service.
* @throws MalformedURLException when an malformed URL is used.
* @throws ServiceException when the request causes an error in the Doclist
* service.
* @throws DocumentListException
*/
private void executeRevisions(String[] args) throws IOException,
ServiceException, DocumentListException {
if (args.length == 2) {
RevisionFeed feed = documentList.getRevisionsFeed(args[1]);
if (feed != null) {
out.println("List of revisions...");
for (RevisionEntry entry : feed.getEntries()) {
printRevisionEntry(entry);
}
} else {
printMessage(COMMAND_HELP_REVISIONS);
}
} else {
printMessage(COMMAND_HELP_REVISIONS);
}
}
/**
* Execute the "help" command.
*
* @param args arguments for the "help" command.
* args[0] = "help"
* args[1] = command
*/
private void executeHelp(String[] args) {
if (args.length == 1) {
printMessage(COMMAND_HELP_MESSAGE);
} else if (args.length == 2) {
if (HELP_MESSAGES.containsKey(args[1])) {
printMessage(HELP_MESSAGES.get(args[1]));
} else {
printMessage(HELP_MESSAGES.get("error"));
}
} else {
printMessage(COMMAND_HELP_MESSAGE);
}
}
/**
* Gets the type of file from the extension on the filename.
*
* @param filename the filename to extract the type of file from.
*/
private String getTypeFromFilename(String filename) {
return filename.substring(filename.lastIndexOf(".") + 1);
}
/**
* Parses the command entered by the user into individual arguments.
*
* @param command the entire command entered by the user to be broken up into
* arguments.
*/
private String[] parseCommand(String command) {
// Special cases:
if (command.startsWith("search")) {
// if search command, only break into two args (command, search_string)
return command.trim().split(" ", 2);
} else if (command.startsWith("create")) {
// if create command, break into three args (command, file_type, title)
return command.trim().split(" ", 3);
} else if (command.startsWith("upload")) {
// if upload command, break into three args (command, file_path, title)
return command.trim().split(" ", 3);
}
// Default case, split into n args using a space as the separator.
return command.trim().split(" ");
}
/**
* Reads and executes one command.
*
* @param reader to read input from the keyboard
* @return false if the user quits, true on exception
* @throws IOException
* @throws ServiceException
*/
private boolean executeCommand(BufferedReader reader)
throws IOException, ServiceException, InterruptedException {
System.err.print("Command: ");
try {
String command = reader.readLine();
if (command == null) {
return false;
}
String[] args = parseCommand(command);
String name = args[0];
if (name.equals("create")) {
executeCreate(args);
} else if (name.equals("trash")) {
executeTrash(args);
} else if (name.equals("download")) {
executeDownload(args);
} else if (name.equals("list")) {
executeList(args);
} else if (name.equals("move")) {
executeMove(args);
} else if (name.equals("perms")) {
executePerms(args);
} else if (name.equals("remove")) {
executeRemove(args);
} else if (name.equals("search")) {
executeSearch(args);
} else if (name.equals("asearch")) {
executeAdvancedSearch(args);
} else if (name.equals("upload")) {
executeUpload(args);
} else if (name.equals("revisions")) {
executeRevisions(args);
} else if (name.equals("help")) {
executeHelp(args);
} else if (name.startsWith("q") || name.startsWith("exit")) {
return false;
} else {
out.println("Unknown command. Type 'help' for a list of commands.");
}
} catch (DocumentListException e) {
// Show *exactly* what went wrong.
e.printStackTrace();
}
return true;
}
/**
* Starts up the demo and prompts for commands.
*
* @throws ServiceException
* @throws IOException
*/
public void run() throws IOException, ServiceException, InterruptedException {
printMessage(WELCOME_MESSAGE);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (executeCommand(reader)) {
}
}
/**
* Prints out a message.
*
* @param msg the message to be printed.
*/
private static void printMessage(String[] msg) {
for (String s : msg) {
System.out.println(s);
}
}
private static void turnOnLogging() {
// Configure the logging mechanisms
Logger httpLogger =
Logger.getLogger("com.google.gdata.client.http.HttpGDataRequest");
httpLogger.setLevel(Level.ALL);
Logger xmlLogger = Logger.getLogger("com.google.gdata.util.XmlParser");
xmlLogger.setLevel(Level.ALL);
// Create a log handler which prints all log events to the console
ConsoleHandler logHandler = new ConsoleHandler();
logHandler.setLevel(Level.ALL);
httpLogger.addHandler(logHandler);
xmlLogger.addHandler(logHandler);
}
/**
* Runs the demo.
*
* @param args the command-line arguments
*
* @throws DocumentListException
* @throws ServiceException
* @throws IOException
*/
public static void main(String[] args)
throws DocumentListException, IOException, ServiceException,
InterruptedException {
SimpleCommandLineParser parser = new SimpleCommandLineParser(args);
String authSub = parser.getValue("authSub", "auth", "a");
String user = parser.getValue("username", "user", "u");
String password = parser.getValue("password", "pass", "p");
String host = parser.getValue("host", "s");
boolean help = parser.containsKey("help", "h");
if (host == null) {
host = DocumentList.DEFAULT_HOST;
}
if (help || (user == null || password == null) && authSub == null) {
printMessage(USAGE_MESSAGE);
System.exit(1);
}
if (parser.containsKey("log", "l")) {
turnOnLogging();
}
DocumentListDemo demo = new DocumentListDemo(System.out, APPLICATION_NAME,
host);
if (password != null) {
demo.login(user, password);
} else {
demo.login(authSub);
}
demo.run();
}
}
@@ -0,0 +1,30 @@
/* 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.docs;
/**
* Exception to be thrown when there is an issue with the DocumentList class.
*/
public class DocumentListException extends Exception {
public DocumentListException() {
super();
}
public DocumentListException(String msg) {
super(msg);
}
}
@@ -0,0 +1,508 @@
/* 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.docs;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gdata.client.media.ResumableGDataFileUploader;
import sample.util.SimpleCommandLineParser;
import com.google.gdata.data.Link;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
import com.google.gdata.data.media.MediaFileSource;
import com.google.gdata.util.ServiceException;
import com.google.gdata.client.uploader.FileUploadData;
import com.google.gdata.client.uploader.ProgressListener;
import com.google.gdata.client.uploader.ResumableHttpFileUploader;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URL;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* A console aplication to demonstrate interaction with Google Docs API to
* upload/update large media files using Resumable Upload protocol.
*
*
*/
public class DocumentResumableUploadDemo {
/** Default document list feed url. */
private static final String DEFAULT_DOCLIST_FEED_URL =
"https://docs.google.com/feeds/default/private/full";
/** Default create-media-url for uploading documents */
private static final String DEFAULT_RESUMABLE_UPLOAD_URL =
"https://docs.google.com/feeds/upload/create-session/default/private/full";
/** Maximum number of concurrent uploads */
private static final int MAX_CONCURRENT_UPLOADS = 10;
/** Time interval at which upload task will notify about the progress */
private static final int PROGRESS_UPDATE_INTERVAL = 1000;
/** Max size for each upload chunk */
private static final int DEFAULT_CHUNK_SIZE = 10000000;
/**
* Welcome message, introducing the program.
*/
private static final String[] WELCOME_MESSAGE = {
"", "This is a demo of the resumable upload feature for Docs GData API",
"Using this interface, you can upload/update large documents.", ""};
private static final String APPLICATION_NAME = "JavaGDataClientSampleAppV3.0";
private static final String[] USAGE_MESSAGE = {
"Usage: java DocumentResumableUploadDemo.jar --username <user> --password <pass>",
};
private static final String[] COMMAND_HELP_MESSAGE = {
"Commands:",
" list [object_type] "
+ " [[list objects]]",
" upload <file_path1:title1> ... <file_pathN:titleN> "
+ "[<chunk_size_in_byes>] [[uploads set of files]]",
" update <ducument_id> <updated_file_path> [<chunk_size_in_bytes>] "
+ " [[updates content of an object]]",
};
/** Instance of {@link DocumentList} */
private final DocumentList docs;
/** Steam to print status messages to. */
PrintStream output;
/**
* Constructor.
*
* @param docs {@link DocumentList} for interface to DocList API service.
* @param out printstream to output status messages to.
*/
DocumentResumableUploadDemo(DocumentList docs, PrintStream out) {
this.docs = docs;
this.output = out;
}
/**
* Prints out a message.
*
* @param msg the message to be printed.
*/
private static void printMessage(String[] msg) {
for (String s : msg) {
System.out.println(s);
}
}
private String[] parseCommand(String command) {
return command.trim().split(" ");
}
/**
* Prints out the specified document entry.
*
* @param doc the document entry to print.
*/
public void printDocumentEntry(DocumentListEntry doc) {
StringBuffer outputBuffer = new StringBuffer();
outputBuffer.append(" -- " + doc.getTitle().getPlainText() + " ");
if (!doc.getParentLinks().isEmpty()) {
for (Link link : doc.getParentLinks()) {
outputBuffer.append("[" + link.getTitle() + "] ");
}
}
outputBuffer.append(doc.getResourceId());
output.println(outputBuffer);
}
/**
* Uploads given collection of files. The call blocks until all uploads are
* done.
*
* @param url create-session url for initiating resumable uploads for
* documents API.
* @param files list of absolute filepaths to files to upload.
* @param chunkSize max size of each upload chunk.
*/
public Collection<DocumentListEntry> uploadFiles(String url,
List<String> files, int chunkSize)
throws IOException, ServiceException, InterruptedException {
// Create a listener
FileUploadProgressListener listener = new FileUploadProgressListener();
// Pool for handling concurrent upload tasks
ExecutorService executor =
Executors.newFixedThreadPool(MAX_CONCURRENT_UPLOADS);
// Create {@link ResumableGDataFileUploader} for each file to upload
List<ResumableGDataFileUploader> uploaders = Lists.newArrayList();
for (String fileName : files) {
MediaFileSource mediaFile = getMediaFileSource(fileName);
ResumableGDataFileUploader uploader =
new ResumableGDataFileUploader.Builder(
docs.service, new URL(url), mediaFile, null /*empty meatadata*/)
.title(mediaFile.getName())
.chunkSize(chunkSize).executor(executor)
.trackProgress(listener, PROGRESS_UPDATE_INTERVAL)
.build();
uploaders.add(uploader);
}
// attach the listener to list of uploaders
listener.listenTo(uploaders);
// Start the upload
for (ResumableGDataFileUploader uploader : uploaders) {
uploader.start();
}
// wait for uploads to complete
while (!listener.isDone()) {
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
listener.printResults();
throw ie; // rethrow
}
}
// print upload results
listener.printResults();
// return list of uploaded entries
return listener.getUploaded();
}
private MediaFileSource getMediaFileSource(String fileName) {
File file = new File(fileName);
MediaFileSource mediaFile = new MediaFileSource(file,
DocumentListEntry.MediaType.fromFileName(file.getName())
.getMimeType());
return mediaFile;
}
/**
* Execute 'list' command.
*/
private void executeList(String[] args) throws IOException,
ServiceException, DocumentListException {
DocumentListFeed feed = null;
String msg = "";
switch (args.length) {
case 1:
msg = "List of docs: ";
feed = docs.getDocsListFeed("all");
break;
case 2:
msg = "List of all " + args[1] + ": ";
feed = docs.getDocsListFeed(args[1]);
break;
case 3:
if (args[1].equals("folder")) {
msg = "Contents of folder_id '" + args[2] + "': ";
feed = docs.getFolderDocsListFeed(args[2]);
}
break;
}
if (feed != null) {
output.println(msg);
for (DocumentListEntry entry : feed.getEntries()) {
printDocumentEntry(entry);
}
} else {
printMessage(COMMAND_HELP_MESSAGE);
}
}
/**
* Execute 'upload' command.
*/
private void executeUpload(String[] args)
throws IOException, ServiceException, InterruptedException {
if (args.length > 1) {
int chunkSize = DEFAULT_CHUNK_SIZE;
List<String> files = Lists.newArrayList();
for (int index = 1; index < args.length; index++) {
String arg = args[index];
if (index < args.length - 1) {
files.add(arg);
continue;
}
// Last argument can be a file or chunk size
try {
chunkSize = Integer.parseInt(arg);
} catch (NumberFormatException nfe) {
files.add(arg);
}
}
uploadFiles(DEFAULT_RESUMABLE_UPLOAD_URL, files, chunkSize);
output.println("Finished upload");
}
}
/**
* Execute 'update' command.
*/
private void executeUpdate(String[] args)
throws IOException, ServiceException, InterruptedException {
String docIdToUpdate = args[1];
String filePath = args[2];
// retrieve latest entry
DocumentListEntry currentEntry = docs.service.getEntry(
new URL(DEFAULT_DOCLIST_FEED_URL + "/" + docIdToUpdate),
DocumentListEntry.class);
MediaFileSource mediaFile = getMediaFileSource(filePath);
ResumableGDataFileUploader uploader =
new ResumableGDataFileUploader
.Builder(docs.service, mediaFile, currentEntry)
.title(mediaFile.getName())
.requestType(
ResumableGDataFileUploader.RequestType.UPDATE_MEDIA_ONLY)
.build();
uploader.start();
// wait for upload to complete
while (!uploader.isDone()) {
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
output.println("Media update interrupted at: "
+ String.format("%3.0f", uploader.getProgress() * 100) + "%");
throw ie; // rethrow
}
}
DocumentListEntry updatedEntry =
uploader.getResponse(DocumentListEntry.class);
output.println("Finished update");
}
private boolean executeCommand(BufferedReader reader) throws IOException,
ServiceException, InterruptedException {
output.println("Enter a command");
try {
String command = reader.readLine();
if (command == null) {
return false;
}
String[] args = parseCommand(command);
String name = args[0];
if (name.equals("list")) {
executeList(args);
} else if (name.equals("upload")) {
executeUpload(args);
} else if (name.equals("update")) {
executeUpdate(args);
} else if (name.startsWith("q") || name.startsWith("exit")) {
return false;
} else if (name.equals("help")) {
printMessage(COMMAND_HELP_MESSAGE);
} else {
output.println("Unknown command. Type 'help' for list of commands");
}
} catch (DocumentListException e) {
e.printStackTrace();
}
return true;
}
void run() throws IOException, ServiceException, InterruptedException {
printMessage(WELCOME_MESSAGE);
printMessage(COMMAND_HELP_MESSAGE);
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
while (executeCommand(reader)) {
}
}
public static void main(String[] args) throws DocumentListException,
IOException, ServiceException, InterruptedException {
SimpleCommandLineParser parser = new SimpleCommandLineParser(args);
String user = parser.getValue("username", "user", "u");
String password = parser.getValue("password", "pass", "p");
boolean help = parser.containsKey("help", "h");
if (help || (user == null || password == null)) {
printMessage(USAGE_MESSAGE);
System.exit(1);
}
// authenticate
DocumentList docs = new DocumentList(APPLICATION_NAME);
docs.login(user, password);
DocumentResumableUploadDemo demo = new DocumentResumableUploadDemo(
docs, System.out);
demo.run();
System.exit(1);
}
/**
* A {@link ProgressListener} implementation to track upload progress.
* The listener can track multiple uploads at the same time.
* Use {@link #isDone} to check if all uploads are completed and
* use {@link #getUploaded} to access results of successful uploads.
*/
private class FileUploadProgressListener implements ProgressListener {
private Collection<ResumableGDataFileUploader> trackedUploaders
= Lists.newArrayList();
private int pendingRequests;
Map<String, DocumentListEntry> uploaded = Maps.newHashMap();
Map<String, String> failed = Maps.newHashMap();
boolean processed;
public FileUploadProgressListener() {
this.pendingRequests = 0;
}
public void listenTo(Collection<ResumableGDataFileUploader> uploaders) {
this.trackedUploaders.addAll(uploaders);
this.pendingRequests = trackedUploaders.size();
}
public synchronized void progressChanged(ResumableHttpFileUploader uploader)
{
String fileId = ((FileUploadData) uploader.getData()).getFileName();
switch(uploader.getUploadState()) {
case COMPLETE:
case CLIENT_ERROR:
pendingRequests -= 1;
output.println(fileId + ": Completed");
break;
case IN_PROGRESS:
output.println(fileId + ":"
+ String.format("%3.0f", uploader.getProgress() * 100) + "%");
break;
case NOT_STARTED:
output.println(fileId + ":" + "Not Started");
break;
}
}
public synchronized boolean isDone() {
// not done if there are any pending requests.
if (pendingRequests > 0) {
return false;
}
// if all responses are processed., nothing to do.
if (processed) {
return true;
}
// check if all response streams are available.
for (ResumableGDataFileUploader uploader : trackedUploaders) {
if (!uploader.isDone()) {
return false;
}
}
// process all responses
for (ResumableGDataFileUploader uploader : trackedUploaders) {
String fileId = ((FileUploadData) uploader.getData()).getFileName();
switch(uploader.getUploadState()) {
case COMPLETE:
try {
DocumentListEntry entry =
uploader.getResponse(DocumentListEntry.class);
uploaded.put(fileId, entry);
} catch (IOException e) {
failed.put(fileId, "Upload completed, but unexpected error "
+ "reading server response");
} catch (ServiceException e) {
failed.put(fileId,
"Upload completed, but failed to parse server response");
}
break;
case CLIENT_ERROR:
failed.put(fileId, "Failed at " + uploader.getProgress());
break;
}
}
processed = true;
output.println("All requests done");
return true;
}
public synchronized Collection<DocumentListEntry> getUploaded() {
if (!isDone()) {
return null;
}
return uploaded.values();
}
public synchronized void printResults() {
if (!isDone()) {
return;
}
output.println("Result: " + uploaded.size() + ", " + failed.size());
if (uploaded.size() > 0) {
output.println(" Successfully Uploaded:");
for (Map.Entry<String, DocumentListEntry> entry : uploaded.entrySet()) {
printDocumentEntry(entry.getValue());
}
}
if (failed.size() > 0) {
output.println(" Failed to upload:");
for (Map.Entry entry : failed.entrySet()) {
output.println(" " + entry.getKey() + ":" + entry.getValue());
}
}
}
/**
* Prints out the specified document entry.
*
* @param doc the document entry to print.
*/
public void printDocumentEntry(DocumentListEntry doc) {
StringBuffer buffer = new StringBuffer();
buffer.append(" -- " + doc.getTitle().getPlainText() + " ");
if (!doc.getParentLinks().isEmpty()) {
for (Link link : doc.getParentLinks()) {
buffer.append("[" + link.getTitle() + "] ");
}
}
buffer.append(doc.getResourceId());
output.println(buffer);
}
}
}
Binary file not shown.