Example usage for java.lang Process waitFor

List of usage examples for java.lang Process waitFor

Introduction

In this page you can find the example usage for java.lang Process waitFor.

Prototype

public abstract int waitFor() throws InterruptedException;

Source Link

Document

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.

Usage

From source file:jeplus.RadianceWinTools.java

/**
 * Call a sequence of DaySim programs to run the simulation
 * @param config Radiance Configuration//from   www .jav 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 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  a  v a 2s. 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 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:io.sloeber.core.managers.InternalPackageManager.java

@SuppressWarnings("nls")
private static void link(File actualFile, File linkName) throws IOException, InterruptedException {
    String[] command = new String[] { "ln", actualFile.getAbsolutePath(), linkName.getAbsolutePath() };
    if (SystemUtils.IS_OS_WINDOWS) {
        command = new String[] { "cmd", "/c", "mklink", "/H", linkName.getAbsolutePath(),
                actualFile.getAbsolutePath() };
    }// w  w  w.ja va2  s  . co  m
    Process process = Runtime.getRuntime().exec(command, null, null);
    process.waitFor();
}

From source file:edu.stanford.epad.common.dicom.DCM4CHEEUtil.java

public static void dcmsnd(String inputPathFile, boolean throwException) throws Exception {
    InputStream is = null;//from   w  w  w  .  j  a v  a2  s.co m
    InputStreamReader isr = null;
    BufferedReader br = null;

    try {
        String dcmServerTitlePort = aeTitle + "@localhost:" + dicomServerPort;
        dcmServerTitlePort = dcmServerTitlePort.trim();
        log.info("Sending file - command: ./dcmsnd " + dcmServerTitlePort + " " + inputPathFile);
        String[] command = { "./dcmsnd", dcmServerTitlePort, inputPathFile };
        ProcessBuilder pb = new ProcessBuilder(command);
        String dicomBinDirectoryPath = EPADConfig.getEPADWebServerDICOMBinDir();
        log.info("DICOM binary directory: " + dicomBinDirectoryPath);
        pb.directory(new File(dicomBinDirectoryPath));
        Process process = pb.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("./dcmsend output: " + line);
        }

        try {
            int exitValue = process.waitFor();
            log.info("dcmsnd exit value is: " + exitValue);
            if (sb.toString().contains("Sent 0 objects")) {
                log.warning("Zero objects sent to dcm4che, some error has occurred");
                throw new Exception("Error sending files to dcm4che");
            }

        } catch (InterruptedException e) {
            log.warning("Error sending DICOM files in: " + inputPathFile, e);
        }
        String cmdLineOutput = sb.toString();

        if (cmdLineOutput.toLowerCase().contains("error")) {
            throw new IllegalStateException("Failed for: " + cmdLineOutput);
        }
    } catch (Exception e) {
        if (e instanceof IllegalStateException && throwException) {
            throw e;
        }
        log.warning("dcmsnd failed: " + e.getMessage());
        if (throwException) {
            throw new IllegalStateException("dcmsnd failed", e);
        }
    } catch (OutOfMemoryError oome) {
        log.warning("dcmsnd ran out of memory", oome);
        if (throwException) {
            throw new IllegalStateException("dcmsnd ran out of memory", oome);
        }
    } finally {
        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(isr);
    }
}

From source file:org.cloudifysource.azure.AbstractCliAzureDeploymentTest.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");
    }//from   www  .j a va 2s.  co  m

    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:azkaban.utils.FileIOUtils.java

/**
 * Run a unix command that will symlink files, and recurse into directories.
 *///  w  w  w .  ja  va  2  s .co  m
