Example usage for java.lang ProcessBuilder command

List of usage examples for java.lang ProcessBuilder command

Introduction

In this page you can find the example usage for java.lang ProcessBuilder command.

Prototype

List command

To view the source code for java.lang ProcessBuilder command.

Click Source Link

Usage

From source file:io.mesosphere.mesos.frameworks.cassandra.executor.ProdObjectFactory.java

@NotNull
private static String processBuilderToString(@NotNull final ProcessBuilder builder) {
    return "ProcessBuilder{\n" + "directory() = " + builder.directory() + ",\n" + "command() = "
            + Joiner.on(" ").join(builder.command()) + ",\n" + "environment() = "
            + Joiner.on("\n").withKeyValueSeparator("->").join(builder.environment()) + "\n}";
}

From source file:org.apache.karaf.kittests.Helper.java

public static Process launchScript(File homeDir, String script, String args) throws IOException {
    ProcessBuilder builder = new ProcessBuilder();
    builder.directory(homeDir);//  ww  w  . j a va2  s. c om
    if (isWindowsOs()) {
        builder.command("cmd.exe", "/c", new File(homeDir, "bin\\" + script + ".bat").getAbsolutePath(), args);
    } else {
        builder.command("/bin/sh", new File(homeDir, "bin/" + script).getAbsolutePath(), args);
    }
    builder.redirectErrorStream(true);
    Process process = builder.start();
    PumpStreamHandler pump = new PumpStreamHandler(System.in, System.out, System.err);
    pump.attach(process);
    pump.start();
    return process;
}

From source file:org.esa.s2tbx.dataio.openjpeg.OpenJpegUtils.java

/**
 * Get the tile layout with opj_dump// w  w w  .  ja  va 2  s.c o m
 *
 * @param opjdumpPath path to opj_dump
 * @param jp2FilePath the path to the jpeg file
 * @return the tile layout for the openjpeg file
 * @throws IOException
 * @throws InterruptedException
 */
public static TileLayout getTileLayoutWithOpenJPEG(String opjdumpPath, Path jp2FilePath)
        throws IOException, InterruptedException {

    if (opjdumpPath == null) {
        throw new IllegalStateException("Cannot retrieve tile layout, opj_dump cannot be found");
    }

    TileLayout tileLayout;

    String pathToImageFile = jp2FilePath.toAbsolutePath().toString();
    if (SystemUtils.IS_OS_WINDOWS) {
        pathToImageFile = Utils.GetIterativeShortPathName(pathToImageFile);
    }

    ProcessBuilder builder = new ProcessBuilder(opjdumpPath, "-i", pathToImageFile);
    builder.redirectErrorStream(true);

    CommandOutput exit = OpenJpegUtils.runProcess(builder);

    if (exit.getErrorCode() != 0) {
        StringBuilder sbu = new StringBuilder();
        for (String fragment : builder.command()) {
            sbu.append(fragment);
            sbu.append(' ');
        }

        throw new IOException(
                String.format("Command [%s] failed with error code [%d], stdoutput [%s] and stderror [%s]",
                        sbu.toString(), exit.getErrorCode(), exit.getTextOutput(), exit.getErrorOutput()));
    }
    tileLayout = OpenJpegUtils.parseOpjDump(exit.getTextOutput());

    return tileLayout;
}

From source file:org.sonar.application.process.ProcessLauncherImpl.java

private static <T extends AbstractCommand> void logLaunchedCommand(AbstractCommand<T> command,
        ProcessBuilder processBuilder) {
    if (LOG.isInfoEnabled()) {
        LOG.info("Launch process[{}] from [{}]: {}", command.getProcessId(),
                command.getWorkDir().getAbsolutePath(), String.join(" ", processBuilder.command()));
    }//from  w  w w .jav  a 2 s  .  c  o  m
}

From source file:edu.uci.ics.asterix.test.aql.TestsUtils.java

public static String executeScript(ProcessBuilder pb, String scriptPath) throws Exception {
    pb.command(scriptPath);
    Process p = pb.start();//  w ww  .  j  a  v a 2s. co m
    p.waitFor();
    return getProcessOutput(p);
}

From source file:org.fiware.cybercaptor.server.api.InformationSystemManagement.java

/**
 * Execute MulVAL on the topology and return the attack graph
 *
 * @return the associated attack graph object
 *//*w w  w . j av  a 2 s .c  o m*/
