Example usage for java.lang ProcessBuilder ProcessBuilder

List of usage examples for java.lang ProcessBuilder ProcessBuilder

Introduction

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

Prototype

public ProcessBuilder(String... command) 

Source Link

Document

Constructs a process builder with the specified operating system program and arguments.

Usage

From source file:org.obiba.rserver.service.RServerService.java

private ProcessBuilder buildRProcess() {
    List<String> args = getArguments();
    log.info("Starting R server: {}", StringUtils.collectionToDelimitedString(args, " "));
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.directory(getWorkingDirectory());
    pb.redirectErrorStream(true);/* w  w  w.  j  a  v a  2 s.  c  o  m*/
    pb.redirectOutput(ProcessBuilder.Redirect.appendTo(getRserveLogFile()));
    return pb;
}

From source file:gda.device.detector.mythen.client.TextClientMythenClient.java

private MythenTextClientExecResult execProcess(String... args) throws DeviceException {

    if (!EXEC_LOCK.tryLock()) {
        throw new DeviceException("Cannot acquire: client is already running");
    }/*from   w  w w .ja  v a  2 s  .com*/

    try {
        MythenTextClientExecResult result = new MythenTextClientExecResult();

        // Build argument list
        List<String> argList = new Vector<String>();
        argList.add(host);
        argList.addAll(Arrays.asList(args));
        logger.info("Starting acquisition");
        logger.debug("Executing Mythen client with args " + argList);

        // Prepend executable name to argument list
        argList.add(0, mythenClientCommand);

        ProcessBuilder pb = new ProcessBuilder(argList);
        try {
            Process p = pb.start();
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            try {
                logger.debug("wait for TextClient to complete data acquisition ...");
                p.waitFor();
                logger.debug("TextClient returned.");
            } catch (InterruptedException e) {
                throw new DeviceException("Unable to wait for text client to finish", e);
            }

            result.output = FileCopyUtils.copyToString(br);

            result.exitValue = p.exitValue();
            if (result.exitValue != 0) {
                throw new DeviceException(
                        String.format("Client exited with non-zero status: %d", result.exitValue));
            }
            InterfaceProvider.getTerminalPrinter().print("Save to file " + this.params.getFilename());
            logger.info("Acquisition completed successfully");
            logger.debug("Client successfully exited with status code " + result.exitValue);

            return result;

        } catch (IOException e) {
            throw new DeviceException("Client operation failed", e);
        }
    } finally {
        EXEC_LOCK.unlock();
    }
}

From source file:com.netflix.dynomitemanager.defaultimpl.StorageProcessManager.java

public void stop() throws IOException {
    logger.info("Stopping Storage process ....");
    List<String> command = Lists.newArrayList();
    if (!"root".equals(System.getProperty("user.name"))) {
        command.add(SUDO_STRING);// w w  w  .j  a  v a 2 s . co m
        command.add("-n");
        command.add("-E");
    }
    for (String param : config.getStorageStopScript().split(" ")) {
        if (StringUtils.isNotBlank(param))
            command.add(param);
    }
    ProcessBuilder stopCass = new ProcessBuilder(command);
    stopCass.directory(new File("/"));
    stopCass.redirectErrorStream(true);
    Process stopper = stopCass.start();

    sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS);
    try {
        int code = stopper.exitValue();
        if (code == 0) {
            logger.info("Storage process has been stopped");
            instanceState.setStorageProxyAlive(false);
        } else {
            logger.error("Unable to stop storage process. Error code: {}", code);
            logProcessOutput(stopper);
        }
    } catch (Exception e) {
        logger.warn("couldn't shut down Storage process correctly", e);
    }
}

From source file:functionaltests.RestFuncTHelper.java

