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.github.jrh3k5.mojo.flume.process.AgentProcessTest.java

/**
 * Test the construction of the Flume process.
 * //from w  w  w. j  a v  a 2  s. c o  m
 * @throws Exception
 *             If any errors occur during the test run.
 */
@Test
public void testBuildFlumeProcess() throws Exception {
    final List<String> args = Arrays.asList("arg1", "arg2");
    final AgentProcess.ProcessBuilderProxy builderProxy = new AgentProcess.ProcessBuilderProxy(flumeDirectory,
            args);
    final ProcessBuilder builder = builderProxy.newProcessBuilder();
    assertThat(builder.command()).isEqualTo(args);
    assertThat(builder.directory()).isEqualTo(flumeDirectory);
    assertThat(builder.redirectErrorStream()).isTrue();
}

From source file:edu.brandeis.ggen.GGenCommand.java

public String generateGraphviz() throws GGenException {
    ProcessBuilder pb = new ProcessBuilder();
    List<String> command = new LinkedList<>();
    command.add(GGEN_PATH);// w w w.  j a v a 2s . c o  m
    Arrays.stream(args.split(" ")).forEach(command::add);

    try {
        Process p = pb.command(command).start();

        if (this.input != null)
            p.getOutputStream().write(this.input.generateGraphviz().getBytes());
        p.getOutputStream().close();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        IOUtils.copy(p.getInputStream(), bos);
        return new String(bos.toByteArray());
    } catch (IOException e) {
        throw new GGenException(
                "Could not launch the ggen command. Check that the GGenCommand.GGEN_PATH static variable is correctly set for your system. Message: "
                        + e.getMessage());
    }
}

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

private void executeGaugeSpecs() throws GaugeExecutionFailedException {
    try {/*from w  ww.  j  a  v  a2 s .c om*/
        ProcessBuilder builder = createProcessBuilder();
        debug("Executing => " + builder.command());
        Process process = builder.start();
        Util.InheritIO(process.getInputStream(), System.out);
        Util.InheritIO(process.getErrorStream(), System.err);
        if (process.waitFor() != 0) {
            throw new GaugeExecutionFailedException();
        }
    } catch (InterruptedException e) {
        throw new GaugeExecutionFailedException(e);
    } catch (IOException e) {
        throw new GaugeExecutionFailedException(e);
    }

}

From source file:com.salsaw.msalsa.clustal.ClustalOmegaManager.java

@Override
public void callClustal(String clustalPath, ClustalFileMapper clustalFileMapper)
        throws IOException, InterruptedException, SALSAException {
    // Get program path to execute
    List<String> clustalProcessCommands = new ArrayList<String>();
    clustalProcessCommands.add(clustalPath);

    // Create the name of output files
    String inputFileName = FilenameUtils.getBaseName(clustalFileMapper.getInputFilePath());
    String inputFileFolderPath = FilenameUtils.getFullPath(clustalFileMapper.getInputFilePath());
    Path alignmentFilePath = Paths.get(inputFileFolderPath, inputFileName + "-aln.fasta");
    Path guideTreeFilePath = Paths.get(inputFileFolderPath, inputFileName + "-tree.dnd");

    // Set inside file mapper
    clustalFileMapper.setAlignmentFilePath(alignmentFilePath.toString());
    clustalFileMapper.setGuideTreeFilePath(guideTreeFilePath.toString());
    setClustalFileMapper(clustalFileMapper);

    // Create clustal omega data
    generateClustalArguments(clustalProcessCommands);

    // http://www.rgagnon.com/javadetails/java-0014.html
    ProcessBuilder builder = new ProcessBuilder(clustalProcessCommands);
    builder.redirectErrorStream(true);/* w  w  w .  j  a v a 2  s .c o m*/
    System.out.println(builder.command());
    final Process process = builder.start();
    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    process.waitFor();

    if (process.exitValue() != 0) {
        throw new SALSAException("Failed clustal omega call");
    }
}

From source file:org.eclipse.gyrex.jobs.internal.externalprocess.ExternalProcessJob.java

