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:edu.uci.ics.asterix.test.aql.TestsUtils.java

public static String executeScript(ProcessBuilder pb, String scriptPath) throws Exception {
    pb.command(scriptPath);/*from  w  w w  . java2  s .  c o  m*/
    Process p = pb.start();
    p.waitFor();
    return getProcessOutput(p);
}

From source file:alluxio.cli.ValidateEnv.java

private static boolean validateRemote(String node, String target, String name, CommandLine cmd)
        throws InterruptedException {
    System.out.format("Validating %s environment on %s...%n", target, node);
    if (!Utils.isAddressReachable(node, 22)) {
        System.err.format("Unable to reach ssh port 22 on node %s.%n", node);
        return false;
    }/*from   w w  w .  ja  v a  2  s. co m*/

    // args is not null.
    String argStr = String.join(" ", cmd.getArgs());
    String homeDir = Configuration.get(PropertyKey.HOME);
    String remoteCommand = String.format("%s/bin/alluxio validateEnv %s %s %s", homeDir, target,
            name == null ? "" : name, argStr);
    String localCommand = String.format(
            "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no -tt %s \"bash %s\"", node, remoteCommand);
    String[] command = { "bash", "-c", localCommand };
    try {
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectErrorStream(true);
        builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        builder.redirectInput(ProcessBuilder.Redirect.INHERIT);
        Process process = builder.start();
        process.waitFor();
        return process.exitValue() == 0;
    } catch (IOException e) {
        System.err.format("Unable to validate on node %s: %s.%n", node, e.getMessage());
        return false;
    }
}

From source file:de.tudarmstadt.ukp.dkpro.tc.svmhmm.task.SVMHMMTestTask.java

/**
 * Executes the command (runs a new process outside the JVM and waits for its completion)
 *
 * @param command command as list of Strings
 *//*from w w  w  .j  a va  2 s.c o  m*/
private static void runCommand(List<String> command) throws Exception {
    log.info(StringUtils.join(command, " "));

    if (PRINT_STD_OUT) {
        Process process = new ProcessBuilder().inheritIO().command(command).start();
        process.waitFor();
    } else {
        // create temp files for capturing output instead of printing to stdout/stderr
        File tmpOutLog = File.createTempFile("tmp.out.", ".log");

        ProcessBuilder processBuilder = new ProcessBuilder(command);

        processBuilder.redirectError(tmpOutLog);
        processBuilder.redirectOutput(tmpOutLog);

        // run the process
        Process process = processBuilder.start();
        process.waitFor();

        // re-read the output and debug it
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(tmpOutLog)));
        String line;
        while ((line = br.readLine()) != null) {
            log.debug(line);
        }
        IOUtils.closeQuietly(br);

        // delete files
        FileUtils.deleteQuietly(tmpOutLog);
    }
}

From source file:fr.ens.biologie.genomique.eoulsan.actions.HadoopExecAction.java

/**
 * Run Eoulsan in hadoop mode./* w ww. j  av  a 2 s  . c om*/
 * @param workflowFile workflow file
 * @param designFile design file
 * @param hdfsPath path of data on hadoop file system
 * @param jobDescription job description
 */
private static void run(final File workflowFile, final File designFile, final String hdfsPath,
        final String jobDescription) {

    checkNotNull(workflowFile, "paramFile is null");
    checkNotNull(designFile, "designFile is null");
    checkNotNull(hdfsPath, "hdfsPath is null");

    // Write log entries
    Main.getInstance().flushLog();

    // Repackage application for Hadoop
    System.out.println("Package " + Globals.APP_NAME + " for hadoop mode...");
    final File repackagedJarFile;
    try {
        repackagedJarFile = HadoopJarRepackager.repack();

    } catch (IOException e) {
        Common.errorExit(e, "Error while repackaging " + Globals.APP_NAME_LOWER_CASE + ": " + e.getMessage());

        // Never called
        return;
    }

    getLogger().info("Launch Eoulsan in Hadoop mode.");

    // Create command line
    final List<String> argsList = new ArrayList<>();

    argsList.add("hadoop");
    argsList.add("jar");
    argsList.add(repackagedJarFile.getAbsolutePath());

    final Main main = Main.getInstance();

    if (main.getLogLevelArgument() != null) {
        argsList.add("-loglevel");
        argsList.add(main.getLogLevelArgument());
    }

    if (main.getConfigurationFileArgument() != null) {
        argsList.add("-conf");
        argsList.add(main.getConfigurationFileArgument());
    }

    for (String setting : main.getCommandLineSettings()) {
        argsList.add("-s");
        argsList.add(setting);
    }

    argsList.add(ExecJarHadoopAction.ACTION_NAME);

    if (jobDescription != null) {
        argsList.add("-d");
        argsList.add(jobDescription.trim());
    }

    argsList.add("-e");
    argsList.add("local hadoop cluster");
    argsList.add(workflowFile.toString());
    argsList.add(designFile.toString());
    argsList.add(hdfsPath);

    // execute Hadoop
    System.out.println("Launch " + Globals.APP_NAME + " in hadoop mode...");

    try {

        // Create the process builder the the command line
        final ProcessBuilder builder = new ProcessBuilder(argsList).inheritIO();

        // Set the JVM arguments for Hadoop in the process builder
        builder.environment().put(HADOOP_CLIENT_OPTS_ENV, getJVMArgs());

        // Execute the hadoop jar command
        final int exitCode = builder.start().waitFor();

        // Exit with the same exit of the child process
        System.exit(exitCode);

    } catch (IOException | InterruptedException e) {
        Common.errorExit(e, "Error while executing " + Globals.APP_NAME_LOWER_CASE + ": " + e.getMessage());
    }

}

