Example usage for java.lang ProcessBuilder directory

List of usage examples for java.lang ProcessBuilder directory

Introduction

In this page you can find the example usage for java.lang ProcessBuilder directory.

Prototype

File directory

To view the source code for java.lang ProcessBuilder directory.

Click Source Link

Usage

From source file:org.opencms.workplace.tools.sites.CmsSitesWebserverThread.java

/**
 * Executes the webserver script.<p>
 *
 * @throws IOException if something goes wrong
 * @throws InterruptedException if something goes wrong
 *//*w  w  w .  j  a v  a 2s. c  o m*/
private void executeScript() throws IOException, InterruptedException {

    File script = new File(m_scriptPath);
    List<String> params = new LinkedList<String>();
    params.add(script.getAbsolutePath());
    params.addAll(m_writtenFiles);
    ProcessBuilder pb = new ProcessBuilder(params.toArray(new String[params.size()]));
    pb.directory(new File(script.getParent()));
    Process pr = pb.start();
    pr.waitFor();
    BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    while (buf.ready()) {
        String line = buf.readLine();
        if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(line)) {
            getReport().println(Messages.get().container(Messages.RPT_OUTPUT_WEBSERVER_1, buf.readLine()),
                    I_CmsReport.FORMAT_OK);
        }
    }
}

From source file:repast.simphony.data.analysis.AnalysisPluginRunner.java

public void run(AnalysisPluginWizard wizard) {
    String[] command = null;//from  w  w w .  j av  a2 s . com
    try {
        command = wizard.getExecutionCommand();
        Map<String, String> envVars = wizard.getEnvVars();

        if (command == null) {

            String message = wizard.getCannotRunMessage();
            if (message != null) {
                JOptionPane.showMessageDialog(null, message);
            }

        } else {

            Process process;

            for (String s : command)
                System.out.print(s + " ");
            System.out.print("\n");

            ProcessBuilder builder = new ProcessBuilder(command).redirectErrorStream(true);
            System.out.println(envVars);
            builder.environment().putAll(envVars);
            System.out.println(builder.directory(new File(".").getAbsoluteFile()));
            System.out.println(builder.directory());
            process = builder.start();

            PluginOutputStream pos = new PluginOutputStream(process.getInputStream());
            pos.start();

            PluginOutputStream pos2 = new PluginOutputStream(process.getErrorStream());
            pos2.start();

        }

    } catch (Exception e) {

        e.printStackTrace();

        // LOG.error("Wizard.run: Error executing " + name
        // + ".  Command is: '" + arrayToString(command) + "'",
        // e);
    }
}

From source file:ml.shifu.shifu.core.alg.TensorflowTrainer.java

public void train() throws IOException {
    List<String> commands = buildCommands();
    ProcessBuilder pb = new ProcessBuilder(commands);

    pb.directory(new File("./"));
    pb.redirectErrorStream(true);/*from  www .j  av  a  2 s. c o  m*/
    LOGGER.info("Start trainning sub process. Commands {}", commands.toString());
    Process process = pb.start();
    StreamCollector sc = new StreamCollector(process.getInputStream());
    sc.start();

    try {
        process.waitFor();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } finally {
        if (sc != null) {
            sc.close();
        }
    }
}

From source file:functionaltests.scilab.AbstractScilabTest.java

public void run() throws Throwable {
    init();/*from  w  w w. j  a v  a  2  s.co m*/

    ProcessBuilder pb = new ProcessBuilder();
    pb.directory(sci_tb_home);
    pb.redirectErrorStream(true);
    if (System.getProperty("scilab.bin.path") != null) {
        pb.command(System.getProperty("scilab.bin.path"), "-nw", "-f",
                (new File(test_home + fs + "PrepareTest.sci")).getCanonicalPath());
    } else {
        pb.command("scilab", "-nw", "-f", (new File(test_home + fs + "PrepareTest.sci")).getCanonicalPath());
    }
    System.out.println("Running command : " + pb.command());

    File okFile = new File(sci_tb_home + fs + "ok.tst");
    File koFile = new File(sci_tb_home + fs + "ko.tst");

    if (okFile.exists()) {
        okFile.delete();
    }

    if (koFile.exists()) {
        koFile.delete();
    }

    Process p = pb.start();

    IOTools.LoggingThread lt1 = new IOTools.LoggingThread(p.getInputStream(), "[AbstractScilabTest]",
            System.out);
    Thread t1 = new Thread(lt1, "AbstractScilabTest");
    t1.setDaemon(true);
    t1.start();

    p.waitFor();

    assertTrue("Prepare Scilab Test passed", okFile.exists());

}

