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

ProcessBuilder

Source Link

Usage

From source file:com.github.hdl.tensorflow.yarn.app.TFClient.java

private void execCmd(List<String> cmd) {
    try {/*from   w w  w .ja  v a  2 s.  c  o m*/
        Process process = new ProcessBuilder().command(cmd).inheritIO().start();
        process.waitFor();
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:com.github.psorobka.appium.StartServerMojo.java

@Override
public void execute() throws MojoExecutionException {
    try {/*from w  w w  .  ja va  2s. c  o m*/
        getLog().info("Starting Appium server...");
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.command("appium", "--log-timestamp", "--log",
                new File(target, "appiumLog.txt").getAbsolutePath());
        processBuilder.redirectError(new File(target, "appiumErrorLog.txt"));
        processBuilder.redirectOutput(new File(target, "appiumOutputLog.txt"));
        getLog().debug("Appium server commands " + processBuilder.command());
        Process process = processBuilder.start();
        if (!Processes.newPidProcess(process).isAlive()) {
            throw new MojoExecutionException("Failed to start Appium server");
        }
        int pid = PidUtil.getPid(process);
        getLog().info("Appium server started");
        getLog().debug("Appium server PID " + pid);
        FileUtils.writeStringToFile(new File(target, "appium.pid"), Integer.toString(pid));
        //Dumb way to sleep until appium starts - file watcher would be better
        Thread.sleep(5000);
    } catch (IOException | InterruptedException ex) {
        throw new MojoExecutionException("Failed to start Appium server", ex);
    }
}

From source file:edu.uci.ics.asterix.installer.transaction.RecoveryIT.java

@BeforeClass
public static void setUp() throws Exception {
    File outdir = new File(PATH_ACTUAL);
    outdir.mkdirs();/*from  w w  w .  jav a  2  s.c om*/

    asterixInstallerPath = new File(System.getProperty("user.dir"));
    installerTargetPath = new File(asterixInstallerPath, "target");
    managixHomeDirName = installerTargetPath.list(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return new File(dir, name).isDirectory() && name.startsWith("asterix-installer")
                    && name.endsWith("binary-assembly");
        }
    })[0];
    managixHomePath = new File(installerTargetPath, managixHomeDirName).getAbsolutePath();
    LOGGER.info("MANAGIX_HOME=" + managixHomePath);

    pb = new ProcessBuilder();
    env = pb.environment();
    env.put("MANAGIX_HOME", managixHomePath);
    scriptHomePath = asterixInstallerPath + File.separator + "src" + File.separator + "test" + File.separator
            + "resources" + File.separator + "transactionts" + File.separator + "scripts";
    env.put("SCRIPT_HOME", scriptHomePath);

    TestsUtils.executeScript(pb,
            scriptHomePath + File.separator + "setup_teardown" + File.separator + "configure_and_validate.sh");
    TestsUtils.executeScript(pb,
            scriptHomePath + File.separator + "setup_teardown" + File.separator + "stop_and_delete.sh");
}

From source file:io.grpc.alts.CheckGcpEnvironment.java

private static boolean isRunningOnGcp() {
    try {/*from w  w  w  . j  a  v  a2  s .  com*/
        if (SystemUtils.IS_OS_LINUX) {
            // Checks GCE residency on Linux platform.
            return checkProductNameOnLinux(Files.newBufferedReader(Paths.get(DMI_PRODUCT_NAME), UTF_8));
        } else if (SystemUtils.IS_OS_WINDOWS) {
            // Checks GCE residency on Windows platform.
            Process p = new ProcessBuilder().command(WINDOWS_COMMAND, "Get-WmiObject", "-Class", "Win32_BIOS")
                    .start();
            return checkBiosDataOnWindows(new BufferedReader(new InputStreamReader(p.getInputStream(), UTF_8)));
        }
    } catch (IOException e) {
        logger.log(Level.WARNING, "Fail to read platform information: ", e);
        return false;
    }
    // Platforms other than Linux and Windows are not supported.
    return false;
}

From source file:aiai.ai.core.ExecProcessService.java