From source file:azkaban.utils.FileIOUtils.java

/**
 * Run a unix command that will symlink files, and recurse into directories.
 *///from w  ww.j  a va2s. c  o  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:org.fcrepo.it.SparqlRecipesIT.java

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

    //Determine the snapshot used for testing and its REST api,
    //make it default for snapshot 4 for the current version
    final String fcrepoSnapshot = System.getProperty("fcrepo.version");
    if (fcrepoSnapshot != null && fcrepoSnapshot.indexOf("-") > 0
            && fcrepoSnapshot.indexOf("4.0.0-beta") >= 0) {
        final String[] verTokens = fcrepoSnapshot.split("-");
        if (verTokens.length >= 3) {
            try {
                FCREPO_SNAPSHOT_NUMBER = Short.parseShort(verTokens[2]);
            } catch (final NumberFormatException ne) {
                FCREPO_SNAPSHOT_NUMBER = 4;
            }/*from ww  w . jav a  2  s. c o  m*/
        }
    }
    if (FCREPO_SNAPSHOT_NUMBER < 4) {
        DATASTREAM_URL_SUFIX = "";
        DATASTREAM_CONTENT_URL_SUFIX = "/fcr:content";
        DATASTREAM_MIXIN_TYPE = "fedora:datastream";
        DATASTREAM_RELATION = "fcrepo:hasContent";
    }

    final File commandFile = new File("target/jena-fuseki-1.0.1/fuseki-server");
    final ProcessBuilder b = new ProcessBuilder().inheritIO().directory(commandFile.getParentFile()).command(
            "./fuseki-server", "--update", "--mem", "--port=" + FUSEKI_PORT, "--mgtPort=" + MGT_PORT, "/test");
    fuseki = b.start();

    // It might take a while to startup and be ready to receive messages...
    Thread.sleep(10000);

    setUpTestObjects();
}

From source file:loadTest.loadTestLib.LUtil.java

public static boolean startDockerBuild() throws IOException, InterruptedException {
    if (useDocker) {
        if (runInDockerCluster) {

            HashMap<String, Integer> dockerNodes = getDockerNodes();
            String dockerTar = LUtil.class.getClassLoader().getResource("docker/loadTest.tar").toString()
                    .substring(5);/*from  w ww  .ja v  a  2 s .  c  o  m*/
            ExecutorService exec = Executors.newFixedThreadPool(dockerNodes.size());

            dockerError = false;
            doneDockers = 0;

            for (Entry<String, Integer> entry : dockerNodes.entrySet()) {
                exec.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String url = entry.getKey() + "/images/vauvenal5/loadtest";
                            URL obj = new URL(url);
                            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                            con.setRequestMethod("DELETE");
                            con.setRequestProperty("force", "true");
                            int responseCode = con.getResponseCode();
                            con.disconnect();

                            url = entry.getKey()
                                    + "/build?t=vauvenal5/loadtest&dockerfile=./loadTest/Dockerfile";
                            obj = new URL(url);
                            con = (HttpURLConnection) obj.openConnection();
                            con.setRequestMethod("POST");
                            con.setRequestProperty("Content-type", "application/tar");
                            con.setDoOutput(true);
                            File file = new File(dockerTar);
                            FileInputStream fileStr = new FileInputStream(file);
                            byte[] b = new byte[(int) file.length()];
                            fileStr.read(b);
                            con.getOutputStream().write(b);
                            con.getOutputStream().flush();
                            con.getOutputStream().close();

                            responseCode = con.getResponseCode();

                            if (responseCode != 200) {
                                dockerError = true;
                            }

                            String msg = "";

                            do {
                                Thread.sleep(5000);
                                msg = "";
                                url = entry.getKey() + "/images/json";
                                obj = new URL(url);
                                HttpURLConnection con2 = (HttpURLConnection) obj.openConnection();
                                con2.setRequestMethod("GET");
                                responseCode = con2.getResponseCode();

                                BufferedReader in = new BufferedReader(
                                        new InputStreamReader(con2.getInputStream()));
                                String line = null;

                                while ((line = in.readLine()) != null) {
                                    msg += line;
                                }

                                con2.disconnect();
                            } while (!msg.contains("vauvenal5/loadtest"));

                            con.disconnect();
                            doneDockers++;
                        } catch (MalformedURLException ex) {
                            dockerError = true;
                        } catch (FileNotFoundException ex) {
                            dockerError = true;
                        } catch (IOException ex) {
                            dockerError = true;
                        } catch (InterruptedException ex) {
                            dockerError = true;
                        }
                    }
                });
            }

            while (doneDockers < dockerNodes.size()) {
                Thread.sleep(5000);
            }

            return !dockerError;
        }

        //get the path and substring the 'file:' from the URI
        String dockerfile = LUtil.class.getClassLoader().getResource("docker/loadTest").toString().substring(5);

        ProcessBuilder processBuilder = new ProcessBuilder("docker", "rmi", "-f", "vauvenal5/loadtest");
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        Process docker = processBuilder.start();

        docker.waitFor();

        processBuilder = new ProcessBuilder("docker", "build", "-t", "vauvenal5/loadtest", dockerfile);
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        Process proc = processBuilder.start();
        return proc.waitFor() == 0;
    }
    return true;
}

