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:net.pms.util.ProcessUtil.java

public static boolean kill(Integer pid, int signal) {
    boolean killed = false;
    LOGGER.warn("Sending kill -" + signal + " to the Unix process: " + pid);
    try {/*from  w  ww  .ja va  2  s. co m*/
        ProcessBuilder processBuilder = new ProcessBuilder("kill", "-" + signal, Integer.toString(pid));
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();
        // consume the error and output process streams
        StreamGobbler.consume(process.getInputStream(), true);
        int exit = waitFor(process);
        if (exit == 0) {
            killed = true;
            LOGGER.debug("Successfully sent kill -" + signal + " to the Unix process: " + pid);
        }
    } catch (IOException e) {
        LOGGER.error("Error calling: kill -" + signal + " " + pid, e);
    }

    return killed;
}

From source file:com.asakusafw.bulkloader.testutil.UnitTestUtil.java

public static void setUpBeforeClass() throws Exception {
    targetDir.mkdir();/*from   w w  w .j av  a  2 s .  co  m*/
    if (!SystemUtils.IS_OS_WINDOWS) {
        ProcessBuilder pb = new ProcessBuilder("chmod", "777", targetDir.getAbsolutePath());
        pb.start();
    }
}

From source file:com.github.DroidPHP.ServerUtils.java

/**
 * /*from  w w w  . j av  a2 s. co  m*/
 * @param mUsername
 * @param mPassword
 */

public static void startMYSQLMointor(String mUsername, String mPassword) {
    String[] query = new String[] { getAppDirectory() + "/mysql-monitor", "-h", "127.0.0.1", "-T", "-f", "-r",
            "-t", "-E", "--disable-pager", "-n", "--user=" + mUsername, "--password=" + mPassword,
            "--default-character-set=utf8", "-L" };
    try {

        ProcessBuilder pb = (new ProcessBuilder(query));
        pb.redirectErrorStream(true);
        proc = pb.start();
        stdin = proc.getOutputStream();
        stdout = proc.getInputStream();

    } catch (IOException e) {

        Log.e(TAG, "MSQL Monitor", e);
        /**
         * I have commented <string>proc.destroy</strong> because this is
         * usually cause bug
         */
        // proc.destroy();
    }

}

From source file:edu.clemson.cs.nestbed.server.util.UsbPowerControl.java

private static void setPowerState(int bus, int device, int port, int state) {
    ProcessBuilder processBuilder;
    Process process;//w  ww  .  ja v a 2  s  .  co  m
    int exitValue;

    try {
        //processBuilder = new ProcessBuilder(SET_DEV_POWER,
        processBuilder = new ProcessBuilder("/usr/bin/sudo", SET_DEV_POWER, "-b", Integer.toString(bus), "-d",
                Integer.toString(device), "-P", Integer.toString(port), "-p", Integer.toString(state));
        process = processBuilder.start();

        process.waitFor();
        exitValue = process.exitValue();

        if (exitValue == 0) {
            log.debug("Set power state successfully");
        } else {
            log.error("Unable to set power state");
        }
    } catch (InterruptedException ex) {
        log.error("Process interrupted", ex);
    } catch (IOException ex) {
        log.error("I/O Exception occured while reading device info", ex);
    }
}

From source file:ExifUtils.ExifReadWrite.java

private static ArrayList<String> exifTool_builder(String[] parameters, File directory) {
    //        final String command[] = "exiftool " + parameters;
    ArrayList<String> lines = new ArrayList<>();
    try {//from   www.j av a2 s  .co  m
        ProcessBuilder processBuilder = new ProcessBuilder(parameters).directory(directory);
        Process p = processBuilder.start();
        final BufferedReader stdinReader = new BufferedReader(
                new InputStreamReader(p.getInputStream(), "ISO-8859-1"));
        final BufferedReader stderrReader = new BufferedReader(
                new InputStreamReader(p.getErrorStream(), "ISO-8859-1"));
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String s;
                    while ((s = stdinReader.readLine()) != null) {
                        lines.add(s);
                    }
                } catch (IOException e) {
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String s;
                    while ((s = stderrReader.readLine()) != null) {
                        lines.add(s);
                    }
                } catch (IOException e) {
                }
            }
        }).start();
        int returnVal = p.waitFor();
    } catch (Exception e) {
        errorOut("xmp", e);
    }
    return lines;
}

