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:com.kylinolap.common.util.OSCommandExecutor.java

private void runNativeCommand() throws IOException {
    String[] cmd = new String[3];
    String osName = System.getProperty("os.name");
    if (osName.startsWith("Windows")) {
        cmd[0] = "cmd.exe";
        cmd[1] = "/C";
    } else {//w  ww .  ja v  a 2  s .c om
        cmd[0] = "/bin/bash";
        cmd[1] = "-c";
    }
    cmd[2] = command;

    ProcessBuilder builder = new ProcessBuilder(cmd);
    builder.redirectErrorStream(true);
    Process proc = builder.start();

    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    IOUtils.copy(proc.getInputStream(), buf);
    output = buf.toString("UTF-8");

    try {
        exitCode = proc.waitFor();
    } catch (InterruptedException e) {
        throw new IOException(e);
    }
}

From source file:com.gordoni.opal.ScenarioSet.java

public void subprocess(String cmd, String prefix, String... args) throws IOException, InterruptedException {
    String real_cwd = System.getProperty("user.dir");
    List<String> arguments = new ArrayList<String>(Arrays.asList(args));
    arguments.add(0, real_cwd + "/" + cmd);
    ProcessBuilder pb = new ProcessBuilder(arguments);
    Map<String, String> env = pb.environment();
    env.put("OPAL_FILE_PREFIX", cwd + "/" + prefix);
    pb.redirectError(Redirect.INHERIT);/*from   w  ww . j  av a 2 s .c  o  m*/
    Process p = pb.start();

    InputStream stdout = p.getInputStream();
    byte buf[] = new byte[8192];
    while (stdout.read(buf) != -1) {
    }
    p.waitFor();
    assert (p.exitValue() == 0);
}

From source file:com.twitter.bazel.checkstyle.PythonCheckstyle.java

private static void runLinter(List<String> command) throws IOException {
    LOG.finer("checkstyle command: " + command);

    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
    Process pylint = processBuilder.start();

    try {//from  w  ww  .  j av a2  s.  co m
        pylint.waitFor();
    } catch (InterruptedException e) {
        throw new RuntimeException("python checkstyle command was interrupted: " + command, e);
    }

    if (pylint.exitValue() == 30) {
        LOG.warning("python checkstyle detected bad styles.");
        // SUPPRESS CHECKSTYLE RegexpSinglelineJava
        System.exit(1);
    }

    if (pylint.exitValue() != 0) {
        throw new RuntimeException("python checkstyle command failed with status " + pylint.exitValue());
    }
}

From source file:com.orange.clara.cloud.servicedbdumper.dbdumper.core.AbstractCoreDbAction.java

private ProcessBuilder generateProcessBuilder(String[] commandLine) {
    if (this.showCommandLine) {
        logger.info("Running command line: " + String.join(" ", commandLine));
    }//from  w  w w . j a  v a 2 s .  co m
    ProcessBuilder pb = new ProcessBuilder(commandLine);
    return pb;
}

From source file:com.vaadin.addon.charts.util.SVGGenerator.java

protected static Process startPhantomJS() {
    try {/*from  ww w  . j av  a  2 s.  c o m*/
        ArrayList<String> commands = new ArrayList<String>();
        commands.add(PHANTOM_EXEC);
        // comment out for debugging
        // commands.add("--remote-debugger-port=9001");

        ensureTemporaryFiles();

        commands.add(JS_CONVERTER.getAbsolutePath());

        commands.add("-jsstuff");
        commands.add(JS_STUFF.getAbsolutePath());

        final Process process = new ProcessBuilder(commands).start();
        final BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(process.getInputStream()));
        String readLine = bufferedReader.readLine();
        if (!readLine.contains("ready")) {
            throw new RuntimeException("PHANTOM JS NOT READY");
        }
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                super.run();
                if (process != null) {
                    System.out.println("Shutting down PhantomJS instance");
                    process.destroy();
                }
            }
        });

        return process;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.apress.prospringintegration.customadapters.outbound.ShellMessageWritingMessageEndpoint.java

protected int writeToShellCommand(String[] cmds, String msg) {
    try {//from   w w  w  .ja v  a 2 s. co  m
        ProcessBuilder processBuilder = new ProcessBuilder(Arrays.asList(cmds));
        Process proc = processBuilder.start();

        Writer streamWriter = null;

        try {
            streamWriter = new OutputStreamWriter(proc.getOutputStream());
            streamWriter.write(msg);
        } finally {
            IOUtils.closeQuietly(streamWriter);
        }

        int retVal = proc.waitFor();

        if (retVal != 0) {
            throw new RuntimeException("couldn't write message to 'write'");
        }

        return retVal;
    } catch (Throwable th) {
        throw new RuntimeException(th);
    }
}

From source file:net.sourceforge.atunes.kernel.modules.player.mplayer.MPlayerEngine.java

@Override
public boolean isEngineAvailable() {
    InputStream in = null;/*from   w  ww  . ja  v a  2 s  .co m*/
    try {
        // Processes in Windows need to read input stream, if not process is
        // blocked
        // so read input stream
        String command = getOsManager().getPlayerEngineCommand(this);
        if (command != null) {
            Process testEngineProcess = new ProcessBuilder(command).start();
            in = testEngineProcess.getInputStream();
            IOUtils.readLines(in);
            int rc = testEngineProcess.waitFor();
            return rc == 0;
        }
    } catch (IOException e) {
        Logger.error(e);
    } catch (InterruptedException e) {
        Logger.error(e);
    } finally {
        ClosingUtils.close(in);
    }
    return false;
}

