获取文档内容
文档的媒体内容是用户希望阅读或更新的数据。例如,媒体内容可以是 PDF 文件。在显示库中的文档列表之后,用户可以通过双击文档查看其媒体内容。当用户双击文档时,需要在相关联的应用程序中打开文档(比如用 Adobe Reader 打开 PDF 文件)。首先,需要获得文档的媒体内容,让应用程序有数据可处理。这需要使用保存在文档节点的 TreeObject 实例中的 edit-media 链接:
http://quickr.acme.com/dm/atom/library/5d06ab0044ed8129bd5ebd4caeec5df1
/document/7f37550044f10d5b9144bbd6afe18010/media
在对这个 URL 发出 GET 请求时,会在响应中返回文档的媒体内容。读取响应,将它保存在一个临时文件中,然后使用相关联的应用程序运行这个临时文件。清单 5 给出执行这个操作的代码。
清单 5. 下载和运行文档的部分代码
public void doOpen(String url) { TreeObject item = (TreeObject) ((IStructuredSelection) viewer .getSelection()).getFirstElement(); try { String tmpDir = File.createTempFile("qkr", "tmp").getParent(); File file = new File(tmpDir + "/" + item.getName()); if (file.exists()) { file.delete(); } ClientResponse response = httpClient.get(url); if (response.getStatus() == 200) { BufferedInputStream bis = new BufferedInputStream( response.getInputStream()); file.createNewFile(); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(file)); byte[] bytes = new byte[1024]; int count = 0; while ((count = bis.read(bytes)) != -1) { bos.write(bytes, 0, count); } bis.close(); bos.close(); // open the local file in editor IWorkspace ws = ResourcesPlugin.getWorkspace(); IProject project = ws.getRoot().getProject("Quickr Files"); if (!project.exists()) { project.create(null); } if (!project.isOpen()) { project.open(null); } IPath location = new Path(file.getPath()); IFile iFile = project.getFile(location.lastSegment()); if (!iFile.exists()) { iFile.createLink(location, IResource.NONE, null); } FileEditorInput fileEditorInput = new FileEditorInput(iFile); IEditorRegistry registry = PlatformUI.getWorkbench() .getEditorRegistry(); IWorkbenchPage page = getViewSite().getWorkbenchWindow() .getActivePage(); if (page != null) { if( registry.isSystemExternalEditorAvailable( iFile.getName())) { page.openEditor( fileEditorInput, IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID); } else if (registry.isSystemInPlaceEditorAvailable(iFile .getName())) { page.openEditor(fileEditorInput, IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID); } else { showMessage("No viewer available for this file type. You can download it instead."); } } } response.release(); } catch (IOException e) { e.printStackTrace(); } catch (CoreException e) { e.printStackTrace(); } }