001/*
002 * (C) Copyright 2006-2014 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 *     Vladimir Pasquier <vpasquier@nuxeo.com>
019 */
020package org.nuxeo.ecm.automation.core.operations.execution;
021
022import org.nuxeo.ecm.automation.AutomationService;
023import org.nuxeo.ecm.automation.OperationContext;
024import org.nuxeo.ecm.automation.OperationException;
025import org.nuxeo.ecm.automation.core.Constants;
026import org.nuxeo.ecm.automation.core.annotations.Context;
027import org.nuxeo.ecm.automation.core.annotations.Operation;
028import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
029import org.nuxeo.ecm.automation.core.annotations.Param;
030import org.nuxeo.ecm.automation.core.util.Properties;
031import org.nuxeo.ecm.core.api.CoreSession;
032import org.nuxeo.ecm.core.api.DocumentModel;
033import org.nuxeo.ecm.core.api.DocumentModelList;
034import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
035
036import java.util.HashMap;
037import java.util.Map;
038
039/**
040 * Run an embedded operation chain that returns a DocumentModel using the current input.
041 *
042 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
043 */
044@Operation(id = RunDocumentChain.ID, category = Constants.CAT_SUBCHAIN_EXECUTION, label = "Run Document Chain", description = "Run an operation chain which is returning a document in the current context. The input for the chain ro run is the current input of the operation. Return the output of the chain as a document. The 'parameters' injected are accessible in the subcontext ChainParameters. For instance, @{ChainParameters['parameterKey']}.", aliases = { "Context.RunDocumentOperation" })
045public class RunDocumentChain {
046
047    public static final String ID = "RunDocumentOperation";
048
049    @Context
050    protected OperationContext ctx;
051
052    @Context
053    protected AutomationService service;
054
055    @Context
056    protected CoreSession session;
057
058    @Param(name = "id")
059    protected String chainId;
060
061    @Param(name = "isolate", required = false, values = "false")
062    protected boolean isolate = false;
063
064    @Param(name = "parameters", description = "Accessible in the subcontext ChainParameters. For instance, @{ChainParameters['parameterKey']}.", required = false)
065    protected Properties chainParameters;
066
067    /**
068     * @since 6.0 Define if the chain in parameter should be executed in new transaction.
069     */
070    @Param(name = "newTx", required = false, values = "false", description = "Define if the chain in parameter should be executed in new transaction.")
071    protected boolean newTx = false;
072
073    /**
074     * @since 6.0 Define transaction timeout (default to 60 sec).
075     */
076    @Param(name = "timeout", required = false, description = "Define transaction timeout (default to 60 sec).")
077    protected Integer timeout = 60;
078
079    /**
080     * @since 6.0 Define if transaction should rollback or not (default to true).
081     */
082    @Param(name = "rollbackGlobalOnError", required = false, values = "true", description = "Define if transaction should rollback or not (default to true)")
083    protected boolean rollbackGlobalOnError = true;
084
085    @OperationMethod
086    @SuppressWarnings("unchecked")
087    public DocumentModel run(DocumentModel doc) throws OperationException {
088        // Handle isolation option
089        Map<String, Object> vars = isolate ? new HashMap<>(ctx.getVars()) : ctx.getVars();
090        OperationContext subctx = ctx.getSubContext(isolate, doc);
091
092        // Running chain/operation
093        DocumentModel result = null;
094        if (newTx) {
095            result = (DocumentModel) service.runInNewTx(subctx, chainId, chainParameters, timeout,
096                    rollbackGlobalOnError);
097        } else {
098            result = (DocumentModel) service.run(subctx, chainId, (Map) chainParameters);
099        }
100
101        // reconnect documents in the context
102        if (!isolate) {
103            for (String varName : vars.keySet()) {
104                if (!ctx.getVars().containsKey(varName)) {
105                    ctx.put(varName, vars.get(varName));
106                } else {
107                    Object value = vars.get(varName);
108                    if (session != null && value != null && value instanceof DocumentModel) {
109                        ctx.getVars().put(varName, session.getDocument(((DocumentModel) value).getRef()));
110                    } else {
111                        ctx.getVars().put(varName, value);
112                    }
113                }
114            }
115        }
116        return result;
117    }
118
119    @OperationMethod
120    public DocumentModelList run(DocumentModelList docs) throws OperationException {
121        DocumentModelList result = new DocumentModelListImpl(docs.size());
122        for (DocumentModel doc : docs) {
123            result.add(run(doc));
124        }
125        return result;
126    }
127
128}