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

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

Introduction

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

Prototype

void setWorkingDirectory(File dir);

Source Link

Document

Set the working directory of the created process.

Usage

From source file:com.zxy.commons.exec.CmdExecutor.java

/**
 * //w w  w.  j  a va 2 s  .  c  o m
 * 
 * @param workHome workHome
 * @param command command
 * @return ???
 * @throws InterruptedException InterruptedException
 * @throws IOException IOException
 */
public static ExecutorResult exec(String workHome, String command) throws InterruptedException, IOException {
    CommandLine cmdLine = CommandLine.parse(PRE_CMD + command);
    Executor executor = new DefaultExecutor();
    executor.setWorkingDirectory(new File(workHome));

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream);
    executor.setStreamHandler(streamHandler);

    int code = executor.execute(cmdLine, EnvironmentUtils.getProcEnvironment());
    String successMsg = outputStream.toString(ENCODING);
    String errorMsg = errorStream.toString(ENCODING);
    return new ExecutorResult(code, successMsg, errorMsg);
}

From source file:com.zxy.commons.exec.CmdExecutor.java

/**
 * //from  www.  ja  v a2 s.co  m
 * 
 * @param workHome workHome
 * @param command command
 * @throws InterruptedException InterruptedException
 * @throws IOException IOException
 */
public static void execAsyc(String workHome, String command) throws InterruptedException, IOException {
    CommandLine cmdLine = CommandLine.parse(PRE_CMD + command);
    Executor executor = new DefaultExecutor();
    executor.setWorkingDirectory(new File(workHome));

    executor.setStreamHandler(new PumpStreamHandler(new LogOutputStream() {
        @Override
        protected void processLine(String line, int level) {
            LOGGER.debug(line);
        }
    }, new LogOutputStream() {
        @Override
        protected void processLine(String line, int level) {
            LOGGER.debug(line);
        }
    }));

    ExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    executor.execute(cmdLine, EnvironmentUtils.getProcEnvironment(), resultHandler);
    // resultHandler.waitFor();
}

From source file:com.jivesoftware.os.jive.utils.shell.utils.Invoke.java

public static int invoke(File home, String[] command, final InputStream writeToProcess,
        final ConcurrentLinkedQueue<String> response) throws Exception {
    Executor executor = new DefaultExecutor();
    executor.setExitValue(0);//from   w ww  . j  a  va 2s .co  m
    if (home != null) {
        executor.setWorkingDirectory(home);
    }

    //give all the processes 120s to return that they started successfully
    ExecuteWatchdog watchdog = new ExecuteWatchdog(120000);
    executor.setWatchdog(watchdog);

    LogOutputStream outputStream = new LogOutputStream(20000) {
        @Override
        protected void processLine(final String line, final int level) {
            response.add(line);
        }
    };

    LogOutputStream errorStream = new LogOutputStream(40000) {
        @Override
        protected void processLine(final String line, final int level) {
            response.add(line);
        }
    };

    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, errorStream, writeToProcess);
    executor.setStreamHandler(pumpStreamHandler);
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());

    CommandLine commandLine = new CommandLine(command[0]);
    for (int i = 1; i < command.length; i++) {
        commandLine.addArgument(command[i]);
    }
    try {
        //executor.execute(commandLine, handler);
        return executor.execute(commandLine);
        //handler.waitFor(20000);
    } catch (Exception x) {
        x.printStackTrace();
        return 1;
    }
}

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

/**
 * Invoke TG admin synchronously. /*from   ww  w. j a  v a  2 s .c  om*/
 * Admin operation blocks until it is completed.
 * 
 * @param tgHome TG admin home
 * @param url Url to connect to TG server
 * @param user System User name
 * @param pwd System User password
 * @param logFile TG admin log file location - Generated by admin
 * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
 * @param cmd TG admin command file or command string
 * @param memSize Specify the maximum memory usage (MB). -1 for default (8 MB)
 * @param timeout Number of milliseconds allowed to complete admin operation
 * 
 * @return Output console of admin operation 
 * @throws TGAdminException Admin execution fails or timeout occurs 
 */
