I’m working with the Google Docs Java API in a Google Apps environment and running into an issue. My code can successfully authenticate and impersonate a user to fetch document metadata, but when I try to actually download the file content, I get a ServiceForbiddenException.
The strange part is that the authentication seems to work fine. I can retrieve file information like the document title without any problems. But the download process fails every time.
Has anyone encountered this before? Is there a workaround using direct HTTP calls with the Protocol API instead?
public class DocumentManager {
private static DocsService service = new DocsService("Document Manager");
public static void main(String[] args) throws Exception {
String domainAdmin = args[0];
String password = args[1];
String token = args[2];
String targetUser = args[3];
authenticateService(domainAdmin, password, token);
URL feedUrl = new URL("https://docs.google.com/feeds/" + targetUser + "/private/full");
DocumentListFeed docFeed = service.getFeed(feedUrl, DocumentListFeed.class);
DocumentListEntry document = docFeed.getEntries().get(0);
String docTitle = document.getTitle().getPlainText();
System.out.println(docTitle);
String docType = document.getType();
if (docType.equals("document")) {
String encodedUser = URLEncoder.encode(domainAdmin);
String resId = document.getResourceId();
String cleanId = resId.substring(resId.indexOf(':') + 1);
String exportUrl = "https://docs.google.com/feeds/download/documents/Export" +
"?xoauth_requestor=" + encodedUser +
"&docId=" + cleanId +
"&exportFormat=doc";
exportDocument(exportUrl, docTitle + ".doc");
}
}
private static void authenticateService(String admin, String pwd, String authToken)
throws OAuthException, AuthenticationException {
String domainName = admin.substring(admin.indexOf('@') + 1);
GoogleOAuthParameters params = new GoogleOAuthParameters();
params.setOAuthConsumerKey(domainName);
params.setOAuthConsumerSecret(authToken);
params.setOAuthType(OAuthType.TWO_LEGGED_OAUTH);
params.setScope("https://docs.google.com/feeds/ http://spreadsheets.google.com/feeds/ http://docs.googleusercontent.com/");
service.useSsl();
service.setOAuthCredentials(params, new OAuthHmacSha1Signer());
service.setUserCredentials(admin, pwd);
}
public static void exportDocument(String url, String filename)
throws IOException, ServiceException {
System.out.println("Downloading from: " + url);
MediaContent content = new MediaContent();
content.setUri(url);
MediaSource source = service.getMedia(content);
InputStream input = null;
FileOutputStream output = null;
try {
input = source.getInputStream();
output = new FileOutputStream(filename);
int data;
while ((data = input.read()) != -1) {
output.write(data);
}
} finally {
if (input != null) input.close();
if (output != null) {
output.flush();
output.close();
}
}
}
}