From source file:net.urlgrey.mythpodcaster.transcode.FFMpegTranscoderImpl.java

public void transcode(File workingDirectory, GenericTranscoderConfigurationItem genericConfig, File inputFile,
        File outputFile) throws Exception {
    LOG.info("transcode started: inputFile [" + inputFile.getAbsolutePath() + "], outputFile ["
            + outputFile.getAbsolutePath() + "]");

    FFMpegTranscoderConfigurationItem config = (FFMpegTranscoderConfigurationItem) genericConfig;
    List<String> commandList = new ArrayList<String>();
    commandList.add(niceLocation);/*from w  w  w  . j a  v  a  2  s. c  o  m*/
    commandList.add("-n");
    commandList.add(Integer.toString(config.getNiceness()));
    commandList.add(ffmpegLocation);
    commandList.add("-i");
    commandList.add(inputFile.getAbsolutePath());
    commandList.addAll(config.getParsedEncoderArguments());
    commandList.add(outputFile.getAbsolutePath());
    ProcessBuilder pb = new ProcessBuilder(commandList);

    // Needed for ffmpeg
    pb.environment().put("LD_LIBRARY_PATH", "/usr/local/lib:");
    pb.redirectErrorStream(true);
    pb.directory(workingDirectory);
    Process process = null;

    try {
        // Get the ffmpeg process
        process = pb.start();
        // We give a couple of secs to complete task if needed
        Future<List<String>> stdout = pool.submit(new OutputMonitor(process.getInputStream()));
        List<String> result = stdout.get(config.getTimeout(), TimeUnit.SECONDS);
        process.waitFor();
        final int exitValue = process.exitValue();
        LOG.info("FFMPEG exit value: " + exitValue);
        if (exitValue != 0) {
            for (String line : result) {
                LOG.error(line);
            }
            throw new Exception("FFMpeg return code indicated failure: " + exitValue);
        }
    } catch (InterruptedException e) {
        throw new Exception("FFMpeg process interrupted by another thread", e);
    } catch (ExecutionException ee) {
        throw new Exception("Something went wrong parsing FFMpeg output", ee);
    } catch (TimeoutException te) {
        // We could not get the result before timeout
        throw new Exception("FFMpeg process timed out", te);
    } catch (RuntimeException re) {
        // Unexpected output from FFMpeg
        throw new Exception("Something went wrong parsing FFMpeg output", re);
    } finally {
        if (process != null) {
            process.destroy();
        }
    }

    LOG.debug("transcoding finished");
}

From source file:com.mcapanel.bukkit.BukkitServer.java

private BukkitServer(Long id, String serverName, File serverJar, String minMemory, String maxMemory) {
    this.ap = AdminPanelWrapper.getInstance();

    this.serverId = id;
    this.consoleFocus = false;

    this.serverJar = serverJar;
    this.serverName = serverName;

    this.minMemory = minMemory;
    this.maxMemory = maxMemory;

    this.bukkitConfig = new BukkitConfig(serverJar);
    this.serverStatus = ServerStatus.STOPPED;

    pluginConnector = new PluginConnector(this);

    processBuilder = new ProcessBuilder(new String[] { "java", "-Djline.terminal=jline.UnsupportedTerminal",
            "-Xms" + minMemory, "-Xmx" + maxMemory, "-jar", serverJar.getAbsolutePath() });

    processBuilder.directory(serverJar.getParentFile());

    copyPlugin();/*  w  w w  .  j  av a  2  s  . co  m*/
}

From source file:com.netscape.cmstools.profile.ProfileEditCLI.java

public void execute(String[] args) throws Exception {
    // Always check for "--help" prior to parsing
    if (Arrays.asList(args).contains("--help")) {
        printHelp();/* ww  w. java  2 s  .co m*/
        return;
    }

    CommandLine cmd = parser.parse(options, args);

    String[] cmdArgs = cmd.getArgs();

    if (cmdArgs.length < 1) {
        throw new Exception("No Profile ID specified.");
    }

    String profileId = cmdArgs[0];

    ProfileClient profileClient = profileCLI.getProfileClient();

    // read profile into temporary file
    byte[] orig = profileClient.retrieveProfileRaw(profileId);
    ProfileCLI.checkConfiguration(orig, false /* requireProfileId */, true /* requireDisabled */);
    Path tempFile = Files.createTempFile("pki", ".cfg");

    try {
        Files.write(tempFile, orig);

        // invoke editor on temporary file
        String editor = System.getenv("EDITOR");
        String[] command;
        if (editor == null || editor.trim().isEmpty()) {
            command = new String[] { "/usr/bin/env", "vi", tempFile.toString() };
        } else {
            command = new String[] { editor.trim(), tempFile.toString() };
        }
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.inheritIO();
        int exitCode = pb.start().waitFor();
        if (exitCode != 0) {
            throw new Exception("Exited abnormally.");
        }

        // read data from temporary file and modify if changed
        byte[] cur = ProfileCLI.readRawProfileFromFile(tempFile);
        if (!Arrays.equals(cur, orig)) {
            profileClient.modifyProfileRaw(profileId, cur);
        }
        System.out.write(cur);
    } finally {
        Files.delete(tempFile);
    }
}