public static void createDeepSymlink(File sourceDir, File destDir) throws IOException {
    if (!sourceDir.exists()) {
        throw new IOException("Source directory " + sourceDir.getPath() + " doesn't exist");
    } else if (!destDir.exists()) {
        throw new IOException("Destination directory " + destDir.getPath() + " doesn't exist");
    } else if (sourceDir.isFile() && destDir.isFile()) {
        throw new IOException("Source or Destination is not a directory.");
    }

    Set<String> paths = new HashSet<String>();
    createDirsFindFiles(sourceDir, sourceDir, destDir, paths);

    StringBuffer buffer = new StringBuffer();
    for (String path : paths) {
        File sourceLink = new File(sourceDir, path);
        path = "." + path;

        buffer.append("ln -s ").append(sourceLink.getAbsolutePath()).append("/*").append(" ").append(path)
                .append(";");
    }

    String command = buffer.toString();
    ProcessBuilder builder = new ProcessBuilder().command("sh", "-c", command);
    builder.directory(destDir);

    // XXX what about stopping threads ??
    Process process = builder.start();
    try {
        NullLogger errorLogger = new NullLogger(process.getErrorStream());
        NullLogger inputLogger = new NullLogger(process.getInputStream());
        errorLogger.start();
        inputLogger.start();

        try {
            if (process.waitFor() < 0) {
                // Assume that the error will be in standard out. Otherwise it'll be
                // in standard in.
                String errorMessage = errorLogger.getLastMessages();
                if (errorMessage.isEmpty()) {
                    errorMessage = inputLogger.getLastMessages();
                }

                throw new IOException(errorMessage);
            }

            // System.out.println(errorLogger.getLastMessages());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } finally {
        IOUtils.closeQuietly(process.getInputStream());
        IOUtils.closeQuietly(process.getOutputStream());
        IOUtils.closeQuietly(process.getErrorStream());
    }
}

From source file:com.pclinuxos.rpm.util.FileUtils.java

/**
 * The method extracts a srpm into the default directory used by the program (/home/<user>/RCEB/srpms/tmp)
 * //  w w w .ja  va 2  s  .  c o  m
 * @param srpm the srpm to extract
 * @return 0 if the extraction was successfully, -1 if a IOException occurred, -2 if a InterruptException
 *  occurred. Values > 0 for return codes of the rpm2cpio command.
 */
public static int extractSrpm(String srpm) {

    int returnCode = 0;

    try {

        Process extractProcess = Runtime.getRuntime()
                .exec("rpm2cpio " + FileConstants.SRCSRPMS.getAbsolutePath() + "/" + srpm);
        // 64kb buffer
        byte[] buffer = new byte[0xFFFF];
        InputStream inread = extractProcess.getInputStream();

        FileOutputStream out = new FileOutputStream(new File(FileConstants.F4SRPMEX + "archive.cpio"));

        while (inread.read(buffer) != -1) {

            out.write(buffer);
        }

        returnCode = extractProcess.waitFor();

        if (returnCode == 0) {

            CpioArchiveInputStream cpioIn = new CpioArchiveInputStream(
                    new FileInputStream(FileConstants.F4SRPMEX + "archive.cpio"));
            CpioArchiveEntry cpEntry;

            while ((cpEntry = cpioIn.getNextCPIOEntry()) != null) {

                FileOutputStream fOut = new FileOutputStream(FileConstants.F4SRPMEX + cpEntry.getName());
                // Do not make this buffer bigger it breaks the cpio decompression
                byte[] buffer2 = new byte[1];
                ArrayList<Byte> buf = new ArrayList<Byte>();

                while (cpioIn.read(buffer2) != -1) {

                    buf.add(buffer2[0]);
                }

                byte[] file = new byte[buf.size()];

                for (int i = 0; i < buf.size(); i++) {

                    file[i] = buf.get(i);
                }

                fOut.write(file);

                fOut.flush();
                fOut.close();
            }

            cpioIn.close();
        }
    } catch (IOException e) {

        returnCode = -1;
    } catch (InterruptedException e) {

        returnCode = -2;
    }

    new File(FileConstants.F4SRPMEX + "archive.cpio").delete();

    return returnCode;
}

From source file:org.kaaproject.kaa.sandbox.web.services.SandboxServiceImpl.java

private static String executeCommand(String... command) throws SandboxServiceException {

    StringBuilder output = new StringBuilder();
    Process process;//from w  w w  . j a v a2s . co m

    try {
        process = Runtime.getRuntime().exec(command);
        process.waitFor();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }
        }
    } catch (Exception ex) {
        throw Utils.handleException(ex);
    }
    return output.toString();
}

From source file:ReadTemp.java

/** Executes the given applescript code and returns the first line of the 
 output as a string *///w w  w.j  av a  2s  . c  o  m
static String doApplescript(String script) {
    String line;
    try {
        // Start applescript 
        Process p = Runtime.getRuntime().exec("/usr/bin/osascript -s o -");

        // Send applescript via stdin
        OutputStream stdin = p.getOutputStream();
        stdin.write(script.getBytes());
        stdin.flush();
        stdin.close();

        // get first line of output
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        line = input.readLine();
        input.close();

        // If we get an exit code, print it out
        if (p.waitFor() != 0) {
            System.err.println("exit value = " + p.exitValue());
            System.err.println(line);
        }
        return line;
    } catch (Exception e) {
        System.err.println(e);
    }

    return "";
}

From source file:Main.java

public static String getSystemOutput(String paramString) {
    String str1 = "";
    try {//  w  w w.  j a va2 s  .  c  o m
        Process localProcess = Runtime.getRuntime().exec(paramString);
        InputStream localInputStream = localProcess.getInputStream();
        InputStreamReader localInputStreamReader = new InputStreamReader(localInputStream);
        BufferedReader localBufferedReader = new BufferedReader(localInputStreamReader);
        for (;;) {
            String str2 = localBufferedReader.readLine();
            if (str2 == null) {
                break;
            }
            StringBuilder localStringBuilder1 = new StringBuilder();
            str1 = str1 + str2;
            StringBuilder localStringBuilder2 = new StringBuilder();
            str1 = str1 + "\n";
        }
        int i = localProcess.waitFor();
        PrintStream localPrintStream = System.out;
        StringBuilder localStringBuilder3 = new StringBuilder();
        localPrintStream.println("Process exitValue: " + i);
        return str1;
    } catch (Throwable localThrowable) {
        for (;;) {
            localThrowable.printStackTrace();
        }
    }
}