From source file:eu.europa.ejusticeportal.dss.applet.model.service.FileSeekerTest.java

@BeforeClass
public static void setUpTestFileStructure() throws IOException, InterruptedException {

    assertTrue(s != null && s.length() != 0);
    assertTrue(home.exists());/*ww  w.  j a  v a  2  s  .  c om*/
    File testFileStructure = new File(home, "dss_applet_test/aaa/bb bb/cc ccc/ddd dd");

    if (testFileStructure.exists()) {
        FileUtils.deleteDirectory(testFileStructure);
    }
    testFileStructure = new File(home, "dss_applet_test/aaa/bb bb/cc ccc/ddd dd");
    if (!testFileStructure.exists()) {
        testFileStructure.mkdirs();
    }
    assertTrue(testFileStructure.exists());
    File library = new File(testFileStructure, "library.dll");
    if (!library.exists()) {
        library.createNewFile();
    }
    assertTrue(library.exists());

    File library2Folder = new File(home, "dss_applet_test/aaa");
    File library2 = new File(library2Folder, "pkcs11.so");
    if (!library2.exists()) {
        library2.createNewFile();
    }
    assertTrue(library2.exists());

    File library3Folder = new File(home, "dss_applet_test/aaa/bb bb/cc ccc");
    File library3 = new File(library3Folder, "pkcs11.so");
    if (!library3.exists()) {
        library3.createNewFile();
    }
    assertTrue(library3.exists());

    try {
        //Show the directory structure we created
        ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "tree", "/a", "/F",
                new File(home, "dss_applet_test").getAbsolutePath());

        Process p = pb.start();
        InputStreamReader isr = new InputStreamReader(p.getInputStream(), Charset.forName("US-ASCII"));
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) {
            log(line);
        }
    } catch (Exception e) {
        log(e.getMessage());
    }
}

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

private static boolean killProcess(final String pid, final Optional<Integer> kill_signal) throws IOException {
    //      kill -15 the process, wait a few cycles to let it die            
    final ProcessBuilder pb = new ProcessBuilder(Arrays.asList("kill", "-" + kill_signal.orElse(15), pid));
    logger.debug("trying to kill -" + kill_signal.orElse(15) + " pid: " + pid);
    final Process px = pb.start();
    for (int i = 0; i < 5; ++i) {
        try {//from   ww  w  .j a v a2 s  . com
            Thread.sleep(1000L);
        } catch (Exception e) {
        }
        if (!isProcessRunning(pid)) {
            break;
        }
    }
    if (!isProcessRunning(pid)) {
        return 0 == px.exitValue();
    } else {
        //we are still alive, so send a harder kill signal if we haven't already sent a 9
        if (kill_signal.isPresent() && kill_signal.get() == 9) {
            return false;
        } else {
            logger.debug("Timed out trying to kill: " + pid + " sending kill -9 to force kill");
            return killProcess(pid, Optional.of(9));
        }

    }
}

From source file:com.kylinolap.metadata.tool.HiveSourceTableMgmt.java

public static InputStream executeHiveCommand(String command) throws IOException {

    ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", "hive -e \"" + command + "\"");

    // Run hive/*from   www . j  a v  a  2  s  .  c o  m*/
    pb.redirectErrorStream(true);
    Process p = pb.start();
    InputStream is = p.getInputStream();

    return is;
}

From source file:fr.inria.eventcloud.deployment.cli.launchers.EventCloudsManagementServiceDeployer.java

/**
 * Deploys an EventCloudsRegistry and an EventClouds Management Service in a
 * separate JVM according to the specified parameters.
 * /* w  ww.  ja  v a 2  s  . c  o m*/
 * @param onRelease
 *            {@code true} if the lastest release of the EventCloud has to
 *            be used, {@code false} to use the latest snapshot version.
 * @param port
 *            the port used to deploy the EventClouds Management Service and
 *            which will also be used to deploy WS-Notification services.
 * @param urlSuffix
 *            the suffix appended to the end of the URL associated to the
 *            EventClouds Management Service to be deployed.
 * @param activateLoggers
 *            {@code true} if the loggers have to be activated,
 *            {@code false} otherwise.
 * @param properties
 *            additional Java properties set to the new JVM.
 * 
 * @return the endpoint URL of the EventClouds Management Service.
 * 
 * @throws IOException
 *             if an error occurs during the deployment.
 */
