Example usage for org.apache.commons.exec DefaultExecutor setWorkingDirectory

List of usage examples for org.apache.commons.exec DefaultExecutor setWorkingDirectory

Introduction

In this page you can find the example usage for org.apache.commons.exec DefaultExecutor setWorkingDirectory.

Prototype

public void setWorkingDirectory(final File dir) 

Source Link

Usage

From source file:org.codehaus.mojo.latex.LaTeXMojo.java

private void execute(CommandLine commandLine, File dir) throws IOException, MojoFailureException {
    final DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(dir);
    if (executor.execute(commandLine) != 0) {
        throw new MojoFailureException("Error code returned for: " + commandLine.toString());
    }// ww  w . j a  va2  s  . c om
}

From source file:org.codice.git.GitIntegrationTest.java

private int executeGitCommand(String[] args) throws IOException {
    int exitValue = 0;
    List<String> outputLines = null;
    CommandLine cmdLine = new CommandLine("git");
    for (String arg : args) {
        cmdLine.addArgument(arg);/*  ww w .  j  av  a  2s  .co m*/
    }
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    executor.setWorkingDirectory(trash);
    CollectingLogOutputStream output = new CollectingLogOutputStream();
    PumpStreamHandler pump = new PumpStreamHandler(output, output);
    executor.setStreamHandler(pump);
    try {
        exitValue = executor.execute(cmdLine);
        outputLines = output.getLines();
    } catch (IOException e) {
        boolean hookRan = false;
        String errorMessage = "";
        // Check if we got the aborted message from the hook - implies it ran successfully
        outputLines = output.getLines();
        if ((outputLines != null) && (outputLines.size() > 0)) {
            errorMessage = outputLines.get(0);
            for (String line : outputLines) {
                if (line.contains("HOOK ABORTED")) {
                    hookRan = true;
                    break;
                }
            }
        }
        if (hookRan) {
            LOGGER.debug("Hook ran successfully - returning an error to abort the git command");
        } else {
            LOGGER.warn("Unexpected error during hook processing - first line of output: {}", errorMessage, e);
            throw e;
        }
        exitValue = 1;
    }

    for (String line : outputLines) {
        System.err.println(line);
    }
    return exitValue;
}

From source file:org.eclipse.sisu.equinox.launching.internal.DefaultEquinoxLauncher.java

@Override
public int execute(LaunchConfiguration configuration, int forkedProcessTimeoutInSeconds)
        throws EquinoxLaunchingException {

    String executable = configuration.getJvmExecutable();
    if (executable == null || "".equals(executable)) {
        // use the same JVM as the one used to run Maven (the "java.home" one)
        executable = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
        if (File.separatorChar == '\\') {
            executable = executable + ".exe";
        }/*from   www .  j a  va  2 s  .  co m*/
    }
    CommandLine cli = new CommandLine(executable);

    final boolean handleQuotes = false;
    cli.addArguments(configuration.getVMArguments(), handleQuotes);

    cli.addArguments(new String[] { "-jar", getCanonicalPath(configuration.getLauncherJar()) }, handleQuotes);

    cli.addArguments(configuration.getProgramArguments(), handleQuotes);

    log.info("Command line:\n\t" + cli.toString());

    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = null;
    if (forkedProcessTimeoutInSeconds > 0) {
        watchdog = new ExecuteWatchdog(forkedProcessTimeoutInSeconds * 1000L);
        executor.setWatchdog(watchdog);
    }
    // best effort to avoid orphaned child process
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    executor.setWorkingDirectory(configuration.getWorkingDirectory());
    try {
        return executor.execute(cli, getMergedEnvironment(configuration));
    } catch (ExecuteException e) {
        if (watchdog != null && watchdog.killedProcess()) {
            log.error("Timeout " + forkedProcessTimeoutInSeconds + " s exceeded. Process was killed.");
        }
        return e.getExitValue();
    } catch (IOException e) {
        throw new EquinoxLaunchingException(e);
    }
}

From source file:org.evosuite.utils.ProcessLauncher.java

