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.ng200.openolympus.cerberus.executors.JavaExecutor.java

@Override
public ExecutionResult execute(final Path program) throws IOException {

    final Path chrootRoot = this.storage.getPath().resolve("chroot");

    final Path chrootedProgram = chrootRoot.resolve(program.getFileName().toString());

    FileAccess.createDirectories(chrootedProgram);
    FileAccess.copyDirectory(program, chrootedProgram, StandardCopyOption.REPLACE_EXISTING,
            StandardCopyOption.COPY_ATTRIBUTES);

    final Path outOfMemoryFile = chrootRoot.resolve("outOfMemory");

    final Path policyFile = this.storage.getPath().resolve("olymp.policy");

    try (Stream<Path> paths = FileAccess.walkPaths(storage.getPath())) {
        paths.forEach(path -> {/* ww  w. ja v a  2 s.c  om*/
            try {
                Files.setPosixFilePermissions(path,
                        new HashSet<PosixFilePermission>(
                                Lists.from(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ,
                                        PosixFilePermission.OWNER_WRITE, PosixFilePermission.GROUP_EXECUTE,
                                        PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_WRITE,
                                        PosixFilePermission.OTHERS_EXECUTE, PosixFilePermission.OTHERS_READ)));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }

    this.buildPolicy(chrootRoot, policyFile);

    final CommandLine commandLine = new CommandLine("sudo");
    commandLine.addArgument("olympus_watchdog");

    this.setUpOlrunnerLimits(commandLine);

    commandLine.addArgument("--security=0");
    commandLine.addArgument("--jail=/");

    commandLine.addArgument("--");

    commandLine.addArgument("/usr/bin/java");

    commandLine.addArgument("-classpath");
    commandLine.addArgument(chrootedProgram.toAbsolutePath().toString());
    commandLine.addArgument("-Djava.security.manager");
    commandLine.addArgument("-Djava.security.policy=" + policyFile.toAbsolutePath().toString());

    commandLine.addArgument("-Xmx" + this.getMemoryLimit());
    commandLine.addArgument("-Xms" + this.getMemoryLimit());

    commandLine.addArgument(MessageFormat.format("-XX:OnOutOfMemoryError=touch {0}; echo \"\" > {0}",
            outOfMemoryFile.toAbsolutePath().toString()), false);

    commandLine.addArgument("Main");

    final DefaultExecutor executor = new DefaultExecutor();

    executor.setWatchdog(new ExecuteWatchdog(20000)); // 20 seconds for the
    // sandbox to
    // complete
    executor.setWorkingDirectory(chrootRoot.toFile());

    executor.setStreamHandler(new PumpStreamHandler(this.outputStream, this.errorStream, this.inputStream));
    try {
        executor.execute(commandLine);
    } catch (final IOException e) {
        if (!e.getMessage().toLowerCase().equals("stream closed")) {
            throw e;
        }
    }
    final ExecutionResult readOlrunnerVerdict = this.readOlrunnerVerdict(chrootRoot.resolve("verdict.txt"));

    if (FileAccess.exists(outOfMemoryFile)) {
        readOlrunnerVerdict.setResultType(ExecutionResultType.MEMORY_LIMIT);
    }

    readOlrunnerVerdict.setMemoryPeak(this.getMemoryLimit());

    return readOlrunnerVerdict;
}

From source file:org.ng200.openolympus.cerberus.executors.SandboxedExecutor.java

@Override
public ExecutionResult execute(final Path program) throws IOException {
    SandboxedExecutor.logger.debug("Copying program into jail");
    final Path chrootedProgram = this.storage.getPath().resolve("chroot")
            .resolve(program.getFileName().toString());
    chrootedProgram.getParent().toFile().mkdirs();
    FileAccess.copy(program, chrootedProgram, StandardCopyOption.COPY_ATTRIBUTES);

    final CommandLine commandLine = new CommandLine("sudo");
    commandLine.addArgument("olympus_watchdog");

    this.setUpOlrunnerLimits(commandLine);

    commandLine.addArgument(MessageFormat.format("--jail={0}",
            this.storage.getPath().resolve("chroot").toAbsolutePath().toString()));

    commandLine.addArgument("--");
    commandLine//  w  w  w.  j av a  2 s.c  o m
            .addArgument("/" + this.storage.getPath().resolve("chroot").relativize(chrootedProgram).toString());

    final DefaultExecutor executor = new DefaultExecutor();

    executor.setExitValue(0);

    executor.setWatchdog(new ExecuteWatchdog(60000)); // 60 seconds for the
    // sandbox to
    // complete

    executor.setWorkingDirectory(this.storage.getPath().toFile());

    executor.setStreamHandler(new PumpStreamHandler(this.outputStream, this.errorStream, this.inputStream));

    SandboxedExecutor.logger.debug("Executing in sandbox: {}", commandLine.toString());
    try {
        executor.execute(commandLine);
    } catch (final ExecuteException e) {
        SandboxedExecutor.logger.info("Execution failed: {}", e);
        throw e;
    } catch (final IOException e) {
        if (!e.getMessage().toLowerCase().equals("stream closed")) {
            throw e;
        }
    }

    return this.readOlrunnerVerdict(this.storage.getPath().resolve("verdict.txt"));
}

From source file:org.onehippo.forge.gallerymagick.core.command.AbstractMagickCommand.java

/**
 * Execute the Magick command with the sub-command and arguments.
 * @param stdOut standard output stream/*from   www  .  ja v  a 2  s .co m*/
 * @throws MagickExecuteException if an execution exception occurs
 * @throws IOException if IO exception occurs
 */
public void execute(final OutputStream stdOut) throws IOException {
    CommandLine cmdLine = createCommandLine();
    ByteArrayOutputStream errStream = null;
    int exitValue = 0;
    DefaultExecuteResultHandler resultHandler = null;

    try {
        errStream = new ByteArrayOutputStream(512);

        final DefaultExecutor executor = new DefaultExecutor();
        ExecuteStreamHandler streamHandler;

        if (stdOut != null) {
            streamHandler = new PumpStreamHandler(stdOut, errStream);
        } else {
            streamHandler = new PumpStreamHandler(System.out, errStream);
        }

        executor.setStreamHandler(streamHandler);

        if (getWorkingDirectory() != null) {
            executor.setWorkingDirectory(getWorkingDirectory());
        }

        long timeout = NumberUtils.toLong(System.getProperty(PROP_TIMEOUT), DEFAULT_COMMAND_TIMEOUT);

        if (timeout > 0) {
            ExecuteWatchdog watchdog = new ExecuteWatchdog(DEFAULT_COMMAND_TIMEOUT);
            executor.setWatchdog(watchdog);
            resultHandler = new DefaultExecuteResultHandler();
            executor.execute(cmdLine, resultHandler);
            log.debug("Executed with watchdog: {}", cmdLine);
            resultHandler.waitFor();
        } else {
            exitValue = executor.execute(cmdLine);
            log.debug("Executed without watchdog: {}", cmdLine);
        }
    } catch (ExecuteException | InterruptedException e) {
        if (resultHandler != null) {
            exitValue = resultHandler.getExitValue();
        }
        if (e.getCause() == null) {
            throw new MagickExecuteException(getExecutionErrorMessage(cmdLine, errStream, e), exitValue);
        } else {
            throw new MagickExecuteException(getExecutionErrorMessage(cmdLine, errStream, e), exitValue,
                    e.getCause());
        }
    } finally {
        IOUtils.closeQuietly(errStream);
    }
}

From source file:org.sonatype.sisu.bl.support.DefaultDropwizardBundle.java

@Override
protected void startApplication() {
    File bundleDirectory = getBundleDirectory();
    List<String> javaOptions = getConfiguration().getJavaOptions();
    List<String> javaAgentOptions = getJavaAgentOptions();

    CommandLine cmdLine = new CommandLine(new File(System.getProperty("java.home"), "/bin/java"));
    if (javaAgentOptions.size() > 0) {
        cmdLine.addArguments(javaAgentOptions.toArray(new String[javaAgentOptions.size()]));
    }//from   w  ww  . ja v  a  2  s . co m
    if (javaOptions.size() > 0) {
        cmdLine.addArguments(javaOptions.toArray(new String[javaOptions.size()]));
    }
    cmdLine.addArgument("-jar").addArgument(getJarName()).addArguments(getConfiguration().arguments())
            .addArgument("config.yaml");

    log.debug("Launching: {}", cmdLine.toString());

    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(bundleDirectory);
    executor.setWatchdog(watchdog = new ExecuteWatchdog(Time.minutes(5).toMillis()));

    try {
        executor.setStreamHandler(streamHandler = new PumpStreamHandler(
                new FileOutputStream(new File(bundleDirectory, "output.log"))));
        executor.execute(cmdLine, new DefaultExecuteResultHandler());
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.springframework.data.release.io.CommonsExecOsCommandOperations.java

private Future<CommandResult> executeCommand(String command, File executionDirectory, boolean silent)
        throws IOException {

    StringWriter writer = new StringWriter();
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    try (WriterOutputStream outputStream = new WriterOutputStream(writer)) {

        String outerCommand = "/bin/bash -lc";

        CommandLine outer = CommandLine.parse(outerCommand);
        outer.addArgument(command, false);

        DefaultExecutor executor = new DefaultExecutor();
        executor.setWorkingDirectory(executionDirectory);
        executor.setStreamHandler(new PumpStreamHandler(silent ? outputStream : System.out, null));
        executor.execute(outer, ENVIRONMENT, resultHandler);

        resultHandler.waitFor();/*from   w ww.  j  av  a  2s .  c om*/

    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }

    return new AsyncResult<CommandResult>(
            new CommandResult(resultHandler.getExitValue(), writer.toString(), resultHandler.getException()));
}

From source file:org.stem.ExternalNode.java

private DefaultExecuteResultHandler startStemProcess(CommandLine commandLine, Map env)
        throws MojoExecutionException {
    try {//from   www  .ja va 2  s.  c o m
        DefaultExecutor exec = new DefaultExecutor();
        DefaultExecuteResultHandler execHandler = new DefaultExecuteResultHandler();
        exec.setWorkingDirectory(nodeDir);
        exec.setProcessDestroyer(new ShutdownHookProcessDestroyer());

        LogOutputStream stdout = new MavenLogOutputStream(log);
        LogOutputStream stderr = new MavenLogOutputStream(log);

        log.debug("Executing command line: " + commandLine);

        PumpStreamHandler streamHandler = new PumpStreamHandler(stdout, stderr);
        streamHandler.start();
        exec.setStreamHandler(streamHandler);

        exec.execute(commandLine, env, execHandler);
        //            try
        //            {
        //                execHandler.waitFor();
        //            }
        //            catch (InterruptedException e)
        //            {
        //                e.printStackTrace();
        //            }
        return execHandler;
    } catch (IOException e) {
        throw new MojoExecutionException("Command execution failed.", e);
    }
}

From source file:org.wisdom.maven.node.NPM.java

/**
 * Executes the current NPM./*from w ww  .j a v a  2  s.c om*/
 * NPM can have several executable attached to them, so the 'binary' argument specifies which
 * one has to be executed. Check the 'bin' entry of the package.json file to determine which
 * one you need. 'Binary' is the key associated with the executable to invoke. For example, in
 * <code>
 * <pre>
 *      "bin": {
 *           "coffee": "./bin/coffee",
 *           "cake": "./bin/cake"
 *      },
 *     </pre>
 * </code>
 * <p/>
 * we have two alternatives: 'coffee' and 'cake'.
 *
 * @param binary the key of the binary to invoke
 * @param args   the arguments
 * @return the execution exit status
 * @throws MojoExecutionException if the execution failed
 */
public int execute(String binary, String... args) throws MojoExecutionException {
    File destination = getNPMDirectory();
    if (!destination.isDirectory()) {
        throw new IllegalStateException("The npm module " + this.npmName + " is not installed");
    }

    CommandLine cmdLine = new CommandLine(node.getNodeExecutable());
    File npmExec = null;
    try {
        npmExec = findExecutable(binary);
    } catch (IOException | ParseException e) { //NOSONAR
        log.error(e);
    }
    if (npmExec == null) {
        throw new IllegalStateException(
                "Cannot execute NPM " + this.npmName + " - cannot find the JavaScript file " + "matching "
                        + binary + " in the " + PACKAGE_JSON + " file");
    }

    // NPM is launched using the main file.
    cmdLine.addArgument(npmExec.getAbsolutePath(), false);
    for (String arg : args) {
        cmdLine.addArgument(arg, this.handleQuoting);
    }

    DefaultExecutor executor = new DefaultExecutor();

    executor.setExitValue(0);

    errorStreamFromLastExecution = new LoggedOutputStream(log, true, true);
    outputStreamFromLastExecution = new LoggedOutputStream(log, false, registerOutputStream);
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStreamFromLastExecution,
            errorStreamFromLastExecution);

    executor.setStreamHandler(streamHandler);
    executor.setWorkingDirectory(node.getWorkDir());
    log.info("Executing " + cmdLine.toString() + " from " + executor.getWorkingDirectory().getAbsolutePath());

    try {
        return executor.execute(cmdLine, extendEnvironmentWithNodeInPath(node));
    } catch (IOException e) {
        throw new MojoExecutionException("Error during the execution of the NPM " + npmName, e);
    }

}

From source file:org.wisdom.maven.node.NPM.java

/**
 * Executes the current NPM using the given binary file.
 *
 * @param binary the program to run//from  w w  w  .j  av a 2  s . c  o  m
 * @param args   the arguments
 * @return the execution exit status
 * @throws MojoExecutionException if the execution failed
 */
public int execute(File binary, String... args) throws MojoExecutionException {
    File destination = getNPMDirectory();
    if (!destination.isDirectory()) {
        throw new IllegalStateException("NPM " + this.npmName + " not installed");
    }

    CommandLine cmdLine = new CommandLine(node.getNodeExecutable());

    if (binary == null) {
        throw new IllegalStateException(
                "Cannot execute NPM " + this.npmName + " - the given binary is 'null'.");
    }

    if (!binary.isFile()) {
        throw new IllegalStateException("Cannot execute NPM " + this.npmName + " - the given binary does not "
                + "exist: " + binary.getAbsoluteFile() + ".");
    }

    // NPM is launched using the main file.
    cmdLine.addArgument(binary.getAbsolutePath(), false);
    for (String arg : args) {
        cmdLine.addArgument(arg, this.handleQuoting);
    }

    DefaultExecutor executor = new DefaultExecutor();

    executor.setExitValue(0);

    errorStreamFromLastExecution = new LoggedOutputStream(log, true, true);
    outputStreamFromLastExecution = new LoggedOutputStream(log, false, registerOutputStream);

    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStreamFromLastExecution,
            errorStreamFromLastExecution);

    executor.setStreamHandler(streamHandler);
    executor.setWorkingDirectory(node.getWorkDir());
    log.info("Executing " + cmdLine.toString() + " from " + executor.getWorkingDirectory().getAbsolutePath());

    try {
        return executor.execute(cmdLine, extendEnvironmentWithNodeInPath(node));
    } catch (IOException e) {
        throw new MojoExecutionException("Error during the execution of the NPM " + npmName, e);
    }

}

From source file:org.wisdom.maven.utils.WisdomExecutor.java

/**
 * Launches the Wisdom server. This method blocks until the wisdom server shuts down.
 * It uses the {@literal Java} executable directly.
 *
 * @param mojo        the mojo//from   www.  j  av  a 2  s.co m
 * @param interactive enables the shell prompt
 * @param debug       the debug port (0 to disable it)
 * @param jvmArgs     JVM arguments to add to the `java` command (before the -jar argument).
 * @param destroyer   a process destroyer that can be used to destroy the process, if {@code null}
 *                    a {@link org.apache.commons.exec.ShutdownHookProcessDestroyer} is used.
 * @throws MojoExecutionException if the Wisdom instance cannot be started or has thrown an unexpected status
 *                                while being stopped.
 */
public void execute(AbstractWisdomMojo mojo, boolean interactive, int debug, String jvmArgs,
        ProcessDestroyer destroyer) throws MojoExecutionException {
    // Get java
    File java = ExecUtils.find("java", new File(mojo.javaHome, "bin"));
    if (java == null) {
        throw new MojoExecutionException("Cannot find the java executable");
    }

    CommandLine cmdLine = new CommandLine(java);

    if (debug != 0) {
        cmdLine.addArgument("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=" + debug, false);
    }

    if (!Strings.isNullOrEmpty(jvmArgs)) {
        cmdLine.addArguments(jvmArgs, false);
    }

    cmdLine.addArgument("-jar");
    cmdLine.addArgument("bin/chameleon-core-" + CHAMELEON_VERSION + ".jar");
    if (interactive) {
        cmdLine.addArgument("--interactive");
    }

    appendSystemPropertiesToCommandLine(mojo, cmdLine);

    DefaultExecutor executor = new DefaultExecutor();
    if (destroyer != null) {
        executor.setProcessDestroyer(destroyer);
    } else {
        executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    }

    executor.setWorkingDirectory(mojo.getWisdomRootDirectory());
    if (interactive) {
        executor.setStreamHandler(new PumpStreamHandler(System.out, System.err, System.in)); //NOSONAR
        // Using the interactive mode the framework should be stopped using the 'exit' command,
        // and produce a '0' status.
        executor.setExitValue(0);
    } else {
        executor.setStreamHandler(new PumpStreamHandler(System.out, System.err)); // NOSONAR
        // As the execution is intended to be interrupted using CTRL+C, the status code returned is expected to be 1
        // 137 or 143 is used when stopped by the destroyer.
        executor.setExitValues(new int[] { 1, 137, 143 });
    }
    try {
        mojo.getLog().info("Launching Wisdom Server");
        mojo.getLog().debug("Command Line: " + cmdLine.toString());
        // The message is different whether or not we are in the interactive mode.
        if (interactive) {
            mojo.getLog().info("You are in interactive mode");
            mojo.getLog().info("Hit 'exit' to shutdown");
        } else {
            mojo.getLog().info("Hit CTRL+C to exit");
        }
        if (debug != 0) {
            mojo.getLog().info("Wisdom launched with remote debugger interface enabled on port " + debug);
        }
        // Block execution until ctrl+c
        executor.execute(cmdLine);
    } catch (IOException e) {
        throw new MojoExecutionException("Cannot execute Wisdom", e);
    }
}

From source file:org.wso2.ppaas.configurator.tests.ConfiguratorTestManager.java

/**
 * Execute shell command/*from  w  ww. j  a v  a  2s. com*/
 *
 * @param commandText
 */
protected int executeCommand(final String commandText, Map<String, String> environment) {
    final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal();
    int result;
    try {
        CommandLine commandline = CommandLine.parse(commandText);
        DefaultExecutor exec = new DefaultExecutor();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        exec.setWorkingDirectory(new File(ConfiguratorTestManager.class.getResource(PATH_SEP).getPath() + ".."
                + PATH_SEP + CONFIGURATOR_DIR_NAME));
        exec.setStreamHandler(streamHandler);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
        exec.setWatchdog(watchdog);
        result = exec.execute(commandline, environment);

    } catch (Exception e) {
        log.error(outputStream.toString(), e);
        throw new RuntimeException(e);
    }
    return result;
}