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.samsung.sjs.Compiler.java

public static Process exec(boolean should_inherit_io, String... args) throws IOException {
    System.err.println("Executing: " + Arrays.toString(args));
    Path tmp = Files.createTempDirectory("testing");
    tmp.toFile().deleteOnExit();//from  w  w  w  . java 2s.co m
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.directory(tmp.toFile());
    if (should_inherit_io) {
        pb.inheritIO();
    }
    return pb.start();
}

From source file:autoupdater.DownloadLatestZipFromRepo.java

/**
 * Simple jar launch through a {@code ProcessBuilder}.
 *
 * @param downloadedFile the downloaded jar file to start
 * @param args           the args to give to the jar file
 * @return true if the launch succeeded//from  w ww  .j  av  a  2  s . c om
 * @throws IOException if the process could not start
 */
private static Process launchJar(MavenJarFile downloadedFile, String[] args)
        throws NullPointerException, IOException {
    Process jar;
    ProcessBuilder p;
    List<String> processToRun = new ArrayList<String>();
    try {
        processToRun.add("java");
        processToRun.add("-jar");
        processToRun.add(downloadedFile.getAbsoluteFilePath());
        if (args != null) {
            processToRun.addAll(Arrays.asList(args));
        }
        p = new ProcessBuilder(processToRun);
        p.directory(new File(downloadedFile.getAbsoluteFilePath()).getParentFile());
        jar = p.start();
    } catch (NullPointerException npe) {
        throw new IOException("could not start the jar");
    }
    return jar;
}

From source file:com.mhs.hboxmaintenanceserver.utils.Utils.java

/**
 * Get LIST of HBOX in DHCP//ww w  .j av a  2  s.c  o m
 *
 * @param ip_range
 * @param manufacturer
 * @return
 * @throws IOException
 */
public static Host[] getListOfHBox_IN_DHCP(String ip_range, String manufacturer) throws IOException {
    ProcessBuilder pb = new ProcessBuilder("nmap", "-sP", ip_range);
    Process process = pb.start();
    ArrayList<Host> hosts;
    try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
        String line, hostname;
        Host host = null;
        Pattern pattern;
        Matcher matcher;
        hosts = new ArrayList<>();
        while ((line = br.readLine()) != null) {
            if (host == null && line.contains("Nmap scan report for")) {
                pattern = Pattern.compile(IPADDRESS_PATTERN, Pattern.CASE_INSENSITIVE);
                matcher = pattern.matcher(line);
                host = new Host();

                String ip_address = "";

                while (matcher.find()) {
                    ip_address += matcher.group();
                }
                host.setIp_address(ip_address);

            } else if (host != null && line.matches("MAC Address: (.*) \\(" + manufacturer + "\\)")) {
                pattern = Pattern.compile(MACADDRESS_PATTERN, Pattern.CASE_INSENSITIVE);
                matcher = pattern.matcher(line);

                String mac_address = "";

                while (matcher.find()) {
                    mac_address += matcher.group();
                }
                host.setMac_address(mac_address.replaceAll("\\:", ""));
                hostname = host.getMac_address();
                hostname = hostname.substring(hostname.length() - 6, hostname.length());
                host.setHost_name("HBOX-" + hostname.toLowerCase());

                hosts.add(host);

                host = null;
            }
        }
    }

    if (!hosts.isEmpty()) {
        return hosts.toArray(new Host[hosts.size()]);
    }

    return null;
}

From source file:jeplus.RadianceWinTools.java

/**
 * Call Rtrace to run the simulation//from  w  w  w .  ja  va  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 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: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  w w  w  .  j  av a  2 s . c o 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:edu.stanford.epad.epadws.dcm4chee.Dcm4CheeOperations.java

public static boolean deleteStudy(String studyUID) {
    InputStream is = null;/*  w w  w  .j a v  a  2 s  .  c  om*/
    InputStreamReader isr = null;
    BufferedReader br = null;
    boolean success = false;
    try {
        log.info("Deleting study " + studyUID + " files - command: ./dcmdeleteStudy " + studyUID);

        String[] command = { "./dcmdeleteStudy", studyUID };

        ProcessBuilder pb = new ProcessBuilder(command);
        String dicomScriptsDir = EPADConfig.getEPADWebServerDICOMScriptsDir() + "bin/";
        File script = new File(dicomScriptsDir, "dcmdeleteStudy");
        if (!script.exists())
            dicomScriptsDir = EPADConfig.getEPADWebServerMyScriptsDir();
        script = new File(dicomScriptsDir, "dcmdeleteStudy");
        // Java 6 - Runtime.getRuntime().exec("chmod u+x "+script.getAbsolutePath());
        script.setExecutable(true);
        pb.directory(new File(dicomScriptsDir));

        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) {
            log.info("./dcmdeleteStudy: " + line);
            sb.append(line).append("\n");
        }

        try {
            int exitValue = process.waitFor();
            log.info("DICOM delete study exit value is: " + exitValue);
            if (exitValue == 0)
                success = true;
        } catch (Exception e) {
            log.warning("Failed to delete DICOM study " + studyUID, e);
        }
        String cmdLineOutput = sb.toString();

        if (cmdLineOutput.toLowerCase().contains("error")) {
            throw new IllegalStateException("Failed for: " + parseError(cmdLineOutput));
        }
    } catch (Exception e) {
        log.warning("Failed to delete DICOM study " + studyUID, e);
    }
    return success;
}

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

/**
 * Extract an attachment/*from w  w  w  . ja  v  a 2 s  . c o m*/
 *
 * @param attachment the attachment to extract
 * @param setImage true, if a set image should be extracted; in this case ".set" is append before file extension
 * @param counter a counter (only used for NFOs cause there may be multiple NFOs in one file)
 * @return
 */
