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.trustedanalytics.servicebroker.gearpump.service.externals.helpers.ExternalProcessExecutor.java

public ExternalProcessExecutorResult run(String[] command, String workingDir, Map<String, String> properties) {

    String lineToRun = Arrays.asList(command).stream().collect(Collectors.joining(" "));

    LOGGER.info("===================");
    LOGGER.info("Command to invoke: {}", lineToRun);

    ProcessBuilder processBuilder = new ProcessBuilder(command);
    updateEnvOfProcessBuilder(processBuilder.environment(), properties);

    if (workingDir != null) {
        processBuilder.directory(new File(workingDir));
    }/*  w  ww  .j av  a  2  s .com*/
    processBuilder.redirectErrorStream(true);

    StringBuilder processOutput = new StringBuilder();
    Process process;
    BufferedReader stdout = null;

    try {
        process = processBuilder.start();
        stdout = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String line;
        while ((line = stdout.readLine()) != null) {
            LOGGER.debug(":::::: " + line);
            processOutput.append(line);
            processOutput.append('\n');
        }

        try {
            process.waitFor();
        } catch (InterruptedException e) {
            LOGGER.error("Command '" + lineToRun + "' interrupted.", e);
        }
    } catch (IOException e) {
        LOGGER.error("Problem executing external process.", e);
        return new ExternalProcessExecutorResult(Integer.MIN_VALUE, "", e);
    } finally {
        closeReader(stdout);
    }

    ExternalProcessExecutorResult result = new ExternalProcessExecutorResult(process.exitValue(),
            processOutput.toString(), null);

    LOGGER.info("Exit value: {}", result.getExitCode());
    LOGGER.info("===================");
    return result;
}

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

/**
* Executes mainModule/*w  w  w  . j av  a 2s .  c om*/
* 
* We replace the run script by a new version, which will write the Result
* to STDOUT Furthermore to detect faults, we have a Timeout process, which
* will kill the runtime system after 2 seconds
*/
private String run(File workDir, String mainModule) throws Exception {
    String val = null;
    File runFile = new File(workDir, "run");
    Files.write(RUN_SCRIPT, runFile, Charset.forName("UTF-8"));
    runFile.setExecutable(true);
    ProcessBuilder pb = new ProcessBuilder(runFile.getAbsolutePath(), mainModule);
    pb.directory(workDir);
    pb.redirectErrorStream(true);
    Process p = pb.start();

    Thread t = new Thread(new TimeoutThread(p));
    t.start();
    // Search for result
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    while (true) {
        String line = br.readLine();
        if (line == null)
            break;
        if (line.startsWith("RES="))
            val = line.split("=")[1];
    }
    int res = p.waitFor();
    t.interrupt();
    if (res != 0)
        return null;
    return val;

}

From source file:net.sf.jasperreports.phantomjs.PhantomJSProcess.java