public static String invoke(String tgHome, String url, String user, String pwd, String logFile, String logLevel,
        String cmd, int memSize, long timeout) throws TGAdminException {
    if (tgHome == null)
        throw new TGAdminException("TGAdmin - TGDB home is not defined");
    File ftgHome = new File(tgHome);
    if (!ftgHome.exists())
        throw new TGAdminException("TGAdmin - TGDB home '" + tgHome + "' does not exist");

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    Executor tgExec = new DefaultExecutor();
    tgExec.setStreamHandler(psh);
    tgExec.setWorkingDirectory(new File(tgHome + "/bin"));

    CommandLine tgCL = new CommandLine((new File(tgHome + "/bin/" + process)).getAbsolutePath());

    // Define arguments
    List<String> args = new ArrayList<String>();
    if (url != null) {
        args.add("--url");
        args.add(url);
    }
    if (user != null) {
        args.add("--uid");
        args.add(user);
    }
    if (pwd != null) {
        args.add("--pwd");
        args.add(pwd);
    }
    if (logFile != null) {
        args.add("--log");
        args.add(logFile);
    }
    if (logLevel != null) {
        args.add("--log-level");
        args.add(logLevel);
    }
    if (memSize >= 0) {
        args.add("--max-memory");
        args.add(Integer.toString(memSize));
    }

    File cmdFile = null;
    if (cmd == null)
        throw new TGAdminException("TGAdmin - Command is required.");
    if (cmd.matches(
            "(?s)^(kill|show|describe|create|stop|info|checkpoint|dump|set|connect|disconnect|export|import|exit).*$")) {
        try {
            cmdFile = new File(tgHome + "/invokeAdminScript.txt");
            Files.write(Paths.get(cmdFile.toURI()), cmd.getBytes(StandardCharsets.UTF_8));
        } catch (IOException ioe) {
            throw new TGAdminException("TGAdmin - " + ioe.getMessage());
        }
    } else {
        cmdFile = new File(cmd);
    }

    if (!cmdFile.exists()) {
        throw new TGAdminException("TGAdmin - Command file '" + cmdFile + "' does not exist");
    }
    args.add("--file");
    args.add(cmdFile.getAbsolutePath());

    tgCL.addArguments((String[]) args.toArray(new String[args.size()]));

    ExecuteWatchdog tgWatch = new ExecuteWatchdog(timeout);
    tgExec.setWatchdog(tgWatch);
    System.out.println("TGAdmin - Invoking " + StringUtils.toString(tgCL.toStrings(), " "));

    long endProcTime = 0;
    long totalProcTime = 0;
    try {
        TGAdmin.startProcTime = System.currentTimeMillis();
        tgExec.execute(tgCL);
        endProcTime = System.currentTimeMillis();
    } catch (IOException ee) {
        if (tgWatch.killedProcess())
            throw new TGAdminException("TGAdmin - Operation did not complete within " + timeout + " ms",
                    output.toString());
        else {
            try {
                Thread.sleep(1000); // make sure output has time to fill up
            } catch (InterruptedException ie) {
                ;
            }
            throw new TGAdminException("TGAdmin - Execution failed: " + ee.getMessage(), output.toString());
        }
    }
    if (url != null && !output.toString().contains("Successfully connected to server"))
        throw new TGAdminException("TGAdmin - Admin could not connect to server " + url + " with user " + user,
                output.toString());
    if (endProcTime != 0)
        totalProcTime = endProcTime - TGAdmin.startProcTime;
    if (TGAdmin.showOperationBanner)
        System.out.println(
                "TGAdmin - Operation completed" + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : ""));
    return output.toString();
}

From source file:com.github.mjeanroy.maven.plugins.node.commands.CommandExecutor.java

/**
 * Execute command line and return the result status.
 *
 * @param workingDirectory Working directory (i.e where the command line is executed).
 * @param command Command, containing executable path with arguments.
 * @param logger Logger to use to log command output.
 * @return Command result object.//from  ww  w .  java2s  .c om
 */
