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:es.amplia.research.maven.protodocbook.cmd.Factory.java

private void execute(File directory, String... cmd) throws Exception {
    ProcessBuilder pb = new ProcessBuilder(cmd);
    Map<String, String> env = pb.environment();
    pb.directory(directory);/* w  ww  . j  a v a  2  s .c o m*/
    pb.redirectErrorStream(true);
    Process p = pb.start();
    p.waitFor();
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = null;
    while ((line = br.readLine()) != null) {
        if (this.log.isInfoEnabled())
            this.log.info(line);
    }
}

From source file:de.hopmann.msc.slave.util.RCMDBuilder.java

public RCMDOutputReader start() throws IOException {

    List<String> commands = new ArrayList<String>();
    commands.add(rExecutablePath.toAbsolutePath().toString());
    commands.add("CMD");

    processCommands(commands);/*from  w ww  .j  a  v  a2  s  .  c  o  m*/

    if (targetLibraryPath != null) {
        commands.add("--library=" + targetLibraryPath.toAbsolutePath().toString());
    }

    commands.add(packagePath.toAbsolutePath().toString());

    ProcessBuilder cmdProcessBuilder = new ProcessBuilder(commands)
            .directory(workingDirectoryPath.toAbsolutePath().toFile()).redirectErrorStream(true);

    if (!sourceLibraryPaths.isEmpty()) {
        StringBuilder rlibs = new StringBuilder();

        for (Path libPath : sourceLibraryPaths) {
            if (rlibs.length() != 0) {
                // Add separator char
                rlibs.append(SystemUtils.IS_OS_WINDOWS ? ";" : ":");
            }
            rlibs.append(libPath.toAbsolutePath().toString());
        }
        Map<String, String> processEnvironment = cmdProcessBuilder.environment();
        processEnvironment.put(R_LIBS_ENVIR, rlibs.toString());
        processEnvironment.put(R_LANGUAGE_ENVIR, "en");
        processEnvironment.put(LC_ALL, "English");
        processEnvironment.put(CYQWIN_ENVIR, "nodosfilewarning");
        for (Entry<String, String> envirEntry : customEnvironment.entrySet()) {
            processEnvironment.put(envirEntry.getKey(), envirEntry.getValue());
        }
    }

    processEnvironment(cmdProcessBuilder.environment());

    final Process cmdProcess = cmdProcessBuilder.start();

    // BufferedReader processOut = new BufferedReader(
    // new InputStreamReader(installProcess.getInputStream()));
    // while (processOut.readLine() != null) { }

    // IOUtils.copy(installProcess.getInputStream(), System.out);

    return new RCMDOutputReader(cmdProcess, logPrintStream) {
        @Override
        public void close() throws IOException {
            try {
                cmdProcess.waitFor();// XXX or .destroy()?
            } catch (InterruptedException e) {

            }
            super.close();
        }
    };

}

From source file:de.fosd.jdime.strategy.LinebasedStrategy.java

/**
 * This line-based <code>merge</code> method uses the merging routine of
 * the external tool <code>git</code>.
 * <p>//w ww . j a va2 s  . co  m
 * Basically, the input <code>FileArtifacts</code> are passed as arguments to
 * `git merge-file -q -p`.
 * <p>
 * In a common run, the number of processed lines of code, the number of
 * conflicting situations, and the number of conflicting lines of code will
 * be counted. Empty lines and comments are skipped to keep
 * <code>MergeStrategies</code> comparable, as JDime does (in its current
 * implementation) not respect comments.
 * <p>
 * In case of a performance benchmark, the output is simply ignored for the
 * sake of speed, and the merge will be run the specified amount of times,
 * aiming to allow the computation of a reasonable mean runtime.
 *
 * @param operation <code>MergeOperation</code> that is executed by this strategy
 * @param context <code>MergeContext</code> that is used to retrieve environmental parameters
 *
 * @throws IOException
 * @throws InterruptedException
 */
