Example usage for java.lang ProcessBuilder ProcessBuilder

List of usage examples for java.lang ProcessBuilder ProcessBuilder

Introduction

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

Prototype

public ProcessBuilder(String... command) 

Source Link

Document

Constructs a process builder with the specified operating system program and arguments.

Usage

From source file:com.netflix.dynomitemanager.defaultimpl.FloridaProcessManager.java

public void start() throws IOException {
    logger.info(String.format("Starting dynomite server"));

    List<String> command = Lists.newArrayList();
    if (!"root".equals(System.getProperty("user.name"))) {
        command.add(SUDO_STRING);//  w  ww  . j av  a 2 s .  c om
        command.add("-n");
        command.add("-E");
    }
    command.addAll(getStartCommand());

    ProcessBuilder startDynomite = new ProcessBuilder(command);
    Map<String, String> env = startDynomite.environment();
    setEnv(env);

    startDynomite.directory(new File("/"));
    startDynomite.redirectErrorStream(true);
    Process starter = startDynomite.start();

    try {
        sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS);
        int code = starter.exitValue();
        if (code == 0) {
            logger.info("Dynomite server has been started");
            instanceState.setStorageProxyAlive(true);
        } else {
            logger.error("Unable to start Dynomite server. Error code: {}", code);
        }

        logProcessOutput(starter);
    } catch (Exception e) {
        logger.warn("Starting Dynomite has an error", e);
    }
}

From source file:com.thoughtworks.go.task.rpmbuild.RPMBuildTask.java

Process runProcess(TaskExecutionContext taskExecutionContext, List<String> command) throws IOException {
    ProcessBuilder builder = new ProcessBuilder(command).directory(new File(taskExecutionContext.workingDir()));
    return builder.start();
}

From source file:mitm.common.sms.transport.gnokii.Gnokii.java

/**
 * Sends the message to the number.//from   ww  w .j av  a 2s. c o  m
 */
public String sendSMS(String phoneNumber, String message) throws GnokiiException {
    List<String> cmd = new LinkedList<String>();

    cmd.add(GNOKII_BIN);
    cmd.add("--sendsms");
    cmd.add(phoneNumber);

    if (maxMessageSize != DEFAULT_MAX_MESSAGE_SIZE) {
        cmd.add("-l");
        cmd.add(Integer.toString(maxMessageSize));
    }

    if (requestForDeliveryReport) {
        cmd.add("-r");
    }

    try {
        ProcessBuilder processBuilder = new ProcessBuilder(cmd);
        processBuilder.redirectErrorStream(true);

        Process process = processBuilder.start();

        byte[] bytes = MiscStringUtils.toAsciiBytes(message);

        IOUtils.write(bytes, process.getOutputStream());

        process.getOutputStream().close();

        String output = IOUtils.toString(process.getInputStream());

        int exitValue;

        try {
            exitValue = process.waitFor();
        } catch (InterruptedException e) {
            throw new GnokiiException("Error sending SMS. Output: " + output);
        }

        if (exitValue != 0) {
            throw new GnokiiException("Error sending SMS. Output: " + output);
        }

        return output;
    } catch (IOException e) {
        throw new GnokiiException(e);
    }
}

From source file:net.landora.video.programs.ProgramsAddon.java

public boolean isAvaliable(Program program) {
    String path = getConfiguredPath(program);
    if (path == null) {
        return false;
    }/*from   w  w w  .j  ava2s .  c om*/

    ArrayList<String> command = new ArrayList<String>();
    command.add(path);
    command.addAll(program.getTestArguments());
    ProcessBuilder builder = new ProcessBuilder(command);
    builder.redirectErrorStream(true);

    try {
        Process p = builder.start();
        IOUtils.copy(p.getInputStream(), new NullOutputStream());
        p.waitFor();
        return true;
    } catch (Exception e) {
        log.info("Error checking for program: " + program, e);
        return false;
    }
}

From source file:com.limegroup.gnutella.util.Launcher.java

/**
 * Opens the default web browser on windows, passing it the specified
 * url.//w  ww. j a v a2s.c o m
 *
 * @param url the url to open in the browser
 * @return the error code of the native call, -1 if the call failed
 *  for any reason
 */
private static int openURLWindows(String url) throws IOException {
    //Windows like escaping of '&' character when passed as part of a parameter
    //& -> ^&
    url = url.replace("&", "^&");
    String[] command = new String[] { "cmd.exe", "/c", "start", url };
    ProcessBuilder pb = new ProcessBuilder(command);
    pb.start();
    return 0;
}

From source file:com.microsoft.alm.plugin.idea.common.setup.WindowsStartup.java

/**
 * Run script to launch elevated process to create registry keys
 *
 * @param regeditFilePath//w ww  .  java2s  . c om
 */
private static void launchElevatedCreation(final String regeditFilePath) {
    try {
        final String[] cmd = { "cmd", "/C", "regedit", "/s", regeditFilePath };
        final ProcessBuilder processBuilder = new ProcessBuilder(cmd);
        final Process process = processBuilder.start();
        process.waitFor();
    } catch (IOException e) {
        logger.warn("Running regedit encountered an IOException: {}", e.getMessage());
    } catch (Exception e) {
        logger.warn("Waiting for the process to execute resulted in an error: " + e.getMessage());
    }
}

From source file:mitm.common.sms.transport.gnokii.Gnokii.java

public static String identify() throws GnokiiException {
    String[] cmd = new String[] { GNOKII_BIN, "--identify" };

    try {// w  w  w  .j av  a2  s.c om
        ProcessBuilder processBuilder = new ProcessBuilder(cmd);
        processBuilder.redirectErrorStream(true);

        Process process = processBuilder.start();

        String output = IOUtils.toString(process.getInputStream());

        int exitValue;

        try {
            exitValue = process.waitFor();
        } catch (InterruptedException e) {
            throw new GnokiiException("Identify error. Output: " + output);
        }

        if (exitValue != 0) {
            throw new GnokiiException("Identify error. Output: " + output);
        }

        return output;
    } catch (IOException e) {
        throw new GnokiiException(e);
    }
}

