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:drat.proteus.DratStartForm.java

private void parseAsVersionControlledRepo(String path, String command, boolean downloadPhase)
        throws IOException {
    if (!downloadPhase) {
        startDrat(path, command);/*from  w w  w.j  a  v a  2s  .  c o m*/
        return;
    }

    String projectName = null;
    boolean git = path.endsWith(".git");
    File tmpDir = new File(System.getProperty("java.io.tmpdir"));
    String tmpDirPath = tmpDir.getCanonicalPath();
    String line = null;
    if (git) {
        projectName = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("."));
        line = "git clone --depth 1 --branch master " + path;
    } else {
        projectName = path.substring(path.lastIndexOf("/") + 1);
        line = "svn export " + path;
    }
    String clonePath = tmpDirPath + File.separator + projectName;
    File cloneDir = new File(clonePath);
    if (cloneDir.isDirectory() && cloneDir.exists()) {
        LOG.info("Git / SVN clone: [" + clonePath + "] already exists, removing it.");
        FileUtils.removeDir(cloneDir);
    }
    LOG.info("Cloning Git / SVN project: [" + projectName + "] remote repo: [" + path + "] into " + tmpDirPath);

    CommandLine cmdLine = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(tmpDir);
    int exitValue = executor.execute(cmdLine);

    if (git) {
        String gitHiddenDirPath = clonePath + File.separator + ".git";
        File gitHiddenDir = new File(gitHiddenDirPath);
        LOG.info("Removing .git directory from " + gitHiddenDirPath);
        FileUtils.removeDir(gitHiddenDir);
    }

    startDrat(clonePath, command);

}

From source file:eu.crisis_economics.abm.dashboard.cluster.script.BashScheduler.java

/** {@inheritDoc} 
 * @throws SchedulerException /*from  ww  w  . j a  v  a  2s  .  c  o m*/
 */
@Override
public String runParameterSweep(final Model paramSweepConfig, final String timeLimit, final File workDir)
        throws SchedulerException {

    File file = null;
    try {
        //         file = File.createTempFile("paramsweep-", ".xml");
        file = new File(workDir, "paramsweep-config.xml");
        Marshaller marshaller = JAXBContext.newInstance(Model.class).createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(paramSweepConfig, file);
        //      } catch (IOException e) {
        //         throw new SchedulerException("Could not create temporary parameter-sweep configuration xml.", e);
    } catch (JAXBException e) {
        throw new SchedulerException(
                "Could not write temporary parameter-sweep configuration xml: " + file.toString(), e);
    }
    CommandLine cmd = new CommandLine(cmdFile);
    Map<String, Object> substitutions = new HashMap<String, Object>();
    substitutions.put(CMD_SUBSTITUTION_NAME_FILE, file);
    cmd.setSubstitutionMap(substitutions);

    if (timeLimit != null && !timeLimit.isEmpty()) {
        cmd.addArgument("-t", false);
        cmd.addArgument(timeLimit, false);
    }

    // add server port argument
    cmd.addArgument("-p", false);
    cmd.addArgument(String.valueOf(serverPort), false);

    cmd.addArgument("${" + CMD_SUBSTITUTION_NAME_FILE + "}", false);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(workDir);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(byteArrayOutputStream);

    executor.setStreamHandler(streamHandler);

    try {
        executor.execute(cmd);
    } catch (ExecuteException e) {
        throw new SchedulerException(
                paramSweepCmd + " exited with " + e.getExitValue() + ". Output:\n" + byteArrayOutputStream, e);
    } catch (IOException e) {
        throw new SchedulerException(
                "Execution of " + paramSweepCmd + " failed. Output:\n" + byteArrayOutputStream, e);
    }

    // the standard output of the script is the job id
    final String jobId = byteArrayOutputStream.toString();

    return jobId;
}

From source file:ch.ivyteam.ivy.maven.engine.EngineControl.java

private Executor createEngineExecutor() {
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(context.engineDirectory);
    return executor;
}

From source file:de.akquinet.innovation.play.maven.Play2CompilationMojo.java

public void execute() throws MojoExecutionException {

    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    cmdLine.addArgument("compile");
    DefaultExecutor executor = new DefaultExecutor();

    if (timeout > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        executor.setWatchdog(watchdog);/*ww  w  . j  av  a 2s  .  c  o  m*/
    }

    executor.setExitValue(0);
    executor.setWorkingDirectory(project.getBasedir());
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        throw new MojoExecutionException("Error during compilation", e);
    }
}

From source file:de.akquinet.innovation.play.maven.Play2TestMojo.java

public void execute() throws MojoExecutionException {

    if (isSkipExecution()) {
        getLog().info("Test phase skipped");
        return;/*  w  w w  .java  2  s .c  o  m*/
    }

    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    cmdLine.addArguments(getPlay2SystemPropertiesArguments(), false);
    cmdLine.addArgument("test");
    DefaultExecutor executor = new DefaultExecutor();

    if (timeout > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        executor.setWatchdog(watchdog);
    }

    executor.setWorkingDirectory(project.getBasedir());

    executor.setExitValue(0);
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        if (testFailureIgnore) {
            getLog().error("Test execution failures ignored");
        } else {
            throw new MojoExecutionException("Error during compilation", e);
        }
    }
}

From source file:com.sonar.scanner.api.it.tools.CommandExecutor.java

