Example usage for java.lang ProcessBuilder environment

List of usage examples for java.lang ProcessBuilder environment

Introduction

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

Prototype

Map environment

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

Click Source Link

Usage

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
 *///from  ww w .  j  av a 2 s.c  om
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:com.googlecode.promnetpp.research.main.CompareOutputMain.java

private static void doSeedRun(int seed) throws IOException, InterruptedException {
    System.out.println("Running with seed " + seed);
    String pattern = "int random = <INSERT_SEED_HERE>;";
    int start = sourceCode.indexOf(pattern);
    int end = start + pattern.length();
    String line = sourceCode.substring(start, end);
    line = line.replace("<INSERT_SEED_HERE>", Integer.toString(seed));
    String sourceCodeWithSeed = sourceCode.replace(pattern, line);
    File tempFile = new File("temp.pml");
    FileUtils.writeStringToFile(tempFile, sourceCodeWithSeed);
    //Create a "project" folder
    String fileNameWithoutExtension = fileName.split("[.]")[0];
    File folder = new File("test1-" + fileNameWithoutExtension);
    if (folder.exists()) {
        FileUtils.deleteDirectory(folder);
    }//from ww w .  j  av  a2s.  c om
    folder.mkdir();
    //Copy temp.pml to our new folder
    FileUtils.copyFileToDirectory(tempFile, folder);
    //Simulate the model using Spin
    List<String> spinCommand = new ArrayList<String>();
    spinCommand.add(GeneralData.spinHome + "/spin");
    spinCommand.add("-u1000000");
    spinCommand.add("temp.pml");
    ProcessBuilder processBuilder = new ProcessBuilder(spinCommand);
    processBuilder.directory(folder);
    processBuilder.redirectOutput(new File(folder, "spin-" + seed + ".txt"));
    Process process = processBuilder.start();
    process.waitFor();
    //Translate via PROMNeT++
    List<String> PROMNeTppCommand = new ArrayList<String>();
    PROMNeTppCommand.add("java");
    PROMNeTppCommand.add("-enableassertions");
    PROMNeTppCommand.add("-jar");
    PROMNeTppCommand.add("\"" + GeneralData.getJARFilePath() + "\"");
    PROMNeTppCommand.add("temp.pml");
    processBuilder = new ProcessBuilder(PROMNeTppCommand);
    processBuilder.directory(folder);
    processBuilder.environment().put("PROMNETPP_HOME", GeneralData.PROMNeTppHome);
    process = processBuilder.start();
    process.waitFor();
    //Run opp_makemake
    FileUtils.copyFileToDirectory(new File("opp_makemake.bat"), folder);
    List<String> makemakeCommand = new ArrayList<String>();
    if (Utilities.operatingSystemType.equals("windows")) {
        makemakeCommand.add("cmd");
        makemakeCommand.add("/c");
        makemakeCommand.add("opp_makemake.bat");
    } else {
        throw new RuntimeException("Support for Linux/OS X not implemented" + " here yet.");
    }
    processBuilder = new ProcessBuilder(makemakeCommand);
    processBuilder.directory(folder);
    process = processBuilder.start();
    process.waitFor();
    //Run make
    FileUtils.copyFileToDirectory(new File("opp_make.bat"), folder);
    List<String> makeCommand = new ArrayList<String>();
    if (Utilities.operatingSystemType.equals("windows")) {
        makeCommand.add("cmd");
        makeCommand.add("/c");
        makeCommand.add("opp_make.bat");
    } else {
        throw new RuntimeException("Support for Linux/OS X not implemented" + " here yet.");
    }
    processBuilder = new ProcessBuilder(makeCommand);
    processBuilder.directory(folder);
    process = processBuilder.start();
    process.waitFor();
    System.out.println(Utilities.getStreamAsString(process.getInputStream()));
    System.exit(1);
}

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
 *//*from w w  w . jav  a  2 s .c  om*/
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.eclipse.php.composer.core.ComposerService.java