public static AttackGraph generateAttackGraphWithMulValUsingAlreadyGeneratedMulVALInputFile() {
    try {
        //Load MulVAL properties

        String mulvalPath = ProjectProperties.getProperty("mulval-path");
        String xsbPath = ProjectProperties.getProperty("xsb-path");
        String outputFolderPath = ProjectProperties.getProperty("output-path");

        File mulvalInputFile = new File(ProjectProperties.getProperty("mulval-input"));

        File mulvalOutputFile = new File(outputFolderPath + "/AttackGraph.xml");
        if (mulvalOutputFile.exists()) {
            mulvalOutputFile.delete();
        }

        Logger.getAnonymousLogger().log(Level.INFO, "Launching MulVAL");
        ProcessBuilder processBuilder = new ProcessBuilder(mulvalPath + "/utils/graph_gen.sh",
                mulvalInputFile.getAbsolutePath(), "-l");

        if (ProjectProperties.getProperty("mulval-rules-path") != null) {
            processBuilder.command().add("-r");
            processBuilder.command().add(ProjectProperties.getProperty("mulval-rules-path"));
        }

        processBuilder.directory(new File(outputFolderPath));
        processBuilder.environment().put("MULVALROOT", mulvalPath);
        String path = System.getenv("PATH");
        processBuilder.environment().put("PATH", mulvalPath + "/utils/:" + xsbPath + ":" + path);
        Process process = processBuilder.start();
        process.waitFor();

        if (!mulvalOutputFile.exists()) {
            Logger.getAnonymousLogger().log(Level.INFO, "Empty attack graph!");
            return null;
        }

        MulvalAttackGraph ag = new MulvalAttackGraph(mulvalOutputFile.getAbsolutePath());

        return ag;

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.fiware.cybercaptor.server.api.InformationSystemManagement.java

/**
 * Execute MulVAL on the topology and return the attack graph
 *
 * @param informationSystem the input network
 * @return the associated attack graph object
 *//*www  .j a v  a 2s . c  o  m*/
public static AttackGraph prepareInputsAndExecuteMulVal(InformationSystem informationSystem) {
    if (informationSystem == null)
        return null;
    try {
        //Load MulVAL properties

        String mulvalPath = ProjectProperties.getProperty("mulval-path");
        String xsbPath = ProjectProperties.getProperty("xsb-path");
        String outputFolderPath = ProjectProperties.getProperty("output-path");

        File mulvalInputFile = new File(ProjectProperties.getProperty("mulval-input"));

        File mulvalOutputFile = new File(outputFolderPath + "/AttackGraph.xml");
        if (mulvalOutputFile.exists()) {
            mulvalOutputFile.delete();
        }
        Logger.getAnonymousLogger().log(Level.INFO, "Genering MulVAL inputs");
        informationSystem.exportToMulvalDatalogFile(mulvalInputFile.getAbsolutePath());

        Logger.getAnonymousLogger().log(Level.INFO, "Launching MulVAL");
        ProcessBuilder processBuilder = new ProcessBuilder(mulvalPath + "/utils/graph_gen.sh",
                mulvalInputFile.getAbsolutePath(), "-l");

        if (ProjectProperties.getProperty("mulval-rules-path") != null) {
            processBuilder.command().add("-r");
            processBuilder.command().add(ProjectProperties.getProperty("mulval-rules-path"));
        }

        processBuilder.directory(new File(outputFolderPath));
        processBuilder.environment().put("MULVALROOT", mulvalPath);
        String path = System.getenv("PATH");
        processBuilder.environment().put("PATH", mulvalPath + "/utils/:" + xsbPath + ":" + path);
        Process process = processBuilder.start();
        process.waitFor();

        if (!mulvalOutputFile.exists()) {
            Logger.getAnonymousLogger().log(Level.INFO, "Empty attack graph!");
            return null;
        }

        MulvalAttackGraph ag = new MulvalAttackGraph(mulvalOutputFile.getAbsolutePath());

        ag.loadMetricsFromTopology(informationSystem);

        return ag;

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.libreplan.web.print.CutyPrint.java

/**
 * It blocks until the snapshot is ready.
 * It invokes cutycapt program in order to take a snapshot from a specified url.
 *
 * @return the path in the web application to access via a HTTP GET to the
 *         generated snapshot.//from w  w w. j av  a 2 s  .  com
 */
private static String takeSnapshot(CutyCaptParameters params) {

    ProcessBuilder capture = new ProcessBuilder(CUTYCAPT_COMMAND);
    params.fillParameters(capture);
    String generatedSnapshotServerPath = params.getGeneratedSnapshotServerPath();

    Process printProcess = null;
    Process serverProcess = null;
    try {
        LOG.info("calling printing: " + capture.command());

        // If there is a not real X server environment then use Xvfb
        if (StringUtils.isEmpty(System.getenv("DISPLAY"))) {
            ProcessBuilder s = new ProcessBuilder("Xvfb", ":" + params.getXvfbDisplayNumber());
            serverProcess = s.start();
            capture.environment().put("DISPLAY", ":" + params.getXvfbDisplayNumber() + ".0");
        }

        printProcess = capture.start();
        printProcess.waitFor();

        // Once the printProcess finishes, the print snapshot is available
        return generatedSnapshotServerPath;
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        LOG.error("error invoking command", e);
        throw new RuntimeException(e);
    } finally {
        if (printProcess != null) {
            destroy(printProcess);
        }
        if (serverProcess != null) {
            destroy(serverProcess);
        }
    }
}

From source file:org.spoutcraft.launcher.entrypoint.Mover.java

private static void execute(String[] args, boolean exe) throws Exception {
    File temp;/*from  w w w .  jav a  2s. c o  m*/
    if (exe) {
        temp = new File(Utils.getSettingsDirectory(), "temp.exe");
    } else {
        temp = new File(Utils.getSettingsDirectory(), "temp.jar");
    }
    File codeSource = new File(args[0]);
    codeSource.delete();
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
        fis = new FileInputStream(temp);
        fos = new FileOutputStream(codeSource);
        IOUtils.copy(fis, fos);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(fos);
    }

    codeSource.setExecutable(true, true);

    ProcessBuilder processBuilder = new ProcessBuilder();
    ArrayList<String> commands = new ArrayList<String>();
    if (!exe) {
        if (OperatingSystem.getOperatingSystem().equals(OperatingSystem.WINDOWS)) {
            commands.add("javaw");
        } else {
            commands.add("java");
        }
        commands.add("-Xmx256m");
        commands.add("-cp");
        commands.add(codeSource.getAbsolutePath());
        commands.add(SpoutcraftLauncher.class.getName());
    } else {
        commands.add(temp.getAbsolutePath());
        commands.add("-Launcher");
    }
    commands.addAll(Arrays.asList(args));
    processBuilder.command(commands);

    processBuilder.start();
}

From source file:com.ikanow.aleph2.data_model.utils.ProcessUtils.java

/**
 * Starts the given process by calling process_builder.start();
 * Records the started processes pid and start date.
 *  /*from  w  w w . j  av a2s  .c  o  m*/
 * @param process_builder
 * @throws IOException 
 * @return returns any error in _1(), the pid in _2()
 */
public static Tuple2<String, String> launchProcess(final ProcessBuilder process_builder,
        final String application_name, final DataBucketBean bucket, final String aleph_root_path,
        final Optional<Tuple2<Long, Integer>> timeout_kill) {
    try {
        if (timeout_kill.isPresent()) {
            final Stream<String> timeout_stream = Stream.of("timeout", "-s", timeout_kill.get()._2.toString(),
                    timeout_kill.get()._1.toString());
            process_builder.command(Stream.concat(timeout_stream, process_builder.command().stream())
                    .collect(Collectors.toList()));
        }

        //starts the process, get pid back
        logger.debug("Starting process: " + process_builder.command().toString());
        final Process px = process_builder.start();
        String err = null;
        String pid = null;
        if (!px.isAlive()) {
            err = "Unknown error: " + px.exitValue() + ": "
                    + process_builder.command().stream().collect(Collectors.joining(" "));
            // (since not capturing output)
        } else {
            pid = getPid(px);
            //get the date on the pid file from /proc/<pid>
            final long date = getDateOfPid(pid);
            //record pid=date to aleph_root_path/pid_manager/bucket._id/application_name
            storePid(application_name, bucket, aleph_root_path, pid, date);
        }
        return Tuples._2T(err, pid);

    } catch (Throwable t) {
        return Tuples._2T(ErrorUtils.getLongForm("{0}", t), null);
    }
}