Example usage for java.lang ProcessBuilder redirectInput

List of usage examples for java.lang ProcessBuilder redirectInput

Introduction

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

Prototype

public ProcessBuilder redirectInput(File file) 

Source Link

Document

Sets this process builder's standard input source to a file.

Usage

From source file:Main.java

public static void main(String[] args) {

    // create a new list of arguments for our process
    String[] list = { "notepad.exe", "test.txt" };

    // create the process builder
    ProcessBuilder pb = new ProcessBuilder(list);
    try {/*from  w  w w .  j  a  va2 s  . c  o  m*/

        pb = pb.redirectInput(new File("c:/"));
        pb.start();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:de.uni.bremen.monty.moco.Main.java

private static void runExecutable(File executable) throws IOException, InterruptedException {
    ProcessBuilder processBuilder = new ProcessBuilder(executable.getAbsolutePath());

    String readFromFile = System.getProperty("testrun.readFromFile");
    if (readFromFile != null) {
        processBuilder.redirectInput(new File(readFromFile));
    } else {/*w  w w.java  2 s  . c om*/
        processBuilder.redirectInput(ProcessBuilder.Redirect.INHERIT);
    }
    Process process = processBuilder.start();
    System.err.print(IOUtils.toString(process.getErrorStream()));
    System.out.print(IOUtils.toString(process.getInputStream()));
}

From source file:de.uni.bremen.monty.moco.Main.java

private static void runCode(File llvmCode) throws IOException {
    ProcessBuilder processBuilder = new ProcessBuilder("lli", llvmCode.getAbsolutePath());
    String readFromFile = System.getProperty("testrun.readFromFile");
    if (readFromFile == null) {
        processBuilder.redirectInput(ProcessBuilder.Redirect.INHERIT);
    } else {/*  w w w.  j  a v a  2  s .  c  o m*/
        processBuilder.redirectInput(new File(readFromFile));
    }
    Process process = processBuilder.start();

    System.err.print(IOUtils.toString(process.getErrorStream()));
    System.out.print(IOUtils.toString(process.getInputStream()));
}

From source file:alluxio.cli.ValidateEnv.java

private static boolean validateRemote(String node, String target, String name, CommandLine cmd)
        throws InterruptedException {
    System.out.format("Validating %s environment on %s...%n", target, node);
    if (!Utils.isAddressReachable(node, 22)) {
        System.err.format("Unable to reach ssh port 22 on node %s.%n", node);
        return false;
    }/*from  w w  w . java2s. c om*/

    // args is not null.
    String argStr = String.join(" ", cmd.getArgs());
    String homeDir = Configuration.get(PropertyKey.HOME);
    String remoteCommand = String.format("%s/bin/alluxio validateEnv %s %s %s", homeDir, target,
            name == null ? "" : name, argStr);
    String localCommand = String.format(
            "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no -tt %s \"bash %s\"", node, remoteCommand);
    String[] command = { "bash", "-c", localCommand };
    try {
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectErrorStream(true);
        builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        builder.redirectInput(ProcessBuilder.Redirect.INHERIT);
        Process process = builder.start();
        process.waitFor();
        return process.exitValue() == 0;
    } catch (IOException e) {
        System.err.format("Unable to validate on node %s: %s.%n", node, e.getMessage());
        return false;
    }
}

From source file:jeplus.RadianceWinTools.java

/**
 * Call Rtrace to run the simulation//  ww w . j av a2  s .c  om
 * @param config Radiance Configuration
 * @param WorkDir The working directory where the input files are stored and the output files to be generated
 * @param args
 * @param model
 * @param in
 * @param out
 * @param err
 * @param process
 * @return the result code represents the state of execution steps. >=0 means successful
 */
public static int runRtrace(RadianceConfig config, String WorkDir, String args, String model, String in,
        String out, String err, ProcessWrapper process) {

    int ExitValue = -99;

    try {
        StringBuilder buf = new StringBuilder(config.getResolvedRadianceBinDir());
        buf.append(File.separator).append("rtrace");

        List<String> command = new ArrayList<>();
        command.add(buf.toString());
        String[] arglist = args.split("\\s+");
        command.addAll(Arrays.asList(arglist));
        command.add(model);
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(new File(WorkDir));
        builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedRadianceLibDir());
        builder.redirectError(new File(WorkDir + File.separator + err));
        builder.redirectOutput(new File(WorkDir + File.separator + out));
        builder.redirectInput(new File(WorkDir + File.separator + in));

        Process proc = builder.start();
        if (process != null) {
            process.setWrappedProc(proc);
        }
        ExitValue = proc.waitFor();
    } catch (IOException | InterruptedException ex) {
        logger.error("Error occoured when executing Rtrace", ex);
    }

    // Return Radiance exit value
    return ExitValue;
}

From source file:jeplus.RadianceWinTools.java

/**
 * Call a sequence of DaySim programs to run the simulation
 * @param config Radiance Configuration/* w  w w .jav a  2  s.c o m*/
 * @param WorkDir The working directory where the input files are stored and the output files to be generated
 * @param model
 * @param in
 * @param out
 * @param err
 * @param process
 * @return the result code represents the state of execution steps. >=0 means successful
 */
public static int runDaySim(RadianceConfig config, String WorkDir, String model, String in, String out,
        String err, ProcessWrapper process) {

    int ExitValue = -99;

    // Manipulate header file
    HashMap<String, String> props = new HashMap<>();
    // props.put("project_name", "");
    props.put("project_directory", "./");
    props.put("bin_directory", config.getResolvedDaySimBinDir());
    props.put("tmp_directory", "./");
    props.put("Template_File", config.getResolvedDaySimBinDir() + "../template/DefaultTemplate.htm");
    props.put("sensor_file", in);
    try {
        FileUtils.moveFile(new File(WorkDir + File.separator + model),
                new File(WorkDir + File.separator + model + ".ori"));
    } catch (IOException ex) {
        logger.error("Error renaming header file to " + WorkDir + File.separator + model + ".ori", ex);
    }
    DaySimModel.updateHeaderFile(WorkDir + File.separator + model + ".ori", WorkDir + File.separator + model,
            props);

    // Run gen_dc command
    try {
        StringBuilder buf = new StringBuilder(config.getResolvedDaySimBinDir());
        buf.append(File.separator).append("gen_dc");

        List<String> command = new ArrayList<>();
        command.add(buf.toString());
        command.add(model);
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(new File(WorkDir));
        builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedDaySimLibDir());
        builder.redirectError(new File(WorkDir + File.separator + err));
        builder.redirectOutput(new File(WorkDir + File.separator + out));
        if (in != null) {
            builder.redirectInput(new File(WorkDir + File.separator + in));
        }
        Process proc = builder.start();
        if (process != null) {
            process.setWrappedProc(proc);
        }
        ExitValue = proc.waitFor();
    } catch (IOException | InterruptedException ex) {
        logger.error("Error occoured when executing gen_dc", ex);
    }

    // Run ds_illum command
    try {
        StringBuilder buf = new StringBuilder(config.getResolvedDaySimBinDir());
        buf.append(File.separator).append("ds_illum");

        List<String> command = new ArrayList<>();
        command.add(buf.toString());
        command.add(model);
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(new File(WorkDir));
        builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedDaySimLibDir());
        builder.redirectError(ProcessBuilder.Redirect.appendTo(new File(WorkDir + File.separator + err)));
        builder.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(WorkDir + File.separator + out)));
        if (in != null) {
            builder.redirectInput(new File(WorkDir + File.separator + in));
        }
        Process proc = builder.start();
        if (process != null) {
            process.setWrappedProc(proc);
        }
        ExitValue = proc.waitFor();
    } catch (IOException | InterruptedException ex) {
        logger.error("Error occoured when executing ds_illum", ex);
    }

    // Run ds_el_lighting command
    try {
        StringBuilder buf = new StringBuilder(config.getResolvedDaySimBinDir());
        buf.append(File.separator).append("ds_el_lighting");

        List<String> command = new ArrayList<>();
        command.add(buf.toString());
        command.add(model);
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(new File(WorkDir));
        builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedDaySimLibDir());
        builder.redirectError(ProcessBuilder.Redirect.appendTo(new File(WorkDir + File.separator + err)));
        builder.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(WorkDir + File.separator + out)));
        if (in != null) {
            builder.redirectInput(new File(WorkDir + File.separator + in));
        }
        Process proc = builder.start();
        ExitValue = proc.waitFor();
    } catch (IOException | InterruptedException ex) {
        logger.error("Error occoured when executing ds_el_lighting", ex);
    }

    // Return Radiance exit value
    return ExitValue;
}