public CommandResult execute(File workingDirectory, Command command, Log logger) {
    CommandLine commandLine = new CommandLine(command.getExecutable());
    for (String argument : command.getArguments()) {
        commandLine.addArgument(argument);
    }

    try {
        Executor executor = new DefaultExecutor();
        executor.setWorkingDirectory(workingDirectory);
        executor.setExitValue(0);

        // Define custom output stream
        LogStreamHandler stream = new LogStreamHandler(logger);
        PumpStreamHandler handler = new PumpStreamHandler(stream);
        executor.setStreamHandler(handler);

        int status = executor.execute(commandLine);
        return new CommandResult(status);
    } catch (ExecuteException ex) {
        return new CommandResult(ex.getExitValue());
    } catch (IOException ex) {
        throw new CommandException(ex);
    }
}

From source file:com.github.peterjanes.node.NpmPackMojo.java

/**
 *
 * @throws MojoExecutionException if anything unexpected happens.
 *///from   w  w  w.  j a  va 2s .c  o  m
public void execute() throws MojoExecutionException {
    if (!outputDirectory.exists()) {
        outputDirectory.mkdirs();
    }

    CommandLine commandLine = new CommandLine(executable);
    Executor exec = new DefaultExecutor();
    exec.setWorkingDirectory(outputDirectory);

    List commandArguments = new ArrayList();
    commandArguments.add("pack");
    commandArguments.add("./commonjs");

    String[] args = new String[commandArguments.size()];
    for (int i = 0; i < commandArguments.size(); i++) {
        args[i] = (String) commandArguments.get(i);
    }

    commandLine.addArguments(args, false);

    OutputStream stdout = System.out;
    OutputStream stderr = System.err;

    try {
        getLog().debug("Executing command line: " + commandLine);
        exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in));

        int resultCode = exec.execute(commandLine);

        if (0 != resultCode) {
            throw new MojoExecutionException(
                    "Result of " + commandLine + " execution is: '" + resultCode + "'.");
        }

        Artifact artifact = mavenProject.getArtifact();
        String fileName = String.format("%s-%s.tgz", artifact.getArtifactId(),
                mavenProject.getProperties().getProperty("node.project.version"));
        artifact.setFile(new File(outputDirectory, fileName));
    } catch (ExecuteException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);
    } catch (IOException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);
    }
}

From source file:com.github.peterjanes.node.NpmTestMojo.java

/**
 *
 * @throws MojoExecutionException if anything unexpected happens.
 *//* ww w. j a va 2 s .  c om*/
public void execute() throws MojoExecutionException {
    if (!workingDirectory.exists()) {
        workingDirectory.mkdirs();
    }

    CommandLine commandLine = new CommandLine(executable);
    Executor exec = new DefaultExecutor();
    exec.setWorkingDirectory(workingDirectory);

    Map env = new HashMap();
    try {
        Map systemEnvVars = EnvironmentUtils.getProcEnvironment();
        env.putAll(systemEnvVars);
    } catch (IOException e) {
        getLog().error("Could not assign default system enviroment variables.", e);
    }
    env.put("NODE_PATH", new File(workingDirectory, "node_modules").getAbsolutePath());
    env.put("XUNIT_FILE", outputFile.getAbsolutePath());

    List commandArguments = new ArrayList();
    commandArguments.add("test");

    String[] args = new String[commandArguments.size()];
    for (int i = 0; i < commandArguments.size(); i++) {
        args[i] = (String) commandArguments.get(i);
    }

    commandLine.addArguments(args, false);

    OutputStream stdout = System.out;
    OutputStream stderr = System.err;

    try {
        outputFile.getParentFile().mkdirs();
        getLog().debug("Executing command line " + commandLine + " in directory "
                + workingDirectory.getAbsolutePath());
        exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in));

        int resultCode = exec.execute(commandLine, env);

        if (0 != resultCode) {
            throw new MojoExecutionException(
                    "Result of " + commandLine + " execution is: '" + resultCode + "'.");
        }
    } catch (ExecuteException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);

    } catch (IOException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);
    }
}

From source file:com.github.peterjanes.node.AbstractNpmInstallMojo.java

/**
 *
 * @param outputDirectory The working directory for the npm command.
 * @param npmDependencies A comma-separated list of npm packages to install.
 * @param extraArguments Extra arguments to provide to the npm command.
 * @param artifactScope Scope of the artifacts to include.
 * @throws MojoExecutionException if anything unexpected happens.
 *//*from  www  .  j a  v a 2s  . com*/
