Example usage for java.lang ProcessBuilder redirectError

List of usage examples for java.lang ProcessBuilder redirectError

Introduction

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

Prototype

public ProcessBuilder redirectError(File file) 

Source Link

Document

Sets this process builder's standard error destination to a file.

Usage

From source file:actors.ConfigUtil.java

static ProcessBuilder buildProcess(String javaCmd, String etlJobName, long whEtlExecId, String cmdParam,
        Properties etlJobProperties) {
    String classPath = System.getProperty("java.class.path");
    String outDir = etlJobProperties.getProperty(Constant.WH_APP_FOLDER_KEY, WH_APPLICATION_DEFAULT_DIRECTORY);
    String configFile = outDir + "/" + whEtlExecId + ".properties";

    String[] cmdParams = isNotBlank(cmdParam) ? cmdParam.trim().split(" ") : new String[0];

    ProcessBuilder pb = new ProcessBuilder(new ImmutableList.Builder<String>().add(javaCmd)
            .addAll(Arrays.asList(cmdParams)).add("-cp").add(classPath).add("-Dconfig=" + configFile)
            .add("-DCONTEXT=" + etlJobName).add("-Dlogback.configurationFile=etl_logback.xml")
            .add("-DLOG_DIR=" + outDir).add(Launcher.class.getCanonicalName()).build());
    pb.redirectOutput(ProcessBuilder.Redirect.to(new File(outDir + "/stdout")));
    pb.redirectError(ProcessBuilder.Redirect.to(new File(outDir + "/stderr")));
    return pb;//from   w  w w. j av a  2  s.  co  m
}

From source file:com.opentable.db.postgres.embedded.EmbeddedPostgres.java