public static void downloadComposerPhar(File dest, String phpExec) throws CoreException {
    try {/* ww  w  .ja va2  s  .  co  m*/
        if (dest.exists()) {
            boolean update = ComposerPreferences.getBoolean(ComposerPreferences.COMPOSER_PHAR_NODE, true);
            if (!update)
                return;

            long expDate = parseExpDate(dest) * 1000;
            if (System.currentTimeMillis() < expDate)
                return;
        }
        if (dest.exists()) {
            dest.delete();
        }

        File composerPhar = new File(dest, ComposerPreferences.COMPOSER_PHAR);
        String script = HttpHelper.executeGetRequest(GETCOMPOSER_ORG, null, null, 200);
        if (script != null) {
            File scriptFile = new File(getTemp(), "composertemp.php"); //$NON-NLS-1$
            if (!scriptFile.exists()) {
                scriptFile.createNewFile();
            }
            FileOutputStream outStream = new FileOutputStream(scriptFile);
            outStream.write(script.getBytes());
            outStream.close();

            String phpIni = PHPINIUtil.findPHPIni(phpExec).getAbsolutePath();
            List<String> command = new ArrayList<String>();
            command.add(phpExec);
            if (phpIni != null) {
                command.add("-c"); //$NON-NLS-1$
                command.add(phpIni);
            }
            command.add(scriptFile.getCanonicalPath());
            command.add("--"); //$NON-NLS-1$
            command.add(INSTALL_DIR + dest.getParentFile().getAbsolutePath());

            ProcessBuilder processBuilder = new ProcessBuilder(command);
            processBuilder.redirectErrorStream(true);
            PHPLaunchUtilities.appendLibrarySearchPathEnv(processBuilder.environment(),
                    new File(phpExec).getParentFile());

            Process p = processBuilder.start();
            String output = IOUtils.toString(p.getInputStream());

            try {
                int result = p.waitFor();
                if (result != 0) {
                    composerPhar.delete();
                    throw new CoreException(new org.eclipse.core.runtime.Status(IStatus.ERROR,
                            ComposerCorePlugin.PLUGIN_ID, NLS.bind(
                                    Messages.ComposerService_Error_Downloading_Composer_Phar, result, output)));
                }
            } catch (InterruptedException e) {
                ComposerCorePlugin.logError(e);
            } finally {
                scriptFile.delete();
            }
        }
    } catch (IOException e) {
        ComposerCorePlugin.logError(e);
    }
}

From source file:org.cloudifysource.azure.CliAzureDeploymentTest.java

