Example usage for org.apache.commons.exec CommandLine toString

List of usage examples for org.apache.commons.exec CommandLine toString

Introduction

In this page you can find the example usage for org.apache.commons.exec CommandLine toString.

Prototype

@Override
public String toString() 

Source Link

Document

Stringify operator returns the command line as a string.

Usage

From source file:hoot.services.command.CommandRunnerImpl.java

@Override
public CommandResult exec(String command) throws IOException {
    logger.debug("Executing the following command: {}", command);

    try (OutputStream stdout = new ByteArrayOutputStream(); OutputStream stderr = new ByteArrayOutputStream()) {

        CommandLine cmdLine = CommandLine.parse(command);

        ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(stdout, stderr);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(executeStreamHandler);

        int exitValue;
        try {//from  ww w  . j  a  v a2  s. co m
            exitValue = executor.execute(cmdLine);
        } catch (Exception e) {
            exitValue = -1;
            logger.warn("Error executing: {}", cmdLine, e);
        }

        CommandResult commandResult = new CommandResult(cmdLine.toString(), exitValue, stdout.toString(),
                stderr.toString());

        this.stdout = stdout.toString();

        logger.debug("Finished executing: {}", commandResult);

        return commandResult;
    }
}

From source file:io.selendroid.android.impl.AbstractDevice.java

