Example usage for java.lang ProcessBuilder start

List of usage examples for java.lang ProcessBuilder start

Introduction

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

Prototype

public Process start() throws IOException 

Source Link

Document

Starts a new process using the attributes of this process builder.

Usage

From source file:com.moviejukebox.scanner.AttachmentScanner.java

/**
 * Scans a matroska movie file for attachments.
 *
 * @param movieFile the movie file to scan
 *//*from   w  ww.ja  v a 2s.  c  om*/
private static void scanAttachments(MovieFile movieFile) {
    if (movieFile.isAttachmentsScanned()) {
        // attachments has been scanned during rescan of movie
        return;
    }

    // clear existing attachments
    movieFile.clearAttachments();

    // the file with possible attachments
    File scanFile = movieFile.getFile();

    LOG.debug("Scanning file {}", scanFile.getName());
    int attachmentId = 0;
    try {
        // create the command line
        List<String> commandMkvInfo = new ArrayList<>(MT_INFO_EXE);
        commandMkvInfo.add(scanFile.getAbsolutePath());

        ProcessBuilder pb = new ProcessBuilder(commandMkvInfo);

        // set up the working directory.
        pb.directory(MT_PATH);

        Process p = pb.start();

        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line = localInputReadLine(input);
        while (line != null) {
            if (line.contains("+ Attached")) {
                // increase the attachment id
                attachmentId++;
                // next line contains file name
                String fileNameLine = localInputReadLine(input);
                // next line contains MIME type
                String mimeTypeLine = localInputReadLine(input);

                Attachment attachment = createAttachment(attachmentId, fileNameLine, mimeTypeLine,
                        movieFile.getFirstPart(), movieFile.getLastPart());
                if (attachment != null) {
                    attachment.setSourceFile(movieFile.getFile());
                    movieFile.addAttachment(attachment);
                }
            }

            line = localInputReadLine(input);
        }

        if (p.waitFor() != 0) {
            LOG.error("Error during attachment retrieval - ErrorCode={}", p.exitValue());
        }
    } catch (IOException | InterruptedException ex) {
        LOG.error(SystemTools.getStackTrace(ex));
    }

    // attachments has been scanned; no double scan of attachments needed
    movieFile.setAttachmentsScanned(Boolean.TRUE);
}

From source file:uk.ac.kcl.iop.brc.core.pipeline.dncpipeline.service.PythonService.java

/**
 * Runs the Python interpreter./*  w ww  . ja  va  2s. c o  m*/
 * @param args List of arguments to be supplied to the python command.
 * @return Result from python string
 * @throws IOException
 */
public String runFile(List<String> args) throws IOException {
    LinkedList<String> list = new LinkedList<>(args);
    list.addFirst("python");
    ProcessBuilder processBuilder = new ProcessBuilder(list);
    Process p = processBuilder.start();
    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    StringWriter stringWriter = new StringWriter();
    in.lines().forEach(stringWriter::append);
    p.destroy();
    return stringWriter.toString();
}

From source file:jeplus.RadianceWinTools.java

/**
 * Call a sequence of DaySim programs to run the simulation
 * @param config Radiance Configuration//from   w ww. jav  a  2s.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//from  w w  w  .j  av a 2 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:com.orange.clara.cloud.servicedbdumper.task.boot.sequences.BootSequenceBinaries.java

@Override
public void runSequence() throws BootSequenceException {
    String[] commands = { "/bin/chmod", "-R", "+x", binariesPath.getAbsolutePath() };
    logger.debug("Running command: " + String.join(" ", commands) + " ...");
    ProcessBuilder pb = new ProcessBuilder(commands);
    Process p = null;/*from w ww  . j a va 2  s  .c om*/
    try {
        p = pb.start();
        p.waitFor();
    } catch (IOException | InterruptedException e) {
        throw new BootSequenceException("Error when booting: " + e.getMessage(), e);
    }
    logger.debug("Finished Command: " + String.join(" ", commands) + ".");
}

From source file:com.yahoo.rdl.maven.ProcessRunner.java

