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:io.jmnarloch.cd.go.plugin.gradle.GradleTaskExecutor.java

/**
 * Builds the Gradle process for later execution, it configures all the build properties based on the current
 * task configuration. It also takes into account the current task execution context.
 *
 * @param config the task configuration//  ww w.j  ava  2s .com
 * @param environment the task execution environment
 * @return the created Gradle build process
 */
private static ProcessBuilder buildGradleProcess(ExecutionConfiguration config, ExecutionContext environment) {
    final Map<String, String> env = environment.getEnvironmentVariables();
    String workingDirectory = unifyPath(environment.getWorkingDirectory());
    workingDirectory = workingDirectory.endsWith(File.separator) ? workingDirectory
            : workingDirectory + File.separator;
    String relativePath = config.getProperty(GradleTaskConfig.RELATIVE_PATH.getName());
    workingDirectory = StringUtils.isBlank(relativePath) ? workingDirectory
            : unifyPath(workingDirectory + relativePath);
    final List<String> command = parse(config, env, workingDirectory);

    logger.debug("Executing command: " + command);

    final ProcessBuilder builder = new ProcessBuilder(command);
    builder.environment().putAll(env);
    builder.directory(new File(workingDirectory));
    return builder;
}

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

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

    SegmenterTranscoderConfigurationItem config = (SegmenterTranscoderConfigurationItem) genericConfig;
    List<String> commandList = new ArrayList<String>();
    commandList.add(niceLocation);//from   ww w. j  av a  2 s  .  co  m
    commandList.add("-n");
    commandList.add(Integer.toString(config.getNiceness()));
    commandList.add(segmenterLocation);
    commandList.add(inputFile.getAbsolutePath());
    commandList.add(config.getSegmentDuration());
    commandList.add(config.getSegmentFilePrefix());
    commandList.add(config.getPlaylistFileName());
    commandList.add(config.getHttpPrefix());
    ProcessBuilder pb = new ProcessBuilder(commandList);

    pb.environment().put("LD_LIBRARY_PATH", "/usr/local/lib:");
    pb.redirectErrorStream(true);
    pb.directory(outputFile.getParentFile());
    Process process = null;

    try {
        // Get the segmenter 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("Segmenter exit value: " + exitValue);
        if (exitValue != 0) {
            for (String line : result) {
                LOG.error(line);
            }
            throw new Exception("Segmenter return code indicated failure: " + exitValue);
        }
    } catch (InterruptedException e) {
        throw new Exception("Segmenter process interrupted by another thread", e);
    } catch (ExecutionException ee) {
        throw new Exception("Something went wrong parsing Segmenter output", ee);
    } catch (TimeoutException te) {
        // We could not get the result before timeout
        throw new Exception("Segmenter process timed out", te);
    } catch (RuntimeException re) {
        // Unexpected output from Segmenter
        throw new Exception("Something went wrong parsing Segmenter output", re);
    } finally {
        if (process != null) {
            process.destroy();
        }
    }

    LOG.debug("transcoding finished");
}

From source file:com.amazonaws.services.kinesis.multilang.MultiLangRecordProcessorFactory.java

@Override
public IRecordProcessor createProcessor() {
    LOG.debug(String.format("Creating new record processor for client executable: %s", command));
    /*/*from w  w w  .ja  v a2 s  .  c  o m*/
     * Giving ProcessBuilder the command as an array of Strings allows users to specify command line arguments.
     */
    return new MultiLangRecordProcessor(new ProcessBuilder(commandArray), executorService, this.objectMapper);
}

From source file:com.diversityarrays.kdxplore.trialdesign.JobRunningTask.java

