Executes command, and waits for the expected phrase in console printout.

@param command command line

@return console output as a list of strings

@throws IOException          for command error
@throws InterruptedException when interrupted
168189
public static List<String> cmd(String[] command) throws IOException, InterruptedException {
        return cmd(command, null, null, 300000L, null);
    }
751967
public void runCommands(final String[] commands) throws IOException {
		doLines(0, new LineReader() {
			private int commandC = 0;

			@Override
			public String getNextLine(String prompt) {
				if (commandC >= commands.length) {
					return null;
				} else {
					return commands[commandC++];
				}
			}
		}, true);
	}
580876
def execute_command(self, cmd, timeout, wait_for_string, password):
        """"""
        try:
            self.last_command_result = None
            self.ctrl.send_command(cmd, password=password)
            if wait_for_string is None:
                wait_for_string = self.prompt_re

            # hide cmd in case it's password for further error messages or exceptions.
            if password:
                cmd = "*** Password ***"

            if not self.driver.wait_for_string(wait_for_string, timeout):
                self.chain.connection.log("Unexpected session disconnect during '{}' command execution".format(cmd))
                raise ConnectionError("Unexpected session disconnect", host=self.hostname)

            if self.last_command_result:
                output = self.last_command_result.replace('\r', '')
            else:
                output = self.ctrl.before.replace('\r', '')

            # not needed. Fixes the issue #11
            # second_line_index = output.find('\n') + 1
            # output = output[second_line_index:]
            return output

        except CommandSyntaxError as e:  # pylint: disable=invalid-name
            self.chain.connection.log("{}: '{}'".format(e.message, cmd))
            e.command = cmd
            # TODO: Verify why lint raises an issue
            raise e  # pylint: disable=raising-bad-type

        except (CommandTimeoutError, pexpect.TIMEOUT):
            self.chain.connection.log("Command timeout: '{}'".format(cmd))
            raise CommandTimeoutError(message="Command timeout", host=self.hostname, command=cmd)

        except ConnectionError as e:  # pylint: disable=invalid-name
            self.chain.connection.log("{}: '{}'".format(e.message, cmd))
            raise

        except pexpect.EOF:
            self.chain.connection.log("Unexpected session disconnect")
            raise ConnectionError("Unexpected session disconnect", host=self.hostname)

        except Exception as e:  # pylint: disable=invalid-name
            self.chain.connection.log("Exception {}".format(e))
            raise ConnectionError(message="Unexpected error", host=self.hostname)
650753
private String executeCommand() throws IOException, InterruptedException {
        ProcessBuilder processBuilder = new ProcessBuilder(command);

        ByteArrayOutputStream commandOutput = new ByteArrayOutputStream();

        Process process = processBuilder.start();
        try {
            IOUtils.copy(process.getInputStream(), commandOutput, processOutputLimit);

            process.waitFor();

            if (process.exitValue() != 0) {
                throw new IllegalStateException("Command returned non-zero exit value: " + process.exitValue());
            }

            return new String(commandOutput.toByteArray(), StringUtils.UTF8);
        } finally {
            process.destroy();
        }
    }
199065
public int execute(final String user, final List<String> command) throws IOException {
    log.info("Command: " + command);
    final Process process = new ProcessBuilder()
        .command(constructExecuteAsCommand(user, command))
        .inheritIO()
        .start();

    int exitCode;
    try {
      exitCode = process.waitFor();
    } catch (final InterruptedException e) {
      log.error(e.getMessage(), e);
      exitCode = 1;
    }
    return exitCode;
  }
