PageRenderTime 55ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 1ms

/src/DocumentList.java

http://google-docs-upload.googlecode.com/
Java | 1060 lines | 527 code | 126 blank | 407 comment | 198 complexity | 0e001081c0585c2a561bac3443733afc MD5 | raw file
  1. /* Copyright (c) 2008 Google Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. import java.io.File;
  16. import java.io.FileOutputStream;
  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. import java.net.MalformedURLException;
  20. import java.net.URL;
  21. import java.util.HashMap;
  22. import java.util.Iterator;
  23. import java.util.Map;
  24. import java.util.Set;
  25. import javax.activation.MimetypesFileTypeMap;
  26. import com.google.gdata.client.DocumentQuery;
  27. import com.google.gdata.client.GoogleService;
  28. import com.google.gdata.client.Query;
  29. import com.google.gdata.client.GoogleAuthTokenFactory.UserToken;
  30. import com.google.gdata.client.docs.DocsService;
  31. import com.google.gdata.data.Link;
  32. import com.google.gdata.data.MediaContent;
  33. import com.google.gdata.data.PlainTextConstruct;
  34. import com.google.gdata.data.acl.AclEntry;
  35. import com.google.gdata.data.acl.AclFeed;
  36. import com.google.gdata.data.acl.AclRole;
  37. import com.google.gdata.data.acl.AclScope;
  38. import com.google.gdata.data.docs.DocumentEntry;
  39. import com.google.gdata.data.docs.DocumentListEntry;
  40. import com.google.gdata.data.docs.DocumentListFeed;
  41. import com.google.gdata.data.docs.FolderEntry;
  42. import com.google.gdata.data.docs.PresentationEntry;
  43. import com.google.gdata.data.docs.RevisionFeed;
  44. import com.google.gdata.data.docs.SpreadsheetEntry;
  45. import com.google.gdata.data.media.MediaSource;
  46. import com.google.gdata.util.AuthenticationException;
  47. import com.google.gdata.util.ServiceException;
  48. /**
  49. * An application that serves as a sample to show how the GoogleDocsUpload List
  50. * Service can be used to search your documents, upload and download files,
  51. * change sharing permission, file documents in folders, and view revisions
  52. * history.
  53. */
  54. public class DocumentList {
  55. public DocsService service;
  56. public GoogleService spreadsheetsService;
  57. public static final String DEFAULT_AUTH_PROTOCOL = "https";
  58. public static final String DEFAULT_AUTH_HOST = "docs.google.com";
  59. public static final String DEFAULT_PROTOCOL = "http";
  60. public static final String DEFAULT_HOST = "docs.google.com";
  61. public static final String SPREADSHEETS_SERVICE_NAME = "wise";
  62. public static final String SPREADSHEETS_HOST = "spreadsheets.google.com";
  63. private final String URL_FEED = "/feeds";
  64. private final String URL_DOWNLOAD = "/download";
  65. private final String URL_DOCLIST_FEED = "/private/full";
  66. private final String URL_DEFAULT = "/default";
  67. private final String URL_FOLDERS = "/contents";
  68. private final String URL_ACL = "/acl";
  69. private final String URL_REVISIONS = "/revisions";
  70. private final String URL_CATEGORY_DOCUMENT = "/-/document";
  71. private final String URL_CATEGORY_SPREADSHEET = "/-/spreadsheet";
  72. private final String URL_CATEGORY_PDF = "/-/pdf";
  73. private final String URL_CATEGORY_PRESENTATION = "/-/presentation";
  74. private final String URL_CATEGORY_STARRED = "/-/starred";
  75. private final String URL_CATEGORY_TRASHED = "/-/trashed";
  76. private final String URL_CATEGORY_FOLDER = "/-/folder";
  77. private final String URL_CATEGORY_EXPORT = "/Export";
  78. private final String PARAMETER_SHOW_FOLDERS = "showfolders=true";
  79. @SuppressWarnings("unused")
  80. private String applicationName;
  81. @SuppressWarnings("unused")
  82. private String authProtocol;
  83. @SuppressWarnings("unused")
  84. private String authHost;
  85. private String protocol;
  86. private String host;
  87. @SuppressWarnings("unused")
  88. private String username;
  89. @SuppressWarnings("unused")
  90. private String password;
  91. @SuppressWarnings("unused")
  92. private String authSubToken;
  93. private final Map<String, String> DOWNLOAD_DOCUMENT_FORMATS;
  94. {
  95. DOWNLOAD_DOCUMENT_FORMATS = new HashMap<String, String>();
  96. DOWNLOAD_DOCUMENT_FORMATS.put("doc", "doc");
  97. DOWNLOAD_DOCUMENT_FORMATS.put("txt", "txt");
  98. DOWNLOAD_DOCUMENT_FORMATS.put("odt", "odt");
  99. DOWNLOAD_DOCUMENT_FORMATS.put("pdf", "pdf");
  100. DOWNLOAD_DOCUMENT_FORMATS.put("png", "png");
  101. DOWNLOAD_DOCUMENT_FORMATS.put("rtf", "rtf");
  102. DOWNLOAD_DOCUMENT_FORMATS.put("html", "html");
  103. DOWNLOAD_DOCUMENT_FORMATS.put("zip", "zip");
  104. }
  105. private final Map<String, String> DOWNLOAD_PRESENTATION_FORMATS;
  106. {
  107. DOWNLOAD_PRESENTATION_FORMATS = new HashMap<String, String>();
  108. DOWNLOAD_PRESENTATION_FORMATS.put("pdf", "pdf");
  109. DOWNLOAD_PRESENTATION_FORMATS.put("png", "png");
  110. DOWNLOAD_PRESENTATION_FORMATS.put("ppt", "ppt");
  111. DOWNLOAD_PRESENTATION_FORMATS.put("swf", "swf");
  112. DOWNLOAD_PRESENTATION_FORMATS.put("txt", "txt");
  113. }
  114. private final Map<String, String> DOWNLOAD_SPREADSHEET_FORMATS;
  115. {
  116. DOWNLOAD_SPREADSHEET_FORMATS = new HashMap<String, String>();
  117. DOWNLOAD_SPREADSHEET_FORMATS.put("xls", "xls");
  118. DOWNLOAD_SPREADSHEET_FORMATS.put("ods", "ods");
  119. DOWNLOAD_SPREADSHEET_FORMATS.put("pdf", "pdf");
  120. DOWNLOAD_SPREADSHEET_FORMATS.put("csv", "csv");
  121. DOWNLOAD_SPREADSHEET_FORMATS.put("tsv", "tsv");
  122. DOWNLOAD_SPREADSHEET_FORMATS.put("html", "html");
  123. }
  124. /**
  125. * Constructor.
  126. *
  127. * @param applicationName name of the application.
  128. * @throws DocumentListException the document list exception
  129. */
  130. public DocumentList(String applicationName) throws DocumentListException {
  131. this(applicationName, DEFAULT_AUTH_PROTOCOL, DEFAULT_AUTH_HOST, DEFAULT_PROTOCOL, DEFAULT_HOST);
  132. }
  133. /**
  134. * Constructor.
  135. *
  136. * @param applicationName name of the application
  137. * @param authProtocol the protocol to use for authentication
  138. * @param authHost the host to use for authentication
  139. * @param protocol the protocol to use for the http calls.
  140. * @param host the host that contains the feeds
  141. * @throws DocumentListException the document list exception
  142. */
  143. public DocumentList(String applicationName, String authProtocol, String authHost, String protocol, String host) throws DocumentListException {
  144. if (authProtocol == null || authHost == null || protocol == null || host == null) {
  145. throw new DocumentListException("null passed in required parameters");
  146. }
  147. service = new DocsService(applicationName);
  148. // Creating a spreadsheets service is necessary for downloading
  149. // spreadsheets
  150. spreadsheetsService = new GoogleService(SPREADSHEETS_SERVICE_NAME, applicationName);
  151. this.applicationName = applicationName;
  152. this.authProtocol = authProtocol;
  153. this.authHost = authHost;
  154. this.protocol = protocol;
  155. this.host = host;
  156. }
  157. /**
  158. * Set user credentials based on a username and password.
  159. *
  160. * @param user username to log in with.
  161. * @param pass password for the user logging in.
  162. * @throws AuthenticationException the authentication exception
  163. * @throws DocumentListException the document list exception
  164. */
  165. public void login(String user, String pass) throws AuthenticationException, DocumentListException {
  166. if (user == null || pass == null) {
  167. throw new DocumentListException("null login credentials");
  168. }
  169. this.username = user;
  170. this.password = pass;
  171. this.authSubToken = "";
  172. service.setUserCredentials(user, pass);
  173. spreadsheetsService.setUserCredentials(user, pass);
  174. }
  175. /**
  176. * Allow a user to login using an AuthSub token.
  177. *
  178. * @param token the token to be used when logging in.
  179. * @throws AuthenticationException the authentication exception
  180. * @throws DocumentListException the document list exception
  181. */
  182. public void loginWithAuthSubToken(String token) throws AuthenticationException, DocumentListException {
  183. if (token == null) {
  184. throw new DocumentListException("null login credentials");
  185. }
  186. this.authSubToken = token;
  187. this.username = "";
  188. this.password = "";
  189. service.setAuthSubToken(token);
  190. spreadsheetsService.setAuthSubToken(token);
  191. }
  192. /**
  193. * Create a new item in the DocList.
  194. *
  195. * @param title the title of the document to be created.
  196. * @param type the type of the document to be created. One of "spreadsheet",
  197. * "presentation", or "document".
  198. * @return the document list entry
  199. * @throws MalformedURLException the malformed url exception
  200. * @throws IOException Signals that an I/O exception has occurred.
  201. * @throws ServiceException the service exception
  202. * @throws DocumentListException the document list exception
  203. */
  204. public DocumentListEntry createNew(String title, String type) throws MalformedURLException, IOException, ServiceException, DocumentListException {
  205. if (title == null || type == null) {
  206. throw new DocumentListException("null title or type");
  207. }
  208. DocumentListEntry newEntry = null;
  209. if (type.equals("document")) {
  210. newEntry = new DocumentEntry();
  211. } else if (type.equals("presentation")) {
  212. newEntry = new PresentationEntry();
  213. } else if (type.equals("spreadsheet")) {
  214. newEntry = new SpreadsheetEntry();
  215. } else if (type.equals("folder")) {
  216. newEntry = new FolderEntry();
  217. }
  218. newEntry.setTitle(new PlainTextConstruct(title));
  219. return service.insert(buildUrl(URL_DEFAULT + URL_DOCLIST_FEED), newEntry);
  220. }
  221. /**
  222. * Creates the new sub folder.
  223. *
  224. * @param title the title
  225. * @param folderResourceId the folder resource id
  226. * @return the document list entry
  227. * @throws IOException Signals that an I/O exception has occurred.
  228. * @throws ServiceException the service exception
  229. * @throws DocumentListException the document list exception
  230. */
  231. public DocumentListEntry createNewSubFolder(String title, String folderResourceId) throws IOException, ServiceException, DocumentListException {
  232. DocumentListEntry newEntry = new FolderEntry();
  233. newEntry.setTitle(new PlainTextConstruct(title));
  234. URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + folderResourceId + URL_FOLDERS);
  235. return service.insert(url, newEntry);
  236. }
  237. /**
  238. * Gets a feed containing the documents.
  239. *
  240. * @param category
  241. * what types of documents to list: "all": lists all the doc
  242. * objects (documents, spreadsheets, presentations) "folders":
  243. * lists all doc objects including folders. "documents": lists
  244. * only documents. "spreadsheets": lists only spreadsheets.
  245. * "pdfs": lists only pdfs. "presentations": lists only
  246. * presentations. "starred": lists only starred objects.
  247. * "trashed": lists trashed objects.
  248. *
  249. * @throws IOException
  250. * @throws MalformedURLException
  251. * @throws ServiceException
  252. * @throws DocumentListException
  253. */
  254. public DocumentListFeed getDocsListFeed(String category) throws IOException, MalformedURLException, ServiceException, DocumentListException {
  255. if (category == null) {
  256. throw new DocumentListException("null category");
  257. }
  258. URL url;
  259. if (category.equals("all")) {
  260. url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED);
  261. } else if (category.equals("folders")) {
  262. String[] parameters = { PARAMETER_SHOW_FOLDERS };
  263. url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_FOLDER, parameters);
  264. } else if (category.equals("documents")) {
  265. url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_DOCUMENT);
  266. } else if (category.equals("spreadsheets")) {
  267. url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_SPREADSHEET);
  268. } else if (category.equals("pdfs")) {
  269. url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_PDF);
  270. } else if (category.equals("presentations")) {
  271. url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_PRESENTATION);
  272. } else if (category.equals("starred")) {
  273. url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_STARRED);
  274. } else if (category.equals("trashed")) {
  275. url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_TRASHED);
  276. } else {
  277. return null;
  278. }
  279. DocumentQuery query = new DocumentQuery(url);
  280. // if (!category.equals("folders")) {
  281. // query.setMaxResults(101);
  282. // }
  283. return service.getFeed(query, DocumentListFeed.class);
  284. }
  285. public DocumentListFeed getDocsListFeed(Link link) throws MalformedURLException, IOException, ServiceException, DocumentListException {
  286. if (link != null) {
  287. return service.getFeed(new URL(link.getHref()), DocumentListFeed.class);
  288. }
  289. return null;
  290. }
  291. /**
  292. * Gets the entry for the provided object id.
  293. *
  294. * @param resourceId the resource id of the object to fetch an entry for.
  295. * @return the docs list entry
  296. * @throws IOException Signals that an I/O exception has occurred.
  297. * @throws MalformedURLException the malformed url exception
  298. * @throws ServiceException the service exception
  299. * @throws DocumentListException the document list exception
  300. */
  301. public DocumentListEntry getDocsListEntry(String resourceId) throws IOException, MalformedURLException, ServiceException, DocumentListException {
  302. if (resourceId == null) {
  303. throw new DocumentListException("null resourceId");
  304. }
  305. URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + resourceId);
  306. return service.getEntry(url, DocumentListEntry.class);
  307. }
  308. /**
  309. * Gets the feed for all the objects contained in a folder.
  310. *
  311. * @param folderResourceId the resource id of the folder to return the feed for the
  312. * contents.
  313. * @return the folder docs list feed
  314. * @throws IOException Signals that an I/O exception has occurred.
  315. * @throws MalformedURLException the malformed url exception
  316. * @throws ServiceException the service exception
  317. * @throws DocumentListException the document list exception
  318. */
  319. public DocumentListFeed getFolderDocsListFeed(String folderResourceId) throws IOException, MalformedURLException, ServiceException,
  320. DocumentListException {
  321. if (folderResourceId == null) {
  322. throw new DocumentListException("null folderResourceId");
  323. }
  324. URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + folderResourceId + URL_FOLDERS);
  325. return service.getFeed(url, DocumentListFeed.class);
  326. }
  327. /**
  328. * Gets the feed for all the folders contained in a folder.
  329. *
  330. * @param folderResourceId the resource id of the folder to return the feed for the
  331. * contents.
  332. * @return the sub folders
  333. * @throws IOException Signals that an I/O exception has occurred.
  334. * @throws MalformedURLException the malformed url exception
  335. * @throws ServiceException the service exception
  336. * @throws DocumentListException the document list exception
  337. */
  338. public DocumentListFeed getSubFolders(String folderResourceId) throws IOException, MalformedURLException, ServiceException, DocumentListException {
  339. if (folderResourceId == null) {
  340. throw new DocumentListException("null folderResourceId");
  341. }
  342. String[] parameters = { PARAMETER_SHOW_FOLDERS };
  343. URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + folderResourceId + URL_FOLDERS + URL_CATEGORY_FOLDER, parameters);
  344. return service.getFeed(url, DocumentListFeed.class);
  345. }
  346. /**
  347. * Gets a feed containing the documents.
  348. *
  349. * @param resourceId the resource id of the object to fetch revisions for.
  350. * @return the revisions feed
  351. * @throws IOException Signals that an I/O exception has occurred.
  352. * @throws MalformedURLException the malformed url exception
  353. * @throws ServiceException the service exception
  354. * @throws DocumentListException the document list exception
  355. */
  356. public RevisionFeed getRevisionsFeed(String resourceId) throws IOException, MalformedURLException, ServiceException, DocumentListException {
  357. if (resourceId == null) {
  358. throw new DocumentListException("null resourceId");
  359. }
  360. URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + resourceId + URL_REVISIONS);
  361. return service.getFeed(url, RevisionFeed.class);
  362. }
  363. /**
  364. * Search the documents, and return a feed of docs that match.
  365. *
  366. * @param searchParameters parameters to be used in searching criteria.
  367. * @return the document list feed
  368. * @throws IOException Signals that an I/O exception has occurred.
  369. * @throws MalformedURLException the malformed url exception
  370. * @throws ServiceException the service exception
  371. * @throws DocumentListException the document list exception
  372. */
  373. public DocumentListFeed search(Map<String, String> searchParameters) throws IOException, MalformedURLException, ServiceException,
  374. DocumentListException {
  375. return search(searchParameters, null);
  376. }
  377. /**
  378. * Search the documents, and return a feed of docs that match.
  379. *
  380. * @param searchParameters
  381. * parameters to be used in searching criteria. accepted
  382. * parameters are: "q": Typical search query "alt": "author":
  383. * "updated-min": Lower bound on the last time a document'
  384. * content was changed. "updated-max": Upper bound on the last
  385. * time a document' content was changed. "edited-min": Lower
  386. * bound on the last time a document was edited by the current
  387. * user. This value corresponds to the app:edited value in the
  388. * Atom entry, which represents changes to the document's content
  389. * or metadata. "edited-max": Upper bound on the last time a
  390. * document was edited by the current user. This value
  391. * corresponds to the app:edited value in the Atom entry, which
  392. * represents changes to the document's content or metadata.
  393. * "title": Specifies the search terms for the title of a
  394. * document. This parameter used without title-exact will only
  395. * submit partial queries, not exact queries. "title-exact":
  396. * Specifies whether the title query should be taken as an exact
  397. * string. Meaningless without title. Possible values are true
  398. * and false. "opened-min": Bounds on the last time a document
  399. * was opened by the current user. Use the RFC 3339 timestamp
  400. * format. For example: 2005-08-09T10:57:00-08:00 "opened-max":
  401. * Bounds on the last time a document was opened by the current
  402. * user. Use the RFC 3339 timestamp format. For example:
  403. * 2005-08-09T10:57:00-08:00 "owner": Searches for documents with
  404. * a specific owner. Use the email address of the owner.
  405. * "writer": Searches for documents which can be written to by
  406. * specific users. Use a single email address or a comma
  407. * separated list of email addresses. "reader": Searches for
  408. * documents which can be read by specific users. Use a single
  409. * email address or a comma separated list of email addresses.
  410. * "showfolders": Specifies whether the query should return
  411. * folders as well as documents. Possible values are true and
  412. * false.
  413. * @param category
  414. * define the category to search. (documents, spreadsheets,
  415. * presentations, starred, trashed, folders)
  416. *
  417. * @throws IOException
  418. * @throws MalformedURLException
  419. * @throws ServiceException
  420. * @throws DocumentListException
  421. */
  422. public DocumentListFeed search(Map<String, String> searchParameters, String category) throws IOException, MalformedURLException,
  423. ServiceException, DocumentListException {
  424. if (searchParameters == null) {
  425. throw new DocumentListException("searchParameters null");
  426. }
  427. URL url;
  428. if (category == null || category.equals("")) {
  429. url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED);
  430. } else if (category.equals("documents")) {
  431. url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_DOCUMENT);
  432. } else if (category.equals("spreadsheets")) {
  433. url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_SPREADSHEET);
  434. } else if (category.equals("presentations")) {
  435. url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_PRESENTATION);
  436. } else if (category.equals("starred")) {
  437. url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_STARRED);
  438. } else if (category.equals("trashed")) {
  439. url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_TRASHED);
  440. } else if (category.equals("folders")) {
  441. url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + URL_CATEGORY_FOLDER);
  442. } else {
  443. throw new DocumentListException("invaild category");
  444. }
  445. Query qry = new Query(url);
  446. for (String key : searchParameters.keySet()) {
  447. qry.setStringCustomParameter(key, searchParameters.get(key));
  448. }
  449. return service.query(qry, DocumentListFeed.class);
  450. }
  451. /**
  452. * Upload a file.
  453. *
  454. * @param filepath path to uploaded file.
  455. * @param title title to use for uploaded file.
  456. * @param convert the convert
  457. * @param hidden the hidden
  458. * @return the document list entry
  459. * @throws IOException when an error occurs in communication with the Doclist
  460. * service.
  461. * @throws ServiceException when the request causes an error in the Doclist service.
  462. * @throws DocumentListException the document list exception
  463. */
  464. public DocumentListEntry uploadFile(String filepath, String title, boolean convert, boolean hidden) throws IOException, ServiceException,
  465. DocumentListException {
  466. if (filepath == null || title == null) {
  467. throw new DocumentListException("null passed in for required parameters");
  468. }
  469. File file = new File(filepath);
  470. DocumentEntry newDocument = new DocumentEntry();
  471. newDocument.setFile(file, getMimeType(file));
  472. newDocument.setTitle(new PlainTextConstruct(title));
  473. newDocument.setHidden(hidden);
  474. String url = URL_DEFAULT + URL_DOCLIST_FEED;
  475. if (!convert) {
  476. url += "?convert=false";
  477. }
  478. return service.insert(buildUrl(url), newDocument);
  479. }
  480. /**
  481. * Upload a file to a folder.
  482. *
  483. * @param filepath path to uploaded file.
  484. * @param title title to use for uploaded file.
  485. * @param folderResourceId the folder resource id
  486. * @param convert the convert
  487. * @param hidden the hidden
  488. * @return the document list entry
  489. * @throws IOException when an error occurs in communication with the Doclist
  490. * service.
  491. * @throws ServiceException when the request causes an error in the Doclist service.
  492. * @throws DocumentListException the document list exception
  493. */
  494. public DocumentListEntry uploadFileToFolder(String filepath, String title, String folderResourceId, boolean convert, boolean hidden)
  495. throws IOException, ServiceException, DocumentListException {
  496. if (filepath == null || title == null) {
  497. throw new DocumentListException("null passed in for required parameters");
  498. }
  499. File file = new File(filepath);
  500. DocumentEntry newDocument = new DocumentEntry();
  501. newDocument.setFile(file, getMimeType(file));
  502. newDocument.setTitle(new PlainTextConstruct(title));
  503. newDocument.setHidden(hidden);
  504. String url = URL_DEFAULT + URL_DOCLIST_FEED + "/" + folderResourceId + URL_FOLDERS;
  505. if (!convert) {
  506. url += "?convert=false";
  507. }
  508. return service.insert(buildUrl(url), newDocument);
  509. }
  510. public DocumentListEntry updateFile(String filepath, String title, DocumentListEntry entry, boolean hidden) throws IOException, ServiceException,
  511. DocumentListException {
  512. if (filepath == null || title == null) {
  513. throw new DocumentListException("null passed in for required parameters");
  514. }
  515. File file = new File(filepath);
  516. entry.setFile(file, getMimeType(file));
  517. entry.setHidden(hidden);
  518. return entry.updateMedia(true);
  519. }
  520. public String getMimeType(File file) {
  521. String mimeType = "";
  522. try {
  523. mimeType = DocumentListEntry.MediaType.fromFileName(file.getName()).getMimeType();
  524. } catch (IllegalArgumentException e) {
  525. }
  526. if (mimeType == "") {
  527. mimeType = new MimetypesFileTypeMap().getContentType(file);
  528. }
  529. return mimeType;
  530. }
  531. /**
  532. * Trash an object.
  533. *
  534. * @param resourceId the resource id of object to be trashed.
  535. * @param delete true to delete the permanently, false to move it to the trash.
  536. * @throws IOException Signals that an I/O exception has occurred.
  537. * @throws MalformedURLException the malformed url exception
  538. * @throws ServiceException the service exception
  539. * @throws DocumentListException the document list exception
  540. */
  541. public void trashObject(String resourceId, boolean delete) throws IOException, MalformedURLException, ServiceException, DocumentListException {
  542. if (resourceId == null) {
  543. throw new DocumentListException("null resourceId");
  544. }
  545. String feedUrl = URL_DEFAULT + URL_DOCLIST_FEED + "/" + resourceId;
  546. if (delete) {
  547. feedUrl += "?delete=true";
  548. }
  549. service.delete(buildUrl(feedUrl), getDocsListEntry(resourceId).getEtag());
  550. }
  551. /**
  552. * Remove an object from a folder.
  553. *
  554. * @param resourceId the resource id of an object to be removed from the folder.
  555. * @param folderResourceId the resource id of the folder to remove the object from.
  556. * @throws IOException Signals that an I/O exception has occurred.
  557. * @throws MalformedURLException the malformed url exception
  558. * @throws ServiceException the service exception
  559. * @throws DocumentListException the document list exception
  560. */
  561. public void removeFromFolder(String resourceId, String folderResourceId) throws IOException, MalformedURLException, ServiceException,
  562. DocumentListException {
  563. if (resourceId == null || folderResourceId == null) {
  564. throw new DocumentListException("null passed in for required parameters");
  565. }
  566. URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + folderResourceId + URL_FOLDERS + "/" + resourceId);
  567. service.delete(url, getDocsListEntry(resourceId).getEtag());
  568. }
  569. /**
  570. * Downloads a file.
  571. *
  572. * @param exportUrl the full url of the export link to download the file from.
  573. * @param filepath path and name of the object to be saved as.
  574. * @throws IOException Signals that an I/O exception has occurred.
  575. * @throws MalformedURLException the malformed url exception
  576. * @throws ServiceException the service exception
  577. * @throws DocumentListException the document list exception
  578. */
  579. public void downloadFile(URL exportUrl, String filepath) throws IOException, MalformedURLException, ServiceException, DocumentListException {
  580. if (exportUrl == null || filepath == null) {
  581. throw new DocumentListException("null passed in for required parameters");
  582. }
  583. MediaContent mc = new MediaContent();
  584. mc.setUri(exportUrl.toString());
  585. MediaSource ms = service.getMedia(mc);
  586. InputStream inStream = null;
  587. FileOutputStream outStream = null;
  588. try {
  589. inStream = ms.getInputStream();
  590. outStream = new FileOutputStream(filepath);
  591. int c;
  592. while ((c = inStream.read()) != -1) {
  593. outStream.write(c);
  594. }
  595. } finally {
  596. if (inStream != null) {
  597. inStream.close();
  598. }
  599. if (outStream != null) {
  600. outStream.flush();
  601. outStream.close();
  602. }
  603. }
  604. }
  605. /**
  606. * Downloads a spreadsheet file.
  607. *
  608. * @param resourceId the resource id of the object to be downloaded.
  609. * @param filepath path and name of the object to be saved as.
  610. * @param format format to download the file to. The following file types are
  611. * supported: spreadsheets: "ods", "pdf", "xls", "csv", "html",
  612. * "tsv"
  613. * @throws IOException Signals that an I/O exception has occurred.
  614. * @throws MalformedURLException the malformed url exception
  615. * @throws ServiceException the service exception
  616. * @throws DocumentListException the document list exception
  617. */
  618. public void downloadSpreadsheet(String resourceId, String filepath, String format) throws IOException, MalformedURLException, ServiceException,
  619. DocumentListException {
  620. if (resourceId == null || filepath == null || format == null) {
  621. throw new DocumentListException("null passed in for required parameters");
  622. }
  623. UserToken docsToken = (UserToken) service.getAuthTokenFactory().getAuthToken();
  624. UserToken spreadsheetsToken = (UserToken) spreadsheetsService.getAuthTokenFactory().getAuthToken();
  625. service.setUserToken(spreadsheetsToken.getValue());
  626. HashMap<String, String> parameters = new HashMap<String, String>();
  627. parameters.put("key", resourceId.substring(resourceId.lastIndexOf(':') + 1));
  628. parameters.put("exportFormat", format);
  629. // If exporting to .csv or .tsv, add the gid parameter to specify which
  630. // sheet to export
  631. if (format.equals(DOWNLOAD_SPREADSHEET_FORMATS.get("csv")) || format.equals(DOWNLOAD_SPREADSHEET_FORMATS.get("tsv"))) {
  632. parameters.put("gid", "0"); // download only the first sheet
  633. }
  634. URL url = buildUrl(SPREADSHEETS_HOST, URL_DOWNLOAD + "/spreadsheets" + URL_CATEGORY_EXPORT, parameters);
  635. downloadFile(url, filepath);
  636. // Restore docs token for our DocList client
  637. service.setUserToken(docsToken.getValue());
  638. }
  639. /**
  640. * Downloads a document.
  641. *
  642. * @param resourceId the resource id of the object to be downloaded.
  643. * @param filepath path and name of the object to be saved as.
  644. * @param format format to download the file to. The following file types are
  645. * supported: documents: "doc", "txt", "odt", "png", "pdf",
  646. * "rtf", "html"
  647. * @throws IOException Signals that an I/O exception has occurred.
  648. * @throws MalformedURLException the malformed url exception
  649. * @throws ServiceException the service exception
  650. * @throws DocumentListException the document list exception
  651. */
  652. public void downloadDocument(String resourceId, String filepath, String format) throws IOException, MalformedURLException, ServiceException,
  653. DocumentListException {
  654. if (resourceId == null || filepath == null || format == null) {
  655. throw new DocumentListException("null passed in for required parameters");
  656. }
  657. String[] parameters = { "docID=" + resourceId, "exportFormat=" + format };
  658. URL url = buildUrl(URL_DOWNLOAD + "/documents" + URL_CATEGORY_EXPORT, parameters);
  659. downloadFile(url, filepath);
  660. }
  661. /**
  662. * Downloads a presentation.
  663. *
  664. * @param resourceId the resource id of the object to be downloaded.
  665. * @param filepath path and name of the object to be saved as.
  666. * @param format format to download the file to. The following file types are
  667. * supported: presentations: "pdf", "ppt", "png", "swf", "txt"
  668. * @throws IOException Signals that an I/O exception has occurred.
  669. * @throws MalformedURLException the malformed url exception
  670. * @throws ServiceException the service exception
  671. * @throws DocumentListException the document list exception
  672. */
  673. public void downloadPresentation(String resourceId, String filepath, String format) throws IOException, MalformedURLException, ServiceException,
  674. DocumentListException {
  675. if (resourceId == null || filepath == null || format == null) {
  676. throw new DocumentListException("null passed in for required parameters");
  677. }
  678. String[] parameters = { "docID=" + resourceId, "exportFormat=" + format };
  679. URL url = buildUrl(URL_DOWNLOAD + "/presentations" + URL_CATEGORY_EXPORT, parameters);
  680. downloadFile(url, filepath);
  681. }
  682. /**
  683. * Moves a object to a folder.
  684. *
  685. * @param resourceId the resource id of the object to be moved to the folder.
  686. * @param folderId the id of the folder to move the object to.
  687. * @return the document list entry
  688. * @throws IOException Signals that an I/O exception has occurred.
  689. * @throws MalformedURLException the malformed url exception
  690. * @throws ServiceException the service exception
  691. * @throws DocumentListException the document list exception
  692. */
  693. public DocumentListEntry moveObjectToFolder(String resourceId, String folderId) throws IOException, MalformedURLException, ServiceException,
  694. DocumentListException {
  695. if (resourceId == null || folderId == null) {
  696. throw new DocumentListException("null passed in for required parameters");
  697. }
  698. DocumentListEntry doc = new DocumentListEntry();
  699. doc.setId(buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + resourceId).toString());
  700. URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + folderId + URL_FOLDERS);
  701. return service.insert(url, doc);
  702. }
  703. /**
  704. * Gets the access control list for a object.
  705. *
  706. * @param resourceId the resource id of the object to retrieve the ACL for.
  707. * @return the acl feed
  708. * @throws IOException Signals that an I/O exception has occurred.
  709. * @throws MalformedURLException the malformed url exception
  710. * @throws ServiceException the service exception
  711. * @throws DocumentListException the document list exception
  712. */
  713. public AclFeed getAclFeed(String resourceId) throws IOException, MalformedURLException, ServiceException, DocumentListException {
  714. if (resourceId == null) {
  715. throw new DocumentListException("null resourceId");
  716. }
  717. URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + resourceId + URL_ACL);
  718. return service.getFeed(url, AclFeed.class);
  719. }
  720. /**
  721. * Add an ACL role to an object.
  722. *
  723. * @param role the role of the ACL to be added to the object.
  724. * @param scope the scope for the ACL.
  725. * @param resourceId the resource id of the object to set the ACL for.
  726. * @return the acl entry
  727. * @throws IOException Signals that an I/O exception has occurred.
  728. * @throws MalformedURLException the malformed url exception
  729. * @throws ServiceException the service exception
  730. * @throws DocumentListException the document list exception
  731. */
  732. public AclEntry addAclRole(AclRole role, AclScope scope, String resourceId) throws IOException, MalformedURLException, ServiceException,
  733. DocumentListException {
  734. if (role == null || scope == null || resourceId == null) {
  735. throw new DocumentListException("null passed in for required parameters");
  736. }
  737. AclEntry entry = new AclEntry();
  738. entry.setRole(role);
  739. entry.setScope(scope);
  740. URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + resourceId + URL_ACL);
  741. return service.insert(url, entry);
  742. }
  743. /**
  744. * Change the ACL role of a file.
  745. *
  746. * @param role the new role of the ACL to be updated.
  747. * @param scope the new scope for the ACL.
  748. * @param resourceId the resource id of the object to be updated.
  749. * @return the acl entry
  750. * @throws IOException Signals that an I/O exception has occurred.
  751. * @throws MalformedURLException the malformed url exception
  752. * @throws ServiceException the service exception
  753. * @throws DocumentListException the document list exception
  754. */
  755. public AclEntry changeAclRole(AclRole role, AclScope scope, String resourceId) throws IOException, MalformedURLException, ServiceException,
  756. DocumentListException {
  757. if (role == null || scope == null || resourceId == null) {
  758. throw new DocumentListException("null passed in for required parameters");
  759. }
  760. URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + resourceId + URL_ACL);
  761. return service.update(url, scope, role);
  762. }
  763. /**
  764. * Remove an ACL role from a object.
  765. *
  766. * @param scope scope of the ACL to be removed.
  767. * @param email email address to remove the role of.
  768. * @param resourceId the resource id of the object to remove the role from.
  769. * @throws IOException Signals that an I/O exception has occurred.
  770. * @throws MalformedURLException the malformed url exception
  771. * @throws ServiceException the service exception
  772. * @throws DocumentListException the document list exception
  773. */
  774. public void removeAclRole(String scope, String email, String resourceId) throws IOException, MalformedURLException, ServiceException,
  775. DocumentListException {
  776. if (scope == null || email == null || resourceId == null) {
  777. throw new DocumentListException("null passed in for required parameters");
  778. }
  779. URL url = buildUrl(URL_DEFAULT + URL_DOCLIST_FEED + "/" + resourceId + URL_ACL + "/" + scope + "%3A" + email);
  780. service.delete(url);
  781. }
  782. /**
  783. * Returns the format code based on a file extension, and object id.
  784. *
  785. * @param resourceId the resource id of the object you want the format for.
  786. * @param ext extension of the file you want the format for.
  787. * @return the download format
  788. * @throws DocumentListException the document list exception
  789. */
  790. public String getDownloadFormat(String resourceId, String ext) throws DocumentListException {
  791. if (resourceId == null || ext == null) {
  792. throw new DocumentListException("null passed in for required parameters");
  793. }
  794. if (resourceId.indexOf("document") == 0) {
  795. if (DOWNLOAD_DOCUMENT_FORMATS.containsKey(ext)) {
  796. return DOWNLOAD_DOCUMENT_FORMATS.get(ext);
  797. }
  798. } else if (resourceId.indexOf("presentation") == 0) {
  799. if (DOWNLOAD_PRESENTATION_FORMATS.containsKey(ext)) {
  800. return DOWNLOAD_PRESENTATION_FORMATS.get(ext);
  801. }
  802. } else if (resourceId.indexOf("spreadsheet") == 0) {
  803. if (DOWNLOAD_SPREADSHEET_FORMATS.containsKey(ext)) {
  804. return DOWNLOAD_SPREADSHEET_FORMATS.get(ext);
  805. }
  806. }
  807. throw new DocumentListException("invalid document type");
  808. }
  809. /**
  810. * Gets the suffix of the resourceId. If the resourceId is
  811. * "document:dh3bw3j_0f7xmjhd8", "dh3bw3j_0f7xmjhd8" will be returned.
  812. *
  813. * @param resourceId the resource id to extract the suffix from.
  814. * @return the resource id suffix
  815. * @throws DocumentListException the document list exception
  816. */
  817. public String getResourceIdSuffix(String resourceId) throws DocumentListException {
  818. if (resourceId == null) {
  819. throw new DocumentListException("null resourceId");
  820. }
  821. if (resourceId.indexOf("%3A") != -1) {
  822. return resourceId.substring(resourceId.lastIndexOf("%3A") + 3);
  823. } else if (resourceId.indexOf(":") != -1) {
  824. return resourceId.substring(resourceId.lastIndexOf(":") + 1);
  825. }
  826. throw new DocumentListException("Bad resourceId");
  827. }
  828. /**
  829. * Gets the prefix of the resourceId. If the resourceId is
  830. * "document:dh3bw3j_0f7xmjhd8", "document" will be returned.
  831. *
  832. * @param resourceId the resource id to extract the suffix from.
  833. * @return the resource id prefix
  834. * @throws DocumentListException the document list exception
  835. */
  836. public String getResourceIdPrefix(String resourceId) throws DocumentListException {
  837. if (resourceId == null) {
  838. throw new DocumentListException("null resourceId");
  839. }
  840. if (resourceId.indexOf("%3A") != -1) {
  841. return resourceId.substring(0, resourceId.indexOf("%3A"));
  842. } else if (resourceId.indexOf(":") != -1) {
  843. return resourceId.substring(0, resourceId.indexOf(":"));
  844. } else {
  845. throw new DocumentListException("Bad resourceId");
  846. }
  847. }
  848. /**
  849. * Builds a URL from a patch.
  850. *
  851. * @param path the path to add to the protocol/host
  852. * @return the URL
  853. * @throws MalformedURLException the malformed url exception
  854. * @throws DocumentListException the document list exception
  855. */
  856. private URL buildUrl(String path) throws MalformedURLException, DocumentListException {
  857. if (path == null) {
  858. throw new DocumentListException("null path");
  859. }
  860. return buildUrl(path, null);
  861. }
  862. /**
  863. * Builds a URL with parameters.
  864. *
  865. * @param path the path to add to the protocol/host
  866. * @param parameters parameters to be added to the URL.
  867. * @return the uRL
  868. * @throws MalformedURLException the malformed url exception
  869. * @throws DocumentListException the document list exception
  870. */
  871. private URL buildUrl(String path, String[] parameters) throws MalformedURLException, DocumentListException {
  872. if (path == null) {
  873. throw new DocumentListException("null path");
  874. }
  875. return buildUrl(host, path, parameters);
  876. }
  877. /**
  878. * Builds a URL with parameters.
  879. *
  880. * @param domain the domain of the server
  881. * @param path the path to add to the protocol/host
  882. * @param parameters parameters to be added to the URL.
  883. * @return the uRL
  884. * @throws MalformedURLException the malformed url exception
  885. * @throws DocumentListException the document list exception
  886. */
  887. private URL buildUrl(String domain, String path, String[] parameters) throws MalformedURLException, DocumentListException {
  888. if (path == null) {
  889. throw new DocumentListException("null path");
  890. }
  891. StringBuffer url = new StringBuffer();
  892. url.append(protocol + "://" + domain + URL_FEED + path);
  893. if (parameters != null && parameters.length > 0) {
  894. url.append("?");
  895. for (int i = 0; i < parameters.length; i++) {
  896. url.append(parameters[i]);
  897. if (i != (parameters.length - 1)) {
  898. url.append("&");
  899. }
  900. }
  901. }
  902. return new URL(url.toString());
  903. }
  904. /**
  905. * Builds a URL with parameters.
  906. *
  907. * @param domain the domain of the server
  908. * @param path the path to add to the protocol/host
  909. * @param parameters parameters to be added to the URL as key value pairs.
  910. * @return the uRL
  911. * @throws MalformedURLException the malformed url exception
  912. * @throws DocumentListException the document list exception
  913. */
  914. private URL buildUrl(String domain, String path, Map<String, String> parameters) throws MalformedURLException, DocumentListException {
  915. if (path == null) {
  916. throw new DocumentListException("null path");
  917. }
  918. StringBuffer url = new StringBuffer();
  919. url.append(protocol + "://" + domain + URL_FEED + path);
  920. if (parameters != null && parameters.size() > 0) {
  921. Set<Map.Entry<String, String>> params = parameters.entrySet();
  922. Iterator<Map.Entry<String, String>> itr = params.iterator();
  923. url.append("?");
  924. while (itr.hasNext()) {
  925. Map.Entry<String, String> entry = itr.next();
  926. url.append(entry.getKey() + "=" + entry.getValue());
  927. if (itr.hasNext()) {
  928. url.append("&");
  929. }
  930. }
  931. }
  932. return new URL(url.toString());
  933. }
  934. }