private void startLogging() {
    logoutput = new ByteArrayOutputStream();
    DefaultExecutor exec = new DefaultExecutor();
    exec.setStreamHandler(new PumpStreamHandler(logoutput));
    CommandLine command = adbCommand("logcat", "ResourceType:S", "dalvikvm:S", "Trace:S", "SurfaceFlinger:S",
            "StrictMode:S", "ExchangeService:S", "SVGAndroid:S", "skia:S", "LoaderManager:S",
            "ActivityThread:S", "-v", "time");
    log.info("starting logcat:");
    log.fine(command.toString());
    try {/* w  w  w  .j  ava  2 s .  c  o m*/
        exec.execute(command, new DefaultExecuteResultHandler());
        logcatWatchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        exec.setWatchdog(logcatWatchdog);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.netflix.genie.core.jobs.workflow.impl.JobKickoffTask.java

/**
 * Create user on the system. Synchronized to prevent multiple threads from trying to create user at the same time.
 *
 * @param user  user id/*from w  w  w  .ja v a 2  s  .  c o m*/
 * @param group group id
 * @throws GenieException If there is any problem.
 */
protected synchronized void createUser(final String user, final String group) throws GenieException {

    // First check if user already exists
    final CommandLine idCheckCommandLine = new CommandLine("id").addArgument("-u").addArgument(user);

    try {
        this.executor.execute(idCheckCommandLine);
        log.debug("User already exists");
    } catch (final IOException ioe) {
        log.debug("User does not exist. Creating it now.");

        // Determine if the group is valid by checking that its not null and not same as user.
        final boolean isGroupValid = StringUtils.isNotBlank(group) && !group.equals(user);

        // Create the group for the user if its not the same as the user.
        if (isGroupValid) {
            log.debug("Group and User are different so creating group now.");
            final CommandLine groupCreateCommandLine = new CommandLine("sudo").addArgument("groupadd")
                    .addArgument(group);

            // We create the group and ignore the error as it will fail if group already exists.
            // If the failure is due to some other reason, then user creation will fail and we catch that.
            try {
                log.debug("Running command to create group:  [" + groupCreateCommandLine.toString() + "]");
                this.executor.execute(groupCreateCommandLine);
            } catch (IOException ioexception) {
                log.debug("Group creation threw an error as it might already exist");
            }
        }

        final CommandLine userCreateCommandLine = new CommandLine("sudo").addArgument("useradd")
                .addArgument(user);
        if (isGroupValid) {
            userCreateCommandLine.addArgument("-G").addArgument(group);
        }
        userCreateCommandLine.addArgument("-M");

        try {
            log.debug("Running command to create user: [" + userCreateCommandLine.toString() + "]");
            this.executor.execute(userCreateCommandLine);
        } catch (IOException ioexception) {
            throw new GenieServerException("Could not create user " + user + " with exception " + ioexception);
        }
    }
}

From source file:hoot.services.command.CommandRunnerImpl.java

@Override
public CommandResult exec(String[] command) throws IOException {
    logger.debug("Executing the following command: {}", Arrays.toString(command));

    try (OutputStream stdout = new ByteArrayOutputStream(); OutputStream stderr = new ByteArrayOutputStream()) {

        CommandLine cmdLine = new CommandLine(command[0]);
        for (int i = 1; i < command.length; i++) {
            cmdLine.addArgument(command[i], false);
        }/*from www  .j  a  v a 2 s. c  o m*/

        ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(stdout, stderr);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(executeStreamHandler);

        int exitValue;
        try {
            exitValue = executor.execute(cmdLine);
        } catch (Exception e) {
            exitValue = -1;
            logger.warn("Error executing: {}", cmdLine, e);
        }

        CommandResult commandResult = new CommandResult(cmdLine.toString(), exitValue, stdout.toString(),
                stderr.toString());

        this.stdout = stdout.toString();

        logger.debug("Finished executing: {}", commandResult);

        return commandResult;
    }
}

From source file:com.netflix.genie.web.tasks.job.JobCompletionService.java

/**
 * Delete the application dependencies off disk to save space.
 *
 * @param jobId  The ID of the job to delete dependencies for
 * @param jobDir The job working directory
 *//* ww w.j  av a2  s  .  com*/
private void deleteApplicationDependencies(final String jobId, final File jobDir) {
    log.debug("Deleting dependencies as its enabled.");
    if (jobDir.exists()) {
        try {
            final List<String> appIds = this.jobSearchService.getJobApplications(jobId).stream()
                    .map(Application::getId).filter(Optional::isPresent).map(Optional::get)
                    .collect(Collectors.toList());

            for (final String appId : appIds) {
                final File appDependencyDir = new File(jobDir,
                        JobConstants.GENIE_PATH_VAR + JobConstants.FILE_PATH_DELIMITER
                                + JobConstants.APPLICATION_PATH_VAR + JobConstants.FILE_PATH_DELIMITER + appId
                                + JobConstants.FILE_PATH_DELIMITER + JobConstants.DEPENDENCY_FILE_PATH_PREFIX);

                if (appDependencyDir.exists()) {
                    if (this.runAsUserEnabled) {
                        final CommandLine deleteCommand = new CommandLine("sudo");
                        deleteCommand.addArgument("rm");
                        deleteCommand.addArgument("-rf");
                        deleteCommand.addArgument(appDependencyDir.getCanonicalPath());
                        log.debug("Delete command is {}", deleteCommand.toString());
                        this.executor.execute(deleteCommand);
                    } else {
                        FileUtils.deleteDirectory(appDependencyDir);
                    }
                }
            }
        } catch (Exception e) {
            log.error("Could not delete job dependencies after completion for job: {} due to error {}", jobId,
                    e);
            this.deleteDependenciesFailure.increment();
        }
    }
}

From source file:be.tarsos.transcoder.ffmpeg.FFMPEGExecutor.java

public String toString() {
    CommandLine cmdLine = new CommandLine(ffmpegExecutablePath);

    int fileNumber = 0;
    Map<String, File> map = new HashMap<String, File>();
    for (int i = 0; i < args.size(); i++) {
        final String arg = args.get(i);
        final Boolean isFile = argIsFile.get(i);
        if (isFile) {
            String key = "file" + fileNumber;
            map.put(key, new File(arg));
            cmdLine.addArgument("${" + key + "}", false);
            fileNumber++;/*from   ww  w  .  ja v  a2 s.com*/
        } else {
            cmdLine.addArgument(arg);
        }
    }
    cmdLine.setSubstitutionMap(map);
    return cmdLine.toString();
}

From source file:com.tupilabs.pbs.PBS.java

/**
 * PBS qsub command.//from  w  ww .j  a  va  2 s.c  o  m
 * <p>
 * Equivalent to qsub [param]
 *
 * @param inputs job input file
 * @param environment environment variables
 * @return job id
 */
public static String qsub(String[] inputs, Map<String, String> environment) {
    final CommandLine cmdLine = new CommandLine(COMMAND_QSUB);
    for (int i = 0; i < inputs.length; ++i) {
        cmdLine.addArgument(inputs[i]);
    }

    final OutputStream out = new ByteArrayOutputStream();
    final OutputStream err = new ByteArrayOutputStream();

    DefaultExecuteResultHandler resultHandler;
    try {
        resultHandler = execute(cmdLine, environment, out, err);
        resultHandler.waitFor(DEFAULT_TIMEOUT);
    } catch (ExecuteException e) {
        throw new PBSException("Failed to execute qsub command: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new PBSException("Failed to execute qsub command: " + e.getMessage(), e);
    } catch (InterruptedException e) {
        throw new PBSException("Failed to execute qsub command: " + e.getMessage(), e);
    }

    final int exitValue = resultHandler.getExitValue();
    LOGGER.info("qsub exit value: " + exitValue);
    LOGGER.fine("qsub output: " + out.toString());

    if (exitValue != 0) {
        throw new PBSException("Failed to submit job script with command line '" + cmdLine.toString()
                + "'. Error output: " + err.toString());
    }

    String jobId = out.toString();
    return jobId.trim();
}

From source file:io.selendroid.standalone.android.impl.AbstractDevice.java

private void startLogging() {
    logoutput = new ByteArrayOutputStream();
    DefaultExecutor exec = new DefaultExecutor();
    exec.setStreamHandler(new PumpStreamHandler(logoutput));
    CommandLine command = adbCommand("logcat", "ResourceType:S", "dalvikvm:S", "Trace:S", "SurfaceFlinger:S",
            "StrictMode:S", "ExchangeService:S", "SVGAndroid:S", "skia:S", "LoaderManager:S",
            "ActivityThread:S", "-v", "time");
    log.info("starting logcat:");
    log.fine(command.toString());
    try {/*from   ww  w .  j av  a 2 s  .  com*/
        exec.execute(command, new DefaultExecuteResultHandler());
        logcatWatchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        exec.setWatchdog(logcatWatchdog);
    } catch (IOException e) {
        log.log(Level.SEVERE, e.getMessage(), e);
    }
}

From source file:com.nts.alphamale.shell.AdbShellExecutor.java

/**
 * @param cmd adb /*from  w ww . j  a  v  a 2  s  . c  o m*/
 * @param synch   ? ? true: synchronous, false: asynchronous
 * @param  (ms)
 * @return Executor Standard Output? Map
 */
public Map<String, Object> execute(CommandLine cmd, boolean synch, long timeoutMilliseconds) {
    Map<String, Object> executorMap = new HashMap<String, Object>();
    DefaultExecutor executor = new DefaultExecutor();
    PipedOutputStream pos = new PipedOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(pos, System.err);
    streamHandler.setStopTimeout(timeoutMilliseconds);
    DataInputStream dis = null;
    try {
        dis = new DataInputStream(new PipedInputStream(pos));
    } catch (IOException e) {
        //log.error(e.getCause() + " : " + e.getMessage());
    }
    executor.setStreamHandler(streamHandler);
    ExecuteWatchdog watchDog = new ExecuteWatchdog(timeoutMilliseconds);
    executor.setWatchdog(watchDog);
    try {
        if (synch)
            executor.execute(cmd);
        else
            executor.execute(cmd, new DefaultExecuteResultHandler());

        log.debug(cmd.toString());
        LineIterator li = IOUtils.lineIterator(dis, "UTF-8");
        if (li != null) {
            executorMap.put("executor", executor);
            executorMap.put("stdOut", li);
        }
    } catch (Exception e) {
        log.error(e.getCause() + ":" + e.getMessage() + "[" + cmd + "]");
    }
    return executorMap;
}

From source file:fr.gouv.culture.vitam.utils.Executor.java

/**
 * Execute an external command//from  w w  w.j a v a2 s .  c  o  m
 * @param cmd
 * @param tempDelay
 * @param correctValues
 * @param showOutput
 * @param realCommand
 * @return correctValues if ok, < 0 if an execution error occurs, or other error values
 */
public static int exec(List<String> cmd, long tempDelay, int[] correctValues, boolean showOutput,
        String realCommand) {
    // Create command with parameters
    CommandLine commandLine = new CommandLine(cmd.get(0));
    for (int i = 1; i < cmd.size(); i++) {
        commandLine.addArgument(cmd.get(i));
    }
    DefaultExecutor defaultExecutor = new DefaultExecutor();
    ByteArrayOutputStream outputStream;
    outputStream = new ByteArrayOutputStream();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream);
    defaultExecutor.setStreamHandler(pumpStreamHandler);

    defaultExecutor.setExitValues(correctValues);
    AtomicBoolean isFinished = new AtomicBoolean(false);
    ExecuteWatchdog watchdog = null;
    Timer timer = null;
    if (tempDelay > 0) {
        // If delay (max time), then setup Watchdog
        timer = new Timer(true);
        watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        defaultExecutor.setWatchdog(watchdog);
        CheckEndOfExecute endOfExecute = new CheckEndOfExecute(isFinished, watchdog, realCommand);
        timer.schedule(endOfExecute, tempDelay);
    }
    int status = -1;
    try {
        // Execute the command
        status = defaultExecutor.execute(commandLine);
    } catch (ExecuteException e) {
        if (e.getExitValue() == -559038737) {
            // Cannot run immediately so retry once
            try {
                Thread.sleep(100);
            } catch (InterruptedException e1) {
            }
            try {
                status = defaultExecutor.execute(commandLine);
            } catch (ExecuteException e1) {
                pumpStreamHandler.stop();
                System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                        + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
                status = -2;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return status;
            } catch (IOException e1) {
                pumpStreamHandler.stop();
                System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                        + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
                status = -2;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return status;
            }
        } else {
            pumpStreamHandler.stop();
            System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                    + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
            status = -2;
            try {
                outputStream.close();
            } catch (IOException e2) {
            }
            return status;
        }
    } catch (IOException e) {
        pumpStreamHandler.stop();
        System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
        status = -2;
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
        return status;
    } finally {
        isFinished.set(true);
        if (timer != null) {
            timer.cancel();
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e1) {
        }
    }
    pumpStreamHandler.stop();
    if (defaultExecutor.isFailure(status) && watchdog != null) {
        if (watchdog.killedProcess()) {
            // kill by the watchdoc (time out)
            if (showOutput) {
                System.err.println(StaticValues.LBL.error_error.get() + "Exec is in Time Out");
            }
        }
        status = -3;
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
    } else {
        if (showOutput) {
            System.out.println("Exec: " + outputStream.toString());
        }
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
    }
    return status;
}