public void startPhantomJS() {
    String mainScriptTempName = director.getScriptManager().getScriptFilename(PhantomJS.MAIN_SCRIPT_RESOURCE);
    String listenAddress = listenURI.getHost() + ":" + listenURI.getPort();
    int idleTimeout = director.getProcessIdleTimeout();

    List<String> command = new ArrayList<String>();
    command.add(director.getPhantomjsExecutablePath());
    String options = "";
    if (director.getOptions() != null) {
        for (PropertySuffix suffix : director.getOptions()) {
            String option = suffix.getValue();
            if (option != null && !option.trim().isEmpty()) {
                command.add(option.trim());
                options += option.trim() + " ";
            }/*from  w w w. j a  v a2  s .  c om*/
        }
    }

    command.add(mainScriptTempName);
    command.add("-listenAddress");
    command.add(listenAddress);
    command.add("-confirmMessage");
    command.add(PHANTOMJS_CONFIRMATION_MESSAGE);
    command.add("-idleTimeout");
    command.add(Integer.toString(idleTimeout));

    log.info("PhantomJS process " + id + " starting on port " + listenURI.getPort());
    if (log.isDebugEnabled()) {
        log.debug(id + " starting phantomjs process with command: " + director.getPhantomjsExecutablePath()
                + options + " \"" + mainScriptTempName + "\"" + " -listenAddress \"" + listenAddress + "\""
                + " -confirmMessage \"" + PHANTOMJS_CONFIRMATION_MESSAGE + "\"" + " -idleTimeout " + idleTimeout
                + "");
    }

    ProcessBuilder pb = new ProcessBuilder(command);
    pb.redirectErrorStream(false);
    pb.directory(director.getScriptManager().getTempFolder());

    try {
        process = pb.start();

        ProcessOutputReader outputReader = new ProcessOutputReader(this);
        outputReader.start();
        boolean started = outputReader.waitConfirmation(director.getProcessStartTimeout());
        if (!started) {
            log.error("PhantomJS process " + id + " failed to start");//TODO lucianc write error output
            process.destroy();

            throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_FAILED_START, (Object[]) null);
        }

        processConnection = new ProcessConnection(director, this);
    } catch (IOException e) {
        throw new JRRuntimeException(e);
    }
}

From source file:com.netflix.raigad.defaultimpl.ElasticSearchProcessManager.java

public void start(boolean join_ring) throws IOException {
    logger.info("Starting elasticsearch server");

    List<String> command = Lists.newArrayList();
    if (!"root".equals(System.getProperty("user.name"))) {
        command.add(SUDO_STRING);// w  w  w . ja  va2  s .  c o m
        command.add("-n");
        command.add("-E");
    }
    command.addAll(getStartCommand());

    ProcessBuilder startEs = new ProcessBuilder(command);
    Map<String, String> env = startEs.environment();

    env.put("DATA_DIR", config.getDataFileLocation());

    startEs.directory(new File("/"));
    startEs.redirectErrorStream(true);
    Process starter = startEs.start();
    logger.info("Starting Elasticsearch server ....");
    try {
        sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS);
        int code = starter.exitValue();
        if (code == 0)
            logger.info("Elasticsearch server has been started");
        else
            logger.error("Unable to start Elasticsearch server. Error code: {}", code);

        logProcessOutput(starter);
    } catch (Exception e) {
        logger.warn("Starting Elasticsearch has an error", e.getMessage());
    }
}

From source file:org.abs_models.backend.erlang.ErlangTestDriver.java

/**
 * Executes mainModule// ww  w.  j  av a 2 s  .  c  om
 *
 * To detect faults, we have a Timeout process which will kill the
 * runtime system after 10 seconds
 */
private String run(File workDir, String mainModule) throws Exception {
    String val = null;
    String runFileName = ErlangBackend.isWindows() ? "run.bat" : "run";
    File runFile = new File(workDir, runFileName);
    ProcessBuilder pb = new ProcessBuilder(runFile.getAbsolutePath(), mainModule);
    pb.directory(workDir);
    pb.redirectErrorStream(true);
    Process p = pb.start();

    Thread t = new Thread(new TimeoutThread(p));
    t.start();
    // Search for result
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    while (true) {
        String line = br.readLine();
        if (line == null)
            break;
        if (line.startsWith("RES=")) // see `genCode' above
            val = line.split("=")[1];
    }
    int res = p.waitFor();
    t.interrupt();
    if (res != 0)
        return null;
    return val;

}

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

private ProcessBuilder getProcessBuilder(File workingDirectory, String binPath, List<String> args,
        String logFilePath) {// www  .  j a  va 2  s  . c  o m
    List<String> commandArgs = new ArrayList<>();
    commandArgs.add(binPath);
    commandArgs.addAll(args);
    ProcessBuilder builder = new ProcessBuilder(commandArgs);

    // working directoy and error and output log outputs
    if (workingDirectory != null) {
        builder.directory(workingDirectory);
    }
    builder.redirectErrorStream(true);
    if (logFilePath != null) {
        builder.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(logFilePath)));
    }

    return builder;
}