public static void startRestfulSchedulerWebapp(int nbNodes) throws Exception {
    // Kill all children processes on exit
    org.apache.log4j.BasicConfigurator.configure(new org.apache.log4j.varia.NullAppender());
    CookieBasedProcessTreeKiller.registerKillChildProcessesOnShutdown("rest_tests");

    List<String> cmd = new ArrayList<>();
    String javaPath = RestFuncTUtils.getJavaPathFromSystemProperties();
    cmd.add(javaPath);/*from   w  ww . j  a  v  a2 s.c  o m*/
    cmd.add("-Djava.security.manager");
    cmd.add(CentralPAPropertyRepository.JAVA_SECURITY_POLICY.getCmdLine() + toPath(serverJavaPolicy));

    cmd.add(CentralPAPropertyRepository.PA_HOME.getCmdLine() + getSchedHome());
    cmd.add(PASchedulerProperties.SCHEDULER_HOME.getCmdLine() + getSchedHome());
    cmd.add(PAResourceManagerProperties.RM_HOME.getCmdLine() + getRmHome());

    cmd.add(PAResourceManagerProperties.RM_DB_HIBERNATE_DROPDB.getCmdLine()
            + System.getProperty("rm.deploy.dropDB", "true"));
    cmd.add(PAResourceManagerProperties.RM_DB_HIBERNATE_CONFIG.getCmdLine() + toPath(rmHibernateConfig));

    cmd.add(PASchedulerProperties.SCHEDULER_DB_HIBERNATE_DROPDB.getCmdLine()
            + System.getProperty("scheduler.deploy.dropDB", "true"));
    cmd.add(PASchedulerProperties.SCHEDULER_DB_HIBERNATE_CONFIG.getCmdLine() + toPath(schedHibernateConfig));

    cmd.add(CentralPAPropertyRepository.PA_COMMUNICATION_PROTOCOL.getCmdLine() + "pnp");
    cmd.add(PNPConfig.PA_PNP_PORT.getCmdLine() + "1200");

    cmd.add("-cp");
    cmd.add(getClassPath());
    cmd.add(SchedulerStarter.class.getName());
    cmd.add("-ln");
    cmd.add("" + nbNodes);

    ProcessBuilder processBuilder = new ProcessBuilder(cmd);
    processBuilder.redirectErrorStream(true);
    schedProcess = processBuilder.start();

    ProcessStreamReader out = new ProcessStreamReader("scheduler-output: ", schedProcess.getInputStream());
    out.start();

    // RM and scheduler are on the same url
    String port = "1200";
    String url = "pnp://localhost:" + port + "/";

    // Connect a scheduler client
    SchedulerAuthenticationInterface schedAuth = SchedulerConnection.waitAndJoin(url,
            TimeUnit.SECONDS.toMillis(60));
    schedulerPublicKey = schedAuth.getPublicKey();
    Credentials schedCred = RestFuncTUtils.createCredentials("admin", "admin", schedulerPublicKey);
    scheduler = schedAuth.login(schedCred);

    // Connect a rm client
    RMAuthentication rmAuth = RMConnection.waitAndJoin(url, TimeUnit.SECONDS.toMillis(60));
    Credentials rmCredentials = getRmCredentials();
    rm = rmAuth.login(rmCredentials);

    restServerUrl = "http://localhost:8080/rest/";
    restfulSchedulerUrl = restServerUrl + "scheduler";

    await().atMost(Duration.FIVE_MINUTES).until(restIsStarted());
}

From source file:edu.uci.ics.asterix.installer.test.AsterixClusterLifeCycleIT.java

private static Process invoke(String... args) throws Exception {
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.redirectErrorStream(true);// ww w  .  j  av a 2  s .  c  om
    Process p = pb.start();
    return p;
}

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   www . ja v  a2  s . co m
        }
    }

    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.nabla.project.application.tool.runner.ServiceInvoker.java

private void invokeInNewJVM(MethodInvocation invocation) {

    try {/*  ww  w .jav a2 s  .  c o m*/

        checkInvocationArgumentsForJVMTransfer(invocation.getArguments());

        String classpath = System.getProperty("java.class.path");

        if (newVMClasspathRoot != null) {

            classpath = generateClassPath(newVMClasspathRoot);

        }

        ProcessBuilder pb = new ProcessBuilder(new String[] { "java", "-classpath", classpath,
                "com.nabla.project.application.tool.runner.ServiceRunner", newVMconfigFileName,
                newVMServiceBeanName, invocation.getMethod().getName() });
        Process p = pb.start();

        ObjectOutputStream oos = new ObjectOutputStream(p.getOutputStream());

        oos.writeObject(invocation.getArguments());
        oos.flush();

    } catch (Exception ioe) {

        throw new RuntimeException(ioe);

    }

}