@Override
public final void merge(final MergeOperation<FileArtifact> operation, final MergeContext context)
        throws IOException, InterruptedException {

    assert (operation != null);
    assert (context != null);

    MergeTriple<FileArtifact> triple = operation.getMergeTriple();
    assert (triple != null);
    assert (triple.isValid()) : "The merge triple is not valid!";
    assert (triple.getLeft() instanceof FileArtifact);
    assert (triple.getBase() instanceof FileArtifact);
    assert (triple.getRight() instanceof FileArtifact);
    assert (triple.getLeft().exists() && !triple.getLeft().isDirectory());
    assert ((triple.getBase().exists() && !triple.getBase().isDirectory()) || triple.getBase().isEmptyDummy());
    assert (triple.getRight().exists() && !triple.getRight().isDirectory());

    context.resetStreams();
    FileArtifact target = null;

    if (operation.getTarget() != null) {
        assert (operation.getTarget() instanceof FileArtifact);
        target = operation.getTarget();
        assert (!target.exists() || target.isEmpty()) : "Would be overwritten: " + target;
    }

    List<String> cmd = new ArrayList<>();
    cmd.add(BASECMD);
    cmd.addAll(Arrays.asList(BASEARGS));

    for (FileArtifact file : triple.getList()) {
        cmd.add(file.getPath());
    }

    ProcessBuilder pb = new ProcessBuilder(cmd);
    ArrayList<Long> runtimes = new ArrayList<>();
    int conflicts = 0;
    int loc = 0;
    int cloc = 0;

    // launch the merge process by invoking GNU merge (rcs has to be
    // installed)
    LOG.debug("Running external command: " + StringUtils.join(cmd, " "));

    for (int i = 0; i < context.getBenchmarkRuns() + 1 && (i == 0 || context.isBenchmark()); i++) {
        long cmdStart = System.currentTimeMillis();
        Process pr = pb.start();

        if (i == 0 && (!context.isBenchmark() || context.hasStats())) {
            // process input stream
            BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
            boolean conflict = false;
            boolean comment = false;

            int tmp = 0;
            String line;
            while ((line = buf.readLine()) != null) {
                context.appendLine(line);

                if (context.hasStats()) {
                    if (line.matches("^$") || line.matches("^\\s*$") || line.matches("^\\s*//.*$")) {
                        // skip empty lines and single line comments
                        continue;
                    } else if (line.matches("^\\s*/\\*.*")) {
                        if (line.matches("^\\s*/\\*.*?\\*/")) {
                            // one line comment
                            continue;
                        } else {
                            // starting block comment
                            comment = true;
                            continue;
                        }
                    } else if (line.matches("^.*?\\*/")) {
                        // ending block comment
                        comment = false;
                        continue;
                    }
                    if (line.matches("^\\s*<<<<<<<.*")) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("CONFLICT in " + triple);
                        }
                        conflict = true;
                        comment = false;
                        tmp = cloc;
                        conflicts++;
                    } else if (line.matches("^\\s*=======.*")) {
                        comment = false;
                    } else if (line.matches("^\\s*>>>>>>>.*")) {
                        conflict = false;
                        comment = false;
                        if (tmp == cloc) {
                            // only conflicting comments or empty lines
                            conflicts--;
                        }
                    } else {
                        loc++;
                        if (conflict && !comment) {
                            cloc++;
                        }
                    }
                }
            }

            buf.close();

            // process error stream
            buf = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
            while ((line = buf.readLine()) != null) {
                if (i == 0 && (!context.isBenchmark() || context.hasStats())) {
                    context.appendErrorLine(line);
                }
            }

            buf.close();
        }
        pr.getInputStream().close();
        pr.getErrorStream().close();
        pr.getOutputStream().close();

        pr.waitFor();

        long runtime = System.currentTimeMillis() - cmdStart;
        runtimes.add(runtime);

        if (LOG.isInfoEnabled() && context.isBenchmark() && context.hasStats()) {
            if (i == 0) {
                LOG.info("Initial run: " + runtime + " ms");
            } else {
                LOG.info("Run " + i + " of " + context.getBenchmarkRuns() + ": " + runtime + " ms");
            }
        }
    }

    if (context.isBenchmark() && runtimes.size() > 1) {
        // remove first run as it took way longer due to all the counting
        runtimes.remove(0);
    }

    Long runtime = MergeContext.median(runtimes);
    LOG.debug("Linebased merge time was " + runtime + " ms.");

    if (context.hasErrors()) {
        LOG.fatal("Errors occured while calling '" + cmd + "')");
        System.err.println(context.getStdErr());
    }

    // write output
    if (target != null) {
        assert (target.exists());
        target.write(context.getStdIn());
    }

    // add statistical data to context
    if (context.hasStats()) {
        assert (cloc <= loc);

        Stats stats = context.getStats();
        StatsElement linesElement = stats.getElement("lines");
        assert (linesElement != null);
        StatsElement newElement = new StatsElement();
        newElement.setMerged(loc);
        newElement.setConflicting(cloc);
        linesElement.addStatsElement(newElement);

        if (conflicts > 0) {
            assert (cloc > 0);
            stats.addConflicts(conflicts);
            StatsElement filesElement = stats.getElement("files");
            assert (filesElement != null);
            filesElement.incrementConflicting();
        } else {
            assert (cloc == 0);
        }

        stats.increaseRuntime(runtime);

        MergeTripleStats scenariostats = new MergeTripleStats(triple, conflicts, cloc, loc, runtime, null, null,
                null);
        stats.addScenarioStats(scenariostats);
    }
}