void execute(File outputDirectory, String npmDependencies, String extraArguments, ResolutionScope artifactScope)
        throws MojoExecutionException {
    if (!outputDirectory.exists()) {
        outputDirectory.mkdirs();
    }

    CommandLine commandLine = new CommandLine(executable);
    Executor exec = new DefaultExecutor();
    exec.setWorkingDirectory(outputDirectory);

    List commandArguments = new ArrayList();
    commandArguments.add("install");

    if (null != npmDependencies) {
        String[] packages = npmDependencies.split(",");
        for (String pkg : packages) {
            commandArguments.add(pkg);
        }
    }

    List<Artifact> nodeArtifacts = getNodeArtifacts(artifactScope);
    for (Artifact artifact : nodeArtifacts) {
        commandArguments.add(artifact.getFile().getAbsolutePath());
    }

    if (null != extraArguments) {
        String[] extraArgs = extraArguments.split(" ");
        for (String extraArg : extraArgs) {
            commandArguments.add(extraArg);
        }
    }

    String[] args = new String[commandArguments.size()];
    for (int i = 0; i < commandArguments.size(); i++) {
        args[i] = (String) commandArguments.get(i);
    }

    commandLine.addArguments(args, false);

    OutputStream stdout = getLog().isDebugEnabled() ? System.err : new ByteArrayOutputStream();
    OutputStream stderr = getLog().isDebugEnabled() ? System.err : new ByteArrayOutputStream();

    try {
        getLog().debug(
                "Executing command line " + commandLine + " in directory " + outputDirectory.getAbsolutePath());
        exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in));

        int resultCode = exec.execute(commandLine);

        if (0 != resultCode) {
            System.out.println("STDOUT: " + stdout);
            System.err.println("STDERR: " + stderr);
            throw new MojoExecutionException(
                    "Result of " + commandLine + " execution is: '" + resultCode + "'.");
        }
    } catch (ExecuteException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);

    } catch (IOException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);
    }
}

From source file:com.github.shyiko.hmp.AbstractHadoopMojo.java

protected void executeCommand(HadoopSettings hadoopSettings, String command, String automaticResponseOnPrompt,
        boolean bindProcessDestroyerToShutdownHook) throws IOException {
    if (getLog().isDebugEnabled()) {
        getLog().debug("Executing " + command);
    }/*w  ww  .j ava 2 s. c o m*/
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(new ExecutionStreamHandler(quiet, automaticResponseOnPrompt));
    executor.setWorkingDirectory(hadoopSettings.getHomeDirectory());
    if (bindProcessDestroyerToShutdownHook) {
        executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    }
    executor.execute(CommandLine.parse(command), hadoopSettings.getEnvironment());
}

From source file:de.torstenwalter.maven.plugins.SQLPlusMojo.java

private void runScriptWithSqlPlus(File file, Map environment)
        throws MojoExecutionException, MojoFailureException {
    checkFileIsReadable(file);/* ww  w .  j a va2  s .c  o m*/

    CommandLine commandLine = new CommandLine(sqlplus);
    // logon only once, without this sql*plus would prompt for
    // credentials if given ones are not correct
    commandLine.addArgument("-L");
    StringTokenizer stringTokenizer = new StringTokenizer(getConnectionIdentifier());
    while (stringTokenizer.hasMoreTokens()) {
        commandLine.addArgument(stringTokenizer.nextToken());
    }
    commandLine.addArgument("@" + file.getName());
    if (arguments != null) {
        for (Object argument : arguments) {
            if (argument == null) {
                throw new MojoExecutionException("Misconfigured argument, value is null. "
                        + "Set the argument to an empty value if this is the required behaviour.");
            } else {
                commandLine.addArgument(argument.toString());
            }
        }
    }

    getLog().info("Executing command line: " + obfuscateCredentials(commandLine.toString(), getCredentials()));

    Executor exec = new DefaultExecutor();
    exec.setWorkingDirectory(file.getParentFile());
    exec.setStreamHandler(new PumpStreamHandler(System.out, System.err));
    try {
        exec.execute(commandLine, environment);
    } catch (ExecuteException e) {
        throw new MojoExecutionException("program exited with exitCode: " + e.getExitValue());
    } catch (IOException e) {
        throw new MojoExecutionException("Command execution failed.", e);
    }
}