001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     bstefanescu
011 */
012package org.nuxeo.ecm.automation.core.operations.blob;
013
014import java.io.File;
015import java.io.IOException;
016
017import org.nuxeo.ecm.automation.core.Constants;
018import org.nuxeo.ecm.automation.core.annotations.Operation;
019import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
020import org.nuxeo.ecm.automation.core.annotations.Param;
021import org.nuxeo.ecm.automation.core.collectors.BlobCollector;
022import org.nuxeo.ecm.core.api.Blob;
023
024/**
025 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
026 */
027@Operation(id = BlobToFile.ID, category = Constants.CAT_BLOB, label = "Export to File", description = "Save the input blob(s) as a file(s) into the given target directory. The blob(s) filename is used as the file name. You can specify an optional <b>prefix</b> string to prepend to the file name. Return back the blob(s).", aliases = { "Blob.ToFile" })
028public class BlobToFile {
029
030    public static final String ID = "Blob.ExportToFS";
031
032    @Param(name = "directory", required = true)
033    protected String directory;
034
035    @Param(name = "prefix", required = false)
036    protected String prefix;
037
038    protected File root;
039
040    protected void init() {
041        root = new File(directory);
042        root.mkdirs();
043    }
044
045    protected File getFile(String name) {
046        return new File(root, prefix != null ? prefix + name : name);
047    }
048
049    protected void writeFile(Blob blob) throws IOException {
050        String name = blob.getFilename();
051        if (name.length() == 0) {
052            name = "blob#" + Integer.toHexString(System.identityHashCode(blob));
053        }
054        // get the output file
055        File file = getFile(name);
056        // use a .tmp extension while writing the blob and rename it when write
057        // is done this is allowing external tools to track when the file becomes
058        // available.
059        File tmp = new File(file.getParentFile(), file.getName() + ".tmp");
060        blob.transferTo(tmp);
061        tmp.renameTo(file);
062    }
063
064    @OperationMethod(collector = BlobCollector.class)
065    public Blob run(Blob blob) throws IOException {
066        init();
067        writeFile(blob);
068        return blob;
069    }
070
071}