From source file:com.github.pemapmodder.pocketminegui.utils.Utils.java

public static String exec(String... cmdLine) {
    try {/*from  w  w  w .  ja  v  a  2s.  c  o m*/
        Process process = new ProcessBuilder(cmdLine).start();
        process.waitFor();
        return new String(IOUtils.toByteArray(process.getInputStream()));
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:frk.gpssimulator.service.impl.DefaultGpsdService.java

/**
 * Start given process.//from   ww w . j  av  a  2 s .c  o m
 * @param command
 * @param wait for process to exit
 * @return
 */
int startProc(String command, Boolean wait) throws IOException, InterruptedException {
    String[] commandArray = command.split(" ");
    ProcessBuilder pb = new ProcessBuilder(commandArray);
    pb.redirectErrorStream(true); //redirect errorstream and outputstream to single stream
    Process proc = pb.start();
    BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    String line;
    //empty the output buff of the proc
    while ((line = in.readLine()) != null) {
        LOGGER.info(line);
    }

    if (wait) {
        return proc.waitFor();
    } else {
        return 0;
    }

}

From source file:interactivespaces.activity.binary.BaseNativeActivityRunner.java

/**
 * Attempt the run.//from   w w  w . j  a va  2 s  . co  m
 *
 * @return the process that was created
 */
private Process attemptRun() {
    try {
        ProcessBuilder builder = new ProcessBuilder(commands);
        builder.directory(executableFolder);

        spaceEnvironment.getLog().info(
                String.format("Starting up native code in folder %s", executableFolder.getAbsolutePath()));

        return builder.start();
    } catch (Exception e) {
        throw new InteractiveSpacesException("Can't start up activity " + appName, e);
    }
}

From source file:com.skcraft.launcher.launch.Runner.java

@Override
public Process call() throws Exception {
    if (!instance.isInstalled()) {
        throw new LauncherException("Update required", _("runner.updateRequired"));
    }/*from  w  w w .jav a 2 s .co  m*/

    config = launcher.getConfig();
    builder = new JavaProcessBuilder();
    assetsRoot = launcher.getAssets();

    // Load manifiests
    versionManifest = mapper.readValue(instance.getVersionPath(), VersionManifest.class);

    // Load assets index
    File assetsFile = assetsRoot.getIndexPath(versionManifest);
    try {
        assetsIndex = mapper.readValue(assetsFile, AssetsIndex.class);
    } catch (FileNotFoundException e) {
        instance.setInstalled(false);
        Persistence.commitAndForget(instance);
        throw new LauncherException("Missing assets index " + assetsFile.getAbsolutePath(),
                _("runner.missingAssetsIndex", instance.getTitle(), assetsFile.getAbsolutePath()));
    } catch (IOException e) {
        instance.setInstalled(false);
        Persistence.commitAndForget(instance);
        throw new LauncherException("Corrupt assets index " + assetsFile.getAbsolutePath(),
                _("runner.corruptAssetsIndex", instance.getTitle(), assetsFile.getAbsolutePath()));
    }

    // Copy over assets to the tree
    try {
        AssetsRoot.AssetsTreeBuilder assetsBuilder = assetsRoot.createAssetsBuilder(versionManifest);
        progress = assetsBuilder;
        virtualAssetsDir = assetsBuilder.build();
    } catch (LauncherException e) {
        instance.setInstalled(false);
        Persistence.commitAndForget(instance);
        throw e;
    }

    progress = new DefaultProgress(0.9, _("runner.collectingArgs"));

    addJvmArgs();
    addLibraries();
    addJarArgs();
    addProxyArgs();
    addWindowArgs();
    addPlatformArgs();

    builder.classPath(getJarPath());
    builder.setMainClass(versionManifest.getMainClass());

    callLaunchModifier();

    ProcessBuilder processBuilder = new ProcessBuilder(builder.buildCommand());
    processBuilder.directory(instance.getContentDir());
    Runner.log.info("Launching: " + builder);
    checkInterrupted();

    progress = new DefaultProgress(1, _("runner.startingJava"));

    return processBuilder.start();
}

From source file:at.ac.tuwien.dsg.cloud.salsa.engine.utils.SystemFunctions.java

/**
 * Run a command and wait/*from  ww w .j a v a2s.c  om*/
 *
 * @param cmd The command to run
 * @param workingDir The folder where the command is run
 * @param executeFrom For logging message to the center of where to execute the command.
 * @return
 */
public static String executeCommandGetOutput(String cmd, String workingDir, String executeFrom) {
    logger.debug("Execute command: " + cmd);
    if (workingDir == null) {
        workingDir = "/tmp";
    }
    try {
        String[] splitStr = cmd.split("\\s+");
        ProcessBuilder pb = new ProcessBuilder(splitStr);
        pb.directory(new File(workingDir));
        pb = pb.redirectErrorStream(true); // this is important to redirect the error stream to output stream, prevent blocking with long output
        Map<String, String> env = pb.environment();
        String path = env.get("PATH");
        path = path + File.pathSeparator + "/usr/bin:/usr/sbin";
        logger.debug("PATH to execute command: " + pb.environment().get("PATH"));
        env.put("PATH", path);

        Process p = pb.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        StringBuffer output = new StringBuffer();
        int lineCount = 0;
        while ((line = reader.readLine()) != null) {
            if (lineCount < 10) { // only get 10 lines to prevent the overflow
                output.append(line);
            }
            lineCount += 1;
            logger.debug(line);
        }
        if (lineCount >= 10) {
            logger.debug("... there are alot of more output here which is not shown ! ...");
        }
        p.waitFor();
        System.out.println("Execute Commang output: " + output.toString().trim());

        if (p.exitValue() == 0) {
            logger.debug("Command exit 0, result: " + output.toString().trim());
            return output.toString().trim();
        } else {
            logger.debug("Command return non zero code: " + p.exitValue());
            return null;
        }
    } catch (InterruptedException | IOException e1) {
        logger.error("Error when execute command. Error: " + e1);
    }
    return null;
}

From source file:io.hops.hopsworks.common.security.PKIUtils.java

public static String verifyCertificate(Settings settings, String cert, boolean intermediate)
        throws IOException, InterruptedException {
    File certFile = File.createTempFile(System.getProperty("java.io.tmpdir"), ".pem");
    FileUtils.writeStringToFile(certFile, cert);
    String certDir = intermediate ? settings.getIntermediateCaDir() : settings.getCaDir();
    String crlFile = intermediate ? certDir + "/crl/intermediate.crl.pem" : certDir + "/crl/ca.crl.pem";
    String pubCert = intermediate ? "/intermediate/certs/intermediate.cert.pem " : "/certs/ca.cert.pem ";
    //update the crl
    createCRL(settings, intermediate);/* w w w .  j av  a2 s .  com*/
    logger.info("Checking certificate...");
    List<String> cmds = new ArrayList<>();
    cmds.add("openssl");
    cmds.add("verify");
    cmds.add("-crl_check");
    cmds.add("-CAfile");
    cmds.add("<(cat " + certDir + pubCert + crlFile + ")");
    cmds.add(certFile.getAbsolutePath());
    StringBuilder sb = new StringBuilder("/usr/bin/");
    for (String s : cmds) {
        sb.append(s).append(" ");
    }
    logger.info(sb.toString());

    Process process = new ProcessBuilder(cmds).directory(new File("/usr/bin/")).redirectErrorStream(true)
            .start();
    BufferedReader br = new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charset.forName("UTF8")));
    String line;
    StringBuilder lines = new StringBuilder("");
    while ((line = br.readLine()) != null) {
        logger.info(line);
        lines.append(line);
    }
    process.waitFor();
    int exitValue = process.exitValue();
    if (exitValue != 0) {
        throw new RuntimeException("Failed cert check. Exit value: " + exitValue);
    }
    logger.info("Done cert check.");
    return lines.toString();
}