@Override
public Either<String, AlgorithmRunResult> generateResult(Closure<Void> arg0) throws Exception {

    AlgorithmRunResult result = new AlgorithmRunResult(algorithmName, algorithmFolder);
    ProcessBuilder pb = new ProcessBuilder(command);

    File tempAlgorithmOutputFile = new File(algorithmFolder, "stdout.txt");
    File tempAlgorithmErrorFile = new File(algorithmFolder, "stderr.txt");

    //pb.redirectErrorStream(true);
    tempAlgorithmErrorFile.createNewFile();
    tempAlgorithmOutputFile.createNewFile();

    pb.redirectOutput(tempAlgorithmOutputFile);
    pb.redirectError(tempAlgorithmErrorFile);

    Process process = pb.start();

    while (!process.waitFor(1000, TimeUnit.MILLISECONDS)) {
        if (backgroundRunner.isCancelRequested()) {
            process.destroy();/*from www. ja  va  2s . co m*/
            throw new CancellationException();
        }
    }

    int exitCode = process.exitValue();
    if (exitCode != 0) {
        String errtxt = Algorithms.readContent("Error Output: (code=" + exitCode + ")",
                new FileInputStream(tempAlgorithmErrorFile));
        return Either.left(errtxt);
    }

    if (!kdxploreOutputFile.exists()) {
        return Either.left("Missing output file: " + kdxploreOutputFile.getPath());
    }

    result.addTrialEntries(kdxploreOutputFile, userTrialEntries);

    return Either.right(result);
}

From source file:edu.umn.msi.tropix.common.execution.process.impl.ProcessFactoryImpl.java

public Process createProcess(final ProcessConfiguration processConfiguration) {
    final List<String> command = new LinkedList<String>();
    final String application = processConfiguration.getApplication();
    Preconditions.checkNotNull(application, "Attempted to create process with null application.");
    command.add(application);//from w w w  .j  av  a 2  s .  co m
    final List<String> arguments = processConfiguration.getArguments();
    if (arguments != null) {
        command.addAll(processConfiguration.getArguments());
    }
    LOG.trace("Creating process builder with commands " + Joiner.on(" ").join(command) + " in directory "
            + processConfiguration.getDirectory());
    final ProcessBuilder processBuilder = new ProcessBuilder(command);
    if (processConfiguration.getEnvironment() != null) {
        for (final Entry<String, String> entry : processConfiguration.getEnvironment().entrySet()) {
            processBuilder.environment().put(entry.getKey(), entry.getValue());
        }
    }
    processBuilder.directory(processConfiguration.getDirectory());

    java.lang.Process baseProcess = null;
    try {
        baseProcess = processBuilder.start();
    } catch (final IOException e) {
        throw new IllegalStateException(
                "Failed to start process corresponding to process configuration " + processConfiguration, e);
    }
    final ProcessImpl process = new ProcessImpl();
    process.setBaseProcess(baseProcess);
    return process;
}

From source file:edu.duke.cabig.c3pr.ant.UseCaseTraceabilityReport.java

public void execute() throws BuildException {
    logger.info("Executing ant task");

    File testCaseList, classpath;
    try {//from  w  ww.  ja v a  2s . co  m
        testCaseList = buildTestCasesListFile();
    } catch (IOException e) {
        throw new BuildException("Failed to build test cases list", e);
    }
    try {
        classpath = buildClasspathFile();
    } catch (IOException e) {
        throw new BuildException("Failed to build test cases list", e);
    }

    String[] cmd = { getAptBin(), "-nocompile", "-factory",
            UseCaseTraceabilityAnnotationProcessorFactory.class.getName(), "-d", destDir.getAbsolutePath(),
            UseCaseTraceabilityAnnotationProcessorFactory.PROJECT_NAME_OPT + projectName,
            UseCaseTraceabilityAnnotationProcessorFactory.USE_CASES_ANNOTATION_CLASS_NAME_OPT
                    + useCasesAnnotationClassName,
            '@' + classpath.getAbsolutePath(), '@' + testCaseList.getAbsolutePath() };

    try {
        logger.info("Executing apt as " + Arrays.asList(cmd));
        Process process = new ProcessBuilder(cmd).redirectErrorStream(true).start();
        IOUtils.copy(process.getInputStream(), System.out);
        process.waitFor();
        if (process.exitValue() != 0) {
            throw new BuildException("apt failed (returned non-zero exit code)");
        }
    } catch (IOException e) {
        throw new BuildException("IO problem while executing apt", e);
    } catch (InterruptedException e) {
        throw new BuildException("Interrupted while waiting for apt", e);
    }

    if (!logger.isDebugEnabled()) {
        testCaseList.delete();

    } else {
        logger.debug("Retained test case list for debugging: " + testCaseList);

    }

}

