001/*
002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     bstefanescu
018 */
019package org.nuxeo.ecm.automation.core.operations.blob;
020
021import java.util.List;
022
023import org.nuxeo.ecm.automation.core.Constants;
024import org.nuxeo.ecm.automation.core.annotations.Operation;
025import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
026import org.nuxeo.ecm.automation.core.annotations.Param;
027import org.nuxeo.ecm.automation.core.collectors.BlobListCollector;
028import org.nuxeo.ecm.automation.core.util.BlobList;
029import org.nuxeo.ecm.core.api.Blob;
030import org.nuxeo.ecm.core.api.DocumentModel;
031import org.nuxeo.ecm.core.api.blobholder.BlobHolder;
032import org.nuxeo.ecm.core.api.model.Property;
033import org.nuxeo.ecm.core.api.model.impl.ListProperty;
034
035/**
036 * Get document blobs inside the files:files property
037 *
038 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
039 * @author tiry
040 */
041@Operation(id = GetDocumentBlobs.ID, category = Constants.CAT_BLOB, label = "Get Document Files", description = "Gets a list of files that are attached on the input document. The files location should be specified using the blob list property xpath. Returns a list of files.", aliases = { "Blob.GetList" })
042public class GetDocumentBlobs {
043
044    public static final String ID = "Document.GetBlobsByProperty";
045
046    @Param(name = "xpath", required = false, values = "files:files")
047    protected String xpath = "files:files";
048
049    @OperationMethod(collector = BlobListCollector.class)
050    public BlobList run(DocumentModel doc) {
051        BlobList blobs = new BlobList();
052        ListProperty list = (ListProperty) doc.getProperty(xpath);
053        if (list == null) {
054            BlobHolder bh = doc.getAdapter(BlobHolder.class);
055            if (bh != null) {
056                List<Blob> docBlobs = bh.getBlobs();
057                if (docBlobs != null) {
058                    for (Blob blob : docBlobs) {
059                        blobs.add(blob);
060                    }
061                }
062            }
063            return blobs;
064        }
065        for (Property p : list) {
066            blobs.add((Blob) p.getValue("file"));
067        }
068        return blobs;
069    }
070
071}