001/* 002 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * bstefanescu 016 */ 017package org.nuxeo.shell.automation.cmds; 018 019import java.io.File; 020 021import org.nuxeo.ecm.automation.client.model.DocRef; 022import org.nuxeo.ecm.automation.client.model.FileBlob; 023import org.nuxeo.shell.Argument; 024import org.nuxeo.shell.Command; 025import org.nuxeo.shell.Context; 026import org.nuxeo.shell.Parameter; 027import org.nuxeo.shell.ShellConsole; 028import org.nuxeo.shell.ShellException; 029import org.nuxeo.shell.automation.DocRefCompletor; 030import org.nuxeo.shell.automation.RemoteContext; 031import org.nuxeo.shell.fs.FileSystem; 032 033/** 034 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> 035 */ 036@Command(name = "getfile", help = "Get a document attached file") 037public class GetBlob implements Runnable { 038 039 @Context 040 protected RemoteContext ctx; 041 042 @Parameter(name = "-xpath", hasValue = true, help = "The xpath of the blob property to get. Defaults to the one used by the File document type.") 043 protected String xpath; 044 045 @Parameter(name = "-todir", hasValue = true, help = "An optional target directory to save the file. The default is the current working directory.") 046 protected File todir; 047 048 @Argument(name = "doc", index = 0, required = false, completor = DocRefCompletor.class, help = "The target document. If not specified the current document is used. To use UID references prefix them with 'doc:'.") 049 protected String path; 050 051 public void run() { 052 ShellConsole console = ctx.getShell().getConsole(); 053 DocRef doc = ctx.resolveRef(path); 054 try { 055 FileBlob blob = ctx.getDocumentService().getBlob(doc, xpath); 056 String fname = blob.getFileName(); 057 if (fname == null || fname.length() == 0) { 058 fname = "unnamed_blob"; 059 } 060 if (todir == null) { 061 todir = ctx.getShell().getContextObject(FileSystem.class).pwd(); 062 } 063 File dst = new File(todir, fname); 064 blob.getFile().renameTo(dst); 065 console.println("File saved to: " + dst.getAbsolutePath()); 066 } catch (Exception e) { 067 throw new ShellException("Failed to get file from " + doc, e); 068 } 069 070 } 071}