From source file:jeplus.RadianceWinTools.java

/**
 * Call Rpict to run the simulation/* w ww.  j  ava 2s  .  c  om*/
 * @param config Radiance Configuration
 * @param WorkDir The working directory where the input files are stored and the output files to be generated
 * @param args
 * @param model
 * @param in
 * @param out
 * @param err
 * @param png Switch for converting scene to jpg or not
 * @param process
 * @return the result code represents the state of execution steps. >=0 means successful
 */
public static int runRpict(RadianceConfig config, String WorkDir, String args, String model, String in,
        String out, String err, boolean png, ProcessWrapper process) {

    int ExitValue = -99;

    // Call rpict
    StringBuilder buf = new StringBuilder(config.getResolvedRadianceBinDir());
    buf.append(File.separator).append("rpict");

    List<String> command = new ArrayList<>();
    command.add(buf.toString());
    String[] arglist = args.split("\\s+");
    command.addAll(Arrays.asList(arglist));
    command.add(model);
    try {
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(new File(WorkDir));
        builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedRadianceLibDir());
        builder.redirectError(new File(WorkDir + File.separator + err));
        builder.redirectOutput(new File(WorkDir + File.separator + out));
        if (in != null) {
            builder.redirectInput(new File(WorkDir + File.separator + in));
        }
        Process proc = builder.start();
        if (process != null) {
            process.setWrappedProc(proc);
        }
        ExitValue = proc.waitFor();
    } catch (IOException | InterruptedException ex) {
        logger.error("Error occoured when executing Rpict", ex);
    }

    if (png) {
        // Sweep everything with the same extension as out. This is for handling
        // -o option in rpict
        String ext = FilenameUtils.getExtension(out);
        File[] files = new File(WorkDir).listFiles((FileFilter) new WildcardFileFilter("*." + ext));
        for (File file : files) {
            String outname = file.getName();

            // Filter scene
            try {
                buf = new StringBuilder(config.getResolvedRadianceBinDir());
                buf.append(File.separator).append("pfilt");

                command = new ArrayList<>();
                command.add(buf.toString());
                // String [] arglist = "-1 -e -3".split("\\s+");
                // command.addAll(Arrays.asList(arglist));
                command.add(outname);
                ProcessBuilder builder = new ProcessBuilder(command);
                builder.directory(new File(WorkDir));
                builder.environment().put("RAYPATH",
                        "." + File.pathSeparator + config.getResolvedRadianceLibDir());
                builder.redirectError(new File(WorkDir + File.separator + err));
                builder.redirectOutput(new File(WorkDir + File.separator + outname + ".flt"));
                Process proc = builder.start();
                ExitValue = proc.waitFor();
            } catch (IOException | InterruptedException ex) {
                logger.error("Error occoured when executing pfilt", ex);
            }

            // Convert to bmp
            try {
                buf = new StringBuilder(config.getResolvedRadianceBinDir());
                buf.append(File.separator).append("ra_bmp");

                command = new ArrayList<>();
                command.add(buf.toString());
                //String [] arglist = "-g 1.0".split("\\s+");
                //command.addAll(Arrays.asList(arglist));
                command.add(outname + ".flt");
                command.add(outname + ".bmp");
                ProcessBuilder builder = new ProcessBuilder(command);
                builder.directory(new File(WorkDir));
                builder.environment().put("RAYPATH",
                        "." + File.pathSeparator + config.getResolvedRadianceLibDir());
                builder.redirectError(
                        ProcessBuilder.Redirect.appendTo(new File(WorkDir + File.separator + err)));
                Process proc = builder.start();
                ExitValue = proc.waitFor();
            } catch (IOException | InterruptedException ex) {
                logger.error("Error occoured when executing ra_bmp", ex);
            }

            // Convert to png
            BufferedImage input_image = null;
            try {
                input_image = ImageIO.read(new File(WorkDir + File.separator + outname + ".bmp")); //read bmp into input_image object
                File outputfile = new File(WorkDir + File.separator + outname + ".png"); //create new outputfile object
                ImageIO.write(input_image, "png", outputfile); //write PNG output to file 
            } catch (Exception ex) {
                logger.error("Error converting bmp to png.", ex);
            }

            // Remove flt and bmp
            new File(WorkDir + File.separator + outname + ".flt").delete();
            new File(WorkDir + File.separator + outname + ".bmp").delete();
        }
    }
    // Return Radiance exit value
    return ExitValue;
}