public int launchNewProcess(File baseDir, String cmdString, int timeout)
        throws IOException, ProcessTimeoutException {

    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog timeoutWatchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(timeoutWatchdog);

    PumpStreamHandler streamHandler = new PumpStreamHandler(this.outAndErr, this.outAndErr, this.input);
    executor.setStreamHandler(streamHandler);
    if (baseDir != null) {
        executor.setWorkingDirectory(baseDir);
    }//w w  w .  j  av a 2  s  .c  o  m

    int exitValue;
    try {
        logger.debug("About to execute command " + cmdString);
        exitValue = executor.execute(CommandLine.parse(cmdString));
        if (executor.isFailure(exitValue) && timeoutWatchdog.killedProcess()) {
            // it was killed on purpose by the watchdog
            logger.debug("A timeout occured while executing a process");
            logger.debug("The command is " + cmdString);
            throw new ProcessTimeoutException("A timeout occurred while executing command " + cmdString);
        }

        return exitValue;
    } catch (ExecuteException e) {
        if (timeoutWatchdog.killedProcess()) {
            logger.debug("A timeout occured while executing a process");
            logger.debug("The command is " + cmdString);
            throw new ProcessTimeoutException("A timeout occurred while executing command " + cmdString);
        } else {
            throw e;
        }

    }

}

From source file:org.fuin.esmp.EventStorePostStartMojo.java

@Override
protected final void executeGoal() throws MojoExecutionException {
    if (postStartCommand == null) {
        throw new MojoExecutionException("postStartCommand not set");
    }/*from w w  w  .j  a  va2s .  c o  m*/
    LOG.info("postStartCommand={}", postStartCommand);

    final CommandLine cmdLine = new CommandLine(postStartCommand);
    final DefaultExecutor executor = new DefaultExecutor();
    try {
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        final PumpStreamHandler psh = new PumpStreamHandler(bos);
        executor.setStreamHandler(psh);
        executor.setWorkingDirectory(getEventStoreDir());
        final int exitCode = executor.execute(cmdLine);
        messages = asList(bos.toString());
        if (exitCode == 0) {
            LOG.info("Post-start command executed successfully");
            logDebug(messages);
        } else {
            LOG.error("Post-start command failed with exit code: {}", exitCode);
            logError(messages);
        }
    } catch (final IOException ex) {
        throw new MojoExecutionException("Error executing the command line: " + cmdLine, ex);
    }
}

From source file:org.grouplens.lenskit.eval.maven.RScriptMojo.java

@Override
public void execute() throws MojoExecutionException {
    getLog().info("The analysis directory is " + analysisDir);
    getLog().info("The analysisScript is " + analysisScript);
    getLog().info("The R executable is " + rscriptExecutable);

    // Copy the script file into the working directory.  We could just execute
    // it from its original location, but it will be easier for our users to 
    // have the copy from the src directory next to its results in target.
    File scriptFile = new File(analysisScript);
    File scriptCopy = new File(analysisDir, scriptFile.getName());
    try {//from   ww  w.j a  v a2s .co  m
        if (!scriptFile.getCanonicalPath().equals(scriptCopy.getCanonicalPath())) {
            copyFile(scriptFile, scriptCopy);
        }
    } catch (IOException e1) {
        throw new MojoExecutionException("Unable to copy scriptFile " + scriptFile.getAbsolutePath()
                + " into working directory " + scriptCopy.getAbsolutePath());
    }

    // Generate the command line for executing R.
    final CommandLine command = new CommandLine(rscriptExecutable).addArgument(scriptCopy.getAbsolutePath(),
            false);
    getLog().debug("command: " + command);

    // Execute the command line, in the working directory.
    final DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(new File(analysisDir));
    try {
        if (executor.execute(command) != 0) {
            throw new MojoExecutionException("Error code returned for: " + command.toString());
        }
    } catch (ExecuteException e) {
        throw new MojoExecutionException("Error executing command: " + command.toString(), e);
    } catch (IOException e) {
        throw new MojoExecutionException("IO Exception while executing command: " + command.toString(), e);
    }
}

From source file:org.jahia.modules.dm.thumbnails.video.impl.VideoThumbnailServiceImpl.java

