Example usage for java.lang ProcessBuilder command

List of usage examples for java.lang ProcessBuilder command

Introduction

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

Prototype

List command

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

Click Source Link

Usage

From source file:com.lithium.flow.vault.AgentVault.java

private void startAgent(@Nonnull String password) {
    try {//from ww  w  .  j  av a  2 s  .c om
        int port = findFreePort();
        String agentPassword = Vaults.securePassword();

        Map<String, String> map = new HashMap<>();
        Store agentStore = new MemoryStore(map);
        Vault agentVault = new SecureVault(Configs.empty(), agentStore);
        agentVault.setup(agentPassword);
        agentVault.putValue("password", password);

        ProcessBuilder builder = new ProcessBuilder();
        builder.command(System.getProperty("java.home") + "/bin/java", "-Dagent.port=" + port,
                AgentServer.class.getName());
        builder.environment().put("CLASSPATH", System.getProperty("java.class.path"));
        Process process = builder.start();

        OutputStream out = process.getOutputStream();
        mapper.writeValue(out, map);
        out.close();

        store.putValue("vault.agent.port", String.valueOf(port));
        store.putValue("vault.agent.password", agentPassword);
    } catch (IOException e) {
        throw new VaultException("failed to start agent", e);
    }
}

From source file:com.synopsys.integration.executable.ProcessBuilderRunner.java

public ExecutableOutput execute(ProcessBuilder processBuilder) throws ExecutableRunnerException {
    logger.info(String.format("Running process builder >%s", getMaskedCommand(processBuilder.command())));
    return executeProcessBuilder(processBuilder);
}

From source file:org.sipfoundry.sipxconfig.backup.BackupCommandRunner.java

String runCommand(String... command) {
    File listFile = null;/*www. ja v  a 2 s  .  c  om*/
    Reader rdr = null;
    String commandLine = StringUtils.EMPTY;
    try {
        listFile = File.createTempFile("archive-command", ".tmp");
        String[] commandOut = new String[command.length + 5];
        System.arraycopy(command, 0, commandOut, 1, command.length);
        commandOut[0] = m_backupScript;
        commandOut[command.length + 1] = "--out";
        commandOut[command.length + 2] = listFile.getAbsolutePath();
        commandOut[command.length + 3] = "--mode"; // Relevant to few cmds, but harmless otherwise
        commandOut[command.length + 4] = m_mode;
        ProcessBuilder pb = new ProcessBuilder(commandOut);
        commandLine = StringUtils.join(pb.command(), ' ');
        LOG.info(commandLine);
        Process process = pb.start();
        if (m_background) {
            return StringUtils.EMPTY;
        }
        int code = process.waitFor();
        if (code != 0) {
            throw new UserException("&archive.command.failed", commandLine, code);
        }
        rdr = new FileReader(listFile);
        return IOUtils.toString(rdr);
    } catch (IOException e) {
        throw new UserException("&error.running.archive.command", commandLine);
    } catch (InterruptedException e) {
        throw new UserException("&timed.out.archive.command", commandLine);
    } finally {
        IOUtils.closeQuietly(rdr);
        if (listFile != null) {
            listFile.delete();
        }
    }
}

From source file:script.manager.Executor.java

/**
 * http://stackoverflow.com/questions/16217060/psql-script-not-committing-when-executed-from-java
 * @param command/*from ww w .  j a  v a 2  s  .c o  m*/
 */
public void executeCommand(String command) {
    try {
        FileUtils.writeStringToFile(new File(SHELL_FILE_NAME), command, StandardCharsets.UTF_8);
        ArrayList<String> cmdargs = new ArrayList<>();
        cmdargs.add("bash");
        cmdargs.add(SHELL_FILE_NAME);
        ProcessBuilder pb = new ProcessBuilder(cmdargs);
        LOG.log(Level.INFO, "Wrote the commmand file. {1}, COMMAND: {0}",
                new Object[] { command, pb.command().toString() });
        //            Map<String, String> env = pb.environment();
        //            env.put("PGPASSWORD", "user");
        Process p = pb.start();
        try (final BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                final BufferedReader stdIn = new BufferedReader(new InputStreamReader(p.getInputStream()));) {
            String s;
            while ((s = stdError.readLine()) != null) {
                LOG.log(Level.WARNING, s);
            }
            while ((s = stdIn.readLine()) != null) {
                LOG.log(Level.INFO, s);
            }
        }
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, null, ex);
    }
}

From source file:com.kelveden.karma.AbstractKarmaMojo.java

protected Process startKarmaProcess(ProcessBuilder builder) throws MojoExecutionException {
    try {/*from w ww  .j a  v  a2s  .  c  om*/
        builder.redirectErrorStream(true);

        System.out.println(StringUtils.join(builder.command().iterator(), " "));

        return builder.start();

    } catch (IOException e) {
        throw new MojoExecutionException("There was an error executing Karma.", e);
    }
}

From source file:com.thoughtworks.gauge.maven.GaugeExecutionMojo.java

private ProcessBuilder createProcessBuilder() {
    ProcessBuilder builder = new ProcessBuilder();
    builder.command(createGaugeCommand());
    String customClasspath = createCustomClasspath();
    debug("Setting Custom classpath => %s", customClasspath);
    builder.environment().put(GAUGE_CUSTOM_CLASSPATH_ENV, customClasspath);
    return builder;
}

