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:com.nesscomputing.db.postgres.embedded.EmbeddedPostgreSQL.java

private void startPostmaster() throws IOException {
    final StopWatch watch = new StopWatch();
    watch.start();/*from www.  j  a v a  2 s.c  o m*/
    Preconditions.checkState(started.getAndSet(true) == false, "Postmaster already started");

    final List<String> args = Lists.newArrayList(pgBin("postgres"), "-D", dataDirectory.getPath(), "-p",
            Integer.toString(port), "-i", "-F");

    for (final Entry<String, String> config : postgresConfig.entrySet()) {
        args.add("-c");
        args.add(config.getKey() + "=" + config.getValue());
    }

    final ProcessBuilder builder = new ProcessBuilder(args);
    builder.redirectErrorStream(true);
    builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    postmaster = builder.start();
    LOG.info("{} postmaster started as {} on port {}.  Waiting up to {}ms for server startup to finish.",
            instanceId, postmaster.toString(), port, PG_STARTUP_WAIT_MS);

    Runtime.getRuntime().addShutdownHook(newCloserThread());

    waitForServerStartup(watch);
}

From source file:com.streamsets.datacollector.util.SystemProcessImpl.java

@Override
public void start(Map<String, String> env) throws IOException {
    Utils.checkState(output.createNewFile(), Utils.formatL("Could not create output file: {}", output));
    Utils.checkState(error.createNewFile(), Utils.formatL("Could not create error file: {}", error));
    Utils.checkState(delegate == null, "start can only be called once");
    LOG.info("Standard output for process written to file: " + output);
    LOG.info("Standard error for process written to file: " + error);
    ProcessBuilder processBuilder = new ProcessBuilder().redirectInput(input).redirectOutput(output)
            .redirectError(error).directory(tempDir).command(args);
    processBuilder.environment().putAll(env);
    LOG.info("Starting: " + args);
    delegate = processBuilder.start();
    ThreadUtil.sleep(100); // let it start
    outputTailer = new SimpleFileTailer(output);
    errorTailer = new SimpleFileTailer(error);
}

From source file:com.anuta.internal.YangHelperMojo.java

/**
 * This method checks if a pyang is installed or not. If pyang is not installed it will silently return. 
 * @return/*from ww  w  . j a  va 2s  .  com*/
 */