public boolean generateThumbnail(File videoFile, File outputFile, int offsetSeconds, String size)
        throws DocumentOperationException {
    if (!isEnabled()) {
        logger.info("FFmpeg service is not enabled." + " Skip converting file {}", videoFile);

        return false;
    }/*from   ww  w. ja va  2s.  c o  m*/

    long timer = System.currentTimeMillis();

    CommandLine cmd = getConvertCommandLine(videoFile, outputFile, String.valueOf(offsetSeconds),
            StringUtils.defaultIfEmpty(size, "320x240"));

    if (logger.isDebugEnabled()) {
        logger.debug("Execuiting thumbnail generation command: {}", cmd.toString());
    }

    int exitValue = 0;

    StringOutputStream err = new StringOutputStream();
    try {
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(null, err));
        if (workingDir != null) {
            if (workingDir.exists() || workingDir.mkdirs()) {
                executor.setWorkingDirectory(workingDir);
            }
        }
        exitValue = executor.execute(cmd, System.getenv());
    } catch (Exception e) {
        throw new DocumentOperationException(e);
    } finally {
        if (exitValue > 0 && err.getLength() > 0) {
            logger.error("External process finished with error. Cause: {}", err.toString());
        }
        if (logger.isDebugEnabled() && err.getLength() > 0) {
            logger.debug(err.toString());
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Generating thumbnail {} from {} done (exit code: {}) in {} ms",
                new Object[] { outputFile, videoFile, exitValue, (System.currentTimeMillis() - timer) });
    }

    return exitValue == 0;
}

From source file:org.jahia.modules.dm.viewer.impl.PDF2SWFConverterService.java

public boolean convert(File inputPdfFile, File outputSwfFile) throws DocumentOperationException {
    if (!isEnabled()) {
        logger.info("pdf2swf conversion service is not enabled." + " Skip converting file {}", inputPdfFile);

        return false;
    }/*  w  w w .j  a  v a  2s  . c o m*/

    long timer = System.currentTimeMillis();

    CommandLine cmd = getConvertCommandLine(inputPdfFile, outputSwfFile);

    if (logger.isDebugEnabled()) {
        logger.debug("Execuiting conversion command: {}", cmd.toString());
    }

    int exitValue = 0;

    StringOutputStream out = new StringOutputStream();
    StringOutputStream err = new StringOutputStream();
    try {
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(out, err));
        if (workingDir != null) {
            if (workingDir.exists() || workingDir.mkdirs()) {
                executor.setWorkingDirectory(workingDir);
            }
        }
        exitValue = executor.execute(cmd, System.getenv());
    } catch (Exception e) {
        throw new DocumentOperationException(e);
    } finally {
        if (err.getLength() > 0) {
            logger.error("Conversion process finished with error. Cause: {}", err.toString());
        }
        if (logger.isDebugEnabled() && out.getLength() > 0) {
            logger.debug(out.toString());
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Conversion from {} to {} done (exit code: {}) in {} ms",
                new Object[] { inputPdfFile, outputSwfFile, exitValue, (System.currentTimeMillis() - timer) });
    }

    return exitValue == 0;
}

From source file:org.jahia.utils.ProcessHelper.java

/**
 * Executes the external process using the provided command, arguments (optional), parameter substitution map to expand variables in the
 * command or arguments in form of <code>${variable}<code> (optional) and a working directory (optional).
 * Buffers for process output and error stream can be provided.
 * /*from   w w  w. ja va2  s  .co  m*/
 * @param command
 *            the command to be executed
 * @param arguments
 *            optional arguments for the command
 * @param parameterSubstitutionMap
 *            optional values for variables to be expanded
 * @param workingDir
 *            optional working directory for the process to be started from
 * @param resultOut
 *            the buffer to write the process execution output into (optional)
 * @param resultErr
 *            the buffer to write the process execution error into (optional)
 * @return the execution status
 * @return redirectOutputs if set to <code>true</code> the output of the execution will be also redirected to standard system out and
 *         the error to error out
 * @throws JahiaRuntimeException
 *             in case the process execution failed
 */