public String run(List<String> command, ProcessBuilder processBuilder) throws IOException {
    Process process = processBuilder.start();
    try (StreamConsumer stdout = new StreamConsumer(process.getInputStream()).start()) {
        try (StreamConsumer stderr = new StreamConsumer(process.getErrorStream()).start()) {
            if (!process.waitFor(10, TimeUnit.SECONDS)) {
                throw new IOException("Process took longer than 10 seconds to execute: " + command);
            }//from   ww  w. j  a  v  a2  s.  c om
            if (process.exitValue() != 0) {
                String s = stderr.getContents();
                throw new IOException("command '" + StringUtils.join(command, " ") + "' produced error: " + s);
            }
        }
        return stdout.getContents();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

}

From source file:com.heliosdecompiler.helios.controller.ProcessController.java

public Process launchProcess(ProcessBuilder launch) throws IOException {
    Process process = launch.start();
    try {/* w w w.java2 s.  co m*/
        lock.lock();
        processes.add(process);
    } finally {
        lock.unlock();
    }
    backgroundTaskHelper.submit(new BackgroundTask(
            Message.TASK_LAUNCH_PROCESS.format(launch.command().stream().collect(Collectors.joining(" "))),
            true, () -> {
                try {
                    process.waitFor();
                    if (!process.isAlive()) {
                        processes.remove(process);
                    }
                } catch (InterruptedException ignored) {
                }
            }, () -> {
                process.destroyForcibly();
                try {
                    lock.lock();
                    processes.remove(process);
                } finally {
                    lock.unlock();
                }
            }));
    return process;
}

From source file:edu.stanford.epad.epadws.dcm4chee.Dcm4CheeOperations.java

/**
 * TODO This does not work. The ./dcmdeleteSeries script invoked the dcm4chee twiddle command but it appears that the
 * moveSeriesToTrash operation it calls has no effect in this version of dcm4chee. See:
 * http://www.dcm4che.org/jira/browse/WEB-955
 *//*from w w  w . j  a  va2s .  c o  m*/
public static boolean deleteSeries(String seriesUID, String seriesPk) {
    InputStream is = null;
    InputStreamReader isr = null;
    BufferedReader br = null;
    boolean success = false;

    try {
        log.info("Deleting series " + seriesUID + " seriesPK:" + seriesPk);

        String[] command = { "./dcmdeleteSeries", seriesPk, EPADConfig.xnatUploadProjectPassword };
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        String dicomScriptsDir = EPADConfig.getEPADWebServerDICOMScriptsDir() + "bin/";
        File script = new File(dicomScriptsDir, "dcmdeleteSeries");
        if (!script.exists())
            dicomScriptsDir = EPADConfig.getEPADWebServerMyScriptsDir();
        script = new File(dicomScriptsDir, "dcmdeleteSeries");
        // Java 6 - Runtime.getRuntime().exec("chmod u+x "+script.getAbsolutePath());
        script.setExecutable(true);
        processBuilder.directory(new File(dicomScriptsDir));
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();
        process.getOutputStream();
        is = process.getInputStream();
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);

        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
            log.info("./dcmdeleteSeries: " + line);
        }
        try {
            int exitValue = process.waitFor();
            if (exitValue == 0) {
                log.info("Deleted DICOM series " + seriesUID + " pk:" + seriesPk);
                success = true;
            } else {
                log.warning("Failed to delete DICOM series " + seriesUID + " pk=" + seriesPk + "; exitValue="
                        + exitValue + "\n" + sb.toString());
            }
        } catch (Exception e) {
            log.warning("Failed to delete DICOM series " + seriesUID, e);
        }

        String cmdLineOutput = sb.toString();

        if (cmdLineOutput.toLowerCase().contains("error")) {
            throw new IllegalStateException("Failed for: " + parseError(cmdLineOutput));
        }
    } catch (IOException e) {
        log.warning("Failed to delete DICOM series " + seriesUID, e);
    } finally {
        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(is);
    }
    return success;
}

From source file:gsilva.lirc.io.CommandLineIOEngine.java

public boolean startIOEngine() {
    try {/*from w  w  w  .j av  a  2  s . co  m*/
        List<String> cmd = new ArrayList<String>();
        cmd.add(command);
        if (device != null)
            cmd.add(device);

        ProcessBuilder pb = new ProcessBuilder(cmd);
        process = pb.start();

        stdout = process.getInputStream();
        stderr = process.getErrorStream();
        stdin = process.getOutputStream();

        new ErrorThread().start();

        return true;
    } catch (Exception e) {
        log.error("Error starting command: " + command, e);
        return false;
    }
}

From source file:com.synflow.cx.tests.codegen.CodegenPassTests.java

/**
 * Executes a command in the path given by the location, and returns its exit code.
 * //from   w  w  w. j  a  va2  s  .co  m
 * @param directory
 *            a directory
 * @param command
 *            a list of String
 * @return the return code of the process
 * @throws IOException
 * @throws InterruptedException
 */
protected final Process executeCommand(File directory, String... command)
        throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder(command).directory(directory);
    Process process = pb.start();
    new StreamCopier(process.getErrorStream(), System.err).start();
    return process;
}