/* (non-Javadoc)
@see nz.co.senanque.workflow.WorkflowManager#execute(nz.co.senanque.workflow.instances.ProcessInstance)
320736
@Transactional
	public void execute(ProcessInstance processInstance) {
		HashIdLogger.log(this,"execute");
		TaskBase task = getCurrentTask(processInstance);
		if (processInstance.getStatus() == TaskStatus.DONE) {
			return;
		}
		while (true) {
			log.debug("processInstanceId={} processName={} taskId={} status={}",processInstance.getId(),task.getOwnerProcess().getName(),task.getTaskId(), processInstance.getStatus());
			boolean b = true;
			Audit audit = createAudit(processInstance, task);
			try {
				if (processInstance.getStatus()==TaskStatus.ABORTING)
				{
					// Someone (external) set our status to ABORTING.
					// Don't attempt to execute the current instruction just throw an abort error.
					throw new AbortException(processInstance.getComment());
				}
				if (processInstance.getStatus()==TaskStatus.TIMEOUT)
				{
					// Just throw an exception and the exception handler looks after it.
					throw new TimeoutException();
				}
				if (processInstance.getStatus()==TaskStatus.GO)
				{
					if (task instanceof TaskEnd) {
						throw new WorkflowException("Trying to restart an end task, should never happen "+task.toString());
					}
					log.debug("moving on from "+task.toString());
					// simple search for the task after this one.
					task = task.getNextTask(processInstance);
					if (task == null) {
						// There is no task, this should never happen
						throw new WorkflowException("Failed to find a next task");
					}
					// Not the end of the process, so ensure the next task is pending.
					audit.setTaskId(task.getTaskId());
					audit.setProcessDefinitionName(task.getOwnerProcess().getName());
					audit.setComment(trimComment(task.toString()));
					audit.setHandler(task.getHandler());
					task.loadTask(processInstance);
				}
				audit.setStatus(TaskStatus.PENDING);
				ProcessInstanceUtils.clearQueue(processInstance, TaskStatus.PENDING);
				b = task.execute(processInstance);
			} catch (ContinueException e) {
				task = getCurrentTask(processInstance);
				continue;
			} catch (RetryException e) {
				task = getCurrentTask(processInstance);
				continue;
			} catch (ErrorException e) {
				audit.setStatus(TaskStatus.ERROR);
				if (!handleError(processInstance)) {
					// no appropriate handler, fall back to abort handler
					audit.setStatus(TaskStatus.ERROR);
					audit.setInterrupted(true);
					if (!handleAbort(processInstance)) {
						// Still no handler so we are screwed
						// Setting this status in the process 
						// instance will stop it
						processInstance.setStatus(TaskStatus.ABORTED);
					}
				} else {
					task = getCurrentTask(processInstance);
					continue;
				}
			} catch (AbortException e) {
				audit.setInterrupted(true);
				audit.setStatus(TaskStatus.ABORTED);
				audit.setComment(e.getMessage());
				if (!handleAbort(processInstance)) {
					// No handler found so just force an abort
					// Setting this status in the process instance will stop it
					processInstance.setStatus(TaskStatus.ABORTED);
					tickleParentProcess(processInstance,TaskStatus.ABORTED); // this should abort the sibling processes as well as the parent.
					break;
				} else {
					task = getCurrentTask(processInstance);
					continue;
				}
			} catch (TimeoutException e) {
				processInstance.getAudits().remove(audit);
				if (!handleTimeout(processInstance, audit)) {
					// No handler found so just force an abort
					// Setting this status in the process instance will stop it
					processInstance.setStatus(TaskStatus.ABORTED);
					tickleParentProcess(processInstance,processInstance.getStatus());
					break;
				} else {
					task = getCurrentTask(processInstance);
					continue;
				}
			}
			if (!b) {
				// task was not completed, exit the loop
				processInstance.setStatus(TaskStatus.WAIT);
				audit.setStatus(TaskStatus.WAIT);
				break;
			} else {
				if (task instanceof TaskEnd) {
					endOfProcessDetected(processInstance,audit);
					break;
				} else if (task instanceof TaskTry) {
					task = ((TaskTry)task).getFirstTask();
				} else if (task instanceof TaskIf) {
					task = ((TaskIf)task).getConditionalTask(processInstance);
				} else {
					task = getCurrentTask(processInstance).getNextTask(processInstance);
				}
				if (task == null) {
					throw new WorkflowException("Trying to step to a task when there is none");
				}
				// Not the end of the process, so ensure the next task is pending.
				task.loadTask(processInstance);
			}
		}
	}
12499
private <T> T execute(Operation<T> operation) throws Exception {
    return execute(operation, null);
  }
1359148
@Override
    public void execute() throws UpdateExecutionException {
        try {
            sync();
            getMarkLogicClient().sendUpdateQuery(getQueryString(), getBindings(), getIncludeInferred(), getBaseURI());
        }catch(ForbiddenUserException | FailedRequestException e){
            throw new UpdateExecutionException(e);
        } catch (RepositoryException e) {
            throw new UpdateExecutionException(e);
        } catch (MalformedQueryException e) {
            throw new UpdateExecutionException(e);
        } catch (IOException e) {
            throw new UpdateExecutionException(e);
        }
    }
695012
@Override
    public void execute()
            throws MojoExecutionException, MojoFailureException
    {

        // ---
        // Check configuration and get all configured jar resources
        // ---

        checkConfiguration();

        // ---
        // Prepare working directory layout
        // ---

        IOUtil ioUtil = getIoUtil();

        ioUtil.makeDirectoryIfNecessary( getWorkDirectory() );
        ioUtil.copyResources( getResourcesDirectory(), getWorkDirectory() );

        // ---
        // Resolve common jar resources
        // ---

        getLog().info( "-- Prepare commons jar resources" );
        Set<ResolvedJarResource> resolvedCommonJarResources;

        if ( CollectionUtils.isEmpty( commonJarResources ) )
        {
            resolvedCommonJarResources = Collections.emptySet();
        }
        else
        {
            resolvedCommonJarResources = resolveJarResources( commonJarResources, null );
        }

        Set<ResolvedJarResource> allResolvedJarResources = new LinkedHashSet<>();
        allResolvedJarResources.addAll( resolvedCommonJarResources );

        // ---
        // Resolved jnlpFiles
        // ---

        getLog().info( "-- Prepare jnlp files" );
        Set<ResolvedJnlpFile> resolvedJnlpFiles = new LinkedHashSet<>();

        for ( JnlpFile jnlpFile : jnlpFiles )
        {
            verboseLog( "prepare jnlp " + jnlpFile );

            // resolve jar resources of the jnpl file
            Set<ResolvedJarResource> resolvedJarResources =
                    resolveJarResources( jnlpFile.getJarResources(), resolvedCommonJarResources );

            // keep them (to generate the versions.xml file)
            allResolvedJarResources.addAll( resolvedJarResources );

            // create the resolved jnlp file
            ResolvedJnlpFile resolvedJnlpFile = new ResolvedJnlpFile( jnlpFile, resolvedJarResources );
            resolvedJnlpFiles.add( resolvedJnlpFile );
        }

        // ---
        // Process collected jars
        // ---

        signOrRenameJars();

        // ---
        // Generate jnlp files
        // ---

        for ( ResolvedJnlpFile jnlpFile : resolvedJnlpFiles )
        {
            generateJnlpFile( jnlpFile, getLibPath() );
        }

        // ---
        // Generate version xml file
        // ---

        generateVersionXml( allResolvedJarResources );

        // ---
        // Copy to final directory
        // ---

        //FIXME Should be able to configure this
        File outputDir = new File( getProject().getBuild().getDirectory(),
                                   getProject().getBuild().getFinalName() + File.separator + outputDirectoryName );

        ioUtil.copyDirectoryStructure( getWorkDirectory(), outputDir );
    }
1109051
@Override
    public boolean execute() throws SQLException
    {
        checkClosed();
        boolean result = this.execute(this.Query.getExecutableQuery(this.parameters));
        this.parameters = this.Query.getParameterArray();
        return result;
    }
483691
@Override
    public WarpResult execute(Activity activity, WarpContext warpContext) {
        try {
            setupServerInspection();
            executeActivity(activity);
            awaitServerExecution(warpContext);
            checkActivityFailure();

            return warpContext.getResult();
        } finally {
            cleanup();
        }
    }
202374
@Override
    public void execute() {
        if ((str == null || str.isEmpty()) && !FindContext.isAvailable()) {
            try {
                str = editor.readLine("Find previous:");
                editor.findPrevious(str);
                FindContext.setLastSearch(str);
            } catch (IOException e) {
                //noop
            }
        } else if (FindContext.isAvailable()) {
            editor.findPrevious(FindContext.getLastSearch());
        } else {
            editor.findPrevious(str);
            FindContext.setLastSearch(str);
        }
    }
197342
public void execute() {

    while (!steps.isEmpty()) {
      currentStep = steps.remove(0);

      try {
        LOG.debugPerformOperationStep(currentStep.getName());

        currentStep.performOperationStep(this);
        successfulSteps.add(currentStep);

        LOG.debugSuccessfullyPerformedOperationStep(currentStep.getName());
      }
      catch (Exception e) {

        if(isRollbackOnFailure) {

          try {
            rollbackOperation();
          }
          catch(Exception e2) {
            LOG.exceptionWhileRollingBackOperation(e2);
          }
          // re-throw the original exception
          throw LOG.exceptionWhilePerformingOperationStep(name, currentStep.getName(), e);
        }

        else {
          LOG.exceptionWhilePerformingOperationStep(currentStep.getName(), e);
        }

      }
    }

  }
699280
@Override
  public boolean execute(HttpRequestBase request) {
    DataSenderThread senderThread = new DataSenderThread(HTTP_CLIENT_INSTANCE, request);
    senderThread.run();
    return true;
  }
459648
@AroundInvoke
    public Object execute(InvocationContext context) throws Exception {
        String methodName = "execute";

        String classOperationName = OpenTracingService.getClassOperationName(context.getMethod());
        String methodOperationName = OpenTracingService.getMethodOperationName(context.getMethod());

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, methodName + " operation names", classOperationName, methodOperationName);
        }

        boolean process = true;

        if (!OpenTracingService.isTraced(classOperationName, methodOperationName)) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, methodName + " skipping untraced method");
            }
            process = false;
        }

        if (process && isHandledByFilter(context.getMethod())) {
            // This is already processed as part of the OpentracingContainerFilter
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, methodName + " skipping JAXRS method");
            }
            process = false;
        }

        if (process) {

            String operationName;

            if (OpenTracingService.hasExplicitOperationName(methodOperationName)) {
                operationName = methodOperationName;
            } else {
                // If the annotated method is not a JAX-RS endpoint, the default
                // operation name of the new Span for the method is:
                // <package name>.<class name>.<method name> [...]
                // If operationName is specified on a class, that operationName will be used
                // for all methods of the class unless a method explicitly overrides it with
                // its own operationName."
                // https://github.com/eclipse/microprofile-opentracing/blob/master/spec/src/main/asciidoc/microprofile-opentracing.asciidoc#321-the-traced-annotation
                if (OpenTracingService.hasExplicitOperationName(classOperationName)) {
                    operationName = classOperationName;
                } else {
                    operationName = context.getMethod().getDeclaringClass().getName() + "." + context.getMethod().getName();
                }

                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, methodName + " setting default operationName", operationName);
                }
            }

            Tracer tracer = OpentracingTracerManager.getTracer();

            try (Scope scope = tracer.buildSpan(operationName).startActive(true)) {
                try {
                    Object result = context.proceed();
                    return result;
                } catch (Exception e) {
                    OpentracingService.addSpanErrorInfo(scope.span(), e);
                    throw e;
                } catch (Error e) {
                    OpentracingService.addSpanErrorInfo(scope.span(), e);
                    throw e;
                }
            }
        } else {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, methodName + " normal processing");
            }
            return context.proceed();
        }
    }
1283561
@Override
    public void execute() throws TaskExecutionFailedException {
        String account = bitTask.getAccount();
        String storeId = bitTask.getStoreId();
        String spaceId = bitTask.getSpaceId();
        log.info("starting space comparison where account={} storeId={} spaceId={}",
                 account,
                 storeId,
                 spaceId);

        File spaceListing = null;
        try {

            //write out space listing to file, counting all the items in the process.
            spaceListing = File.createTempFile("spaces", ".txt");
            int count = 0;
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(spaceListing))) {
                Iterator<String> it = store.getSpaceContents(spaceId, null);
                while (it.hasNext()) {
                    if (count > 0) {
                        writer.write("\n");
                    }
                    writer.write(it.next());
                    count++;
                }
                writer.close();
            }

            //load the set of content ids
            WriteOnlyStringSet set = new WriteOnlyStringSet(count);
            try (BufferedReader reader = new BufferedReader(new FileReader(spaceListing))) {
                String contentId = null;
                while ((contentId = reader.readLine()) != null) {
                    set.add(contentId);
                }
            }

            // iterate current non-deleted manifest items
            Iterator<ManifestItem> manifestIterator =
                this.manifestStore.getItems(account, storeId, spaceId, false);

            while (manifestIterator.hasNext()) {
                // if not in storage provider
                ManifestItem item = manifestIterator.next();

                String contentId = item.getContentId();
                if (set.contains(contentId)) {
                    // reset missingInStorageProvider flag to false if true.
                    if (item.isMissingFromStorageProvider()) {
                        manifestStore.updateMissingFromStorageProviderFlag(account,
                                                                           storeId,
                                                                           spaceId,
                                                                           contentId,
                                                                           false);
                    }
                } else {
                    log.debug("no content found in storage provider for manifest item: {}", item);
                    if (!item.isDeleted()) {
                        // is missingInStorageProvider flag true?
                        if (item.isMissingFromStorageProvider()) {
                            this.bitLogStore
                                .write(account,
                                       storeId,
                                       spaceId,
                                       contentId,
                                       new Date(),
                                       storageProviderType,
                                       BitIntegrityResult.ERROR,
                                       null,
                                       null,
                                       item.getContentChecksum(),
                                       "Content item is in the manifest "
                                       + "but not in the storage provider in "
                                       + "the course of the last two bit integrity runs.");

                        } else {
                            manifestStore
                                .updateMissingFromStorageProviderFlag(account,
                                                                      storeId,
                                                                      spaceId,
                                                                      contentId,
                                                                      true);
                        }
                    }

                }
            }

        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            throw new TaskExecutionFailedException("failed to complete task: "
                                                   + ex.getMessage(), ex);
        } finally {
            if (spaceListing != null && spaceListing.exists()) {
                spaceListing.delete();
            }
        }
    }
668626
@Override
  public Object execute(@Nonnull final CommandContext context) throws Exception {
    IO io = context.getIo();
    Variables variables = context.getVariables();

    // TODO: args may need special handling for ~/ as this won't translate to executable

    log.debug("Executing: {}", args);

    ProcessBuilder builder = new ProcessBuilder()
      .command(args)
      .inheritIO();

    File dir = directory;
    if (dir == null) {
      dir = variables.require(VariableNames.SHELL_USER_DIR, File.class);
    }
    log.debug("Directory: {}", dir);
    builder.directory(dir);

    if (!newenvironment) {
      log.debug("Propagating environment variables");
      builder.environment().putAll(System.getenv());
    }

    Process p = builder.start();

    PumpStreamHandler handler = new PumpStreamHandler(io.streams.out, io.streams.err);
    handler.setProcessInputStream(p.getOutputStream());
    handler.setProcessOutputStream(p.getInputStream());
    handler.setProcessErrorStream(p.getErrorStream());

    handler.start();

    log.debug("Waiting for process to exit...");

    int exitCode = p.waitFor();

    log.debug("Process exited w/code: {}", exitCode);

    handler.stop();

    return exitCode;
  }
354058
public void execute ()
        throws MojoExecutionException
    {
        if (mapFile == null) mapFile = new File(base, "compmap.txt");
        if (actionDef == null) actionDef = new File(base, "actions.xml");

        ComponentBundler bundler = new ComponentBundler(mapFile, actionDef) {
            @Override protected boolean keepRawPngs () { return keepRawPngs; }
            @Override protected boolean uncompressed () { return false; }
            @Override protected void logInfo (String message) { getLog().info(message); }
            @Override protected void logWarn (String message) { getLog().warn(message); }
        };

        if (bundleDirectories == null) {
            bundleDirectories = findBundleDirs();
        }
        for (BundleDirectory bdir : bundleDirectories) {
            getLog().info("Processing " + bdir);
            File root = new File(base, bdir.root);

            // create the scanner
            DirectoryScanner scanner = new DirectoryScanner();
            scanner.setBasedir(new File(root, bdir.path));
            scanner.setIncludes(includes.toArray(new String[0]));
            scanner.setExcludes(excludes.toArray(new String[0]));
            scanner.scan();

            File targetDir = new File(targetBase, bdir.root);
            File target = new File(new File(targetDir, bdir.path), "components.jar");
            List<Tuple<File,List<String>>> sourceDirs = Lists.newArrayList();
            sourceDirs.add(Tuple.newTuple(scanner.getBasedir(),
                                          Arrays.asList(scanner.getIncludedFiles())));
            bundler.execute(root.getPath(), target, sourceDirs);
        }
    }
663956
public void execute() throws ActivityException {
        EventWaitInstance received = registerWaitEvents(false, true);
        if (received!=null) {
            setReturnCodeAndExitStatus(received.getCompletionCode());
            processMessage(getExternalEventInstanceDetails(received.getMessageDocumentId()));
            boolean toFinish = handleCompletionCode();
            if (toFinish && exitStatus==null)
                exitStatus = WorkStatus.STATUS_COMPLETED;
        }
        else {
            try {
                // set timeouts
                int timeout = getTimeoutSeconds();
                if (timeout > 0) {
                    loginfo("set activity timeout as " + timeout + " seconds");
                    InternalEvent delayMsg = InternalEvent.createActivityDelayMessage(getActivityInstance(), getMasterRequestId());
                    getEngine().sendDelayedInternalEvent(delayMsg, timeout,
                            ScheduledEvent.INTERNAL_EVENT_PREFIX+getActivityInstanceId()+"timeout", false);
                }
            }
            catch (MdwException e) {
                throw new ActivityException(0, "Failed to set timeout", e);
            }
        }
    }
433843
@Override
    public void execute() {
        Set<String> annotated = db.getAnnotationIndex().get(Audit.class.getName());
        ScanAnnotatedFilter filter = new ScanAnnotatedFilter();
        for (String annotaionClass : annotated) {
            try {
                Class<?> clazz = Class.forName(annotaionClass);
                filter.addClass(clazz);
            } catch (ClassNotFoundException e) {
                throw new InitializationException("", e);
            }
        }
        PreConfigurationContext.addAnnotationFilter(filter);
    }
1041321
@Override
    public Object executeWithArgs(ExecutionType executionType, Object[] args) throws CommandActionExecutionException {
        if(ExecutionType.ASYNCHRONOUS == executionType){
            Closure closure = AsyncClosureFactory.getInstance().createClosure(metaHolder, method, object, args);
            return executeClj(closure.getClosureObj(), closure.getClosureMethod());
        }

        return execute(object, method, args);
    }
1068691
static AsyncResponse executeAsync(final @Nonnull ExecutorService executorService,
									  final @Nonnull String processName,
									  final @Nonnull Runnable operation) {
		return executeAsync(executorService, processName, operation, false);
	}