From source file:jeplus.RadianceWinTools.java

/**
 * Call DaySim gen_dc to run the simulation
 * @param config Radiance Configuration//from   w  w  w.ja  v a  2 s.  c o m
 * @param WorkDir The working directory where the input files are stored and the output files to be generated
 * @param model
 * @param in
 * @param out
 * @param err
 * @param process
 * @return the result code represents the state of execution steps. >=0 means successful
 */
public static int runGen_DC(RadianceConfig config, String WorkDir, String model, String in, String out,
        String err, ProcessWrapper process) {

    int ExitValue = -99;

    // Manipulate header file
    HashMap<String, String> props = new HashMap<>();
    // props.put("project_name", "");
    props.put("project_directory", "./");
    props.put("bin_directory", config.getResolvedDaySimBinDir());
    props.put("tmp_directory", "./");
    props.put("Template_File", config.getResolvedDaySimBinDir() + "../template/");
    props.put("sensor_file", in);
    try {
        FileUtils.moveFile(new File(WorkDir + File.separator + model),
                new File(WorkDir + File.separator + model + ".ori"));
    } catch (IOException ex) {
        logger.error("Error renaming header file to " + WorkDir + File.separator + model + ".ori", ex);
    }
    DaySimModel.updateHeaderFile(WorkDir + File.separator + model + ".ori", WorkDir + File.separator + model,
            props);

    // Run command
    try {
        StringBuilder buf = new StringBuilder(config.getResolvedDaySimBinDir());
        buf.append(File.separator).append("gen_dc");

        List<String> command = new ArrayList<>();
        command.add(buf.toString());
        command.add(model);
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(new File(WorkDir));
        builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedDaySimLibDir());
        builder.redirectOutput(new File(WorkDir + File.separator + out));
        if (err == null || out.equals(err)) {
            builder.redirectErrorStream(true);
        } else {
            builder.redirectError(new File(WorkDir + File.separator + err));
        }
        if (in != null) {
            builder.redirectInput(new File(WorkDir + File.separator + in));
        }
        Process proc = builder.start();
        if (process != null) {
            process.setWrappedProc(proc);
        }
        ExitValue = proc.waitFor();
    } catch (IOException | InterruptedException ex) {
        logger.error("Error occoured when executing DaySim gen_dc", ex);
    }

    // Return Radiance exit value
    return ExitValue;
}