public Result execCommand(List<String> cmd, File execDir, File consoleLogFile)
        throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder();
    pb.command(cmd);/*from w w w.j a  v  a  2s.  c o m*/
    pb.directory(execDir);
    pb.redirectErrorStream(true);
    final Process process = pb.start();

    final StreamHolder streamHolder = new StreamHolder();
    int exitCode;
    try (final FileOutputStream fos = new FileOutputStream(consoleLogFile);
            BufferedOutputStream bos = new BufferedOutputStream(fos)) {
        final Thread reader = new Thread(() -> {
            try {
                streamHolder.is = process.getInputStream();
                int c;
                while ((c = streamHolder.is.read()) != -1) {
                    bos.write(c);
                }
            } catch (IOException e) {
                log.error("Error collect data from output stream", e);
            }
        });
        reader.start();

        exitCode = process.waitFor();
        reader.join();
    } finally {
        try {
            if (streamHolder.is != null) {
                streamHolder.is.close();
            }
        } catch (Throwable th) {
            log.warn("Error with closing InputStream", th);
        }
    }

    log.info("Any errors of execution? {}", (exitCode == 0 ? "No" : "Yes"));
    log.debug("'\tcmd: {}", cmd);
    log.debug("'\texecDir: {}", execDir.getPath());
    String console = readLastLines(500, consoleLogFile);
    log.debug("'\tconsole output:\n{}", console);

    return new Result(exitCode == 0, exitCode, console);
}

From source file:com.blackducksoftware.integration.hub.docker.executor.Executor.java

public String[] executeCommand(final String commandString)
        throws IOException, InterruptedException, HubIntegrationException {
    final List<String> commandStringList = Arrays.asList(commandString.split(" "));
    final ProcessBuilder builder = new ProcessBuilder();
    builder.command(commandStringList.toArray(new String[commandStringList.size()]));
    builder.directory(new File("."));
    final Process process = builder.start();
    final boolean finished = process.waitFor(this.commandTimeout, TimeUnit.MILLISECONDS);
    if (!finished) {
        throw new HubIntegrationException(String.format(
                "Execution of command %s timed out (timeout: %d milliseconds)", commandString, commandTimeout));
    }//  w w w.  j av  a  2  s. c  o  m
    final int errCode = process.exitValue();
    if (errCode == 0) {
        logger.debug(String.format("Execution of command: %s: Succeeded", commandString));
    } else {
        throw new HubIntegrationException(
                String.format("Execution of command: %s: Error code: %d", commandString, errCode));
    }
    final InputStream inputStream = process.getInputStream();
    final String outputString = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
    logger.debug(String.format("Command output:/n%s", outputString));
    return outputString.split(System.lineSeparator());
}

From source file:io.schultz.dustin.service.VideoDownloaderService.java

public void download(final URL url, final OutputStream outputStream) {

    final String filename = downloaderProperties.getDownloadDir() + File.separator + "video-"
            + new Date().getTime() + ".mp4";

    List<String> cmd = new ArrayList<>();
    cmd.add(downloaderProperties.getDownloaderAbsolutePath());
    cmd.add(url.toString());//from ww  w . j ava2  s.  c o m
    cmd.add("-f mp4");
    cmd.add("-o" + filename);

    if (log.isDebugEnabled()) {
        log.debug("Running command: {}", cmd.stream().collect(Collectors.joining(" ")));
    }

    try {
        Process p = new ProcessBuilder().command(cmd).start();
        int c;
        while ((c = p.getInputStream().read()) != -1) {
            outputStream.write(c);
            outputStream.flush();
        }
    } catch (IOException e) {
        log.error("Unable to download video at {}", url, e);
    }
}

From source file:com.yfiton.oauth.receiver.GraphicalReceiver.java

@Override
public AuthorizationData requestAuthorizationData(String authorizationUrl,
        String authorizationCodeParameterName, String... requestParameterNames) throws NotificationException {
    try {//from w w w .  j ava 2s . co m
        File tmpFile = File.createTempFile("yfiton", ".auth");

        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.inheritIO();
        processBuilder.command("java",
                //"-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005",
                "-classpath", getClasspath(), WebBrowser.class.getName(),
                "--authorization-code-parameter-name=" + authorizationCodeParameterName,
                "--authorization-file=" + tmpFile.getAbsolutePath(), "--authorization-url=" + authorizationUrl,
                "--debug=" + (debug ? "true" : "false"),
                "--webengine-listener-class=" + webEngineListenerClazz.getName());

        Process process = processBuilder.start();

        int returnCode = process.waitFor();

        switch (returnCode) {
        case 0:
            return OAuthUtils.readAuthorizationInfo(tmpFile.toPath());
        case 255:
            throw new NotificationException("Authorization process aborted");
        default:
            throw new NotificationException(
                    "Error occurred while waiting for process: return code " + returnCode);
        }
    } catch (ClassNotFoundException | ConfigurationException | IOException | InterruptedException e) {
        throw new NotificationException(e.getMessage());
    }
}