public static String runCliCommands(File cliExecutablePath, List<List<String>> commands, boolean isDebug)
        throws IOException, InterruptedException {
    if (!cliExecutablePath.isFile()) {
        throw new IllegalArgumentException(cliExecutablePath + " is not a file");
    }//w ww .  j a  v a 2  s . c  om

    File workingDirectory = cliExecutablePath.getAbsoluteFile().getParentFile();
    if (!workingDirectory.isDirectory()) {
        throw new IllegalArgumentException(workingDirectory + " is not a directory");
    }

    int argsCount = 0;
    for (List<String> command : commands) {
        argsCount += command.size();
    }

    // needed to properly intercept error return code
    String[] cmd = new String[(argsCount == 0 ? 0 : 1) + 4 /* cmd /c call cloudify.bat ["args"] */];
    int i = 0;
    cmd[i] = "cmd";
    i++;
    cmd[i] = "/c";
    i++;
    cmd[i] = "call";
    i++;
    cmd[i] = cliExecutablePath.getAbsolutePath();
    i++;
    if (argsCount > 0) {
        cmd[i] = "\"";
        //TODO: Use StringBuilder
        for (List<String> command : commands) {
            if (command.size() > 0) {
                for (String arg : command) {
                    if (cmd[i].length() > 0) {
                        cmd[i] += " ";
                    }
                    cmd[i] += arg;
                }
                cmd[i] += ";";
            }
        }
        cmd[i] += "\"";
    }
    final ProcessBuilder pb = new ProcessBuilder(cmd);
    pb.directory(workingDirectory);
    pb.redirectErrorStream(true);

    String extCloudifyJavaOptions = "";

    if (isDebug) {
        extCloudifyJavaOptions += "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9000 -Xnoagent -Djava.compiler=NONE";
    }

    pb.environment().put("EXT_CLOUDIFY_JAVA_OPTIONS", extCloudifyJavaOptions);
    final StringBuilder sb = new StringBuilder();

    logger.info("running: " + cliExecutablePath + " " + Arrays.toString(cmd));

    // log std output and redirected std error
    Process p = pb.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = reader.readLine();
    while (line != null) {
        sb.append(line).append("\n");
        line = reader.readLine();
        logger.info(line);
    }

    final String readResult = sb.toString();
    final int exitValue = p.waitFor();

    logger.info("Exit value = " + exitValue);
    if (exitValue != 0) {
        Assert.fail("Cli ended with error code: " + exitValue);
    }
    return readResult;
}

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.//  w w  w  .  ja va  2s .  c om
 */
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.codehaus.mojo.exec.ExtendedExecutor.java

@Override
protected Process launch(CommandLine command, Map<String, String> env, File dir) throws IOException {
    if (dir != null && !dir.exists()) {
        throw new IOException(dir + " doesn't exist.");
    }//from w ww  .  j a  v  a 2 s. co  m
    ProcessBuilder pb = new ProcessBuilder(command.toStrings());
    pb.environment().putAll(env);
    pb.directory(dir);
    if (inheritIo) {
        pb.inheritIO();
    }
    return pb.start();
}

From source file:com.jbrisbin.vpc.jobsched.exe.ExeMessageHandler.java

public ExeMessage handleMessage(final ExeMessage msg) throws Exception {
    log.debug("handling message: " + msg.toString());

    List<String> args = msg.getArgs();
    args.add(0, msg.getExe());//from   w w  w  .j  a v a 2  s. c  o m

    try {
        ProcessBuilder pb = new ProcessBuilder(args);
        pb.environment().putAll(msg.getEnv());
        pb.directory(new File(msg.getDir()));
        pb.redirectErrorStream(true);
        Process p = pb.start();

        BufferedInputStream stdout = new BufferedInputStream(p.getInputStream());
        byte[] buff = new byte[4096];
        for (int bytesRead = 0; bytesRead > -1; bytesRead = stdout.read(buff)) {
            msg.getOut().write(buff, 0, bytesRead);
        }

        p.waitFor();
    } catch (Throwable t) {
        log.error(t.getMessage(), t);
        Object errmsg = t.getMessage();
        if (null != errmsg) {
            msg.getOut().write(((String) errmsg).getBytes());
        }
    }
    return msg;
}

From source file:org.apache.hcatalog.templeton.tool.TrivialExecService.java

public Process run(List<String> cmd, List<String> removeEnv, Map<String, String> environmentVariables)
        throws IOException {

    logDebugCmd(cmd, environmentVariables);

    ProcessBuilder pb = new ProcessBuilder(cmd);
    for (String key : removeEnv)
        pb.environment().remove(key);
    pb.environment().putAll(environmentVariables);
    return pb.start();
}

From source file:mamo.vanillaVotifier.ShellCommandSender.java

@NotNull
public Process sendCommand(@NotNull String command, @Nullable Map<String, String> environment)
        throws IOException {
    ProcessBuilder processBuilder = new ProcessBuilder(new StrTokenizer(command).getTokenArray());
    if (environment != null) {
        processBuilder.environment().putAll(environment);
    }//from  w w w.j a  v  a  2 s . co m
    return processBuilder.start();
}