public synchronized static String deploy(boolean onRelease, int port, String urlSuffix, boolean activateLoggers,
        String... properties) throws IOException {
    if (eventCloudsManagementServiceProcess == null) {
        String binariesBaseUrl = EVENTCLOUD_BINARIES_URL;

        if (onRelease) {
            binariesBaseUrl += "releases/latest/";
        } else {
            binariesBaseUrl += "snapshots/latest/";
        }

        List<String> cmd = new ArrayList<String>();

        String javaBinaryPath = System.getProperty("java.home") + File.separator + "bin" + File.separator
                + "java";
        if (System.getProperty("os.name").startsWith("Windows")) {
            javaBinaryPath = javaBinaryPath + ".exe";
        }
        cmd.add(javaBinaryPath);

        cmd.add("-cp");
        cmd.add(addClassPath(binariesBaseUrl + "libs/"));

        cmd.addAll(addProperties(binariesBaseUrl + "resources/", activateLoggers));

        Collections.addAll(cmd, properties);

        cmd.add(EventCloudsManagementServiceDeployer.class.getCanonicalName());
        cmd.add(Integer.toString(port));
        cmd.add(urlSuffix);

        final ProcessBuilder processBuilder = new ProcessBuilder(cmd.toArray(new String[cmd.size()]));
        processBuilder.redirectErrorStream(true);
        eventCloudsManagementServiceProcess = processBuilder.start();

        final BufferedReader reader = new BufferedReader(
                new InputStreamReader(eventCloudsManagementServiceProcess.getInputStream()));
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                String line = null;
                try {
                    while ((line = reader.readLine()) != null) {
                        if (!servicesDeployed.getValue() && line.contains(LOG_MANAGEMENT_WS_DEPLOYED)) {
                            servicesDeployed.setValue(true);
                            synchronized (servicesDeployed) {
                                servicesDeployed.notifyAll();
                            }
                        }
                        System.out.println("ECManagement " + line);
                    }
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        });
        t.setDaemon(true);
        t.start();

        synchronized (servicesDeployed) {
            while (!servicesDeployed.getValue()) {
                try {
                    servicesDeployed.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        StringBuilder eventCloudsManagementWsEndpoint = new StringBuilder("http://");
        eventCloudsManagementWsEndpoint.append(ProActiveInet.getInstance().getInetAddress().getHostAddress());
        eventCloudsManagementWsEndpoint.append(':');
        eventCloudsManagementWsEndpoint.append(port);
        eventCloudsManagementWsEndpoint.append('/');
        eventCloudsManagementWsEndpoint.append(urlSuffix);
        return eventCloudsManagementWsEndpoint.toString();
    } else {
        throw new IllegalStateException("EventClouds management process already deployed");
    }
}

From source file:com.sap.prd.mobile.ios.mios.Forker.java

static int forkProcess(final PrintStream out, final File executionDirectory, final String... args)
        throws IOException {

    if (out == null)
        throw new IllegalArgumentException("Print stream for log handling was not provided.");

    if (args == null || args.length == 0)
        throw new IllegalArgumentException("No arguments has been provided.");

    for (final String arg : args)
        if (arg == null || arg.isEmpty())
            throw new IllegalArgumentException(
                    "Invalid argument '" + arg + "' provided with arguments '" + Arrays.asList(args) + "'.");

    final ProcessBuilder builder = new ProcessBuilder(args);

    if (executionDirectory != null)
        builder.directory(executionDirectory);

    builder.redirectErrorStream(true);/* ww w  .java 2s .  c o m*/

    InputStream is = null;

    //
    // TODO: check if there is any support for forking processes in
    // maven/plexus
    //

    try {

        final Process process = builder.start();

        is = process.getInputStream();

        handleLog(is, out);

        return process.waitFor();

    } catch (InterruptedException e) {
        throw new RuntimeException(e.getClass().getName()
                + " caught during while waiting for a forked process. This exception is not expected to be caught at that time.",
                e);
    } finally {
        //
        // Exception raised during close operation below are not reported.
        // That is actually bad.
        // We do not have any logging facility here and we cannot throw the
        // exception since this would swallow any
        // other exception raised in the try block.
        // May be we should revisit that ...
        //
        IOUtils.closeQuietly(is);
    }
}