public static int execute(String command, String arguments[], Map<String, Object> parameterSubstitutionMap,
        File workingDir, StringBuilder resultOut, StringBuilder resultErr, boolean redirectOutputs)
        throws JahiaRuntimeException {

    long timer = System.currentTimeMillis();

    CommandLine cmd = new CommandLine(command);

    if (arguments != null && arguments.length > 0) {
        cmd.addArguments(arguments, false);
    }

    if (parameterSubstitutionMap != null && !parameterSubstitutionMap.isEmpty()) {
        cmd.setSubstitutionMap(parameterSubstitutionMap);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Executing command: {}", cmd.toString());
    } else if (redirectOutputs) {
        logger.info("Executing command: ");
        logger.info(cmd.toString());
    }

    int exitValue = 0;

    StringOutputStream out = new StringOutputStream(redirectOutputs ? System.out : null);
    StringOutputStream err = new StringOutputStream(redirectOutputs ? System.err : null);
    try {
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(out, err));
        if (workingDir != null) {
            if (workingDir.exists() || workingDir.mkdirs()) {
                executor.setWorkingDirectory(workingDir);
            }
        }
        exitValue = executor.execute(cmd, System.getenv());
    } catch (ExecuteException ee) {
        return ee.getExitValue();
    } catch (Exception e) {
        throw new JahiaRuntimeException(e);
    } finally {
        if (resultErr != null) {
            resultErr.append(err.toString());
        }
        if (resultOut != null) {
            resultOut.append(out.toString());
        }
        if (exitValue > 0) {
            logger.error("External process finished with error. Cause: {}", err.toString());
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Execution took {} ms and finished with status {} and output {}",
                    new Object[] { (System.currentTimeMillis() - timer), exitValue, out.toString() });
        }
    }

    return exitValue;
}

From source file:org.jberet.support.io.OsCommandBatchlet.java

/**
 * {@inheritDoc}/*from   w ww  .  j a v a2 s .c o m*/
 * <p>
 * This method runs the OS command.
 * If the command completes successfully, its process exit code is returned.
 * If there is exception while running the OS command, which may be
 * caused by timeout, the command being stopped, or other errors, the process
 * exit code is set as the step exit status, and the exception is thrown.
 *
 * @return the OS command process exit code
 *
 * @throws Exception upon errors
 */
@Override
public String process() throws Exception {
    final DefaultExecutor executor = new DefaultExecutor();
    final CommandLine commandLineObj;
    if (commandLine != null) {
        commandLineObj = CommandLine.parse(commandLine);
    } else {
        if (commandArray == null) {
            throw SupportMessages.MESSAGES.invalidReaderWriterProperty(null, null, "commandArray");
        } else if (commandArray.isEmpty()) {
            throw SupportMessages.MESSAGES.invalidReaderWriterProperty(null, commandArray.toString(),
                    "commandArray");
        }
        commandLineObj = new CommandLine(commandArray.get(0));
        final int len = commandArray.size();
        if (len > 1) {
            for (int i = 1; i < len; i++) {
                commandLineObj.addArgument(commandArray.get(i));
            }
        }
    }

    if (workingDir != null) {
        executor.setWorkingDirectory(workingDir);
    }
    if (streamHandler != null) {
        executor.setStreamHandler((ExecuteStreamHandler) streamHandler.newInstance());
    }

    SupportLogger.LOGGER.runCommand(commandLineObj.getExecutable(),
            Arrays.toString(commandLineObj.getArguments()), executor.getWorkingDirectory().getAbsolutePath());

    if (commandOkExitValues != null) {
        executor.setExitValues(commandOkExitValues);
    }

    watchdog = new ExecuteWatchdog(
            timeoutSeconds > 0 ? timeoutSeconds * 1000 : ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchdog);

    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    executor.execute(commandLineObj, environment, resultHandler);
    resultHandler.waitFor();

    final ExecuteException exception = resultHandler.getException();
    if (exception != null) {
        stepContext.setExitStatus(String.valueOf(resultHandler.getExitValue()));
        if (!isStopped) {
            throw exception;
        } else {
            SupportLogger.LOGGER.warn("", exception);
        }
    }
    return String.valueOf(resultHandler.getExitValue());
}