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 *     Thierry Delprat
018 *     Florent Guillaume
019 */
020
021package org.nuxeo.ecm.automation.core.operations.execution;
022
023import java.util.Arrays;
024import java.util.Collection;
025import java.util.HashMap;
026import java.util.Map;
027
028import org.apache.commons.logging.Log;
029import org.apache.commons.logging.LogFactory;
030import org.nuxeo.ecm.automation.AutomationService;
031import org.nuxeo.ecm.automation.OperationContext;
032import org.nuxeo.ecm.automation.OperationException;
033import org.nuxeo.ecm.automation.core.Constants;
034import org.nuxeo.ecm.automation.core.annotations.Context;
035import org.nuxeo.ecm.automation.core.annotations.Operation;
036import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
037import org.nuxeo.ecm.automation.core.annotations.Param;
038import org.nuxeo.ecm.core.api.CoreSession;
039import org.nuxeo.ecm.core.api.DocumentModel;
040import org.nuxeo.ecm.core.api.NuxeoException;
041import org.nuxeo.runtime.transaction.TransactionHelper;
042
043/**
044 * @deprecated since 6.0. Use instead {@link RunOperationOnList} with ID 'Context.RunOperationOnList'. Run an embedded
045 *             operation chain inside separated transactions using the current input. The output is undefined (Void)
046 * @since 5.7.2
047 */
048@Deprecated
049@Operation(id = RunOperationOnListInNewTransaction.ID, category = Constants.CAT_SUBCHAIN_EXECUTION, label = "Run For Each in new TX", description = "Run an operation/chain in a new Transaction 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 'itemName' 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.", deprecatedSince = "6.0", aliases = {
050        "Context.RunOperationOnListInNewTx" })
051public class RunOperationOnListInNewTransaction {
052
053    protected static Log log = LogFactory.getLog(RunOperationOnListInNewTransaction.class);
054
055    public static final String ID = "RunOperationOnListInNewTx";
056
057    @Context
058    protected OperationContext ctx;
059
060    @Context
061    protected AutomationService service;
062
063    @Context
064    protected CoreSession session;
065
066    @Param(name = "id")
067    protected String chainId;
068
069    @Param(name = "list")
070    protected String listName;
071
072    @Param(name = "itemName", required = false, values = "item")
073    protected String itemName = "item";
074
075    @Param(name = "isolate", required = false, values = "true")
076    protected boolean isolate = true;
077
078    @OperationMethod
079    public void run() throws OperationException {
080        Map<String, Object> vars = isolate ? new HashMap<>(ctx.getVars()) : ctx.getVars();
081
082        Collection<?> list = null;
083        if (ctx.get(listName) instanceof Object[]) {
084            list = Arrays.asList((Object[]) ctx.get(listName));
085        } else if (ctx.get(listName) instanceof Collection<?>) {
086            list = (Collection<?>) ctx.get(listName);
087        } else {
088            throw new UnsupportedOperationException(ctx.get(listName).getClass() + " is not a Collection");
089        }
090
091        // commit the current transaction
092        TransactionHelper.commitOrRollbackTransaction();
093
094        // execute on list in separate transactions
095        for (Object value : list) {
096            try {
097                TransactionHelper.runInNewTransaction(() -> {
098                    try (OperationContext subctx = ctx.getSubContext(isolate, ctx.getInput())) {
099                        subctx.callWithContextVar(() -> {
100                            service.run(subctx, chainId);
101                            return null;
102                        }, itemName, value);
103                    } catch (OperationException e) {
104                        throw new NuxeoException(e);
105                    }
106                });
107            } catch (NuxeoException e) {
108                if (e.getCause() instanceof OperationException) {
109                    throw (OperationException) e.getCause();
110                }
111                throw e;
112            }
113        }
114
115        TransactionHelper.startTransaction();
116
117        // reconnect documents in the context
118        if (!isolate) {
119            for (Map.Entry<String, Object> var : vars.entrySet()) {
120                String key = var.getKey();
121                Object value = var.getValue();
122                if (!ctx.getVars().containsKey(key)) {
123                    ctx.put(key, value);
124                } else {
125                    if (session != null && value != null && value instanceof DocumentModel) {
126                        ctx.getVars().put(key, session.getDocument(((DocumentModel) value).getRef()));
127                    } else {
128                        ctx.getVars().put(key, value);
129                    }
130                }
131            }
132        }
133    }
134
135}