From source file:net.pocketmine.server.ServerUtils.java

final public static void runServer() {
    // restoreOrCreateServerData();
    // restoreConfiguration("lighttpd.conf");
    // restoreConfiguration("php.ini");
    // restoreConfiguration("mysql.ini");
    setPermission();/*from   w  w  w  .  j a v  a  2 s  .c  o m*/

    String[] serverCmd = { getAppDirectory() + "/php",
            // getAppDirectory() + "/php_data/PocketMine-MP.php"
            getDataDirectory() + "/PocketMine-MP.php" };

    try {
        serverProc = (new ProcessBuilder(serverCmd)).redirectErrorStream(true).start();
        stdout = serverProc.getInputStream();
        stdin = serverProc.getOutputStream();

        LogActivity.log("[PocketMine] Server is starting...");

        Thread tMonitor = new Thread() {
            public void run() {
                InputStreamReader reader = new InputStreamReader(stdout, Charset.forName("UTF-8"));
                BufferedReader br = new BufferedReader(reader);
                LogActivity.log("[PocketMine] Server was started.");

                while (isRunning()) {
                    try {
                        char[] buffer = new char[8192];
                        int size = 0;
                        while ((size = br.read(buffer, 0, buffer.length)) != -1) {
                            StringBuilder s = new StringBuilder();
                            for (int i = 0; i < size; i++) {
                                char c = buffer[i];
                                if (c == '\r') {
                                } //
                                else if (c == '\n' || c == '\u0007') {
                                    String line = s.toString();
                                    Log.d(TAG, line);

                                    String lineNoDate = "";
                                    int iof = line.indexOf(" ");
                                    if (iof != -1)
                                        lineNoDate = line.substring(iof + 1);
                                    if (lineNoDate.startsWith("[CMD] There are ") && requestPlayerRefresh
                                            && requestPlayerRefreshCount == -1) {

                                        try {
                                            String num = lineNoDate.substring("[CMD] There are ".length());
                                            num = num.substring(0, num.indexOf("/"));
                                            requestPlayerRefreshCount = Integer.parseInt(num);

                                            if (requestPlayerRefreshCount == 0) {
                                                HomeActivity.updatePlayerList(null);
                                                requestPlayerRefresh = false;
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    } else if (lineNoDate.startsWith("[CMD] ") && requestPlayerRefresh
                                            && requestPlayerRefreshCount != -1) {

                                        String player = lineNoDate.substring(6);
                                        String[] players = player.split(", ");

                                        HomeActivity.updatePlayerList(players);

                                        requestPlayerRefresh = false;
                                    } else if (c == '\u0007' && line.startsWith("\u001B]0;")) {
                                        line = line.substring(4);
                                        System.out.println("[Stat] " + line);
                                        HomeActivity.setStats(getStat(line, "Online"), getStat(line, "RAM"),
                                                getStat(line, "U"), getStat(line, "D"), getStat(line, "TPS"));
                                    } else {
                                        LogActivity.log("[Server] " + (line.replace("&", "&amp;")
                                                .replace("<", "&lt;").replace(">", "&gt;")));

                                        if (line.contains("] logged in with entity id ")
                                                || line.contains("] logged out due to ")) {
                                            refreshPlayers();
                                        }
                                    }

                                    s = new StringBuilder();
                                } else {
                                    s.append(buffer[i]);
                                }
                            }

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            br.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                LogActivity.log("[PocketMine] Server was stopped.");
                HomeActivity.stopNotifyService();
                HomeActivity.hideStats();
            }

        };
        tMonitor.start();

        Log.i(TAG, "PHP is started");
    } catch (java.lang.Exception e) {
        Log.e(TAG, "Unable to start PHP", e);
        LogActivity.log("[PocketMine] Unable to start PHP.");
        HomeActivity.stopNotifyService();
        HomeActivity.hideStats();
        killProcessByName("php");
    }

    return;

}

From source file:com.github.DroidPHP.ServerUtils.java

final public static void runServer() {
    restoreOrCreateServerData();//  ww w.ja  va2 s. co  m
    restoreConfiguration("lighttpd.conf");
    restoreConfiguration("php.ini");
    restoreConfiguration("mysql.ini");
    setPermission();

    String[] serverCmd = { getAppDirectory() + "/lighttpd", "-f", getHttpDirectory() + "/conf/lighttpd.conf",
            "-D"

    };
    String[] mySQLCmd = { getAppDirectory() + "/mysqld",
            "--defaults-file=" + getHttpDirectory() + "/conf/mysql.ini",
            // "--pid-file=" + getHttpDirectory() + "/proc/mysqld.pid",
            "--user=root", "--language=" + getAppDirectory() + "/share/mysql/english" };
    try {
        (new ProcessBuilder(serverCmd)).start();
        Log.i(TAG, "LIGHTTPD is successfully running");
    } catch (java.lang.Exception e) {
        Log.e(TAG, "Unable to start LIGHTTPD", e);
    }

    try {
        (new ProcessBuilder(mySQLCmd)).start();
        Log.i(TAG, "MYSQLD is successfully running");
    } catch (Exception e) {
        Log.e(TAG, "Unable to start MYSQLD", e);
    }

    return;

}

From source file:de.phoenix.submission.SubmissionCompilerAndTest.java

@Override
public PhoenixSubmissionResult controlSubmission(TaskSubmission submission) {

    SubmissionTask task = new SubmissionTask();

    File dir = PhoenixApplication.submissionPipelineDir;
    List<String> commands = getCommands();

    // Check, if all necessary classes are submitted
    Set<String> classes = new HashSet<String>();
    for (Text text : submission.getTask().getTexts()) {
        classes.add(text.getTitle());//w w w . j  a v  a2  s .c  o  m
    }

    for (Text clazz : submission.getTexts()) {
        task.addClass(clazz.convert());
        classes.remove(clazz.getTitle());
    }

    // Some to implement classes are missing -> error
    if (!classes.isEmpty()) {
        return new PhoenixSubmissionResult(SubmissionStatus.MISSING_FILES,
                "Missing classes to implement/submit. Maybe you wrote the name of the class wrong? Missing Classes:\r\n"
                        + classes.toString());
    }

    if (submission.getTask().isAutomaticTest()) {
        for (TaskTest test : submission.getTask().getTaskTests()) {
            addTest(task, test);
        }
    }

    // TODO: Add libraries
    ProcessBuilder builder = new ProcessBuilder(commands);
    builder.directory(dir);

    File errorLog = new File(dir, "error.log");
    errorLog.delete();
    builder.redirectError(errorLog);

    try {
        Process process = builder.start();
        JSON_MAPPER.writeValue(process.getOutputStream(), task);
        process.getOutputStream().close();

        PhoenixSubmissionResult result = JSON_MAPPER.readValue(process.getInputStream(),
                PhoenixSubmissionResult.class);

        return result;
    } catch (Exception e) {
        DebugLog.log(e);
    }

    return new PhoenixSubmissionResult(SubmissionStatus.OK, "Fine");
}

From source file:com.acmutv.ontoqa.tool.runtime.RuntimeManager.java

/**
 * Executes the given command and arguments.
 * @param command The command to execute. Arguments must be given as a separated strings.
 *                E.g.: BashExecutor.runCommand("ls", "-la") or BashExecutor.runCommand("ls", "-l", "-a")
 * @return The command output as a string.
 * @throws IOException when error in process generation or output.
 *///from   ww  w  .ja v a  2  s .  c  o  m
public static String runCommand(String... command) throws IOException {
    LOGGER.trace("command={}", Arrays.asList(command));
    String out;
    ProcessBuilder pb = new ProcessBuilder(command);
    Process p = pb.start();
    try (InputStream in = p.getInputStream()) {
        out = IOUtils.toString(in, Charset.defaultCharset());
    }
    return out.trim();
}