From source file:it.isislab.dmason.util.SystemManagement.Worker.Updater.java

public static void updateWithGUI(Address FTPaddress, String name, String myTopic, Address address) {
    logger.debug("Update (with GUI) command received");
    FTPIP = FTPaddress.getIPaddress();/*from  w w  w  .  j  ava  2s  . c om*/
    FTPPORT = FTPaddress.getPort();
    jarName = name;

    setSeparator();

    downloadJar(jarName, "upd");

    //DOWNLOADED_JAR_PATH+SEPARATOR+
    File fDown = new File(DOWNLOADED_JAR_PATH + SEPARATOR + jarName);
    File fDest = new File(jarName);

    try {
        //FileUtils.copyFile(fDown, fDest);
        copyFile(fDown, fDest);
        try {
            ArrayList<String> command = new ArrayList<String>();

            command.add("java");
            //command.add("-jar");
            command.add("-cp");
            command.add(fDest.getAbsolutePath());
            command.add(DMasonWorkerWithGui.class.getName());
            command.add(address.getIPaddress());
            command.add(address.getPort());
            command.add(myTopic);
            command.add("update");

            logger.info("Restarting with command: " + command.toString());

            ProcessBuilder builder = new ProcessBuilder(command);
            Process process = builder.start();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        /*Timer timer = new Timer(4000, new ActionListener() {
           public void actionPerformed(ActionEvent e) {
              System.exit(0);
                
           }
        });
                
        timer.start();
        */
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:it.isislab.dmason.util.SystemManagement.Worker.Updater.java

public static void updateNoGUI(Address ftpAddress, String name, String myTopic, Address address) {

    logger.debug("Update (with CLI) command received");

    FTPIP = ftpAddress.getIPaddress();// ww  w. j  a va 2  s .com
    FTPPORT = ftpAddress.getPort();
    jarName = name;

    setSeparator();

    downloadJar(jarName, "upd");

    //DOWNLOADED_JAR_PATH+SEPARATOR+
    File fDown = new File(DOWNLOADED_JAR_PATH + SEPARATOR + jarName);
    File fDest = new File(jarName);

    try {

        //FileUtils.copyFile(fDown, fDest);
        copyFile(fDown, fDest);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        ArrayList<String> command = new ArrayList<String>();

        command.add("java");
        //command.add("-jar");
        command.add("-cp");
        command.add(fDest.getAbsolutePath());
        command.add(DMasonWorker.class.getName());
        command.add(address.getIPaddress());
        command.add(address.getPort());
        command.add(myTopic);
        command.add("update");

        System.out.println(command);

        logger.info("Restarting with command: " + command.toString());

        ProcessBuilder builder = new ProcessBuilder(command);
        Process process = builder.start();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    /*Timer timer = new Timer(4000, new ActionListener() {
    public void actionPerformed(ActionEvent e) {
       System.exit(0);
            
    }
    });
            
    timer.start();
    */

}

From source file:it.isislab.dmason.util.SystemManagement.Worker.Updater.java

public static void restart(String myTopic, Address address, boolean isBatch, String topicPrefix) {
    logger.debug("Restart command received");

    // TODO Auto-generated method stub
    String path;/*from  ww  w.ja  v a 2s  .  co  m*/
    try {
        path = URLDecoder.decode(Updater.class.getProtectionDomain().getCodeSource().getLocation().getFile(),
                "UTF-8");
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        path = "";
    }

    if (path.contains(".jar")) //from jar
    {

        File jarfile = new File(path);
        try {
            ArrayList<String> command = new ArrayList<String>();

            // Luca Vicidomini
            command.add("java");
            command.add("-cp");
            command.add(jarfile.getAbsolutePath());
            command.add(DMasonWorker.class.getName());
            command.add(address.getIPaddress());
            command.add(address.getPort());
            command.add(myTopic);
            if (!isBatch)
                command.add("reset");
            else
                command.add(topicPrefix);

            // As wrote by Mario
            //               command.add("java");
            //               command.add("-jar");
            //               command.add(jarfile.getAbsolutePath());
            //               command.add(address.getIPaddress());
            //               command.add(address.getPort());
            //               command.add(myTopic);
            //               if(!isBatch)
            //                  command.add("reset");
            //               else
            //                  command.add(topicPrefix);

            logger.info("Restarting with command: " + command.toString());
            System.out.println("Restarting with command: " + command);

            ProcessBuilder builder = new ProcessBuilder(command);
            Process process = builder.start();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}