From source file:net.fenyo.gnetwatch.actions.ExternalCommand.java

/**
 * Launches a process but do not wait for its completion.
 * any thread./*w ww  .j a  va  2 s  .  co m*/
 * @param none.
 * @return void.
 * @throws IOException i/o exception <bold>before</bold> reading the process output stream.
 */
public synchronized void fork() throws IOException {
    final ProcessBuilder pb = new ProcessBuilder(cmdLine);
    pb.directory(new File(directory));
    pb.redirectErrorStream(merge);
    process = pb.start();

    if (process == null)
        throw new IOException("null process");

    reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
}

From source file:abs.backend.erlang.ErlangTestDriver.java

/**
 * Complies code in workDir//from   w  w  w .j ava  2s .  c om
 */
private void make(File workDir) throws Exception {
    ProcessBuilder pb = new ProcessBuilder("erl", "-pa", "ebin", "-noshell", "-noinput", "-eval",
            "case make:all() of up_to_date -> halt(0); _ -> halt(1) end.");
    pb.directory(workDir);
    pb.inheritIO();
    Process p = pb.start();
    Assert.assertEquals("Compile failed", 0, p.waitFor());
}

From source file:au.com.permeance.liferay.portlet.patchingtoolinfo.cli.PatchingToolCommandRunner.java

private ProcessBuilder configureProcessBuilder() throws Exception {

    String liferayHomePath = System.getProperty(SYS_PROP_KEY_LIFERAY_HOME);

    if (LOG.isDebugEnabled()) {
        LOG.debug(SYS_PROP_KEY_LIFERAY_HOME + " : " + liferayHomePath);
    }// w  ww. j a  v  a2  s. c o  m

    if (liferayHomePath == null) {
        String msg = "Liferay Home property is undefined";
        LOG.error(msg);
        throw new Exception(msg);
    }

    String patchingToolHomePath = liferayHomePath + File.separator + PATCHING_TOOL_HOME_FOLDER_NAME;

    File patchingToolHomeDir = new File(patchingToolHomePath);

    if (LOG.isDebugEnabled()) {
        LOG.debug("patchingToolHomeDir : " + patchingToolHomeDir);
    }

    if (!patchingToolHomeDir.exists()) {
        String msg = "Patching tool home folder does not exist : " + patchingToolHomeDir.getAbsolutePath();
        LOG.error(msg);
        throw new Exception(msg);
    }

    String patchingToolScriptName = buildPatchingToolScriptName();

    if (LOG.isDebugEnabled()) {
        LOG.debug("patchingToolScriptName : " + patchingToolScriptName);
    }

    String patchingToolScriptPath = patchingToolHomePath + File.separator + buildPatchingToolScriptName();

    if (LOG.isDebugEnabled()) {
        LOG.debug("patchingToolScriptPath : " + patchingToolScriptPath);
    }

    File patchingToolScriptFile = new File(patchingToolScriptPath);

    if (LOG.isDebugEnabled()) {
        LOG.debug("patchingToolScriptFile : " + patchingToolScriptFile);
    }

    if (!patchingToolScriptFile.exists()) {
        String msg = "Patching tool script does not exist : " + patchingToolScriptFile.getAbsolutePath();
        LOG.error(msg);
        throw new Exception(msg);
    }

    List<String> commandList = new ArrayList<String>();

    List<String> shellCommand = buildShellCommand();

    if (LOG.isDebugEnabled()) {
        LOG.debug("shellCommand : " + shellCommand);
    }

    commandList.addAll(shellCommand);

    commandList.add(patchingToolScriptName);

    if (LOG.isDebugEnabled()) {
        LOG.debug("patchingToolOptions : " + getPatchingToolOptions());
    }

    if (!getPatchingToolOptions().isEmpty()) {
        commandList.addAll(getPatchingToolOptions());
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("commandList : " + commandList);
    }

    ProcessBuilder pb = new ProcessBuilder(commandList);

    pb.directory(patchingToolHomeDir);

    return pb;
}

From source file:edu.stanford.junction.director.JAVADirector.java

