TODO: should this actually throw only ExecutionException?
434489
@CanIgnoreReturnValue
  @Override
  public <T> T callWithTimeout(
      Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit, boolean amInterruptible)
      throws Exception {
    checkNotNull(callable);
    checkNotNull(timeoutUnit);
    checkArgument(timeoutDuration > 0, "timeout must be positive: %s", timeoutDuration);
    Future<T> future = executor.submit(callable);
    try {
      if (amInterruptible) {
        try {
          return future.get(timeoutDuration, timeoutUnit);
        } catch (InterruptedException e) {
          future.cancel(true);
          throw e;
        }
      } else {
        return Uninterruptibles.getUninterruptibly(future, timeoutDuration, timeoutUnit);
      }
    } catch (ExecutionException e) {
      throw throwCause(e, true);
    } catch (TimeoutException e) {
      future.cancel(true);
      throw new UncheckedTimeoutException(e);
    }
  }
759278
static DatastoreException translateAndThrow(RetryHelperException ex) {
    BaseServiceException.translate(ex);
    throw new DatastoreException(UNKNOWN_CODE, ex.getMessage(), null, ex.getCause());
  }
406463
@Override
    protected void executeImpl() throws TaskExecutionFailedException {

        try {
            String account = task.getAccount();
            String storeId = task.getStoreId();
            String spaceId = task.getSpaceId();
            String contentId = task.getContentId();
            String action = task.getAction();
            Map<String, String> props = task.getContentProperties();
            String acls = task.getSpaceACLs();
            Date timestamp = new Date(Long.valueOf(task.getDateTime()));

            auditLogStore.write(account,
                                storeId,
                                spaceId,
                                contentId,
                                task.getContentChecksum(),
                                task.getContentMimetype(),
                                task.getContentSize(),
                                task.getUserId(),
                                action,
                                props != null ? AuditLogStoreUtil.serialize(props) : null,
                                acls,
                                task.getSourceSpaceId(),
                                task.getSourceContentId(),
                                timestamp);

            log.debug("audit task successfully processed: {}", task);
        } catch (TransactionSystemException e) {
            log.error("failed to write item  ( account={} storeId={} spaceId={} contentId={} timestamp={} ) " +
                      "to the database due to a transactional error. Likely cause: duplicate entry. Details: {}. " +
                      "Ignoring...",
                      task.getAccount(),
                      task.getStoreId(),
                      task.getSpaceId(),
                      task.getContentId(),
                      new Date(Long.valueOf(task.getDateTime())),
                      e.getMessage());
        } catch (Exception e) {
            String message = "Failed to execute " + task + ": " + e.getMessage();
            log.debug(message, e);
            throw new TaskExecutionFailedException(message, e);
        }
    }
1206924
@Override
    protected void executeImpl() throws TaskExecutionFailedException {
        try {
            String account = task.getAccount();
            String storeId = task.getStoreId();
            String spaceId = task.getSpaceId();
            String contentId = task.getContentId();
            String action = task.getAction();
            Date timeStamp = new Date(Long.parseLong(task.getDateTime()));

            if (ActionType.ADD_CONTENT.name().equals(action) ||
                ActionType.COPY_CONTENT.name().equals(action)) {
                String mimetype = task.getContentMimetype();
                if (mimetype == null) {
                    mimetype = "application/octet-stream";
                }

                String size = task.getContentSize();
                if (size == null) {
                    size = "0";
                }

                this.manifestStore.addUpdate(account,
                                             storeId,
                                             spaceId,
                                             contentId,
                                             task.getContentChecksum(),
                                             mimetype,
                                             size,
                                             timeStamp);
            } else if (ActionType.DELETE_CONTENT.name().equals(action)) {
                this.manifestStore.flagAsDeleted(account,
                                                 storeId,
                                                 spaceId,
                                                 contentId,
                                                 timeStamp);
            } else {
                log.debug("action {} not handled by this processor: task={}", action, task);
            }
            log.info("audit task successfully processed: {}", task);
        } catch (Exception e) {
            String message = "Failed to execute " + task + ": " + e.getMessage();
            log.debug(message, e);
            throw new TaskExecutionFailedException(message, e);
        }
    }
390579
@Override
   public void execute() throws BuildException 
   {
      if (getHome() == null)
         throw new BuildException("Home isn't set");

      try 
      {
         ProcessController pc = ProcessController.getInstance();
         int exitCode = pc.stop(getHome());

         if (exitCode != 0)
            throw new BuildException("IronJacamar instance exit code: " + exitCode);

         log("Stopped IronJacamar instance from: " + getHome());
      }
      catch (BuildException be) 
      {
         throw be;
      }
      catch (Throwable t) 
      {
         throw new BuildException(t.getMessage(), t);
      }
   }
