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 java.util.Arrays;
023import java.util.Collection;
024import java.util.HashMap;
025import java.util.Map;
026
027import org.nuxeo.ecm.automation.AutomationService;
028import org.nuxeo.ecm.automation.OperationContext;
029import org.nuxeo.ecm.automation.OperationException;
030import org.nuxeo.ecm.automation.core.Constants;
031import org.nuxeo.ecm.automation.core.annotations.Context;
032import org.nuxeo.ecm.automation.core.annotations.Operation;
033import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
034import org.nuxeo.ecm.automation.core.annotations.Param;
035import org.nuxeo.ecm.automation.core.util.Properties;
036import org.nuxeo.ecm.core.api.CoreSession;
037import org.nuxeo.ecm.core.api.DocumentModel;
038
039/**
040 * Run an embedded operation chain using the current input. The output is undefined (Void)
041 *
042 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
043 * @since 5.5
044 */
045@Operation(id = RunOperationOnList.ID, category = Constants.CAT_SUBCHAIN_EXECUTION, label = "Run For Each", description = "Run an operation for each element from the list defined by the 'list' parameter. The 'list' parameter is pointing to a context variable that represents the list which will be iterated. The 'item' parameter represents the name of the context variable which will point to the current element in the list at each iteration. You can use the 'isolate' parameter to specify whether or not the evalution context is the same as the parent context or a copy of it. If the 'isolate' parameter is 'true' then a copy of the current context is used and so that modifications in this context will not affect the parent context. Any input is accepted. The input is returned back as output when operation terminates. The 'parameters' injected are accessible in the subcontext ChainParameters. For instance, @{ChainParameters['parameterKey']}.", aliases = { "Context.RunOperationOnList" })
046public class RunOperationOnList {
047
048    public static final String ID = "RunOperationOnList";
049
050    @Context
051    protected OperationContext ctx;
052
053    @Context
054    protected AutomationService service;
055
056    @Context
057    protected CoreSession session;
058
059    @Param(name = "id")
060    protected String chainId;
061
062    @Param(name = "list")
063    protected String listName;
064
065    @Param(name = "item", required = false, values = "item")
066    protected String itemName = "item";
067
068    @Param(name = "isolate", required = false, values = "true")
069    protected boolean isolate = true;
070
071    @Param(name = "parameters", description = "Accessible in the subcontext " + "ChainParameters. For instance, "
072            + "@{ChainParameters['parameterKey']}.", required = false)
073    protected Properties chainParameters;
074
075    /**
076     * @since 6.0 Define if the chain in parameter should be executed in new transaction.
077     */
078    @Param(name = "newTx", required = false, values = "false", description = "Define if the chain in parameter should be "
079            + "executed in new transaction.")
080    protected boolean newTx = false;
081
082    /**
083     * @since 6.0 Define transaction timeout (default to 60 sec).
084     */
085    @Param(name = "timeout", required = false, description = "Define " + "transaction timeout (default to 60 sec).")
086    protected Integer timeout = 60;
087
088    /**
089     * @since 6.0 Define if transaction should rollback or not (default to true).
090     */
091    @Param(name = "rollbackGlobalOnError", required = false, values = "true", description = "Define if transaction should rollback or not "
092            + "(default to true)")
093    protected boolean rollbackGlobalOnError = true;
094
095    @OperationMethod
096    @SuppressWarnings("unchecked")
097    public void run() throws OperationException {
098        // Handle isolation option
099        Map<String, Object> vars = isolate ? new HashMap<>(ctx.getVars()) : ctx.getVars();
100        OperationContext subctx = ctx.getSubContext(isolate, ctx.getInput());
101
102        // Running chain/operation for each list elements
103        Collection<?> list = null;
104        if (ctx.get(listName) instanceof Object[]) {
105            list = Arrays.asList((Object[]) ctx.get(listName));
106        } else if (ctx.get(listName) instanceof Collection<?>) {
107            list = (Collection<?>) ctx.get(listName);
108        } else {
109            throw new UnsupportedOperationException(ctx.get(listName).getClass() + " is not a Collection");
110        }
111        for (Object value : list) {
112            subctx.put(itemName, value);
113            // Running chain/operation
114            if (newTx) {
115                service.runInNewTx(subctx, chainId, chainParameters, timeout, rollbackGlobalOnError);
116            } else {
117                service.run(subctx, chainId, (Map) chainParameters);
118            }
119        }
120
121        // reconnect documents in the context
122        if (!isolate) {
123            for (String varName : vars.keySet()) {
124                if (!ctx.getVars().containsKey(varName)) {
125                    ctx.put(varName, vars.get(varName));
126                } else {
127                    Object value = vars.get(varName);
128                    if (session != null && value != null && value instanceof DocumentModel) {
129                        ctx.getVars().put(varName, session.getDocument(((DocumentModel) value).getRef()));
130                    } else {
131                        ctx.getVars().put(varName, value);
132                    }
133                }
134            }
135        }
136    }
137}