private Process launchJAR(URL jarURL, URI activityURI) {
    final String JAR_PATH = "jars/";

    String jarName = JAR_PATH + "/" + jarURL.getPath().substring(1).replace("/", "-");
    File jarFile = new File(jarName);
    File tmpFile = new File(jarName + ".tmp");
    if (!jarFile.exists() && !tmpFile.exists()) {
        try {//from w  w  w. j  av a2s  . co  m
            FileOutputStream out = new FileOutputStream(tmpFile);

            InputStream in = jarURL.openStream();
            byte[] buf = new byte[4 * 1024];
            int bytesRead;
            while ((bytesRead = in.read(buf)) != -1) {
                out.write(buf, 0, bytesRead);
            }
            in.close();
            out.close();

            boolean res = tmpFile.renameTo(jarFile);
            if (!res) {
                throw new Exception("Could not rename file.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    if (!jarFile.exists()) {
        System.out.println("Failed to get JAR file " + jarFile.getName());
        return null;
    }

    // Launch the new JVM
    try {
        List<String> command = new ArrayList<String>();
        command.add("java");
        command.add("-jar");
        command.add(jarFile.getAbsolutePath());
        command.add(activityURI.toString());

        System.out.println("Executing: " + command.toString());

        ProcessBuilder pb = new ProcessBuilder(command);
        pb.directory(jarFile.getParentFile());
        pb.redirectErrorStream(true);
        Process p = pb.start();
        // TODO: make sure it worked

        return p;
    } catch (Exception e) {
        System.out.println("failed to launch JAR.");
        e.printStackTrace();
    }
    return null;
}

From source file:org.dbflute.maven.plugin.command.CommandExecutor.java

public void execute(String cmd) throws MojoExecutionException, MojoFailureException {
    File dbfluteClientDir = plugin.getDbfluteClientDir();
    if (!dbfluteClientDir.isDirectory()) {
        LogUtil.getLog()//from ww  w  . ja  v  a  2  s  .c o m
                .info("Create dbflute client directory. " + "Try to run \'mvn dbflute:create-client\'.");
        return;
    }

    List<String> cmds = new ArrayList<String>();
    if (SystemUtil.isWindows()) {
        cmds.add("cmd.exe");
        cmds.add("/c");
        cmds.add(cmd + ".bat");
        environment.put("pause_at_end", "n");
    } else {
        cmds.add("/bin/bash");
        cmds.add(cmd + ".sh");
    }
    // TODO Mac?

    plugin.updateArgs(cmds);

    LogUtil.getLog().info("Running " + StringUtils.join(cmds.toArray(), " "));
    ProcessBuilder builder = new ProcessBuilder(cmds);
    if (environment.size() > 0) {
        builder.environment().putAll(environment);
    }
    Process process;
    try {
        process = builder.directory(dbfluteClientDir).redirectErrorStream(true).start();
    } catch (IOException e) {
        throw new MojoExecutionException("Could not run the command.", e);
    }

    try (InputStream stdin = process.getInputStream(); OutputStream stdout = process.getOutputStream()) {
        InputStreamThread ist = new InputStreamThread(stdin);
        OutputStreamThread ost = new OutputStreamThread(System.in, stdout);
        ist.start();
        ost.start();

        int exitValue = process.waitFor();

        ist.join();
        //ost.join();

        if (exitValue != 0) {
            throw new MojoFailureException("Build Failed. The exit value is " + exitValue + ".");
        }
    } catch (InterruptedException e) {
        throw new MojoExecutionException("Could not wait a process.", e);
    } catch (IOException e) {
        throw new MojoExecutionException("I/O error.", e);
    }
}

From source file:com.pluribus.vcf.helper.TestSetup.java

@BeforeTest(alwaysRun = true)
@Parameters({ "resetSwitch" })
//Run ansible reset switch script
public void resetSwitchAnsible(@Optional("1") String resetSwitch) throws Exception {
    if (Integer.parseInt(resetSwitch) == 1) {
        String out1;/*from   w w  w  .j  a v  a 2s  .c o  m*/
        StringBuffer output = null;

        String[] command = { "src/test/resources/resetSwitch.expect" };
        ProcessBuilder probuilder = new ProcessBuilder(command);

        //You can set up your work directory
        probuilder.directory(new File(System.getProperty("user.dir")));
        Process process = probuilder.start();

        //Read out dir output
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        System.out.printf("Output of running %s is:\n", Arrays.toString(command));
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

        //Wait to get exit value
        try {
            int exitValue = process.waitFor();
            System.out.println("\n\nExit Value is " + exitValue);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return;
}