From source file:ch.entwine.weblounge.common.impl.util.process.ProcessExecutor.java

/**
 * Executes the process. During execution, {@link #onLineRead(String)} will be
 * called for process output. When finished, {@link #onProcessFinished(int)}
 * is called.//from   w w  w .  ja v a  2 s . c  om
 * 
 * @throws ProcessExcecutorException
 *           if an error occurs during execution
 */
public final void execute() throws ProcessExcecutorException {
    BufferedReader in = null;
    Process process = null;
    StreamHelper errorStreamHelper = null;
    try {
        // create process.
        // no special working directory is set which means the working directory
        // of the current java process is used.
        ProcessBuilder pbuilder = new ProcessBuilder(commandLine);
        pbuilder.redirectErrorStream(redirectErrorStream);
        process = pbuilder.start();
        // Consume error stream if necessary
        if (!redirectErrorStream) {
            errorStreamHelper = new StreamHelper(process.getErrorStream());
        }
        // Read input and
        in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            if (!onLineRead(line))
                break;
        }

        // wait until the task is finished
        process.waitFor();
        int exitCode = process.exitValue();
        onProcessFinished(exitCode);
    } catch (Throwable t) {
        String msg = null;
        if (errorStreamHelper != null) {
            msg = errorStreamHelper.contentBuffer.toString();
        } else {
            msg = t.getMessage();
        }

        // TODO: What if the error stream has been redirected? Can we still get
        // the error message?

        throw new ProcessExcecutorException(msg, t);
    } finally {
        if (process != null)
            process.destroy();
        IOUtils.closeQuietly(in);
    }
}

From source file:com.qhrtech.emr.launcher.TemplateLauncherManager.java

private void doRefresh() {
    synchronized (eventLock) {
        try {//from   w  ww  . j  a  v a 2 s .  c  o  m
            doGeneration();
            if (notifyCommand != null) {
                ProcessBuilder pb = new ProcessBuilder(notifyCommand);
                pb.redirectError(ProcessBuilder.Redirect.INHERIT);
                pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
                pb.start().waitFor();
            }
        } catch (Exception ex) {
            LoggerFactory.getLogger(getClass()).error("Error reloading templates.", ex);
        }
    }
}

From source file:com.jstar.eclipse.services.JStar.java

public Process executeJStar(final IFolder workingDirectory, final IFolder folder, final String spec,
        final String logic, final String abs, final String jimpleFile, final PrintMode printMode,
        final String debugMode) throws IOException {

    final List<String> command = new ArrayList<String>();
    command.add(PreferenceConstants.getJStarExecutable());
    command.add("-e");
    command.add(printMode.getCmdOption());
    command.add("-l");
    command.add(logic);//www.  j av a  2s .c om
    command.add("-a");
    command.add(abs);
    command.add("-s");
    command.add(spec);
    command.add("-f");
    command.add(jimpleFile);

    if (StringUtils.isNotBlank(debugMode)) {
        command.add("-d");
        command.add(debugMode);
    }

    ProcessBuilder pb = new ProcessBuilder(command);
    pb.directory(new File(workingDirectory.getLocation().toOSString()));

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

    //TODO: jStar accepts only ':' as path separator
    env.put(PreferenceConstants.JSTAR_LOGIC_LIBRARY,
            PreferenceConstants.getJStarLogicLibrary() + ':' + folder.getLocation().toOSString());

    env.put(PreferenceConstants.JSTAR_ABS_LIBRARY,
            PreferenceConstants.getJStarAbsLibrary() + ':' + folder.getLocation().toOSString());

    env.put(PreferenceConstants.JSTAR_SPECS_LIBRARY,
            PreferenceConstants.getJStarSpecLibrary() + ':' + folder.getLocation().toOSString());

    env.put(PreferenceConstants.JSTAR_SMT_PATH, PreferenceConstants.getSmtPath());
    env.put(PreferenceConstants.JSTAR_SMT_ARGUMENTS, PreferenceConstants.getSmtAtguments());

    env.put(TERM, XTERMCOLOR);

    return pb.start();
}