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 org.nuxeo.ecm.automation.OperationContext;
022import org.nuxeo.ecm.automation.core.Constants;
023import org.nuxeo.ecm.automation.core.annotations.Context;
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.DocumentModelCollector;
028import org.nuxeo.ecm.core.api.Blob;
029import org.nuxeo.ecm.core.api.CoreSession;
030import org.nuxeo.ecm.core.api.DocumentModel;
031import org.nuxeo.ecm.core.api.model.Property;
032
033/**
034 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
035 */
036@Operation(id = SetBlobFileName.ID, category = Constants.CAT_BLOB, label = "Set File Name", description = "Modify the filename of a file stored in the input document. The file is found in the input document given its xpath specified through the 'xpath' parameter. Return back the input document.", aliases = { "Blob.SetFilename" })
037public class SetBlobFileName {
038
039    public static final String ID = "Document.SetBlobName";
040
041    @Context
042    protected OperationContext ctx;
043
044    @Context
045    protected CoreSession session;
046
047    @Param(name = "name")
048    protected String name;
049
050    @Param(name = "xpath", required = false, values = "file:content")
051    protected String xpath = "file:content";
052
053    @Param(name = "save", required = false, values = "true")
054    protected boolean save = true;
055
056    @OperationMethod(collector = DocumentModelCollector.class)
057    public DocumentModel run(DocumentModel doc) throws java.lang.Exception {
058        Property p = doc.getProperty(xpath);
059        Object o = p.getValue();
060        if (o instanceof Blob) {
061            Blob blob = (Blob) o;
062            blob.setFilename(name);
063            p.setValue(blob);
064        }
065        if (save) {
066            doc = session.saveDocument(doc);
067        }
068        return doc;
069    }
070
071}