564603
private void prepareExecutionAttempt(AsyncExecutionContextImpl<W> executionContext) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
            Tr.event(tc, "Execution {0} enqueuing new execution attempt", executionContext.getId());
        }

        AsyncAttemptContextImpl<W> attemptContext = new AsyncAttemptContextImpl<>(executionContext);

        TimeoutState timeout = FaultToleranceStateFactory.INSTANCE.createTimeoutState(executorService, timeoutPolicy, metricRecorder);
        attemptContext.setTimeoutState(timeout);

        if (!circuitBreaker.requestPermissionToExecute()) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                Tr.event(tc, "Execution {0} Circuit Breaker open, not executing", executionContext.getId());
            }

            MethodResult<W> result = MethodResult.failure(new CircuitBreakerOpenException());
            processEndOfAttempt(attemptContext, result);
            return;
        }

        attemptContext.setCircuitBreakerPermittedExecution(true);

        timeout.start();

        ExecutionReference ref = bulkhead.submit((reservation) -> runExecutionAttempt(attemptContext, reservation), getExceptionHandler(attemptContext));

        if (!ref.wasAccepted()) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                Tr.event(tc, "Execution {0} bulkhead rejected execution", executionContext.getId());
            }

            processEndOfAttempt(attemptContext, MethodResult.failure(new BulkheadException()));
            return;
        }

        timeout.setTimeoutCallback(handleExceptions(() -> timeout(attemptContext, ref), attemptContext, executionContext));

        // Update what we should do if the user cancels the execution
        executionContext.setCancelCallback((mayInterrupt) -> {
            ref.abort(mayInterrupt);
            processEndOfAttempt(attemptContext, MethodResult.failure(new CancellationException()));
        }
810830
public int[] executeBatch() throws SQLException {
        final boolean isExceptionThrown = ExecutorExceptionHandler.isExceptionThrown();
        SQLExecuteCallback<int[]> callback = new SQLExecuteCallback<int[]>(getDatabaseType(), isExceptionThrown) {
            
            @Override
            protected int[] executeSQL(final RouteUnit routeUnit, final Statement statement, final ConnectionMode connectionMode) throws SQLException {
                return statement.executeBatch();
            }
        };
        List<int[]> results = executeCallback(callback);
        if (isAccumulate()) {
            return accumulate(results);
        } else {
            return results.get(0);
        }
    }
730085
public void execute() throws BuildException
   {
      if (file == null)
         throw new BuildException("File not defined");

      if (!file.exists())
         throw new BuildException("File doesn't exists: " + file);

      try
      {
         Boolean result = null;
         if (isLocal())
         {
            Object value = executeCommand("local-undeploy", new Serializable[] {file.toURI().toURL()});

            if (value instanceof Boolean)
            {
               result = (Boolean)value;
            }
            else
            {
               throw (Throwable)value;
            }
         }
         else
         {
            Object value = executeCommand("remote-undeploy", new Serializable[] {file.getName()});

            if (value instanceof Boolean)
            {
               result = (Boolean)value;
            }
            else
            {
               throw (Throwable)value;
            }
         }

         if (result.booleanValue())
         {
            log("Undeployed: " + file.getName());
         }
         else
         {
            log(file.getName() + " wasn't undeployed");
         }
      }
      catch (Throwable t)
      {
         throw new BuildException("Unable to undeploy to " + getHost() + ":" + getPort() + " (" + t.getMessage() + ")",
                                  t);
      }
   }
1087774
private void execute() throws Exception {
		if (result == null) {
			env.execute(executionName);
		} else {
			output.write(executionName.toString(), System.out, result);
		}

		System.out.println();
		algorithm.printAnalytics(System.out);

		if (jobDetailsPath.getValue() != null) {
			writeJobDetails(env, jobDetailsPath.getValue());
		}
	}
937640
private static boolean executesAsSimpleDirective(String line) throws Exception {

        // SHOW or LIST <blah> statement
        String subcommand = SQLParser.parseShowStatementSubcommand(line);
        if (subcommand != null) {
            if (subcommand.equals("proc") || subcommand.equals("procedures")) {
                execListProcedures();
            }
            else if (subcommand.equals("functions")) {
                execListFunctions();
            }
            else if (subcommand.equals("tables")) {
                execListTables();
            }
            else if (subcommand.equals("classes")) {
                execListClasses();
            }
            else if (subcommand.equals("config") || subcommand.equals("configuration")) {
                execListConfigurations();
            }
            else {
                String errorCase = (subcommand.equals("") || subcommand.equals(";")) ?
                        ("Incomplete SHOW command.\n") :
                        ("Invalid SHOW command completion: '" + subcommand + "'.\n");
                System.out.println(errorCase +
                        "The valid SHOW command completions are proc, procedures, tables, or classes.");
            }
            // Consider it handled here, whether or not it was a good SHOW statement.
            return true;
        }

        // HELP commands - ONLY in interactive mode, close batch and parse for execution
        // Parser returns null if it isn't a HELP command. If no arguments are specified
        // the returned string will be empty.
        String helpSubcommand = SQLParser.parseHelpStatement(line);
        if (helpSubcommand != null) {
            // Ignore the arguments for now.
            if (!helpSubcommand.isEmpty()) {
                System.out.printf("Ignoring extra HELP argument(s): %s\n", helpSubcommand);
            }
            printHelp(System.out); // Print readme to the screen
            return true;
        }

        String echoArgs = SQLParser.parseEchoStatement(line);
        if (echoArgs != null) {
            System.out.println(echoArgs);
            return true;
        }

        String echoErrorArgs = SQLParser.parseEchoErrorStatement(line);
        if (echoErrorArgs != null) {
            System.err.println(echoErrorArgs);
            return true;
        }

        // DESCRIBE table
        String describeArgs = SQLParser.parseDescribeStatement(line);
        if (describeArgs != null) {

            // Check if table exists
            String tableName = "";
            String type = "";
            VoltTable tableData = m_client.callProcedure("@SystemCatalog", "TABLES").getResults()[0];
            while (tableData.advanceRow()) {
                String t = tableData.getString(2);
                if (t.equalsIgnoreCase(describeArgs)) {
                    tableName = t;
                    type = tableData.getString(3);
                    break;
                }
            }
            if (tableName.equals("")) {
                System.err.println("Table does not exist");
                return true;
            }

            // Class to temporarily store and sort column attributes
            class Column implements Comparable {
                String name;
                String type;
                long size;
                String remarks;
                long position;
                String notNull;

                @Override
                public String toString() {return "";}

                @Override
                public int compareTo(Object obj) {
                    Column col = (Column) obj;
                    return (int)(this.position - col.position);
                }
            }

            // sort the columns as they are inserted
            SortedSet set = new TreeSet();

            // Retrieve Column attributes
            VoltTable columnData = m_client.callProcedure("@SystemCatalog", "COLUMNS").getResults()[0];
            int maxNameWidth = 10;
            while (columnData.advanceRow()) {
                if (tableName.equalsIgnoreCase(columnData.getString(2))) {

                    Column c = new Column();
                    c.name = columnData.getString(3);
                    if (c.name.length() > maxNameWidth) {
                        maxNameWidth = c.name.length();
                    }

                    c.type = columnData.getString(5);

                    c.size = columnData.getLong(6);
                    if (columnData.wasNull()) {
                        if (c.type.equals("GEOGRAPHY")) {
                            c.size = 32768;
                        }
                        if (c.type.equals("GEOGRAPHY_POINT")) {
                            c.size = 16;
                        }
                    } else if (c.type.equals("TINYINT")) {
                        c.size = 1;
                    } else if (c.type.equals("SMALLINT")) {
                        c.size = 2;
                    } else if (c.type.equals("INTEGER")) {
                        c.size = 4;
                    } else if (c.type.equals("BIGINT")) {
                        c.size = 8;
                    } else if (c.type.equals("FLOAT")) {
                        c.size = 8;
                    } else if (c.type.equals("DECIMAL")) {
                        c.size = 16;
                    } else if (c.type.equals("TIMESTAMP")) {
                        c.size = 8;
                    }

                    c.remarks = columnData.getString(11);
                    if (columnData.wasNull()) {
                        c.remarks = "";
                    }

                    c.position = columnData.getLong(16);

                    String nullableYesNo = columnData.getString(17);
                    c.notNull = "";
                    if (nullableYesNo.equals("NO")) {
                        c.notNull = "NOT NULL";
                    }

                    set.add(c);
                }
            }

            // print output
            String headerFormat = "%-" + maxNameWidth + "s|%-16s|%-11s|%-9s|%-16s\n";
            String rowFormat = "%-" + maxNameWidth + "s|%-16s|%11d|%-9s|%-16s\n";
            System.out.printf(headerFormat,"COLUMN","DATATYPE","SIZE","NULLABLE","REMARKS");
            String DASHES = new String(new char[56+maxNameWidth]).replace("\0", "-");
            System.out.println(DASHES);

            Iterator it = set.iterator();
            while (it.hasNext()) {
                Column c = (Column)it.next();
                System.out.printf(rowFormat,c.name,c.type,c.size,c.notNull,c.remarks);
            }
            System.out.println(DASHES);

            // primary key
            String primaryKey = "";
            VoltTable keyData = m_client.callProcedure("@SystemCatalog", "PRIMARYKEYS").getResults()[0];
            while (keyData.advanceRow()) {
                if (tableName.equalsIgnoreCase(keyData.getString(2))) {
                    String colName = keyData.getString(3);
                    if (!primaryKey.equals("")) {
                        primaryKey += ",";
                    }
                    primaryKey += colName;
                }
            }
            if (!primaryKey.equals("")) {
                System.out.println("Type: " + type + ", Primary Key (" + primaryKey + ")");
            } else {
                System.out.println("Type: " + type);
            }
            return true;
        }

        // It wasn't a locally-interpreted directive.
        return false;
    }
631463
public void execute() throws BuildException {
    log.debug("projectname=" + getProjectName());
    log.debug("src/srcdir=" + getSrcdir());
    log.debug("destdir=" + getDestdir());
    log.debug("failOnError=" + getFailOnError());
    log.debug("checkedArithmetic=" + isCheckedArithmetic());
    log.debug("scriptExtensions=" + getScriptExtensions());
    log.debug("_compileClasspath=" + _compileClasspath);

    if(isCheckedArithmetic()) {
      System.setProperty("checkedArithmetic", "true");
    }
    
    ICompilerDriver driver = new SoutCompilerDriver();
    IGosuCompiler gosuc = new gw.lang.gosuc.simple.GosuCompiler();

    List<String> classpath = new ArrayList<>();
    classpath.addAll(Arrays.asList(_compileClasspath.list()));
    classpath.addAll( GosucUtil.getJreJars());

    String startupMsg = "Initializing Gosu compiler";
    if(!getProjectName().isEmpty()) {
      startupMsg += " for " + getProjectName();
    }
    log.info(startupMsg);
    log.debug("\tsourceFolders:" + Arrays.asList(getSrcdir().list()));
    log.debug("\tclasspath:" + classpath);
    log.debug("\toutputPath:" + getDestdir().getAbsolutePath());

    List<String> sourceRoots = Arrays.asList(getSrcdir().list());
    for (String sourceRootName : sourceRoots) {
      File sourceRoot = getProject().resolveFile(sourceRootName);
      if (!sourceRoot.exists()) {
        throw new BuildException("srcdir \"" + sourceRoot.getPath() + "\" does not exist!", getLocation());
      }
      DirectoryScanner ds = this.getDirectoryScanner(sourceRoot);
      String[] files = ds.getIncludedFiles();
      if( hasSelectors() ) { 
        // we have explicit includes/excludes criteria nested in a <src> element; no need to call scanDir
        // this is the typical use case when ant is invoked dynamically by gradle
        for( String relativeFilename : files ) {
          compileList.add( new File( sourceRoot, relativeFilename ) );
        }
      } else {
        // <src> element was not used - instead we have an explicit list of srcDir elements 
        // and optionally additionalscriptextensions specified in addition to the defaults
        scanDir(sourceRoot, _destDir != null ? _destDir : sourceRoot, files);
      }
    }
    
    gosuc.initializeGosu( sourceRoots, classpath, getDestdir().getAbsolutePath() );

    log.debug("About to compile these files:");
    for(File file : compileList) {
      log.debug("\t" + file.getAbsolutePath());
    }
    
    for(File file : compileList) {
      try {
        gosuc.compile(file, driver);
      } catch (Exception e) {
        log.error(e.getMessage());
        throw new BuildException(e);
      }
    }

    gosuc.uninitializeGosu();

    List<String> warnings = ((SoutCompilerDriver) driver).getWarnings();
    boolean errorsInCompilation = ((SoutCompilerDriver) driver).hasErrors();
    List<String> errors = ((SoutCompilerDriver) driver).getErrors();
    
    List<String> warningMessages = new ArrayList<>();
    List<String> errorMessages = new ArrayList<>();
   
    warnings.forEach(warning -> warningMessages.add("[WARNING] " + warning));
    int numWarnings = warningMessages.size();

    int numErrors = 0;
    if(errorsInCompilation) {
      errors.forEach(error -> errorMessages.add("[ERROR] " + error));
      numErrors = errorMessages.size();
    }

    boolean hasWarningsOrErrors = numWarnings > 0 || errorsInCompilation;
    StringBuilder sb;
    sb = new StringBuilder();
    sb.append(getProjectName().isEmpty() ? "Gosu compilation" : getProjectName());
    sb.append(" completed");
    if(hasWarningsOrErrors) {
      sb.append(" with ");
      if(numWarnings > 0) {
        sb.append(numWarnings).append(" warning").append(numWarnings == 1 ? "" : 's');
      }
      if(errorsInCompilation) {
        sb.append(numWarnings > 0 ? " and " : "");
        sb.append(numErrors).append(" error").append(numErrors == 1 ? "" : 's');
      }
    } else {
      sb.append(" successfully.");
    }

    if(hasWarningsOrErrors) {
      log.warn(sb.toString());
    } else {
      log.info(sb.toString());
    }

    //log at most 100 warnings or errors
    warningMessages.subList(0, Math.min(warningMessages.size(), 100)).forEach(log::info);
    errorMessages.subList(0, Math.min(errorMessages.size(), 100)).forEach(log::error);

    if(errorsInCompilation) {
      if(getFailOnError()) {
        buildError("Gosu compilation failed with errors; see compiler output for details.");
      } else {
        log.warn("Gosu Compiler: Ignoring compilation failure(s) as 'failOnError' was set to false");
      }
    }
    
  }
1009526
synchronized void error(@NotNull Exception e) {
        if (isFinished) {
            throw new RuntimeException("Promise already completed!");
        }
        if (e == null) {
            throw new RuntimeException("Error can't be null");
        }
        isFinished = true;
        exception = e;
        deliverResult();
    }
1021603
private static RuntimeException getCause(InvocationTargetException e) {
        Throwable cause = e.getCause();
        if(cause instanceof RuntimeException)
            throw (RuntimeException) cause;
        else
            throw new IllegalArgumentException(e.getCause());
    }
114754
private void doSet() throws PageException {
	if (entry == null) throw new ApplicationException("attribute entry is required for tag registry, when action is [set]");
	if (type == RegistryEntry.TYPE_ANY) type = RegistryEntry.TYPE_STRING;
	if (value == null) {
	    if (type == RegistryEntry.TYPE_DWORD) value = "0";
	    else value = "";
	}

	try {
	    RegistryQuery.setValue(branch, entry, type, value);
	}
	catch (Exception e) {
	    throw Caster.toPageException(e);
	}

    }
1234305
@SuppressWarnings("PMD.UnusedFormalParameter")
	private void executeProgram(String name, String source) throws Exception
	{
		List<Statement> _directives = executeProgram__compile(source);
		boolean _canProceed = !isAllowedOverrideRequired() || isAllowingOverride();
		if (_canProceed && !_directives.isEmpty())
		{
			executeProgram__parseDirectives(_directives);
			setAllowedOverrideRequired(true);
		}
	}
835548
@SuppressWarnings( "deprecation" )
    @Override
    public org.modeshape.jcr.api.query.QueryResult execute() throws RepositoryException {
        context.checkValid();
        final long start = System.nanoTime();
        // Create an executable query and set it on this object ...
        CancellableQuery newExecutable = context.createExecutableQuery(query, hints, variables);
        CancellableQuery executable = executingQuery.getAndSet(newExecutable);
        if (executable == null) {
            // We are the first to call 'execute()', so use our newly-created one ...
            executable = newExecutable;
        }
        // otherwise, some other thread called execute, so we can use it and just wait for the results ...
        final QueryResults result = executable.execute(); // may be cancelled

        // And reset the reference to null (if not already set to something else) ...
        executingQuery.compareAndSet(executable, null);

        checkForProblems(result.getProblems());
        context.recordDuration(Math.abs(System.nanoTime() - start), TimeUnit.NANOSECONDS, statement, language);
        if (Query.XPATH.equals(language)) {
            return new XPathQueryResult(context, statement, result, hints.restartable, hints.rowsKeptInMemory);
        } else if (Query.SQL.equals(language)) {
            return new JcrSqlQueryResult(context, statement, result, hints.restartable, hints.rowsKeptInMemory);
        }
        return new JcrQueryResult(context, statement, result, hints.restartable, hints.rowsKeptInMemory);
    }
581501
@Override
    public void execute() throws BuildException {
        logger = new DITAOTAntLogger(getProject());
        final MessageBean msgBean = MessageUtils.getMessage(id, readParamValues());
        if (msgBean != null) {
            final String type = msgBean.getType();
            if (ERROR.equals(type)) {
                logger.error(msgBean.toString());
            } else if (WARN.equals(type)) {
                logger.warn(msgBean.toString());
            } else if (INFO.equals(type)) {
                logger.info(msgBean.toString());
            } else if (DEBUG.equals(type)) {
                logger.debug(msgBean.toString());
            }
        }
    }