From source file:com.amazonaws.eclipse.dynamodb.testtool.TestToolProcess.java

/**
 * Start the DynamoDBLocal process./*from   w  ww  .  ja v  a2  s.co  m*/
 *
 * @param  onExitAction optional action to be executed when the process
 *                      exits
 * @throws IOException  if starting the process fails
 */
public synchronized void start(final Runnable onExitAction) throws IOException {

    if (process != null) {
        throw new IllegalStateException("Already started!");
    }

    ProcessBuilder builder = new ProcessBuilder();

    builder.directory(installDirectory);
    builder.command(jre.getInstallLocation().getAbsolutePath().concat("/bin/java"),
            "-Djava.library.path=".concat(findLibraryDirectory().getAbsolutePath()), "-jar",
            "DynamoDBLocal.jar", "--port", Integer.toString(port));

    // Drop STDERR into STDOUT so we can handle them together.
    builder.redirectErrorStream(true);

    // Register a shutdown hook to kill DynamoDBLocal if Eclipse exits.
    Runtime.getRuntime().addShutdownHook(shutdownHook);

    // Start the DynamoDBLocal process.
    process = builder.start();

    // Start a background thread to read any output from DynamoDBLocal
    // and dump it to an IConsole.
    new ConsoleOutputLogger(process.getInputStream(), onExitAction).start();
}

From source file:de.tudarmstadt.ukp.dkpro.core.RSTAnnotator.java

@Override
public void initialize(UimaContext context) throws ResourceInitializationException {
    super.initialize(context);

    // perform sanity check
    if (sanityCheckOnInit) {
        File rstParserSrcDir = new File(rstParserSrcDirPath);

        // create process
        ProcessBuilder processBuilder = new ProcessBuilder().inheritIO();

        // working dir must be set to the src dir of RST parser
        processBuilder.directory(rstParserSrcDir);

        // run the command
        processBuilder.command("python", new File(rstParserSrcDir, "sanity_check.py").getAbsolutePath());

        try {//  w  w  w. j a v a  2 s.  c  o m
            Process process = processBuilder.start();

            // and wait
            int returnValue = process.waitFor();

            if (returnValue != 0) {
                throw new RuntimeException("Process exited with code " + returnValue);
            }

        } catch (IOException | InterruptedException e) {
            throw new ResourceInitializationException(e);
        }
    }
}

From source file:org.jellycastle.maven.Maven.java

/**
 * Get Java process builder with basic command line execution based on
 * given os nature./*from  w  ww . java 2s.com*/
 * @return
 */
private ProcessBuilder getProcessBuilder() {
    List<String> commands = new ArrayList<String>();
    if (SystemUtils.IS_OS_UNIX) {
        commands.add(BASH);
        commands.add(BASH_OPTION_C);
    } else {
        commands.add(CMD);
        commands.add(CMD_OPTION_C);
    }

    commands.add(buildCommand());

    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.directory(Paths.get("").toFile().getAbsoluteFile());

    log.trace("Returning ProcessBuilder for command:" + commands);
    return pb;
}

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

@Deprecated
private ProcessBuilder getProcessBuilder(File workingDirectory, String binPath, List<String> args,
        String logFilePath) {//from   www.j  a  v  a 2 s .  c  o  m
    List<String> commandArgs = new ArrayList<>();
    commandArgs.add(binPath);
    commandArgs.addAll(args);
    ProcessBuilder builder = new ProcessBuilder(commandArgs);

    // working directoy and error and output log outputs
    if (workingDirectory != null) {
        builder.directory(workingDirectory);
    }
    builder.redirectErrorStream(true);
    if (logFilePath != null) {
        builder.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(logFilePath)));
    }

    return builder;
}