private static File extractAttachment(Attachment attachment) {
    File sourceFile = attachment.getSourceFile();
    if (sourceFile == null) {
        // source file must exist
        return null;
    } else if (!sourceFile.exists()) {
        // source file must exist
        return null;
    }

    // build return file name
    StringBuilder returnFileName = new StringBuilder();
    returnFileName.append(tempDirectory.getAbsolutePath());
    returnFileName.append(File.separatorChar);
    returnFileName.append(FilenameUtils.removeExtension(sourceFile.getName()));
    // add attachment id so the extracted file becomes unique per movie file
    returnFileName.append(".");
    returnFileName.append(attachment.getAttachmentId());

    switch (attachment.getContentType()) {
    case NFO:
        returnFileName.append(".nfo");
        break;
    case POSTER:
    case FANART:
    case BANNER:
    case SET_POSTER:
    case SET_FANART:
    case SET_BANNER:
    case VIDEOIMAGE:
        returnFileName.append(VALID_IMAGE_MIME_TYPES.get(attachment.getMimeType()));
        break;
    default:
        returnFileName.append(VALID_IMAGE_MIME_TYPES.get(attachment.getMimeType()));
        break;
    }

    File returnFile = new File(returnFileName.toString());
    if (returnFile.exists() && (returnFile.lastModified() >= sourceFile.lastModified())) {
        // already present or extracted
        LOG.debug("File to extract already exists; no extraction needed");
        return returnFile;
    }

    LOG.trace("Extract attachement ({})", attachment);
    try {
        // Create the command line
        List<String> commandMedia = new ArrayList<>(MT_EXTRACT_EXE);
        commandMedia.add("attachments");
        commandMedia.add(sourceFile.getAbsolutePath());
        commandMedia.add(attachment.getAttachmentId() + ":" + returnFileName.toString());

        ProcessBuilder pb = new ProcessBuilder(commandMedia);
        pb.directory(MT_PATH);
        Process p = pb.start();

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

    if (returnFile != null) {
        if (returnFile.exists()) {
            // need to reset last modification date to last modification date
            // of source file to fulfill later checks
            try {
                returnFile.setLastModified(sourceFile.lastModified());
            } catch (Exception ignore) {
                // nothing to do anymore
            }
        } else {
            // reset return file to null if not existent
            returnFile = null;
        }
    }
    return returnFile;
}

From source file:com.ikanow.aleph2.data_model.utils.ProcessUtils.java

/**
 * Starts the given process by calling process_builder.start();
 * Records the started processes pid and start date.
 *  //from   w ww . ja v  a2  s. c o m
 * @param process_builder
 * @throws IOException 
 * @return returns any error in _1(), the pid in _2()
 */
public static Tuple2<String, String> launchProcess(final ProcessBuilder process_builder,
        final String application_name, final DataBucketBean bucket, final String aleph_root_path,
        final Optional<Tuple2<Long, Integer>> timeout_kill) {
    try {
        if (timeout_kill.isPresent()) {
            final Stream<String> timeout_stream = Stream.of("timeout", "-s", timeout_kill.get()._2.toString(),
                    timeout_kill.get()._1.toString());
            process_builder.command(Stream.concat(timeout_stream, process_builder.command().stream())
                    .collect(Collectors.toList()));
        }

        //starts the process, get pid back
        logger.debug("Starting process: " + process_builder.command().toString());
        final Process px = process_builder.start();
        String err = null;
        String pid = null;
        if (!px.isAlive()) {
            err = "Unknown error: " + px.exitValue() + ": "
                    + process_builder.command().stream().collect(Collectors.joining(" "));
            // (since not capturing output)
        } else {
            pid = getPid(px);
            //get the date on the pid file from /proc/<pid>
            final long date = getDateOfPid(pid);
            //record pid=date to aleph_root_path/pid_manager/bucket._id/application_name
            storePid(application_name, bucket, aleph_root_path, pid, date);
        }
        return Tuples._2T(err, pid);

    } catch (Throwable t) {
        return Tuples._2T(ErrorUtils.getLongForm("{0}", t), null);
    }
}

From source file:lohbihler.process.ProcessRunner.java

public ProcessRunner(final ProcessBuilder pb) throws IOException {
    process = pb.start();
}

From source file:ca.uqac.info.Job.Launcher.JobLauncher.java

/**
 * Sets up the ProcessBuilder for the bat file and start it
 * @return The exitStatus //from   ww  w  .  jav  a 2  s.c  om
 */
private static int launchJob(String fileBat, String outName, File outFolder) throws Exception {
    // The batch file to execute
    final File batchFile = new File(fileBat);

    // The output file. All activity is written to this file
    final File outputFile = new File(outName);

    // Create the process
    final ProcessBuilder processBuilder = new ProcessBuilder(batchFile.getAbsolutePath(), outName);
    // Redirect any output (including error) to a file. This avoids deadlocks
    // when the buffers get full. 
    processBuilder.redirectErrorStream(true);
    processBuilder.redirectOutput(outputFile);

    // Add a new environment variable
    processBuilder.environment().put("JobLauncher", "Bat File Execution");

    // Set the working directory. The batch file will run as if you are in this
    // directory.
    processBuilder.directory(outFolder);

    // Start the process and wait for it to finish. 
    /* while(nextJob != true)
     {
     //Wait the end of the current Job to Launch the next one
     }
             
     nextJob = false;*/
    final Process process = processBuilder.start();
    final int exitStatus = process.waitFor();
    process.destroy();

    return exitStatus;
}