From source file:com.novartis.opensource.yada.plugin.ScriptPreprocessor.java

/**
 * Enables the execution of a script stored in the {@code YADA_BIN} directory.
 * To execute a script preprocessor plugin, pass {@code preArgs}, or just {@code args}
 * the first argument being the name of the script executable, and the rest of the arguments
 * those, in order, to pass to it. If {@link YADARequest#getPreArgs()} is not null
 * and {@link YADARequest#getPlugin()} is null, then the plugin will be set to 
 * {@link YADARequest#SCRIPT_PREPROCESSOR} automatically.  
 * <p>/*from  w w  w .j  a v a2  s .c  o m*/
 * The script must return a JSON object with name/value pairs corresponding
 * to {@link YADARequest} parameters. These name/value pairs are then marshaled into
 * {@code yadaReq}, which is subsequently returned by the method.
 * </p>
 * @see com.novartis.opensource.yada.plugin.Bypass#engage(com.novartis.opensource.yada.YADARequest)
 */
@Override
public YADARequest engage(YADARequest yadaReq) throws YADAPluginException {
    List<String> cmds = new ArrayList<>();
    // get args
    List<String> args = yadaReq.getPreArgs().size() == 0 ? yadaReq.getArgs() : yadaReq.getPreArgs();
    // add plugin
    try {
        cmds.add(Finder.getEnv("yada_bin") + args.remove(0));
    } catch (YADAResourceException e) {
        String msg = "There was a problem locating the resource or variable identified by the supplied JNDI path (yada_bin) in the initial context.";
        throw new YADAPluginException(msg, e);
    }
    // add args
    cmds.addAll(args);
    for (String arg : args) {
        cmds.add(arg);
    }
    // add yadaReq json
    cmds.add(yadaReq.toString());
    l.debug("Executing script plugin: " + cmds);
    String scriptResult = "";
    String s = null;
    try {
        ProcessBuilder builder = new ProcessBuilder(cmds);
        builder.redirectErrorStream(true);
        Process process = builder.start();
        try (BufferedReader si = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            while ((s = si.readLine()) != null) {
                l.debug("  LINE: " + s);
                scriptResult += s;
            }
        }
        process.waitFor();
        JSONObject params = new JSONObject(scriptResult);
        for (String param : JSONObject.getNames(params)) {
            JSONArray ja = (JSONArray) params.get(param);
            l.debug("JSON array " + ja.toString());
            // remove square brackets and leading/trailing quotes
            String values = ja.toString().substring(2, ja.toString().length() - 2);
            // remove "," between values and stuff in array
            String[] value = values.split("\",\"");
            l.debug("Value has " + value.length + " elements");
            yadaReq.invokeSetter(param, value);
        }
    } catch (IOException e) {
        String msg = "Failed to get input from InputStream.";
        throw new YADAPluginException(msg, e);
    } catch (InterruptedException e) {
        String msg = "The external process executing the script was interrupted.";
        throw new YADAPluginException(msg, e);
    } catch (JSONException e) {
        String msg = "Parameter configuration failed. The script return value should conform to the syntax:\n";
        msg += "  {\"key\":[\"value\"...],...}.\n";
        msg += "  The array syntax for values complies to the return value of HTTPServletResponse.getParameterMap().toString()";
        throw new YADAPluginException(msg, e);
    } catch (YADARequestException e) {
        String msg = "Unable to set parameters.";
        throw new YADAPluginException(msg, e);
    }

    return yadaReq;
}

From source file:com.netflix.genie.server.jobmanager.impl.YarnJobManagerImpl.java

/**
 * {@inheritDoc}/* w  w  w . ja  v  a  2s  .co m*/
 */
@Override
public void launch() throws GenieException {
    LOG.info("called");
    if (!this.isInitCalled()) {
        throw new GeniePreconditionException("Init wasn't called. Unable to continue.");
    }

    // create the ProcessBuilder for this process
    final List<String> processArgs = this.createBaseProcessArguments();
    processArgs.addAll(Arrays.asList(StringUtil.splitCmdLine(this.getJob().getCommandArgs())));

    final ProcessBuilder processBuilder = new ProcessBuilder(processArgs);

    // construct the environment variables
    this.setupCommonProcess(processBuilder);
    this.setupYarnProcess(processBuilder);

    // Launch the actual process
    this.launchProcess(processBuilder, ConfigurationManager.getConfigInstance()
            .getInt("com.netflix.genie.server.job.manager.yarn.sleeptime", 5000));
}

From source file:de.fau.cs.osr.hddiff.perfsuite.RunXyDiff.java

private String runXyDiff(File fileA, File fileB, File fileDiff) throws Exception {
    ProcessBuilder pb = new ProcessBuilder(new String[] { xyDiffBin, "-o", fileDiff.getAbsolutePath(),
            fileA.getAbsolutePath(), fileB.getAbsolutePath() });

    try (StringWriter w = new StringWriter()) {
        Process p = pb.start();/*from w  w  w  .  j a v  a 2 s. c  o m*/
        new ThreadedStreamReader(p.getErrorStream(), "ERROR", w);
        new ThreadedStreamReader(p.getInputStream(), "OUTPUT", w);

        try {
            TimeoutProcess.waitFor(p, 2000);
        } catch (Exception e) {
            throw new XyDiffException(e);
        }

        if (p.exitValue() == 0)
            return w.toString();
        else
            throw new XyDiffException(w.toString());
    }
}