@Override
protected IStatus run(final IProgressMonitor monitor) {
    final ProcessBuilder builder = new ProcessBuilder();

    log.debug("Command: {}", command);
    builder.command(command);

    if (workingDirectory != null) {
        log.debug("Using working directory: {}", workingDirectory);
        builder.directory(workingDirectory);
    }/*from   w  w  w  .  j a va2  s . c om*/

    if (clearEnvironment) {
        builder.environment().clear();
        log.debug("Cleared environment!");
    } else {
        // remove all Gyrex specific settings for security reasons
        final Iterator<Entry<String, String>> entries = builder.environment().entrySet().iterator();
        while (entries.hasNext()) {
            final Map.Entry<java.lang.String, java.lang.String> e = entries.next();
            if (StringUtils.startsWithIgnoreCase(e.getKey(), "gyrex")) {
                log.debug("Removing Gyrex specific environment variable: {}", e.getKey());
                entries.remove();
            }
        }
    }

    setEnvironmentVariable(builder, "WORKSPACE", Platform.getInstanceLocation().toOSString());
    setEnvironmentVariable(builder, "JOB_ID", jobId);

    if (additionalEnvironment != null) {
        for (final Entry<String, String> e : additionalEnvironment.entrySet()) {
            log.debug("Additional environment variable: {} = {}", e.getKey(), e.getValue());
            builder.environment().put(e.getKey(), e.getValue());
        }
    }

    AsyncLoggingInputStreamReader inputStreamReader = null, errorStreamReader = null;
    try {
        final Process p = builder.start();
        inputStreamReader = new AsyncLoggingInputStreamReader(jobId + " [OUT Reader]", p.getInputStream(), log,
                Level.INFO);
        errorStreamReader = new AsyncLoggingInputStreamReader(jobId + " [ERR Reader]", p.getErrorStream(), log,
                Level.ERROR);

        final int result = p.waitFor();
        if (result != exitValue)
            return new Status(IStatus.ERROR, JobsActivator.SYMBOLIC_NAME,
                    "Process finished with unexpected exit value: " + result);

    } catch (final InterruptedException e) {
        log.warn("Interrupted while waiting for the process to finish.", e);
        Thread.currentThread().interrupt();
        return Status.CANCEL_STATUS;
    } catch (final Exception | AssertionError | LinkageError e) {
        log.error("Error starting process. {} ", e.getMessage(), e);
        return new Status(IStatus.ERROR, JobsActivator.SYMBOLIC_NAME,
                "Error starting process: " + e.getMessage(), e);
    } finally {
        if (inputStreamReader != null) {
            inputStreamReader.close();
        }
        if (errorStreamReader != null) {
            errorStreamReader.close();
        }
    }

    if (StringUtils.isNotBlank(inputStreamReader.getLastLine()))
        return new Status(IStatus.OK, JobsActivator.SYMBOLIC_NAME, inputStreamReader.getLastLine());

    return Status.OK_STATUS;
}

From source file:org.opencb.cellbase.app.cli.CommandExecutor.java

protected boolean runCommandLineProcess(File workingDirectory, String binPath, List<String> args,
        String logFilePath) throws IOException, InterruptedException {
    ProcessBuilder builder = getProcessBuilder(workingDirectory, binPath, args, logFilePath);

    logger.debug("Executing command: " + StringUtils.join(builder.command(), " "));
    Process process = builder.start();
    process.waitFor();/* w  w  w . j ava  2  s . co  m*/

    // Check process output
    boolean executedWithoutErrors = true;
    int genomeInfoExitValue = process.exitValue();
    if (genomeInfoExitValue != 0) {
        logger.warn("Error executing {}, error code: {}. More info in log file: {}", binPath,
                genomeInfoExitValue, logFilePath);
        executedWithoutErrors = false;
    }
    return executedWithoutErrors;
}

From source file:sorcer.launcher.JavaProcessBuilder.java

