WorkflowLauncherHandler.java 27.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.aemfd.docmanager.Document
 *  com.adobe.granite.workflow.WorkflowSession
 *  com.adobe.granite.workflow.event.WorkflowEvent
 *  com.adobe.granite.workflow.exec.WorkItem
 *  com.adobe.granite.workflow.exec.Workflow
 *  com.adobe.granite.workflow.exec.WorkflowData
 *  com.adobe.granite.workflow.metadata.MetaDataMap
 *  com.adobe.granite.workflow.model.WorkflowModel
 *  javax.jcr.Binary
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.Session
 *  javax.jcr.ValueFactory
 *  org.apache.felix.scr.annotations.Activate
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Deactivate
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.osgi.framework.BundleContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.aemfd.watchfolder.workflow;

import com.adobe.aemfd.docmanager.Document;
import com.adobe.aemfd.watchfolder.config.WatchFolderConfigCache;
import com.adobe.aemfd.watchfolder.config.WatchFolderConfiguration;
import com.adobe.aemfd.watchfolder.job.GUIDGenerator;
import com.adobe.aemfd.watchfolder.service.ServiceCallback;
import com.adobe.aemfd.watchfolder.service.ServiceInvoker;
import com.adobe.aemfd.watchfolder.spi.ActivationCallback;
import com.adobe.aemfd.watchfolder.spi.InputProcessor;
import com.adobe.aemfd.watchfolder.util.DocUtil;
import com.adobe.aemfd.watchfolder.util.JcrUtil;
import com.adobe.aemfd.watchfolder.util.LogUtil;
import com.adobe.aemfd.watchfolder.util.SessionUtil;
import com.adobe.aemfd.watchfolder.util.TopologyHelper;
import com.adobe.aemfd.watchfolder.workflow.VariableInfo;
import com.adobe.aemfd.watchfolder.workflow.WorkflowConfigurationHandler;
import com.adobe.aemfd.watchfolder.workflow.WorkflowContextImpl;
import com.adobe.aemfd.watchfolder.workflow.api.WorkflowContext;
import com.adobe.aemfd.watchfolder.workflow.api.WorkflowContextProcessor;
import com.adobe.aemfd.watchfolder.workflow.api.WorkflowContextService;
import com.adobe.aemfd.watchfolder.workflow.api.payload.PayloadMapper;
import com.adobe.aemfd.watchfolder.workflow.api.payload.WorkflowExecutionContext;
import com.adobe.aemfd.watchfolder.workflow.api.payload.WorkflowInitializationContext;
import com.adobe.aemfd.watchfolder.workflow.api.payload.WorkflowVariable;
import com.adobe.granite.workflow.WorkflowSession;
import com.adobe.granite.workflow.event.WorkflowEvent;
import com.adobe.granite.workflow.exec.WorkItem;
import com.adobe.granite.workflow.exec.Workflow;
import com.adobe.granite.workflow.exec.WorkflowData;
import com.adobe.granite.workflow.metadata.MetaDataMap;
import com.adobe.granite.workflow.model.WorkflowModel;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.jcr.Binary;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Session;
import javax.jcr.ValueFactory;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.ResourceResolver;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/*
 * This class specifies class file version 49.0 but uses Java 6 signatures.  Assumed Java 6.
 */