From source file:com.mesosphere.dcos.cassandra.executor.tasks.RestoreSnapshot.java

@Override
public void run() {
    try {// ww w .  jav  a  2 s .c om
        // Send TASK_RUNNING
        sendStatus(driver, Protos.TaskState.TASK_RUNNING, "Started restoring snapshot");

        if (Objects.equals(context.getRestoreType(), new String("new"))) {
            final String keyspaceDirectory = context.getLocalLocation() + File.separator + context.getName()
                    + File.separator + context.getNodeId();

            final String ssTableLoaderBinary = CassandraPaths.create(version).bin().resolve("sstableloader")
                    .toString();
            final String cassandraYaml = CassandraPaths.create(version).cassandraConfig().toString();

            final File keyspacesDirectory = new File(keyspaceDirectory);
            LOGGER.info("Keyspace Directory {} exists: {}", keyspaceDirectory, keyspacesDirectory.exists());

            final File[] keyspaces = keyspacesDirectory.listFiles();

            String libProcessAddress = System.getenv("LIBPROCESS_IP");
            libProcessAddress = StringUtils.isBlank(libProcessAddress)
                    ? InetAddress.getLocalHost().getHostAddress()
                    : libProcessAddress;

            for (File keyspace : keyspaces) {
                final File[] columnFamilies = keyspace.listFiles();

                final String keyspaceName = keyspace.getName();
                if (keyspaceName.equals(StorageUtil.SCHEMA_FILE))
                    continue;
                LOGGER.info("Going to bulk load keyspace: {}", keyspaceName);

                for (File columnFamily : columnFamilies) {
                    final String columnFamilyName = columnFamily.getName();
                    if (columnFamilyName.equals(StorageUtil.SCHEMA_FILE))
                        continue;
                    LOGGER.info("Bulk loading... keyspace: {} column family: {}", keyspaceName,
                            columnFamilyName);

                    final String columnFamilyPath = columnFamily.getAbsolutePath();
                    final List<String> command = Arrays.asList(ssTableLoaderBinary, "-d", libProcessAddress,
                            "-u", context.getUsername(), "-pw", context.getPassword(), "-f", cassandraYaml,
                            columnFamilyPath);
                    LOGGER.info("Executing command: {}", command);

                    final ProcessBuilder processBuilder = new ProcessBuilder(command);
                    processBuilder.redirectErrorStream(true);
                    Process process = processBuilder.start();

                    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        LOGGER.info(line);
                    }

                    int exitCode = process.waitFor();
                    LOGGER.info("Command exit code: {}", exitCode);

                    // Send TASK_ERROR
                    if (exitCode != 0) {
                        final String errMessage = String.format("Error restoring snapshot. Exit code: %s",
                                (exitCode + ""));
                        LOGGER.error(errMessage);
                        sendStatus(driver, Protos.TaskState.TASK_ERROR, errMessage);
                    }

                    LOGGER.info("Done bulk loading! keyspace: {} column family: {}", keyspaceName,
                            columnFamilyName);
                }
                LOGGER.info("Successfully bulk loaded keyspace: {}", keyspaceName);
            }
            // cleanup downloaded snapshot directory recursively.
            Path rootPath = Paths.get(context.getLocalLocation() + File.separator + context.getName());
            if (rootPath.toFile().exists()) {
                Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder())
                        .map(Path::toFile).forEach(File::delete);
            }
        } else {
            // run nodetool refresh rather than SSTableLoader, as on performance test
            // I/O stream was pretty slow between mesos container processes
            final String localLocation = context.getLocalLocation();
            final List<String> keyspaces = cassandra.getNonSystemKeySpaces();
            for (String keyspace : keyspaces) {
                final String keySpaceDirPath = localLocation + "/" + keyspace;
                File keySpaceDir = new File(keySpaceDirPath);
                File[] cfNames = keySpaceDir
                        .listFiles((current, name) -> new File(current, name).isDirectory());
                for (File cfName : cfNames) {
                    String columnFamily = cfName.getName().substring(0, cfName.getName().indexOf("-"));
                    cassandra.getProbe().loadNewSSTables(keyspace, columnFamily);
                    LOGGER.info("Completed nodetool refresh for keyspace {} & columnfamily {}", keyspace,
                            columnFamily);
                }
            }
        }

        final String message = "Finished restoring snapshot";
        LOGGER.info(message);
        sendStatus(driver, Protos.TaskState.TASK_FINISHED, message);
    } catch (Throwable t) {
        // Send TASK_FAILED
        final String errorMessage = "Failed restoring snapshot. Reason: " + t;
        LOGGER.error(errorMessage, t);
        sendStatus(driver, Protos.TaskState.TASK_FAILED, errorMessage);
    }
}