Example usage for java.lang ProcessBuilder start

List of usage examples for java.lang ProcessBuilder start

Introduction

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

Prototype

public Process start() throws IOException 

Source Link

Document

Starts a new process using the attributes of this process builder.

Usage

From source file:ape.NetworkDisconnectCommand.java

/**
 * This method actually executes the command that would disconnect the network
 *//*w  w w . ja  v a2 s .c  om*/
private boolean executecommand(double time) throws IOException {
    String cmd = "ifdown eth0 && sleep " + time + " && /etc/init.d/network restart";
    ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(true);
    Process p = null;

    try {
        p = pb.start();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    try {
        if (p.waitFor() != 0) {
            System.out.println(
                    "ERROR: Non-zero return code (" + p.exitValue() + ") when executing: '" + cmd + "'");
            Main.logger
                    .info("ERROR: Non-zero return code (" + p.exitValue() + ") when executing: '" + cmd + "'");

            ProcessBuilder tmp2 = new ProcessBuilder("bash", "-c", "/etc/init.d/network restart");
            Process ptmp = tmp2.start();
            try {
                if (ptmp.waitFor() == 0)
                    System.out.println("Connection resumed");
                else {
                    System.out.println("Connection resume failed");
                    return false;
                }
            } catch (InterruptedException e1) {
                e1.printStackTrace();
                System.err.println("Catches an exception when trying to recover the network");
                return false;
            }

            return false;
        }
    } catch (InterruptedException e) {
        System.err.println("Executing Command catches an Interrupt, resume connection");
        ProcessBuilder tmp2 = new ProcessBuilder("bash", "-c", "/etc/init.d/network restart");
        Process ptmp = tmp2.start();
        try {
            if (ptmp.waitFor() == 0)
                System.out.println("Connection Resumed");
            else {
                System.out.println("Connection Resumed Failed");
                return false;
            }
        } catch (InterruptedException e1) {
            e1.printStackTrace();
            System.err.println("Catches an exception when trying to recover the network");
            return false;

        }
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:com.palantir.tslint.services.Bridge.java

private void start() {
    File nodeFile = Bridge.findNode();
    String nodePath = nodeFile.getAbsolutePath();

    // get the path to the bridge.js file
    File bundleFile;// ww  w  . j  av  a 2 s. c om
    try {
        bundleFile = FileLocator.getBundleFile(TSLintPlugin.getDefault().getBundle());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    File bridgeFile = new File(bundleFile, "bin/bridge.js");
    String bridgePath = bridgeFile.getAbsolutePath();

    // construct the arguments
    ImmutableList.Builder<String> argsBuilder = ImmutableList.builder();
    argsBuilder.add(nodePath);
    argsBuilder.add(bridgePath);

    // start the node process and create a reader/writer for its stdin/stdout
    List<String> args = argsBuilder.build();
    ProcessBuilder processBuilder = new ProcessBuilder(args.toArray(new String[args.size()]));
    try {
        this.nodeProcess = processBuilder.start();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    this.nodeStdout = new BufferedReader(
            new InputStreamReader(this.nodeProcess.getInputStream(), Charsets.UTF_8));
    this.nodeStdin = new PrintWriter(new OutputStreamWriter(this.nodeProcess.getOutputStream(), Charsets.UTF_8),
            true);

    // add a shutdown hook to destroy the node process in case its not properly disposed
    Runtime.getRuntime().addShutdownHook(new ShutdownHookThread());
}

From source file:com.cisco.dvbu.cmdline.vcs.spi.AbstractLifecycleListener.java

private Process execute(ProcessBuilder processBuilder) throws VCSException {
    Process result = null;/*from   www . j  a va2 s .c o  m*/

    try {
        result = processBuilder.start();
    } catch (IOException e) {
        throw new VCSException(e);
    }

    return result;
}

From source file:it.polimi.modaclouds.qos.linebenchmark.solver.SolutionEvaluator.java

private void runWithLQNS() {
    StopWatch timer = new StopWatch();
    String solverProgram = "lqns";

    String command = solverProgram + " " + filePath + " -f"; //using the fast option
    logger.info("Launch: " + command);
    //String command = solverProgram+" "+filePath; //without using the fast option
    try {/*from  w  ww. j  ava 2  s  .co  m*/
        ProcessBuilder pb = new ProcessBuilder(splitToCommandArray(command));

        //start counting
        timer.start();
        Process proc = pb.start();
        readStream(proc.getInputStream(), false);
        readStream(proc.getErrorStream(), true);
        int exitVal = proc.waitFor();
        //stop counting
        timer.stop();
        proc.destroy();

        //evaluation error messages
        if (exitVal == LQNS_RETURN_SUCCESS)
            ;
        else if (exitVal == LQNS_RETURN_MODEL_FAILED_TO_CONVERGE) {
            System.err.println(Main.LQNS_SOLVER + " exited with " + exitVal
                    + ": The model failed to converge. Results are most likely inaccurate. ");
            System.err.println("Analysis Result has been written to: " + resultfilePath);
        } else {
            String message = "";
            if (exitVal == LQNS_RETURN_INVALID_INPUT) {
                message = solverProgram + " exited with " + exitVal + ": Invalid Input.";
            } else if (exitVal == LQNS_RETURN_FATAL_ERROR) {
                message = solverProgram + " exited with " + exitVal + ": Fatal error";
            } else {
                message = solverProgram + " returned an unrecognised exit value " + exitVal
                        + ". Key: 0 on success, 1 if the model failed to meet the convergence criteria, 2 if the input was invalid, 4 if a command line argument was incorrect, 8 for file read/write problems and -1 for fatal errors. If multiple input files are being processed, the exit code is the bit-wise OR of the above conditions.";
            }
            System.err.println(message);
        }
    } catch (IOException | InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //tell listeners that the evaluation has been performed
    EvaluationCompletedEvent evaluationCompleted = new EvaluationCompletedEvent(this, 0, null);
    evaluationCompleted.setEvaluationTime(timer.getTime());
    evaluationCompleted.setSolverName(solver);
    evaluationCompleted.setModelPath(filePath.getFileName());
    for (ActionListener l : listeners)
        l.actionPerformed(evaluationCompleted);
}

From source file:com.palantir.typescript.services.Bridge.java

private void start() {
    String nodePath = TypeScriptPlugin.getDefault().getPreferenceStore()
            .getString(IPreferenceConstants.GENERAL_NODE_PATH);
    if (Strings.isNullOrEmpty(nodePath)) {
        throw new IllegalStateException(
                "Node.js could not be found.  If it is installed to a location not on the PATH, please specify the location in the TypeScript preferences.");
    }/*  w  ww  .  j a v a2 s .co  m*/

    // get the path to the bridge.js file
    File bundleFile;
    try {
        bundleFile = FileLocator.getBundleFile(TypeScriptPlugin.getDefault().getBundle());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    File bridgeFile = new File(bundleFile, "bin/bridge.js");
    String bridgePath = bridgeFile.getAbsolutePath();

    // construct the arguments
    ImmutableList.Builder<String> argsBuilder = ImmutableList.builder();
    argsBuilder.add(nodePath);
    if (NODE_DEBUG) {
        argsBuilder.add(NODE_DEBUG_PATH);
        if (!NODE_DEBUG_BREAK_ON_START) {
            argsBuilder.add("--no-debug-brk");
        }
        argsBuilder.add("--web-port=" + Integer.toString(NODE_DEBUG_PORT++));
        argsBuilder.add("--debug-port=" + Integer.toString(NODE_DEBUG_PORT++));
    }
    argsBuilder.add(bridgePath);

    // start the node process and create a reader/writer for its stdin/stdout
    List<String> args = argsBuilder.build();
    ProcessBuilder processBuilder = new ProcessBuilder(args.toArray(new String[args.size()]));
    try {
        this.nodeProcess = processBuilder.start();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    this.nodeStdout = new BufferedReader(
            new InputStreamReader(this.nodeProcess.getInputStream(), Charsets.UTF_8));
    this.nodeStdin = new PrintWriter(new OutputStreamWriter(this.nodeProcess.getOutputStream(), Charsets.UTF_8),
            true);

    // add a shutdown hook to destroy the node process in case its not properly disposed
    Runtime.getRuntime().addShutdownHook(new ShutdownHookThread());
}

From source file:com.alibaba.jstorm.yarn.utils.JStormUtils.java

protected static Process launchProcess(final List<String> cmdlist, final Map<String, String> environment)
        throws IOException {
    ProcessBuilder builder = new ProcessBuilder(cmdlist);
    builder.redirectErrorStream(true);/*from   w  w w . j  av  a  2 s . co m*/
    Map<String, String> process_evn = builder.environment();
    for (Entry<String, String> entry : environment.entrySet()) {
        process_evn.put(entry.getKey(), entry.getValue());
    }

    return builder.start();
}

From source file:org.fcrepo.importexport.integration.ExecutableJarIT.java

private Process startJarProcess(final String... args) throws IOException {
    final String[] fullArgs = new String[3 + args.length];
    fullArgs[0] = "java";
    fullArgs[1] = "-jar";
    fullArgs[2] = EXECUTABLE;//from  w w  w . j  a v  a 2s . c  o  m
    System.arraycopy(args, 0, fullArgs, 3, args.length);
    final ProcessBuilder builder = new ProcessBuilder(fullArgs);

    builder.directory(new File(TARGET_DIR));
    final Process process = builder.start();
    logger.debug("Output of jar run: {}", IOUtils.toString(process.getInputStream()));
    return process;
}

From source file:com.thoughtworks.go.util.ProcessManager.java

Process startProcess(ProcessBuilder processBuilder, String commandLineForDisplay) {
    Process process;/*from  w w  w.j av  a  2s .  c  o m*/
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("[Command Line] START command " + commandLineForDisplay);
        }
        process = processBuilder.start();
        if (LOG.isDebugEnabled()) {
            LOG.debug("[Command Line] END command " + commandLineForDisplay);
        }
    } catch (IOException e) {
        LOG.error(String.format("[Command Line] Failed executing [%s]", commandLineForDisplay));
        LOG.error(String.format("[Command Line] Agent's Environment Variables: %s", System.getenv()));
        throw new CommandLineException(
                String.format("Error while executing [%s] \n Make sure this command can execute manually.",
                        commandLineForDisplay),
                e);
    }
    return process;
}

From source file:com.anrisoftware.globalpom.exec.core.DefaultProcessTask.java

private void startProcess(ProcessBuilder builder)
        throws IOException, InterruptedException, CommandExecException, ExecutionException {
    Process process = builder.start();
    List<Future<?>> streamsTasks = createProcessStreams(process);
    this.process = process;
    this.ret = process.waitFor();
    waitForStreams(streamsTasks);//from   w w  w .jav a 2 s  .c  om
    setChanged();
    notifyObservers();
    if (exitCodes != null && !checkExitCodes(ret, exitCodes)) {
        throw log.invalidExitCode(this, ret, exitCodes, commandLine);
    }
}

From source file:com.mtgi.analytics.test.AbstractPerformanceTestCase.java

private void runTest(ServerSocket listener, ProcessBuilder launcher, StatisticsMBean stats, byte[] jobData)
        throws IOException, InterruptedException {
    Process proc = launcher.start();

    //connect stdout and stderr to parent process streams
    if (log.isDebugEnabled()) {
        new PipeThread(proc.getInputStream(), System.out).start();
        new PipeThread(proc.getErrorStream(), System.err).start();
    } else {/*from  w  w  w  .j  a  v  a 2  s.com*/
        NullOutput sink = new NullOutput();
        new PipeThread(proc.getInputStream(), sink).start();
        new PipeThread(proc.getErrorStream(), sink).start();
    }

    //wait for the incoming connection from the child process.
    Socket sock = listener.accept();
    try {
        //connection established, send the job.
        OutputStream os = sock.getOutputStream();
        os.write(jobData);
        os.flush();

        //read measurements back.
        DataInputStream dis = new DataInputStream(sock.getInputStream());
        for (long measure = dis.readLong(); measure >= 0; measure = dis.readLong())
            stats.add(measure);

        //send ack byte to tell the child proc its ok to hang up.
        os.write(1);
        os.flush();

    } finally {
        sock.close();
    }

    assertEquals("Child process ended successfully", 0, proc.waitFor());
}