public Process2 startProcess() throws IOException {
    ProcessBuilder procBld = new ProcessBuilder().command(command);

    if (debugger) {
        procBld.command().addAll(
                Arrays.asList("-Xdebug", "-Xrunjdwp:transport=dt_socket,server=y,address=" + debugPort));
    }/*from   w  w  w .  j a  v  a  2s. c  om*/

    procBld.command().addAll(_D(properties));
    String classPath = StringUtils.join(classPathList, File.pathSeparator);
    procBld.command().addAll(asList("-classpath", classPath, mainClass));
    if (parameters != null) {
        procBld.command().addAll(parameters);
    }

    if (workingDir == null) {
        // the default
        // make explicit for logging purpose
        workingDir = new File(System.getProperty("user.dir"));
    }
    procBld.directory(workingDir);

    Map<String, String> env = procBld.environment();
    updateEnvironment(env);

    StringBuilder cmdStr = new StringBuilder("[").append(workingDir.getPath()).append("] ")
            .append(StringUtils.join(procBld.command(), " "));
    if (output != null) {
        cmdStr.append(" > ").append(output.getPath());
    }

    log.info(cmdStr.toString());

    redirectIO(procBld);

    Process proc = null;
    try {
        proc = procBld.start();

        try {
            // give it a moment to exit on error
            Thread.sleep(100);
        } catch (InterruptedException ignored) {
            //ignore
        }

        // if the next call throws exception, then we're probably good -
        // process hasn't finished yet.
        int x = proc.exitValue();
        throw new IllegalStateException("Process exited with value " + x);
    } catch (IllegalThreadStateException x) {
        return new Process2(proc);
    }
}

From source file:org.opencb.bionetdb.app.cli.CommandExecutor.java

@Deprecated
protected boolean runCommandLineProcess(File workingDirectory, String binPath, List<String> args,
        String logFilePath) throws IOException, InterruptedException {
    ProcessBuilder builder = getProcessBuilder(workingDirectory, binPath, args, logFilePath);

    logger.debug("Executing command: " + StringUtils.join(builder.command(), " "));
    Process process = builder.start();
    process.waitFor();//from  w w w .  ja v a  2 s .c o m

    // Check process output
    boolean executedWithoutErrors = true;
    int genomeInfoExitValue = process.exitValue();
    if (genomeInfoExitValue != 0) {
        logger.warn("Error executing {}, error code: {}. More info in log file: {}", binPath,
                genomeInfoExitValue, logFilePath);
        executedWithoutErrors = false;
    }
    return executedWithoutErrors;
}

From source file:io.wcm.maven.plugins.nodejs.mojo.Task.java

private void startProcess(ProcessBuilder processBuilder) throws MojoExecutionException {
    try {/* w  ww. j ava2  s .c om*/
        final Process process = processBuilder.start();
        getLog().info("Running process: " + StringUtils.join(processBuilder.command(), " "));
        initLogging(process);
        int result = process.waitFor();
        if (result != 0) {
            throw new MojoExecutionException("Process: " + StringUtils.join(processBuilder.command(), " ")
                    + " terminated with " + result);
        }
    } catch (IOException ex) {
        throw new MojoExecutionException(
                "Error executing process: " + StringUtils.join(processBuilder.command(), " "), ex);
    } catch (InterruptedException ex) {
        throw new MojoExecutionException(
                "Error executing process: " + StringUtils.join(processBuilder.command(), " "), ex);
    }
}

From source file:org.sonar.process.monitor.JavaProcessLauncher.java

ProcessRef launch(JavaCommand command) {
    Process process = null;//from  w ww.  j av  a  2  s  .  c o  m
    try {
        ProcessCommands commands = allProcessesCommands.createAfterClean(command.getProcessId().getIpcIndex());

        ProcessBuilder processBuilder = create(command);
        LoggerFactory.getLogger(getClass()).info("Launch process[{}]: {}", command.getProcessId().getKey(),
                StringUtils.join(processBuilder.command(), " "));
        process = processBuilder.start();
        StreamGobbler inputGobbler = new StreamGobbler(process.getInputStream(),
                command.getProcessId().getKey());
        inputGobbler.start();

        return new ProcessRef(command.getProcessId().getKey(), commands, process, inputGobbler);

    } catch (Exception e) {
        // just in case
        ProcessUtils.sendKillSignal(process);
        throw new IllegalStateException("Fail to launch [" + command.getProcessId().getKey() + "]", e);
    }
}