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 org.nuxeo.ecm.automation.core.Constants;
015import org.nuxeo.ecm.automation.core.annotations.Operation;
016import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
017import org.nuxeo.ecm.automation.core.annotations.Param;
018import org.nuxeo.ecm.automation.core.collectors.BlobCollector;
019import org.nuxeo.ecm.core.api.Blob;
020import org.nuxeo.ecm.core.api.Blobs;
021import org.nuxeo.ecm.core.api.DocumentModel;
022import org.nuxeo.ecm.core.api.blobholder.BlobHolder;
023
024/**
025 * Get document blob inside the file:content property
026 *
027 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
028 * @author tiry
029 */
030@Operation(id = GetDocumentBlob.ID, category = Constants.CAT_BLOB, label = "Get Document File", description = "Gets a file attached to the input document. The file location is specified using an xpath to the blob property of the document. Returns the file.", aliases = { "Blob.Get" })
031public class GetDocumentBlob {
032
033    public static final String ID = "Document.GetBlob";
034
035    @Param(name = "xpath", required = false, values = "file:content")
036    protected String xpath = "file:content";
037
038    @OperationMethod(collector = BlobCollector.class)
039    public Blob run(DocumentModel doc) {
040        Blob blob = (Blob) doc.getPropertyValue(xpath);
041        if (blob == null) {
042            BlobHolder bh = doc.getAdapter(BlobHolder.class);
043            if (bh != null) {
044                blob = bh.getBlob();
045            }
046        }
047        // cannot return null since it may break the next operation
048        if (blob == null) { // create an empty blob
049            blob = Blobs.createBlob("");
050            blob.setFilename(doc.getName() + ".null");
051        }
052        return blob;
053    }
054
055}