From source file:functionaltests.matlab.TestGetResults.java

protected void runCommand(String testName, int nb_iter, int index) throws Exception {

    ProcessBuilder pb = initCommand(testName, nb_iter);
    System.out.println("Running command : " + pb.command());

    File okFile = new File(mat_tb_home + fs + "ok.tst");
    File koFile = new File(mat_tb_home + fs + "ko.tst");
    File reFile = new File(mat_tb_home + fs + "re.tst");
    File startFile = new File(mat_tb_home + fs + "start.tst");

    if (okFile.exists()) {
        okFile.delete();/*from ww w . j av a2 s.  co  m*/
    }

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

    Process p = pb.start();

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

    int code = p.waitFor();
    while (!startFile.exists()) {
        Thread.sleep(100);
    }

    while (!okFile.exists() && !koFile.exists() && !reFile.exists()) {
        Thread.sleep(100);
    }

    if (logFile.exists()) {
        System.out.println(IOUtils.toString(logFile.toURI()));
    }

    if (index < nb_iter) {
        assertTrue(testName + "_" + index + " passed", !koFile.exists());
    } else {
        assertTrue(testName + " passed", okFile.exists());
    }
}

From source file:functionaltests.matlab.TestDisconnected.java

@Override
protected void runCommand(String testName, int nb_iter) throws Exception {
    ProcessBuilder pb = initCommand(testName, nb_iter);
    System.out.println("Running command : " + pb.command());

    File okFile = new File(mat_tb_home + fs + "ok.tst");
    File koFile = new File(mat_tb_home + fs + "ko.tst");
    File reFile = new File(mat_tb_home + fs + "re.tst");
    File startFile = new File(mat_tb_home + fs + "start.tst");

    if (okFile.exists()) {
        okFile.delete();//from   w  ww . j  av a2 s .com
    }

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

    Process p = pb.start();

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

    int code = p.waitFor();
    while (!startFile.exists()) {
        Thread.sleep(100);
    }

    while (!okFile.exists() && !koFile.exists() && !reFile.exists()) {
        Thread.sleep(100);
    }

    if (logFile.exists()) {
        System.out.println(IOUtils.toString(logFile.toURI()));
    }

    if (index < nb_iter) {
        assertTrue(testName + "_" + index + " passed", !koFile.exists());
    } else {
        assertTrue(testName + " passed", okFile.exists());
    }

}

From source file:com.openshift.internal.restclient.capability.resources.AbstractOpenShiftBinaryCapability.java

private void startProcess(String location) {
    String cmdLine = new StringBuilder(location).append(' ').append(buildArgs()).toString();
    String[] args = StringUtils.split(cmdLine, " ");
    ProcessBuilder builder = new ProcessBuilder(args);
    LOG.debug("OpenShift binary args: {}", builder.command());
    try {/* w w  w  .j  av a2 s  .  c om*/
        process = builder.start();
        checkProcessIsAlive();
    } catch (IOException e) {
        LOG.error("Could not start process for {}.", new Object[] { getName(), e });
        throw new OpenShiftException(e, "Does your OpenShift binary location exist? Error starting process: %s",
                e.getMessage());
    }
}

From source file:org.applause.applausedsl.ui.generator.formatter.UncrustifyFormatter.java

/**
 * Formats the given string with Uncrustify.
 * /*from  w  w  w.ja  v  a 2s.co m*/
 * @param unformatted
 *            Unformatted code
 * @param args
 * @return Formatted code
 */
public CharSequence format(CharSequence unformatted, List<String> args) {
    if (unformatted == null) {
        return null;
    }
    if (args == null) {
        throw new IllegalArgumentException("args is null");
    }
    Process proc = null;
    // Store original code as fallback
    CharSequence result = unformatted;
    try {
        int rc;

        ProcessBuilder pb = new ProcessBuilder();
        pb.command(args);

        proc = pb.start();

        Writer stdinWriter = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
        IOUtils.copy(new StringReader(unformatted.toString()), stdinWriter);
        stdinWriter.close();

        rc = proc.waitFor();
        BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
        String lineRead;
        while ((lineRead = br.readLine()) != null) {
            if (lineRead.startsWith("Parsing:")) {
                LOG.debug(lineRead);
            } else {
                LOG.warn(lineRead);
            }
        }
        if (rc != 0) {
            LOG.warn("Execution of uncrustify failed with error.");
        } else {
            StringWriter sw = new StringWriter(unformatted.length());
            IOUtils.copy(proc.getInputStream(), sw);
            result = sw.getBuffer();
            rc = proc.exitValue();
            if (rc != 0) {
                LOG.warn("Execution of uncrustify failed with error.");

            } else {
                if (LOG.isDebugEnabled())
                    LOG.debug("Execution of uncrustify was successful.");
            }
        }
    } catch (Exception re) {
        LOG.warn(re.getClass().getSimpleName() + ": " + re.getMessage());
    } finally {
        if (proc != null) {
            IOUtils.closeQuietly(proc.getErrorStream());
            IOUtils.closeQuietly(proc.getInputStream());
            IOUtils.closeQuietly(proc.getOutputStream());
        }
    }
    return result;
}