private boolean isPyangInstalled() {
    try {
        ProcessBuilder pb = new ProcessBuilder(getCommandString(OperationType.VERSION));
        Process pr = pb.start();
        int exitVal = pr.waitFor();
        if (exitVal == 0) {
            BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
            String pyang_version = input.readLine();
            getLog().info("using " + pyang_version);
            if (pyang_version.contains("pyang ")) {
                String version = pyang_version.substring(pyang_version.indexOf("pyang ") + 6);
                if (versionCompare(version, pyangVersion) != 0) {
                    getLog().warn("Recommended pyang version " + pyangVersion + " using " + version);
                }
            }
            return true;
        } else {
            return false;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:io.hops.hopsworks.api.zeppelin.util.ZeppelinResource.java

private boolean isProccessAlive(String pid) {
    String[] command = { "kill", "-0", pid };
    ProcessBuilder pb = new ProcessBuilder(command);
    if (pid == null) {
        return false;
    }/*from ww  w.  jav a2s. co  m*/

    //TODO: We should clear the environment variables before launching the 
    // redirect stdout and stderr for child process to the zeppelin/project/logs file.
    int exitValue;
    try {
        Process p = pb.start();
        p.waitFor();
        exitValue = p.exitValue();
    } catch (IOException | InterruptedException ex) {

        logger.log(Level.WARNING, "Problem testing Zeppelin Interpreter: {0}", ex.toString());
        //if the pid file exists but we can not test if it is alive then
        //we answer true, b/c pid files are deleted when a process is killed.
        return true;
    }
    return exitValue == 0;
}

From source file:com.joyent.manta.client.MantaClientFindIT.java

/**
 * This test sees if find() can find a large number of files spread across
 * many directories. It validates the results against the node.js Manta CLI
 * tool mls./*from  w  ww  . java 2s .c o  m*/
 *
 * This test is disabled by default because it is difficult to know if the
 * running system has the node.js CLI tools properly installed. Please run
 * this test manually on an as-needed basis.
 */
@Test(enabled = false)
public void findMatchesMfind() throws SecurityException, IOException, InterruptedException {
    ConfigContext context = mantaClient.getContext();
    String reports = context.getMantaHomeDirectory() + SEPARATOR + "reports" + SEPARATOR + "usage" + SEPARATOR
            + "summary";
    String[] cmd = new String[] { "mfind", reports };

    ProcessBuilder processBuilder = new ProcessBuilder(cmd);

    Map<String, String> env = processBuilder.environment();
    env.put("MANTA_URL", context.getMantaURL());
    env.put("MANTA_USER", context.getMantaUser());
    env.put("MANTA_KEY_ID", context.getMantaKeyId());

    long mFindStart = System.nanoTime();
    Process process = processBuilder.start();

    String charsetName = StandardCharsets.UTF_8.name();

    List<String> objects = new LinkedList<>();

    try (Scanner scanner = new Scanner(process.getInputStream(), charsetName)) {
        while (scanner.hasNextLine()) {
            objects.add(scanner.nextLine());
        }
    }

    System.err.println("Waiting for mfind to complete");
    Assert.assertEquals(process.waitFor(), 0, "mfind exited with an error");
    long mFindEnd = System.nanoTime();
    System.err.printf("mfind process completed in %d ms\n", Duration.ofNanos(mFindEnd - mFindStart).toMillis());

    long findStart = System.nanoTime();

    List<String> foundObjects;
    try (Stream<MantaObject> findStream = mantaClient.find(reports)) {
        foundObjects = findStream.map(MantaObject::getPath).collect(Collectors.toList());
    }

    long findEnd = System.nanoTime();
    System.err.printf("find() completed in %d ms\n", Duration.ofNanos(findEnd - findStart).toMillis());

    Assert.assertEqualsNoOrder(objects.toArray(), foundObjects.toArray());
}

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

protected static Process launchProcess(final String[] cmdlist, final Map<String, String> environment)
        throws IOException {
    ArrayList<String> buff = new ArrayList<String>();
    for (String tok : cmdlist) {
        if (!tok.isEmpty()) {
            buff.add(tok);//from w  w  w.  j av a  2  s .  co  m
        }
    }

    ProcessBuilder builder = new ProcessBuilder(buff);
    builder.redirectErrorStream(true);
    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:com.ibm.liberty.starter.service.swagger.api.v1.ProviderEndpoint.java

private int generateCode(String javaHome, String swaggerCodeGenJarPath, String javaClientTemplates,
        String codeGenLanguage, String filePath, String outputDir) throws java.io.IOException {

    try {//  w  w  w  . j  a  va 2 s  .c o  m
        final ArrayList<String> commandList = new ArrayList<String>();

        if (javaHome == null || javaHome.trim().isEmpty()) {
            //Get java home
            javaHome = AccessController.doPrivileged(new PrivilegedAction<String>() {
                @Override
                public String run() {
                    return System.getProperty("java.home");
                }

            });
            if (!javaHome.endsWith("/")) {
                javaHome += "/";
            }
            log.fine("Retrieved Java home location from System property : " + javaHome);
        }

        commandList.add(javaHome + "bin/java");
        commandList.add("-jar");
        commandList.add(swaggerCodeGenJarPath);

        commandList.add("generate");
        commandList.add("-l");
        commandList.add(codeGenLanguage);

        if (javaClientTemplates != null && !javaClientTemplates.trim().isEmpty()) {
            commandList.add("-t");
            commandList.add(javaClientTemplates);
        }

        commandList.add("-i");
        commandList.add(filePath);
        commandList.add("-o");
        commandList.add(outputDir);

        StringBuilder sb = new StringBuilder();
        for (String command : commandList) {
            sb.append(command);
            sb.append(" ");
        }

        log.finer("Swagger code gen commands:\n" + sb.toString());

        //Run the command
        ProcessBuilder builder = new ProcessBuilder(commandList);
        builder.redirectErrorStream(true); //merge error and output together

        Process codeGenProc = builder.start();
        int exitVal = codeGenProc.waitFor();

        log.finer("Exit values: " + exitVal);

        if (exitVal != 0) {
            log.fine("Error : exit value is not 0. exitVal=" + exitVal);
            log.finer("output=" + getOutput(codeGenProc));
        } else {
            log.finer("Successfully generated code using SwaggerCodegen");
        }

        return exitVal;
    } catch (Exception e) {
        log.fine("Exception occurred while executing SwaggerCodegen : e=" + e);
        return -1;
    }
}

From source file:gr.aueb.dmst.istlab.unixtools.actions.impl.ExecuteCustomCommandAction.java

@Override
public void execute(ActionExecutionCallback<DataActionResult<InputStream>> callback)
        throws IOException, InterruptedException {
    DataActionResult<InputStream> result;
    List<String> arguments = EclipsePluginUtil.getSystemShellInfo();

    ProcessBuilder pb;

    if (SystemUtils.IS_OS_WINDOWS) {
        pb = new ProcessBuilder(arguments.get(0), arguments.get(1), arguments.get(2) + "\"cd "
                + this.commandToExecute.getShellDirectory() + ";" + this.commandToExecute.getCommand() + "\"");
    } else {/*w  w w. j a  va 2 s .  c o m*/
        arguments.add(this.commandToExecute.getCommand());
        pb = new ProcessBuilder(arguments);
        pb.directory(new File(this.commandToExecute.getShellDirectory()));
    }
    pb.redirectErrorStream(true);

    Process p;
    try {
        p = pb.start();
        p.waitFor();
        InputStream cmdStream = p.getInputStream();
        result = new DataActionResult<>(cmdStream);
    } catch (IOException e) {
        logger.fatal("IO problem occurred while executing the command");
        result = new DataActionResult<>(e);
        throw new IOException(e);
    } catch (InterruptedException e) {
        logger.fatal("The current thread has been interrupted while executing the command");
        result = new DataActionResult<>(e);
        throw new InterruptedException();
    }

    callback.onCommandExecuted(result);
}

From source file:com.symbian.driver.plugins.romflash.Activator.java

public boolean FlashRom(String romLocation) {

    try {/* w w w.j  a v a  2 s .c o m*/
        File rom = new File(romLocation);
        if (method.compareToIgnoreCase("serial") == 0) {
            if (!(switchOff() && switchOn())) {
                LOGGER.log(Level.SEVERE, "Could not reboot device, so No rom flashing.");
                return false;
            }
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish.");
            }
            File trgtTestFile = JarUtils.extractResource(Activator.class, "/resource/trgtest.exe");
            if (trgtTestFile.isFile()) {
                ProcessBuilder ld = new ProcessBuilder(trgtTestFile.getAbsolutePath(), portNumber,
                        rom.getCanonicalPath());
                ld.directory(trgtTestFile.getParentFile());
                Process pp = ld.start();
                LOGGER.log(Level.INFO, "started trgtest process");
                BufferedReader br = new BufferedReader(new InputStreamReader(pp.getInputStream()));
                StringBuffer sb = new StringBuffer();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line).append("\n");
                    LOGGER.log(Level.INFO, line);
                }
                //String answer = sb.toString();

                try {
                    LOGGER.log(Level.INFO, "going to wait now for trgtest to finish");
                    pp.waitFor();
                } catch (InterruptedException e) {
                    LOGGER.log(Level.SEVERE, "Failed to wait for trgtest.exe to finish.");
                }
                LOGGER.log(Level.INFO, "trgtest returned: " + pp.exitValue());
                pp.destroy();

            } else {
                LOGGER.log(Level.SEVERE, "Could not find trgtest.exe file.");
            }
        } else // usb rom loading
        {
            // switch the device off...
            switchOff();
            List<File> lis1 = Arrays.asList(File.listRoots());
            // get reboot plugin, and reboot the device
            switchOn(); // or just switch on as things may be
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish.");
            }
            File[] listRoots2 = File.listRoots();
            // find the drive that made the difference!!
            File diff = null;
            for (File root : listRoots2) {
                if (!lis1.contains(root)) // found new drive
                {
                    diff = root;
                    break;
                }
            }
            File romfl = new File(diff, rom.getName());
            romfl.delete();
            File aCopyFrom = new File(rom.getCanonicalPath());
            FileChannel lSrcChannel = new FileInputStream(aCopyFrom).getChannel();
            FileChannel lDstChannel = new FileOutputStream(romfl).getChannel();
            lDstChannel.transferFrom(lSrcChannel, 0, lSrcChannel.size());
            lSrcChannel.close();
            lDstChannel.close();

            File syncFile = JarUtils.extractResource(Activator.class, "/resource/sync.exe");
            if (syncFile.isFile()) {

                ProcessBuilder ld = new ProcessBuilder(syncFile.getAbsolutePath(), "-r", "-e", diff.toString());

                ld.directory(syncFile.getParentFile());
                ld.start();
                // wait 10 seconds for the rom to load ...
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish.");
                }
            } else {
                LOGGER.log(Level.SEVERE, "Could not find sync.exe file.");
            }
        }
    } catch (IOException lIOException) {
        LOGGER.log(Level.SEVERE, "Could not flash ROM " + lIOException.getMessage());
        return false;
    }
    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish.");
    }
    return true;
}

From source file:org.generationcp.ibpworkbench.launcher.Launcher.java

protected void stopMySQLService() {
    ProcessBuilder pb = new ProcessBuilder("NET", "stop", "MySQLIBWS");
    try {/*from w  w  w  . j  ava  2 s . co  m*/
        Process process = pb.start();
        process.waitFor();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}