133865
void executeCommand() throws CertificateException {
        String exceptionMessage;
        Throwable cause = null;

        try {
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("Executing keytool command: " + this.toString());
            }
            Process proc = Runtime.getRuntime().exec(cmd.toArray(new String[cmd.size()]));

            if (logger.isLoggable(Level.FINE)) {
                logger.fine("Waiting for keytool command process to complete...");
            }
            int exitCode = proc.waitFor();
            if (exitCode == 0) {
                if (logger.isLoggable(Level.FINE)) {
                    logger.fine("keytool command process completed successfully");
                }
                return;
            } else {
                if (logger.isLoggable(Level.FINE)) {
                    logger.fine("keytool command process failed to complete successfully (exit code: " + exitCode + ")");
                }
                exceptionMessage = getProcErrorOutput(proc);
            }
        } catch (IOException e) {
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("keytool command process execution resulted in IOException: " + e.getMessage());
            }
            exceptionMessage = e.getLocalizedMessage();
            cause = e;
        } catch (InterruptedException e) {
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("InterruptedException while waiting for keytool command process result: " + e.getMessage());
            }
            exceptionMessage = e.getLocalizedMessage();
            cause = e;
        }

        if (cause != null) {
            throw new CertificateException(exceptionMessage, cause);
        } else {
            throw new CertificateException(exceptionMessage);
        }
    }
1219239
public static String command(final Command command, CommandListener listener) throws Exception {
        command.mListener = listener;
        return command(command);
    }
334591
public PowerShellResponse executeCommand(String command) {
        String commandOutput = "";
        boolean isError = false;
        boolean timeout = false;

        checkState();

        PowerShellCommandProcessor commandProcessor = new PowerShellCommandProcessor("standard", p.getInputStream(),
                this.waitPause, this.scriptMode);
        Future<String> result = threadpool.submit(commandProcessor);

        // Launch command
        commandWriter.println(command);

        try {
            if (!result.isDone()) {
                try {
                    commandOutput = result.get(maxWait, TimeUnit.MILLISECONDS);
                } catch (TimeoutException timeoutEx) {
                    timeout = true;
                    isError = true;
                    //Interrupt command after timeout
                    result.cancel(true);
                }
            }
        } catch (InterruptedException | ExecutionException ex) {
            logger.log(Level.SEVERE,
                    "Unexpected error when processing PowerShell command", ex);
            isError = true;
        } finally {
            // issue #2. Close and cancel processors/threads - Thanks to r4lly
            // for helping me here
            commandProcessor.close();
        }

        return new PowerShellResponse(isError, commandOutput, timeout);
    }
379819
public void execute(CommandHandler handler,
            int timeout,
            TimeUnit unit) throws
            CommandLineException,
            InterruptedException, ExecutionException, TimeoutException {
        ExecutableBuilder builder = new ExecutableBuilder() {
            CommandContext c = newTimeoutCommandContext(ctx);
            @Override
            public Executable build() {
                return () -> {
                    handler.handle(c);
                };
            }

            @Override
            public CommandContext getCommandContext() {
                return c;
            }
        };
        execute(builder, timeout, unit);
    }
642010
public static void executeCommand(String[] args) throws Exception {
        String subCmd = (args.length > 0) ? args[0] : "";
        args = AdminToolUtils.copyArrayCutFirst(args);
        if(subCmd.equals("get")) {
            SubCommandQuotaGet.executeCommand(args);
        } else if(subCmd.equals("set")) {
            SubCommandQuotaSet.executeCommand(args);
        } else if(subCmd.equals("reserve-memory")) {
            SubCommandQuotaReserveMemory.executeCommand(args);
        } else if(subCmd.equals("unset")) {
            SubCommandQuotaUnset.executeCommand(args);
        } else {
            printHelp(System.out);
        }
    }
490089
private void executeCommand(String command, List<String> arguments) {

        try {
            CmsShellCommandResult result = m_remoteShell.executeCommand(command, arguments);
            m_out.print(result.getOutput());
            updateState(result);
            if (m_exitCalled) {
                exit(0);
            } else if (m_hasError && (m_errorCode != -1)) {
                exit(m_errorCode);
            }
        } catch (RemoteException r) {
            r.printStackTrace(System.err);
            exit(1);
        }
    }