private static List<String> system(ProcessBuilder.Redirect errorRedirector,
        ProcessBuilder.Redirect outputRedirector, String... command) {
    try {/*from  ww w  .  j  a  va  2 s  .  c o  m*/
        final ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectError(errorRedirector);
        builder.redirectOutput(outputRedirector);
        final Process process = builder.start();
        Verify.verify(0 == process.waitFor(), "Process %s failed\n%s", Arrays.asList(command),
                IOUtils.toString(process.getErrorStream()));
        try (InputStream stream = process.getInputStream()) {
            return IOUtils.readLines(stream);
        }
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:jeplus.RadianceWinTools.java

/**
 * Call Rtrace to run the simulation/*from w w  w.j a  va  2  s .  c  o  m*/
 * @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//from  ww w  .j  a v a 2 s.  com
 * @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//from   w  w w .  j  av a2 s  .  co m
 * @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:uk.ac.sanger.cgp.wwdocker.actions.Local.java

public static int execCommand(String command, Map envs, boolean shellCmd) {
    ProcessBuilder pb;
    if (shellCmd) {
        pb = new ProcessBuilder("/bin/sh", "-c", command);
    } else {/*  w w w . j av a 2 s .  c  om*/
        pb = new ProcessBuilder(command.split(" "));
    }
    Map<String, String> pEnv = pb.environment();
    pEnv.putAll(envs);
    logger.info("Executing: " + command);
    int exitCode = -1;
    Process p = null;
    File tempOut = null;
    File tempErr = null;
    try {
        tempOut = File.createTempFile("wwdExec", ".out");
        tempErr = File.createTempFile("wwdExec", ".err");
        pb.redirectOutput(tempOut);
        pb.redirectError(tempErr);
        p = pb.start();
        exitCode = p.waitFor();
    } catch (InterruptedException | IOException e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (tempOut != null && tempErr != null) {
            try {
                logger.info(IOUtils.toString(new FileInputStream(tempOut)));
                logger.error(IOUtils.toString(new FileInputStream(tempErr)));
                tempOut.delete();
                tempErr.delete();
            } catch (IOException e) {
                logger.error("Failed to get output from log files");
            }
        }
        if (p != null) {
            p.destroy();
            exitCode = p.exitValue();
        }
    }
    logger.trace("Exit code: " + exitCode);
    return exitCode;
}

From source file:uk.ac.sanger.cgp.wwdocker.actions.Local.java

public static Map<String, String> execCapture(String command, Map envs, boolean shellCmd) {
    Map<String, String> result = new HashMap();
    ProcessBuilder pb;
    if (shellCmd) {
        pb = new ProcessBuilder("/bin/sh", "-c", command);
    } else {/*from  w w w . j  a v a 2 s  .  co m*/
        pb = new ProcessBuilder(command.split(" "));
    }
    Map<String, String> pEnv = pb.environment();
    if (envs != null) {
        pEnv.putAll(envs);
    }
    logger.info("Executing: " + command);
    int exitCode = -1;
    Process p = null;
    File tempOut = null;
    File tempErr = null;
    try {
        tempOut = File.createTempFile("wwdExec", ".out");
        tempErr = File.createTempFile("wwdExec", ".err");
        pb.redirectOutput(tempOut);
        pb.redirectError(tempErr);
        p = pb.start();
        exitCode = p.waitFor();
    } catch (InterruptedException | IOException e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (tempOut != null && tempErr != null) {
            try {
                result.put("stdout", StringUtils.chomp(IOUtils.toString(new FileInputStream(tempOut))));
                result.put("stderr", StringUtils.chomp(IOUtils.toString(new FileInputStream(tempErr))));
                tempOut.delete();
                tempErr.delete();
                logger.info(result.get("stdout"));
                logger.error(result.get("stderr"));
            } catch (IOException e) {
                logger.error("Failed to get output from log files");
            }
        }
        if (p != null) {
            p.destroy();
            exitCode = p.exitValue();
        }
    }
    result.put("exitCode", Integer.toString(exitCode));
    return result;
}

From source file:jeplus.RadianceWinTools.java

/**
 * Call DaySim gen_dc to run the simulation
 * @param config Radiance Configuration/*from  ww  w.  j a v a2 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:edu.pitt.dbmi.ccd.queue.service.AlgorithmQueueService.java

@Async
public Future<Void> runAlgorithmFromQueue(JobQueueInfo jobQueueInfo) {
    Long queueId = jobQueueInfo.getId();
    String fileName = jobQueueInfo.getFileName() + ".txt";
    String jsonFileName = jobQueueInfo.getFileName() + ".json";
    String commands = jobQueueInfo.getCommands();
    String tmpDirectory = jobQueueInfo.getTmpDirectory();
    String outputDirectory = jobQueueInfo.getOutputDirectory();

    List<String> cmdList = new LinkedList<>();
    cmdList.addAll(Arrays.asList(commands.split(";")));

    cmdList.add("--out");
    cmdList.add(tmpDirectory);//  w  w w  .ja v  a 2 s  . c o  m

    StringBuilder sb = new StringBuilder();
    cmdList.forEach(cmd -> {
        sb.append(cmd);
        sb.append(" ");
    });
    LOGGER.info("Algorithm command: " + sb.toString());

    String errorFileName = String.format("error_%s", fileName);
    Path error = Paths.get(tmpDirectory, errorFileName);
    Path errorDest = Paths.get(outputDirectory, errorFileName);
    Path src = Paths.get(tmpDirectory, fileName);
    Path dest = Paths.get(outputDirectory, fileName);
    Path json = Paths.get(tmpDirectory, jsonFileName);
    Path jsonDest = Paths.get(outputDirectory, jsonFileName);

    try {
        ProcessBuilder pb = new ProcessBuilder(cmdList);
        pb.redirectError(error.toFile());
        Process process = pb.start();

        //Get process Id
        Long pid = Processes.processId(process);
        JobQueueInfo queuedJobInfo = jobQueueInfoService.findOne(queueId);
        LOGGER.info("Set Job's pid to be: " + pid);
        queuedJobInfo.setPid(pid);
        jobQueueInfoService.saveJobIntoQueue(queuedJobInfo);

        process.waitFor();

        if (process.exitValue() == 0) {
            LOGGER.info(String.format("Moving txt file %s to %s", src, dest));
            Files.move(src, dest, StandardCopyOption.REPLACE_EXISTING);
            LOGGER.info(String.format("Moving json file %s to %s", json, dest));
            Files.move(json, jsonDest, StandardCopyOption.REPLACE_EXISTING);
            Files.deleteIfExists(error);
        } else {
            LOGGER.info(String.format("Deleting tmp txt file %s", src));
            Files.deleteIfExists(src);
            LOGGER.info(String.format("Moving error file %s to %s", error, errorDest));
            Files.move(error, errorDest, StandardCopyOption.REPLACE_EXISTING);
        }
    } catch (IOException | InterruptedException exception) {
        LOGGER.error("Algorithm did not run successfully.", exception);
    }

    LOGGER.info("Delete Job ID from queue: " + queueId);
    jobQueueInfoService.deleteJobById(queueId);

    return new AsyncResult<>(null);
}

From source file:com.twosigma.beakerx.kernel.MagicKernelManager.java

private void initPythonProcess() throws NoSuchKernelException {
    //cleanup communication resources if already in use
    exit();//from  w ww .j  a v a  2s.c  o  m

    port = findFreePort();
    pythonPort = findFreePort();

    try {
        ProcessBuilder pb = new ProcessBuilder(getPy4jCommand());
        pb.redirectError(ProcessBuilder.Redirect.INHERIT);
        pythonProcess = pb.start();
        BufferedReader br = new BufferedReader(new InputStreamReader(pythonProcess.getInputStream()));
        while (!PY4J_INIT_MESSAGE.equals(br.readLine()) && pythonProcess.isAlive()) {
            //wait for python process to initialize properly
        }
        if (!pythonProcess.isAlive() && pythonProcess.exitValue() == NO_SUCH_KERNEL_CODE) {
            throw new NoSuchKernelException(kernelName);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}