From source file:com.web.searchlocal.flashpaper.thread.Covnert2SwfTask.java

/** 
 * /*ww  w .ja va  2  s  .com*/
 */
public void excute() {
    String tmpOutFile = outFile.getPath().concat(File.separator)
            .concat(inFile.getName().replaceAll("[.]{1}.*$", ".swf"));
    List<String> commandArray = new ArrayList<String>();
    commandArray.add(defaultCommand);
    commandArray.add(inFile.getPath());
    commandArray.add("-o");
    commandArray.add(tmpOutFile);
    ProcessBuilder pbObj = new ProcessBuilder();
    pbObj.command(commandArray);
    pbObj.directory(outFile);
    pbObj.redirectErrorStream(true);
    try {
        Process proObj = pbObj.start();
        final InputStream ins = proObj.getInputStream();
        final ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        Thread th = new Thread() {
            public void run() {
                ReadableByteChannel rbcObj = Channels.newChannel(ins);
                try {
                    while (rbcObj.read(byteBuffer) != -1) {
                        byteBuffer.flip();
                        logger.info(java.nio.charset.Charset.defaultCharset().decode(byteBuffer));
                        byteBuffer.clear();
                    }
                } catch (IOException e) {
                    logger.error(e);
                }
            }
        };
        th.setDaemon(true);
        th.start();
        try {
            proObj.waitFor();
            logger.error("??." + tmpOutFile);
        } catch (InterruptedException e) {
            logger.error(e);
        }
    } catch (IOException e) {
        logger.error(e);
    }
}

From source file:functionaltests2.SchedulerCommandLine.java

/**
 * Start a Scheduler and Resource Manager.
 *//*from   w  w  w .  j a  v a2  s .c om*/
public static void startSchedulerCmdLine(boolean restart, File proactiveConf) throws Exception {

    File schedHome = new File(System.getProperty("pa.scheduler.home")).getCanonicalFile();
    File rmHome = new File(System.getProperty("pa.rm.home")).getCanonicalFile();
    if (proactiveConf != null) {
        FileUtils.copyFile(proactiveConf,
                new File(schedHome, "config" + fs + "proactive" + fs + "ProActiveConfiguration.xml"));
    }

    System.out.println(schedHome);

    p = null;
    ProcessBuilder pb = new ProcessBuilder();
    if (OperatingSystem.getOperatingSystem().equals(OperatingSystem.unix)) {
        pb.directory(new File(schedHome + fs + "bin" + fs + "unix"));
        pb.command("/bin/bash", restart ? "scheduler-start" : "scheduler-start-clean",
                "-Dproactive.communication.protocol=pnp", "-Dproactive.pnp.port=9999");
        pb.environment().put("SchedulerTStarter", "SchedulerTStarter");
        p = pb.start();

    } else {

        pb.directory(new File(schedHome + fs + "bin" + fs + "windows"));

        pb.command("cmd.exe", "/c", restart ? "scheduler-start.bat" : "scheduler-start-clean.bat",
                "-Dproactive.communication.protocol=pnp", "-Dproactive.pnp.port=9999");
        pb.environment().put("SchedulerTStarter", "SchedulerTStarter");
        p = pb.start();

    }

    IOTools.LoggingThread lt1 = new IOTools.LoggingThread(p.getInputStream(), "[SchedulerTStarter]",
            System.out);
    Thread t1 = new Thread(lt1, "SchedulerTStarter");
    t1.setDaemon(true);
    t1.start();

    // waiting the initialization
    RMAuthentication rmAuth = RMConnection.waitAndJoin("pnp://localhost:9999");

    System.out.println("RM successfully joined.");

    SchedulerConnection.waitAndJoin("pnp://localhost:9999");
    System.out.println("Scheduler successfully joined.");

}