504161
public synchronized ModelNode doCommand(String command) throws CommandFormatException, IOException {
        ModelNode request = cmdCtx.buildRequest(command);
        return execute(request, isSlowCommand(command)).getResponseNode();
    }
885368
public List<Command> receive(final Command command) {

        Assert.requireNonNull(command, "command");
        LOG.trace("Received command of type {}", command.getClass().getSimpleName());
        List<Command> response = new LinkedList();// collecting parameter pattern

        if (!(command instanceof InterruptLongPollCommand)) {// signal commands must not update thread-confined state
            for (DolphinServerAction it : dolphinServerActions) {
                it.setDolphinResponse(response);// todo: can be deleted as soon as all action refer to the SMS
            }

            serverModelStore.setCurrentResponse(response);
        }


        List<CommandHandler> actions = registry.getActionsFor(command.getClass());
        if (actions.isEmpty()) {
            LOG.warn("There is no server action registered for received command type {}, known commands types are {}", command.getClass().getSimpleName(), registry.getActions().keySet());
            return response;
        }

        // copying the list of actions allows an Action to unregister itself
        // avoiding ConcurrentModificationException to be thrown by the loop
        List<CommandHandler> actionsCopy = new ArrayList<CommandHandler>();
        actionsCopy.addAll(actions);
        try {
            for (CommandHandler action : actionsCopy) {
                action.handleCommand(command, response);
            }

        } catch (Exception exception) {
            throw exception;
        }

        return response;
    }
28311
protected Pair<Integer, InputStream> executeCommand(String command) {
        int resultVal = 1;
        InputStream inputStream = null;
        try {
            logger.debug("Executing command: {}", command);
            Process process =  Runtime.getRuntime().exec(command);

            resultVal = process.waitFor();
            inputStream = process.getInputStream();

        } catch (InterruptedException e) {
            logger.info("Execution of {} failed: code - {} ; message - {}", command, resultVal, e.getMessage());
            Thread.currentThread().interrupt();
        } catch (IOException  e) {
            logger.info("Execution of {} failed: code - {} ; message - {}", command, resultVal, e.getMessage());
        }
        if (inputStream == null) {
           // Create an empty InputStream instead of returning a null
           inputStream = new InputStream() {
               @Override
               public int read() throws IOException {
                   return -1;
               }
           } ;
        }
        return new Pair<>(resultVal, inputStream);
    }
943276
public static String executeProcess(Map<String, String> env, File workingFolder, String... command) throws ProcessException, InterruptedException {
        ProcessBuilder pb = new ProcessBuilder(command);
        if (workingFolder != null) {
            pb.directory(workingFolder);
        }
        if (env != null) {
            pb.environment().clear();
            pb.environment().putAll(env);
        }
        pb.redirectErrorStream(true);
        int code;
        try {
            Process process = pb.start();
            String payload;
            try {
                code = process.waitFor();
            } catch (InterruptedException ex) {
                process.destroy();
                throw ex;
            }
            payload = Miscellaneous.toString(process.getInputStream(), "UTF-8");
            if (code == 0) {
                return payload;
            } else {
                StringBuilder sb = new StringBuilder("Process returned code: " + code + ".");
                if (payload != null) {
                    sb.append("\n").append(payload);
                }
                throw new ProcessException(code, sb.toString());
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }

    }
531329
private static String[] executeShellCommand(String[] command)
  throws IOException {
    String groups = Shell.execCommand(command);
    StringTokenizer tokenizer = new StringTokenizer(groups);
    int numOfTokens = tokenizer.countTokens();
    String[] tokens = new String[numOfTokens];
    for (int i=0; tokenizer.hasMoreTokens(); i++) {
      tokens[i] = tokenizer.nextToken();
    }

    return tokens;
  }
319881
public static void runShellCommand(String cmd,
                                     StringBuilder outputLines,
                                     StringBuilder errorLines)
    throws IOException {
    runShellCommand(new String[] {cmd}, outputLines, errorLines);
  }