public int execute(String[] args, Map<String, String> env, @Nullable Path workingDir) throws IOException {
    if (!Files.isExecutable(file)) {
        Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(file, perms);
    }/*  ww w  . ja v  a 2s  .  com*/

    watchdog = new ExecuteWatchdog(TIMEOUT);
    CommandLine cmd = new CommandLine(file.toFile());
    cmd.addArguments(args, false);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setWatchdog(watchdog);
    exec.setStreamHandler(createStreamHandler());
    exec.setExitValues(null);
    if (workingDir != null) {
        exec.setWorkingDirectory(workingDir.toFile());
    }
    in.close();
    LOG.info("Executing: {}", cmd.toString());
    return exec.execute(cmd, env);
}

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * <pre>/*  www. j  av  a  2 s  .  c  om*/
 * Kill all the TG server processes.
 * Note that this method blindly tries to kill all the servers of the machine 
 * and do not update the running status of those servers.
 * - taskkill on Windows.
 * - kill -9 on Unix.
 * </pre>
 * 
 * @throws Exception Kill operation fails
 */
public static void killAll() throws Exception {

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(psh);
    executor.setWorkingDirectory(new File(System.getProperty("java.io.tmpdir")));
    CommandLine cmdLine;
    if (OS.isFamilyWindows())
        cmdLine = CommandLine.parse("taskkill /f /im " + process + ".exe");
    else { // Unix
        File internalScriptFile = new File(ClassLoader
                .getSystemResource(
                        TGServer.class.getPackage().getName().replace('.', '/') + "/TGKillProcessByName.sh")
                .getFile());
        File finalScriptFile = new File(executor.getWorkingDirectory() + "/" + internalScriptFile.getName());
        Files.copy(internalScriptFile.toPath(), finalScriptFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        cmdLine = CommandLine.parse("sh " + finalScriptFile.getAbsolutePath() + " " + process + "");
    }
    try {
        Thread.sleep(1000);
        executor.execute(cmdLine);
    } catch (ExecuteException ee) {
        if (output.toString().contains(
                "ERROR: The process \"" + process + (OS.isFamilyWindows() ? ".exe\"" : "") + " not found"))
            return;
        throw new ExecuteException(output.toString().trim(), 1); // re-throw with better message
    }
    // Check one more thing :
    // On Windows when some processes do not get killed taskkill still
    // returns exit code
    if (OS.isFamilyWindows()) {
        if (output.toString().contains("ERROR"))
            throw new ExecuteException(output.toString().trim(), 1);
    } else {
        if (output.toString().contains("ERROR: The process \"" + process + "\" not found"))
            return;
    }

    System.out.println("TGServer - Server(s) successfully killed :");
    if (!output.toString().equals(""))
        System.out.println("\t\t- " + output.toString().trim().replace("\n", "\n\t\t- "));
}

From source file:it.sonarlint.cli.tools.CommandExecutor.java

public int execute(String[] args, @Nullable Path workingDir, Map<String, String> addEnv) throws IOException {
    if (!Files.isExecutable(file)) {
        Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(file, perms);
    }/*from  w w w .ja  v a  2  s .co m*/

    ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
    CommandLine cmd = new CommandLine(file.toFile());
    cmd.addArguments(args);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setWatchdog(watchdog);
    exec.setStreamHandler(createStreamHandler());
    exec.setExitValues(null);
    if (workingDir != null) {
        exec.setWorkingDirectory(workingDir.toFile());
    }
    in.close();
    LOG.info("Executing: {}", cmd.toString());
    Map<String, String> env = new HashMap<>(System.getenv());
    env.putAll(addEnv);
    return exec.execute(cmd, env);
}

From source file:its.tools.CommandExecutor.java

public void execute(String[] args, @Nullable Path workingDir) throws IOException {
    if (!Files.isExecutable(file)) {
        Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(file, perms);
    }/*from www.j  a  va2s. c  om*/

    watchdog = new ExecuteWatchdog(TIMEOUT);
    CommandLine cmd = new CommandLine(file.toFile());
    cmd.addArguments(args);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setWatchdog(watchdog);
    exec.setStreamHandler(createStreamHandler());
    exec.setExitValues(null);
    if (workingDir != null) {
        exec.setWorkingDirectory(workingDir.toFile());
    }
    in.close();
    LOG.info("Executing: {}", cmd.toString());
    exec.execute(cmd, new ResultHander());
}

From source file:de.akquinet.innovation.play.maven.Play2CleanMojo.java

public void execute() throws MojoExecutionException {

    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    cmdLine.addArgument("clean");
    DefaultExecutor executor = new DefaultExecutor();

    if (timeout > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        executor.setWatchdog(watchdog);// w  ww.j av  a 2  s .co m
    }

    executor.setWorkingDirectory(project.getBasedir());
    executor.setExitValue(0);
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        throw new MojoExecutionException("Error during cleanup", e);
    }

    // Also delete the dist directory
    File dist = new File(project.getBasedir(), "dist");
    if (dist.exists()) {
        getLog().debug("Deleting " + dist.getAbsolutePath());
        try {
            FileUtils.deleteDirectory(dist);
        } catch (IOException e) {
            throw new MojoExecutionException("Can't delete the dist folder", e);
        }
    } else {
        getLog().debug("'dist' directory not found");
    }

    // Delete the log folder
    File logs = new File(project.getBasedir(), "logs");
    if (logs.exists()) {
        getLog().debug("Deleting " + logs.getAbsolutePath());
        try {
            FileUtils.deleteDirectory(logs);
        } catch (IOException e) {
            throw new MojoExecutionException("Can't delete the logs folder", e);
        }
    } else {
        getLog().debug("'logs' directory not found");
    }

    // Also delete the lib directory if set
    if (cleanLibFolder) {
        File lib = new File(project.getBasedir(), "lib");
        if (lib.exists()) {
            getLog().debug("Deleting " + lib.getAbsolutePath());
            try {
                FileUtils.deleteDirectory(lib);
            } catch (IOException e) {
                throw new MojoExecutionException("Can't delete the " + lib + " folder", e);
            }
        } else {
            getLog().debug("'" + lib + "' directory not found");
        }
    }
}