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.modelon.oslc.adapter.fmi.integration.FMUConnector.java

public static FMU loadSingleFMU(String fmuInterfaceCMDPath, String fmuPath, String unzipTempDir)
        throws IOException {
    File cmd = new File(fmuInterfaceCMDPath);
    File fmu = new File(fmuPath);
    File fmuTempDir = new File(unzipTempDir + File.separator + fmu.getName());
    fmuTempDir.mkdirs();/*from   w w  w  .  j  a  va2 s.c  om*/

    try {
        ProcessBuilder builder = new ProcessBuilder(cmd.getPath(), "read", fmu.getPath(), fmuTempDir.getPath());
        builder.redirectErrorStream(true);
        Process p = builder.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        StringBuilder sbuilder = new StringBuilder();
        String aux = "";

        while ((aux = reader.readLine()) != null) {
            aux = aux.replaceAll("\\\\", "\\\\\\\\");
            aux += "\r\n";
            sbuilder.append(aux);
        }

        String json = sbuilder.toString();
        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        FMU fmuObject = mapper.readValue(json, FMU.class);
        if (fmuObject.fmiVersion != null)
            return mapper.readValue(json, FMU.class);
        else
            return null;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.chinamobile.bcbsp.pipes.Application.java

/**
 * Run a given command in a subprocess, including threads to copy its stdout
 * and stderr to our stdout and stderr.//from   w  w  w  . j a v a2 s  . com
 * @param command
 *        the command and its arguments
 * @param env
 *        the environment to run the process in
 * @return a handle on the process
 * @throws IOException
 */
static Process runClient(List<String> command, Map<String, String> env) throws IOException {
    ProcessBuilder builder = new ProcessBuilder(command);
    if (env != null) {
        builder.environment().putAll(env);
    }
    Process result = builder.start();
    if (result == null) {
        LOG.info("Application : result is null");
    } else {
        LOG.info("Application : result is not null");
    }
    return result;
}

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 .  ja v  a 2s. c o  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:net.pms.util.ProcessUtil.java

public static void reboot(ArrayList<String> cmd, Map<String, String> env, String startdir,
        String... UMSOptions) {//from  w ww . j av a 2s .c om
    final ArrayList<String> reboot = getUMSCommand();
    if (UMSOptions.length > 0) {
        reboot.addAll(Arrays.asList(UMSOptions));
    }
    if (cmd == null) {
        // We're doing a straight reboot
        cmd = reboot;
    } else {
        // We're running a script that will eventually restart UMS
        if (env == null) {
            env = new HashMap<>();
        }
        // Tell the script how to restart UMS
        env.put("RESTART_CMD", StringUtils.join(reboot, " "));
        env.put("RESTART_DIR", System.getProperty("user.dir"));
    }
    if (startdir == null) {
        startdir = System.getProperty("user.dir");
    }

    System.out.println("starting: " + StringUtils.join(cmd, " "));

    final ProcessBuilder pb = new ProcessBuilder(cmd);
    if (env != null) {
        pb.environment().putAll(env);
    }
    pb.directory(new File(startdir));
    System.out.println("in directory: " + pb.directory());
    try {
        pb.start();
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }
    System.exit(0);
}

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  ww.  j a va 2  s . c  o m
        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 {/*from www  . j a va 2s .co 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:net.sf.jasperreports.customvisualization.export.CVElementPhantomJSImageDataProvider.java

/**
 * Executes a command within the given timeout.
 * //from   w w w  .jav a 2s.  c o m
 * @param args
 * @param currentDirectory
 * @param timeout
 */
private static void runCommand(String[] args, File currentDirectory, final int timeout) {
    Thread loggingThread = null;
    Thread interruptingThread = null;

    try {
        String cmd = "";
        for (String arg : args) {
            cmd += " " + arg;
        }

        if (log.isDebugEnabled()) {
            log.debug("Executing external command: " + cmd);
        }
        //System.out.println(cmd);

        ProcessBuilder pb = new ProcessBuilder(Arrays.asList(args));
        pb.directory(currentDirectory);

        final Process externalProcess = pb.start();
        final StringBuilder processOutput = new StringBuilder();

        final boolean[] success = new boolean[1];
        success[0] = false;

        loggingThread = new Thread(new Runnable() {
            @Override
            public void run() {
                BufferedReader br = null;
                try {
                    br = new BufferedReader(new InputStreamReader(externalProcess.getInputStream()));
                    String line;
                    while ((line = br.readLine()) != null) {
                        processOutput.append(line).append("\n");

                        if (line.indexOf("SCRIPT_SUCCESS") >= 0) {
                            success[0] = true;
                            killProcess(externalProcess, 100);
                        } else if (line.indexOf("SCRIPT_ERROR") >= 0) {
                            success[0] = false;
                            killProcess(externalProcess, 100);
                        }
                    }

                    if (log.isDebugEnabled()) {
                        log.debug("External process output:\n" + processOutput.toString());
                    }
                } catch (IOException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e.getMessage());
                    }
                } finally {
                    if (br != null) {
                        try {
                            br.close();
                        } catch (IOException e) {
                            if (log.isWarnEnabled()) {
                                log.warn("Failed to close phantomjs process' inputstream", e);
                            }
                        }
                    }
                }
            }
        });

        interruptingThread = new Thread(new Runnable() {
            @Override
            public void run() {
                if (killProcess(externalProcess, timeout)) {
                    success[0] = false;
                }
            }

        });
        loggingThread.start();
        interruptingThread.start();
        externalProcess.waitFor();

        // We should not care if the phantomjs process does not end on time if it succeeds in producing the desired output.
        if (externalProcess.exitValue() != 0 && !success[0]) {
            // FIXME we should do loggingThread.join(millis) because the
            // process might end before its output if fully processed

            throw new JRRuntimeException("External process did not end properly; exit value: "
                    + externalProcess.exitValue()
                    + (processOutput.length() > 0 ? "; process output:\n" + processOutput + "\n" : "."));
        }

    } catch (IOException e) {
        throw new JRRuntimeException(e);
    } catch (InterruptedException e) {
        throw new JRRuntimeException(e);
    } finally {

        if (interruptingThread != null && interruptingThread.isAlive()) {
            try {
                interruptingThread.interrupt();
            } catch (Exception ex) {
            }
        }
        if (loggingThread != null && loggingThread.isAlive()) {
            try {
                loggingThread.interrupt();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:edu.cornell.med.icb.R.RUtils.java

/**
 * Can be used to start a rserve instance.
 * @param threadPool The ExecutorService used to start the Rserve process
 * @param rServeCommand Full path to command used to start Rserve process
 * @param host Host where the command should be sent
 * @param port Port number where the command should be sent
 * @param username Username to send to the server if authentication is required
 * @param password Password to send to the server if authentication is required
 * @return The return value from the Rserve instance
 *//*from w w w. jav  a  2s  . c o  m*/
static Future<Integer> startup(final ExecutorService threadPool, final String rServeCommand, final String host,
        final int port, final String username, final String password) {
    if (LOG.isInfoEnabled()) {
        LOG.info("Attempting to start Rserve on " + host + ":" + port);
    }

    return threadPool.submit(new Callable<Integer>() {
        public Integer call() throws IOException {
            final List<String> commands = new ArrayList<String>();

            // if the host is not local, use ssh to exec the command
            if (!"localhost".equals(host) && !"127.0.0.1".equals(host)
                    && !InetAddress.getLocalHost().equals(InetAddress.getByName(host))) {
                commands.add("ssh");
                commands.add(host);
            }

            // TODO - this will fail when spaces are in the the path to the executable
            CollectionUtils.addAll(commands, rServeCommand.split(" "));
            commands.add("--RS-port");
            commands.add(Integer.toString(port));

            final String[] command = commands.toArray(new String[commands.size()]);
            LOG.debug(ArrayUtils.toString(commands));

            final ProcessBuilder builder = new ProcessBuilder(command);
            builder.redirectErrorStream(true);
            final Process process = builder.start();
            BufferedReader br = null;
            try {
                final InputStream is = process.getInputStream();
                final InputStreamReader isr = new InputStreamReader(is);
                br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(host + ":" + port + "> " + line);
                    }
                }

                process.waitFor();
                if (LOG.isInfoEnabled()) {
                    LOG.info("Rserve on " + host + ":" + port + " terminated");
                }
            } catch (InterruptedException e) {
                LOG.error("Interrupted!", e);
                process.destroy();
                Thread.currentThread().interrupt();
            } finally {
                IOUtils.closeQuietly(br);
            }

            final int exitValue = process.exitValue();
            if (LOG.isInfoEnabled()) {
                LOG.info("Rserve on " + host + ":" + port + " returned " + exitValue);
            }
            return exitValue;
        }
    });
}

From source file:functionaltests2.SchedulerCommandLine.java

/**
 * Start a Scheduler and Resource Manager.
 *//*from w  w  w. j  a v  a 2  s .c o  m*/
public static void startSchedulerCmdLine(boolean restart, File proactiveConf) throws Exception {

    File schedHome = new File(System.getProperty("pa.scheduler.home")).getCanonicalFile();
    File rmHome = new File(System.getProperty("pa.rm.home")).getCanonicalFile();
    if (proactiveConf != null) {
        FileUtils.copyFile(proactiveConf,
                new File(schedHome, "config" + fs + "proactive" + fs + "ProActiveConfiguration.xml"));
    }

    System.out.println(schedHome);

    p = null;
    ProcessBuilder pb = new ProcessBuilder();
    if (OperatingSystem.getOperatingSystem().equals(OperatingSystem.unix)) {
        pb.directory(new File(schedHome + fs + "bin" + fs + "unix"));
        pb.command("/bin/bash", restart ? "scheduler-start" : "scheduler-start-clean",
                "-Dproactive.communication.protocol=pnp", "-Dproactive.pnp.port=9999");
        pb.environment().put("SchedulerTStarter", "SchedulerTStarter");
        p = pb.start();

    } else {

        pb.directory(new File(schedHome + fs + "bin" + fs + "windows"));

        pb.command("cmd.exe", "/c", restart ? "scheduler-start.bat" : "scheduler-start-clean.bat",
                "-Dproactive.communication.protocol=pnp", "-Dproactive.pnp.port=9999");
        pb.environment().put("SchedulerTStarter", "SchedulerTStarter");
        p = pb.start();

    }

    IOTools.LoggingThread lt1 = new IOTools.LoggingThread(p.getInputStream(), "[SchedulerTStarter]",
            System.out);
    Thread t1 = new Thread(lt1, "SchedulerTStarter");
    t1.setDaemon(true);
    t1.start();

    // waiting the initialization
    RMAuthentication rmAuth = RMConnection.waitAndJoin("pnp://localhost:9999");

    System.out.println("RM successfully joined.");

    SchedulerConnection.waitAndJoin("pnp://localhost:9999");
    System.out.println("Scheduler successfully joined.");

}

From source file:msec.org.Tools.java

static public int runCommand(String[] cmd, StringBuffer sb, boolean waitflag) {

    Process pid = null;/*w  w w.j  a  va2 s .co  m*/
    ProcessBuilder build = new ProcessBuilder(cmd);
    build.redirectErrorStream(true);
    try {
        pid = build.start();
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
    if (sb != null) {
        //BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024);
        InputStream in = pid.getInputStream();
        byte[] buf = new byte[10240];
        try {
            while (true) {
                int len = in.read(buf);
                if (len <= 0) {
                    break;
                }
                sb.append(new String(buf, 0, len));
            }
        } catch (Exception e) {
        }

    }
    if (waitflag) {
        try {
            pid.waitFor();
            int v = pid.exitValue();
            pid.destroy();
            return v;
        } catch (Exception e) {
        }
    }
    return 0;
}