From source file:hyperheuristics.main.comparisons.CompareHypervolumes.java

private static void hypervolumeComparison(String[] problems, String[] heuristicFunctions,
        int numberOfObjectives) throws InterruptedException, IOException {
    for (String heuristicFunction : heuristicFunctions) {
        String path = outpath;/*w  w  w .  ja  v  a 2  s .  co  m*/
        String outputDirectory = path + numberOfObjectives + "objectives/" + heuristicFunction + "/";

        try (FileWriter fileWriter = new FileWriter(outputDirectory + "HYPERVOLUMES.txt")) {

            int hyperheuristicBest = 0;
            int mecbaBest = 0;
            int tied = 0;

            int hyperheuristicBestMean = 0;
            int mecbaBestMean = 0;
            int tiedMean = 0;
            int equivalent = 0;
            for (String problem : problems) {
                fileWriter.append("Hypervolume comparison for " + problem + ":\n");
                fileWriter.append("\n");
                HypervolumeHandler hypervolumeHandler = new HypervolumeHandler();

                String hyperheuristicDirectory = outputDirectory + problem + "/";

                String mecbaDirectory = "resultado/nsgaii/" + problem + "_Comb_" + numberOfObjectives + "obj/";

                //Best hypervolume for PFknown
                hypervolumeHandler.addParetoFront(hyperheuristicDirectory + "FUN.txt");
                hypervolumeHandler.addParetoFront(mecbaDirectory + "All_FUN_nsgaii-" + problem);

                double mecbaHypervolume = hypervolumeHandler
                        .calculateHypervolume(mecbaDirectory + "All_FUN_nsgaii-" + problem, numberOfObjectives);
                double hyperheuristicHypervolume = hypervolumeHandler
                        .calculateHypervolume(hyperheuristicDirectory + "FUN.txt", numberOfObjectives);
                fileWriter.append("MECBA PFknown: " + mecbaHypervolume + "\n");
                fileWriter.append(heuristicFunction + " PFknown: " + hyperheuristicHypervolume + "\n");
                if (mecbaHypervolume == hyperheuristicHypervolume) {
                    fileWriter.append("Best PFknown: Tied!\n");
                    tied++;
                } else {
                    if (mecbaHypervolume > hyperheuristicHypervolume) {
                        fileWriter.append("Best PFknown: MECBA\n");
                        mecbaBest++;
                    } else {
                        fileWriter.append("Best PFknown: " + heuristicFunction + "\n");
                        hyperheuristicBest++;
                    }
                }

                //Best mean hypervolume
                fileWriter.append("\n");

                hypervolumeHandler.clear();

                for (int i = 0; i < EXECUTIONS; i++) {
                    hypervolumeHandler.addParetoFront(hyperheuristicDirectory + "EXECUTION_" + i + "/FUN.txt");
                    hypervolumeHandler.addParetoFront(
                            mecbaDirectory + "FUN_nsgaii-" + problem + "-" + i + ".NaoDominadas");
                }

                double[] mecbaHypervolumes = new double[EXECUTIONS];
                double[] hyperheuristicHypervolumes = new double[EXECUTIONS];

                mecbaHypervolume = 0;
                hyperheuristicHypervolume = 0;

                for (int i = 0; i < EXECUTIONS; i++) {
                    mecbaHypervolumes[i] = hypervolumeHandler.calculateHypervolume(
                            mecbaDirectory + "FUN_nsgaii-" + problem + "-" + i + ".NaoDominadas",
                            numberOfObjectives);
                    mecbaHypervolume += mecbaHypervolumes[i];
                    hyperheuristicHypervolumes[i] = hypervolumeHandler.calculateHypervolume(
                            hyperheuristicDirectory + "EXECUTION_" + i + "/FUN.txt", numberOfObjectives);
                    hyperheuristicHypervolume += hyperheuristicHypervolumes[i];
                }

                mecbaHypervolume /= (double) EXECUTIONS;
                hyperheuristicHypervolume /= (double) EXECUTIONS;

                fileWriter.append("MECBA (Mean): " + mecbaHypervolume + "\n");
                fileWriter.append(heuristicFunction + " (Mean): " + hyperheuristicHypervolume + "\n");

                if (mecbaHypervolume == hyperheuristicHypervolume) {
                    fileWriter.append("Best (Mean): Tied!\n");
                    tiedMean++;
                } else {
                    if (mecbaHypervolume > hyperheuristicHypervolume) {
                        fileWriter.append("Best (Mean): MECBA\n");
                        mecbaBestMean++;
                    } else {
                        fileWriter.append("Best (Mean): " + heuristicFunction + "\n");
                        hyperheuristicBestMean++;
                    }

                    String script = "";

                    script += "MECBA <- c(";
                    for (double value : mecbaHypervolumes) {
                        script += value + ",";
                    }
                    script = script.substring(0, script.lastIndexOf(",")) + ")";

                    script += "\n";

                    script += "MECBA_Hyp <- c(";
                    for (double value : hyperheuristicHypervolumes) {
                        script += value + ",";
                    }
                    script = script.substring(0, script.lastIndexOf(",")) + ")";

                    script += "\n";

                    script += "require(pgirmess)\n";
                    script += "AR1 <- cbind(MECBA, MECBA_Hyp)\n";
                    script += "result <- friedman.test(AR1)\n";
                    script += "m <- data.frame(result$statistic,result$p.value)\n";
                    script += "pos_teste <- friedmanmc(AR1)\n";
                    script += "print(pos_teste)";

                    try (FileWriter scriptWriter = new FileWriter(hyperheuristicDirectory + "temp_input.txt")) {
                        scriptWriter.append(script);
                    }
                    ProcessBuilder processBuilder = new ProcessBuilder("R", "--no-save");

                    File tempOutput = new File(hyperheuristicDirectory + "temp_output.txt");
                    processBuilder.redirectOutput(tempOutput);

                    File tempInput = new File(hyperheuristicDirectory + "temp_input.txt");
                    processBuilder.redirectInput(tempInput);

                    Process process = processBuilder.start();
                    process.waitFor();

                    Scanner scanner = new Scanner(tempOutput);
                    while (scanner.hasNextLine()) {
                        String line = scanner.nextLine();
                        if (line.contains("FALSE")) {
                            equivalent++;
                            fileWriter.append("Statistical Equivalents (Friedman 5%)\n");
                            break;
                        }
                    }

                    tempInput.delete();
                    tempOutput.delete();
                }

                fileWriter.append("\n");
                fileWriter.append("----------\n");
                fileWriter.append("\n");
            }
            fileWriter.append("Problems: " + problems.length + "\n");
            fileWriter.append("\n");
            fileWriter.append("Tied PFknown: " + tied + "\n");
            fileWriter.append("MECBA PFknown: " + mecbaBest + "\n");
            fileWriter.append(heuristicFunction + " PFknown: " + hyperheuristicBest + "\n");
            fileWriter.append("\n");
            fileWriter.append("Tied (Mean): " + tiedMean + "\n");
            fileWriter.append("MECBA (Mean): " + mecbaBestMean + "\n");
            fileWriter.append(heuristicFunction + " (Mean): " + hyperheuristicBestMean + "\n");
            fileWriter.append("Statistically Equivalent: " + equivalent + "\n");
        }
    }
}

From source file:com.anrisoftware.globalpom.exec.core.DefaultProcessTask.java

@Override
public ProcessTask call() throws CommandExecException {
    List<String> command = commandLine.getCommand();
    ProcessBuilder builder = new ProcessBuilder(command);
    builder.directory(commandLine.getWorkingDir());
    builder.redirectOutput(Redirect.PIPE);
    builder.redirectError(Redirect.PIPE);
    builder.redirectInput(Redirect.PIPE);
    try {/*from w ww .ja  v a 2 s .  c o  m*/
        startProcess(builder);
    } catch (IOException e) {
        throw log.errorStartCommand(this, e, commandLine);
    } catch (InterruptedException e) {
        throw log.commandInterrupted(this, e, commandLine);
    } catch (ExecutionException e) {
        throw log.errorStartCommand(this, e.getCause(), commandLine);
    }
    return this;
}