@Component(immediate=1)
@Service(value={WorkflowLauncherHandler.class, WorkflowContextService.class})
public class WorkflowLauncherHandler
implements ActivationCallback,
InputProcessor,
WorkflowContextService {
    private static final Logger logger = LoggerFactory.getLogger(WorkflowLauncherHandler.class);
    private static final String PAYLOAD_TYPE_JCR_PATH = "JCR_PATH";
    private static final String WORKFLOW_METADATA_PREFIX = "com.adobe.aemfd.watchfolder.";
    private static final String WORKFLOW_METADATA_IS_WF_WORKFLOW = "com.adobe.aemfd.watchfolder.isWatchFolderWorkflow";
    private static final String WORKFLOW_METADATA_TRIGGERING_SERVER = "com.adobe.aemfd.watchfolder.triggeringServerId";
    private static final String WORKFLOW_METADATA_SOURCE_FILE = "com.adobe.aemfd.watchfolder.sourceFileOrDir";
    private static final String WORKFLOW_METADATA_WATCH_FOLDER = "com.adobe.aemfd.watchfolder.watchFolderId";
    private static final String STAGING_SUB_DIR = "staging";
    @Reference
    private TopologyHelper topologyHelper;
    @Reference
    private WatchFolderConfigCache watchFolderConfigCache;
    @Reference
    private WorkflowConfigurationHandler workflowConfigurationHandler;
    @Reference
    private SessionUtil sessionUtil;
    private BundleContext bundleContext;

    private String getStagingRoot() {
        return "/etc/fd/watchfolder/staging";
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void createStagingRootIfRequired() throws Exception {
        Session s = this.sessionUtil.getServiceSession(null);
        try {
            JcrUtil.makeSubDirIfRequired(s, "staging", "sling:Folder");
        }
        finally {
            s.logout();
        }
    }

    @Activate
    public void activate(BundleContext bundleContext) throws Exception {
        this.bundleContext = bundleContext;
        this.createStagingRootIfRequired();
    }

    @Deactivate
    public void deactivate() {
        this.bundleContext = null;
    }

    private ResourceResolver getResourceResolver(WatchFolderConfiguration config) throws Exception {
        return this.sessionUtil.getServiceResolver(null);
    }

    private boolean createStagingFolder(String wfId, ResourceResolver rr) throws Exception {
        Session s = (Session)rr.adaptTo(Session.class);
        Node stagingRoot = s.getNode(this.getStagingRoot());
        if (!stagingRoot.hasNode(wfId)) {
            stagingRoot.addNode(wfId, "nt:folder");
            s.save();
            logger.info("Created staging folder for watch-folder " + wfId);
            return true;
        }
        logger.warn("Unexpected: Staging folder already exists for watch-folder " + wfId);
        return false;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    boolean createStagingFolderAndLauncher(String wfId) throws Exception {
        ResourceResolver rr = this.getResourceResolver(null);
        try {
            boolean bl = this.createStagingFolder(wfId, rr);
            return bl;
        }
        finally {
            rr.close();
        }
    }

    @Override
    public void onLocalConfigNodeAdd(String watchFolderId, Node configNode) throws Exception {
        this.createStagingFolderAndLauncher(watchFolderId);
    }

    private boolean deleteStagingFolder(String wfId, ResourceResolver rr) throws Exception {
        String stagingFolder;
        Session s = (Session)rr.adaptTo(Session.class);
        if (s.nodeExists(stagingFolder = this.getStagingRoot() + "/" + wfId)) {
            long pendingPayloadCount = s.getNode(stagingFolder).getNodes().getSize();
            if (pendingPayloadCount > 0) {
                IllegalStateException ise = new IllegalStateException("" + pendingPayloadCount + " jobs still pending processing!");
                logger.error("SEVERE: Watch-folder removed while jobs are still pending processing. Pending jobs will not be processed properly! Do not remove watch-folders until processing for all files has completed.", (Throwable)ise);
            }
            s.removeItem(stagingFolder);
            s.save();
            logger.info("Deleted staging folder for watch-folder " + wfId);
            return true;
        }
        logger.warn("Unexpected: Staging folder does not exist for watch-folder " + wfId);
        return false;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    boolean tearDown(String wfId) throws Exception {
        ResourceResolver rr = this.getResourceResolver(null);
        try {
            boolean bl = this.deleteStagingFolder(wfId, rr);
            return bl;
        }
        finally {
            rr.close();
        }
    }

    @Override
    public void onLocalConfigNodeDelete(Session session, String watchFolderId) throws Exception {
        this.tearDown(watchFolderId);
    }

    private Collection<WorkflowVariable> getVariableDefs(WatchFolderConfiguration config) throws Exception {
        Map<String, VariableInfo> vars = this.workflowConfigurationHandler.getVariableDefinitions(config);
        HashSet<WorkflowVariable> result = new HashSet<WorkflowVariable>();
        result.addAll(vars.values());
        return result;
    }

    <S> S executeWithPayloadMapper(WatchFolderConfiguration config, ServiceCallback<PayloadMapper, S> callback) throws Exception {
        String defaultFilter = "(service.pid=com.adobe.aemfd.watchfolder.workflow.DefaultPayloadMapper)";
        String filter = config.getPayloadMapperFilter();
        if (filter == null || filter.trim().length() == 0) {
            filter = defaultFilter;
        }
        ServiceInvoker si = new ServiceInvoker();
        return si.lookupAndInvoke(this.bundleContext, PayloadMapper.class, filter, callback);
    }

    String triggerWorkflow(String jobId, final WatchFolderConfiguration config, File source, final Map<String, File> inputs) throws Exception {
        String localId = this.topologyHelper.getLocalInstanceId();
        String stagingFolder = this.getStagingRoot() + "/" + config.getId();
        final String payloadName = GUIDGenerator.generate('P');
        logger.warn("Triggering workflow with payload " + stagingFolder + "/" + payloadName + " on local server " + localId + " for watch folder " + config.getId() + " (inputFiles = " + inputs.keySet() + ")");
        ResourceResolver rr = this.getResourceResolver(config);
        try {
            WorkflowSession ws = (WorkflowSession)rr.adaptTo(WorkflowSession.class);
            final WorkflowModel wm = ws.getModel(config.getInputProcessorId());
            if (wm == null) {
                throw new Exception("No workflow model found with ID " + config.getInputProcessorId());
            }
            final Session s = (Session)rr.adaptTo(Session.class);
            final Node sfn = s.getNode(stagingFolder);
            Node payload = (Node)this.executeWithPayloadMapper(config, new ServiceCallback<PayloadMapper, Node>(){

                /*
                 * WARNING - Removed try catching itself - possible behaviour change.
                 */
                @Override
                public Node execute(PayloadMapper pm) throws Exception {
                    Node payloadNode;
                    ArrayList<FileInputStream> toClose = new ArrayList<FileInputStream>(inputs.size());
                    try {
                        HashMap<String, Binary> bins = new HashMap<String, Binary>(inputs.size());
                        for (Map.Entry inp : inputs.entrySet()) {
                            FileInputStream is = new FileInputStream((File)inp.getValue());
                            toClose.add(is);
                            Binary bin = s.getValueFactory().createBinary((InputStream)is);
                            bins.put((String)inp.getKey(), bin);
                        }
                        Collection varDefs = WorkflowLauncherHandler.this.getVariableDefs(config);
                        WorkflowContextImpl ctxt = new WorkflowContextImpl();
                        ctxt.workflowModel = wm;
                        ctxt.watchFolderId = config.getId();
                        ctxt.configParameters = config.getParams();
                        payloadNode = pm.createPayload(ctxt, sfn, payloadName, bins, varDefs);
                        String realPayloadPath = payloadNode.getPath();
                        if (!payloadNode.getParent().getPath().equals(sfn.getPath())) {
                            WorkflowLauncherHandler.this.cleanup(payloadNode, config);
                            throw new IllegalStateException("Payload-mapper " + pm + " failed to enforce contract of creating payload-node" + " as a child of staging folder " + sfn.getPath() + ". Actual payload-node path is " + realPayloadPath + ". Aborting processing for current inputs...");
                        }
                        s.save();
                    }
                    finally {
                        for (InputStream is : toClose) {
                            try {
                                is.close();
                            }
                            catch (Exception e) {
                                logger.error("Exception in closing the InputStream", (Throwable)e);
                            }
                        }
                    }
                    return payloadNode;
                }
            });
            try {
                WorkflowData wd = ws.newWorkflowData("JCR_PATH", (Object)payload.getPath());
                HashMap<String, Object> md = new HashMap<String, Object>();
                md.put("com.adobe.aemfd.watchfolder.isWatchFolderWorkflow", Boolean.TRUE);
                md.put("com.adobe.aemfd.watchfolder.sourceFileOrDir", source.getAbsolutePath());
                md.put("com.adobe.aemfd.watchfolder.triggeringServerId", localId);
                md.put("com.adobe.aemfd.watchfolder.watchFolderId", config.getId());
                if (jobId != null) {
                    md.put("com.adobe.aemfd.watchfolder.jobId", jobId);
                }
                Workflow w = ws.startWorkflow(wm, wd, md);
                logger.info(LogUtil.toJSON(jobId != null ? "START_WORKFLOW_SUCCESS" : "START_WORKFLOW_SUCCESS_SINGLETON", source.getAbsolutePath(), jobId, w.getId()));
                String string = w.getId();
                return string;
            }
            catch (Exception e) {
                logger.warn("Error launching workflow!", (Throwable)e);
                this.cleanup(payload, config);
                throw e;
            }
        }
        finally {
            rr.close();
        }
    }

    @Override
    public boolean isSynch() {
        return false;
    }

    @Override
    public Object processInputs(String jobId, WatchFolderConfiguration config, File source, Map<String, File> inputs) throws Exception {
        return this.triggerWorkflow(jobId, config, source, inputs);
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public void cleanup(Node payload, WatchFolderConfiguration config) throws Exception {
        if (payload == null) {
            return;
        }
        String payloadPath = null;
        try {
            payloadPath = payload.getPath();
            Session s = payload.getSession();
            payload.remove();
            s.save();
        }
        catch (Exception e) {
            if (payloadPath == null) {
                throw e;
            }
            logger.warn("Encountered error '" + e.getMessage() + "' while trying to delete payload with path " + payloadPath + ", attempting again with fresh session.");
            ResourceResolver rr = this.getResourceResolver(config);
            try {
                Session s = (Session)rr.adaptTo(Session.class);
                s.removeItem(payloadPath);
                s.save();
            }
            finally {
                rr.close();
            }
        }
    }

    public boolean sniffWorkflowEvent(WorkflowEvent we) {
        String payloadPath = null;
        if (we != null) {
            Object pl = we.getProperty("payloadPath");
            String string = payloadPath = pl instanceof String ? (String)pl : null;
        }
        if (payloadPath != null && !payloadPath.startsWith(this.getStagingRoot())) {
            logger.warn("WF.shouldProcess(): workflow event has payload " + payloadPath + " which is not of interest to us...");
            return false;
        }
        return true;
    }

    public boolean shouldProcess(Workflow w, String eventType) throws Exception {
        WorkflowData wd;
        if (w == null) {
            logger.warn("WF.shouldProcess(): No workflow to process!");
            return false;
        }
        MetaDataMap mdm = w.getMetaDataMap();
        LinkedHashMap<String, String> wfi = new LinkedHashMap<String, String>();
        WorkflowModel wm = w.getWorkflowModel();
        wfi.put("eventType", eventType);
        if (wm != null) {
            wfi.put("type", wm.getId());
        }
        if ((wd = w.getWorkflowData()) != null && "JCR_PATH".equals(wd.getPayloadType())) {
            wfi.put("payload", (String)wd.getPayload());
        }
        wfi.put("id", w.getId());
        String info = wfi.toString();
        if (mdm != null) {
            Boolean isWfWorkflow = (Boolean)mdm.get("com.adobe.aemfd.watchfolder.isWatchFolderWorkflow", Boolean.class);
            if (isWfWorkflow != null && isWfWorkflow.booleanValue()) {
                String startingServerId;
                String localId = this.topologyHelper.getLocalInstanceId();
                if (localId.equals(startingServerId = (String)mdm.get("com.adobe.aemfd.watchfolder.triggeringServerId", String.class))) {
                    logger.warn("WF.shouldProcess(): Workflow " + info + " should be processed...");
                    return true;
                }
                logger.warn("WF.shouldProcess(): Workflow " + info + " was started by another server " + startingServerId + " (localId = " + localId + "), should not be processed...");
                logger.info(LogUtil.toJSON("WORKFLOW_COMPLETE_OTHER_SERVER", (String)mdm.get("com.adobe.aemfd.watchfolder.sourceFileOrDir", String.class), (String)mdm.get("com.adobe.aemfd.watchfolder.jobId", String.class), w.getId(), "type=" + eventType));
                return false;
            }
            logger.warn("WF.shouldProcess(): Workflow " + info + " is not a watch-folder workflow, should not be processed...");
            return false;
        }
        logger.warn("WF.shouldProcess(): Workflow " + info + " has no metadata, should not be processed...");
        return false;
    }

    public File getSourceFileOrDir(Workflow w) throws Exception {
        return new File((String)w.getMetaDataMap().get("com.adobe.aemfd.watchfolder.sourceFileOrDir", String.class));
    }

    public String getWatchFolderId(Workflow w) throws Exception {
        return (String)w.getMetaDataMap().get("com.adobe.aemfd.watchfolder.watchFolderId", String.class);
    }

    public Node getPayload(Workflow w, ResourceResolver rr) throws Exception {
        String payloadPath = (String)w.getWorkflowData().getPayload();
        Session s = (Session)rr.adaptTo(Session.class);
        return s.getNode(payloadPath);
    }

    private WorkflowContextImpl openContext(WorkItem workItem, WorkflowSession workflowSession, Map args) throws Exception {
        final WorkflowContextImpl result = new WorkflowContextImpl();
        String wfId = this.getWatchFolderId(workItem.getWorkflow());
        WatchFolderConfiguration config = this.watchFolderConfigCache.getConfiguration(wfId);
        final ResourceResolver rr = (ResourceResolver)workflowSession.adaptTo(ResourceResolver.class);
        final Node payload = this.getPayload(workItem.getWorkflow(), rr);
        result.watchFolderId = wfId;
        result.configParameters = this.watchFolderConfigCache.getConfiguration(wfId).getParams();
        result.workItem = workItem;
        result.workflowSession = workflowSession;
        result.args = args;
        this.executeWithPayloadMapper(config, new ServiceCallback<PayloadMapper, Object>(){

            @Override
            public Object execute(PayloadMapper pm) throws Exception {
                result.inputMap = pm.getInputs(result, result, payload, rr);
                result.committedResults = pm.getIntermediateOutputs(result, result, payload, rr);
                result.committedVariables = pm.getVariables(result, result, payload);
                return null;
            }
        });
        return result;
    }

    private void writeVariables(Node payloadNode, WorkflowContextImpl ctxt, WatchFolderConfiguration config, PayloadMapper pm) throws Exception {
        for (Map.Entry<String, Object> me : ctxt.variableMap.entrySet()) {
            String varName = me.getKey();
            VariableInfo vi = this.workflowConfigurationHandler.getVariableDefinition(config, varName);
            pm.setVariable(ctxt, ctxt, payloadNode, new VariableInfo(vi, me.getValue()));
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void writeOutputsAndVariables(final WorkflowContextImpl ctxt) throws Exception {
        final ResourceResolver rr = (ResourceResolver)ctxt.workflowSession.adaptTo(ResourceResolver.class);
        final WatchFolderConfiguration config = this.watchFolderConfigCache.getConfiguration(ctxt.watchFolderId);
        final Node payload = this.getPayload(ctxt.workItem.getWorkflow(), rr);
        final ArrayList toClose = new ArrayList(ctxt.resultMap.size());
        try {
            this.executeWithPayloadMapper(config, new ServiceCallback<PayloadMapper, Object>(){

                @Override
                public Object execute(PayloadMapper pm) throws Exception {
                    for (Map.Entry de : ctxt.resultMap.entrySet()) {
                        int outMode;
                        Object key = de.getKey();
                        Object value = de.getValue();
                        if (!(key instanceof String) || value != null && !(value instanceof Document)) {
                            logger.warn("Unexpected key-value pair (" + key + ", " + value + ") in result-map, skipping this entry...");
                            continue;
                        }
                        String fileName = (String)key;
                        Document contents = (Document)value;
                        if (ctxt.committedResults.containsKey(fileName) && contents == null) {
                            logger.info("Deleting output " + fileName);
                            pm.setOutput(ctxt, ctxt, payload, fileName, null, 3);
                            continue;
                        }
                        if (ctxt.committedResults.containsKey(fileName)) {
                            logger.info("Updating output " + fileName);
                            outMode = 2;
                        } else {
                            logger.info("Adding output " + fileName);
                            outMode = 1;
                        }
                        InputStream is = contents.getInputStream();
                        toClose.add(is);
                        Session s = (Session)rr.adaptTo(Session.class);
                        Binary bin = s.getValueFactory().createBinary(is);
                        pm.setOutput(ctxt, ctxt, payload, fileName, bin, outMode);
                    }
                    WorkflowLauncherHandler.this.writeVariables(payload, ctxt, config, pm);
                    return null;
                }
            });
            ((Session)ctxt.workflowSession.adaptTo(Session.class)).save();
        }
        finally {
            for (InputStream is : toClose) {
                try {
                    is.close();
                }
                catch (Exception e) {
                    logger.error("Exception in closing the InputStream", (Throwable)e);
                }
            }
        }
    }

    private void performThrow(Object error, String wfId) throws Exception {
        if (error instanceof Exception) {
            throw (Exception)error;
        }
        if (error instanceof Throwable) {
            throw new Exception((Throwable)error);
        }
        throw new Exception("Workflow execution for processing files in watch-folder " + wfId + " failed with error " + error);
    }

    private void revertPayload(WorkflowContextImpl ctxt) throws Exception {
        ResourceResolver rr = (ResourceResolver)ctxt.workflowSession.adaptTo(ResourceResolver.class);
        Node payload = this.getPayload(ctxt.workItem.getWorkflow(), rr);
        payload.refresh(false);
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void finish(WorkflowContextImpl ctxt, boolean success, Object error) throws Exception {
        block6 : {
            try {
                if (success) {
                    try {
                        this.writeOutputsAndVariables(ctxt);
                        break block6;
                    }
                    catch (Exception e) {
                        this.revertPayload(ctxt);
                        throw e;
                    }
                }
                this.performThrow(error, ctxt.watchFolderId);
            }
            finally {
                Map<String, Document> toDispose = DocUtil.pruneForDisposal(ctxt.inputMap, ctxt.resultMap);
                DocUtil.disposeAll(toDispose);
                toDispose = DocUtil.pruneForDisposal(ctxt.committedResults, ctxt.resultMap);
                DocUtil.disposeAll(toDispose);
                DocUtil.disposeAll(ctxt.resultMap);
                ctxt.clear();
            }
        }
    }

    @Override
    public void execute(WorkflowContextProcessor processor, WorkItem workItem, WorkflowSession workflowSession, Map args) throws Exception {
        WorkflowContextImpl ctxt = this.openContext(workItem, workflowSession, args);
        String wfId = ctxt.watchFolderId;
        boolean processorSucceeded = false;
        try {
            processor.processWorkflowContext(ctxt);
            processorSucceeded = true;
            this.finish(ctxt, true, null);
        }
        catch (Throwable e) {
            if (!processorSucceeded) {
                this.finish(ctxt, false, e);
            }
            this.performThrow(e, wfId);
        }
    }

    protected void bindTopologyHelper(TopologyHelper topologyHelper) {
        this.topologyHelper = topologyHelper;
    }

    protected void unbindTopologyHelper(TopologyHelper topologyHelper) {
        if (this.topologyHelper == topologyHelper) {
            this.topologyHelper = null;
        }
    }

    protected void bindWatchFolderConfigCache(WatchFolderConfigCache watchFolderConfigCache) {
        this.watchFolderConfigCache = watchFolderConfigCache;
    }

    protected void unbindWatchFolderConfigCache(WatchFolderConfigCache watchFolderConfigCache) {
        if (this.watchFolderConfigCache == watchFolderConfigCache) {
            this.watchFolderConfigCache = null;
        }
    }

    protected void bindWorkflowConfigurationHandler(WorkflowConfigurationHandler workflowConfigurationHandler) {
        this.workflowConfigurationHandler = workflowConfigurationHandler;
    }

    protected void unbindWorkflowConfigurationHandler(WorkflowConfigurationHandler workflowConfigurationHandler) {
        if (this.workflowConfigurationHandler == workflowConfigurationHandler) {
            this.workflowConfigurationHandler = null;
        }
    }

    protected void bindSessionUtil(SessionUtil sessionUtil) {
        this.sessionUtil = sessionUtil;
    }

    protected void unbindSessionUtil(SessionUtil sessionUtil) {
        if (this.sessionUtil == sessionUtil) {
            this.sessionUtil = null;
        }
    }

}