List of usage examples for java.lang ProcessBuilder start
public Process start() throws IOException
From source file:lohbihler.process.epoll.ProcessMonitor.java
public ProcessMonitor(final ProcessBuilder pb, final ExecutorService executorService, final long timeout) throws InterruptedException, IOException { this(pb.start(), executorService, timeout); }
From source file:com.google.dart.server.internal.remote.StdioServerSocket.java
@Override public void start() throws Exception { String[] arguments = computeProcessArguments(); if (debugStream != null) { StringBuilder builder = new StringBuilder(); builder.append(" "); int count = arguments.length; for (int i = 0; i < count; i++) { if (i > 0) { builder.append(' '); }//w w w .j a va 2 s . co m builder.append(arguments[i]); } debugStream.println(System.currentTimeMillis() + " started analysis server:"); debugStream.println(builder.toString()); } ProcessBuilder processBuilder = new ProcessBuilder(arguments); process = processBuilder.start(); requestSink = new ByteRequestSink(process.getOutputStream(), debugStream); responseStream = new ByteResponseStream(process.getInputStream(), debugStream); errorStream = new ByteLineReaderStream(process.getErrorStream()); }
From source file:org.apache.asterix.test.aql.TestExecutor.java
private static String executeVagrantManagix(ProcessBuilder pb, String command) throws Exception { pb.command("vagrant", "ssh", "cc", "--", pb.environment().get("MANAGIX_HOME") + command); Process p = pb.start();/*from ww w .j a v a2s .co m*/ p.waitFor(); InputStream input = p.getInputStream(); return IOUtils.toString(input, StandardCharsets.UTF_8.name()); }
From source file:com.tw.go.plugin.material.artifactrepository.yum.exec.command.ProcessRunner.java
public ProcessOutput execute(String[] command, Map<String, String> envMap) { ProcessBuilder processBuilder = new ProcessBuilder(command); Process process = null;// ww w.j a v a2 s . c o m ProcessOutput processOutput = null; try { processBuilder.environment().putAll(envMap); process = processBuilder.start(); int returnCode = process.waitFor(); List outputStream = IOUtils.readLines(process.getInputStream()); List errorStream = IOUtils.readLines(process.getErrorStream()); processOutput = new ProcessOutput(returnCode, outputStream, errorStream); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } finally { if (process != null) { closeQuietly(process.getInputStream()); closeQuietly(process.getErrorStream()); closeQuietly(process.getOutputStream()); process.destroy(); } } return processOutput; }
From source file:com.l2jfree.sql.L2DataSourceMySQL.java
@Override public void backup() { final String databaseName = getComboPooledDataSource().getJdbcUrl().replaceAll("^.*/", ""); _log.info("DatabaseBackupManager: backing up `" + databaseName + "`..."); final Process run; try {/*ww w.j av a2 s .c o m*/ final ArrayList<String> commands = new ArrayList<String>(); commands.add("mysqldump"); commands.add(" --user=" + getComboPooledDataSource().getUser()); // The MySQL user name to use when connecting to the server commands.add(" --password=" + getComboPooledDataSource().getPassword()); // The password to use when connecting to the server commands.add("--compact"); // Produce more compact output. commands.add("--complete-insert"); // Use complete INSERT statements that include column names commands.add("--default-character-set=utf8"); // Use charset_name as the default character set commands.add("--extended-insert"); // Use multiple-row INSERT syntax that include several VALUES lists commands.add("--lock-tables"); // Lock all tables before dumping them commands.add("--quick"); // Retrieve rows for a table from the server a row at a time commands.add("--skip-triggers"); // Do not dump triggers commands.add(databaseName); // db_name final ProcessBuilder pb = new ProcessBuilder(commands); pb.directory(new File(".")); run = pb.start(); } catch (Exception e) { _log.warn("DatabaseBackupManager: Could not execute mysqldump!", e); return; } writeBackup(databaseName, run); }
From source file:ape.NetworkDropPacketsCommand.java
/** * This method implement the event by using the netem module * @param percent The percentage of packets that are to be dropped * @param period The duration that the packet loss should last * @return True if the execution was successful, false if an error occurred * @throws IOException// w ww .j a v a 2 s. co m */ private boolean executecommand(double percent, double period) throws IOException { String cmd = "tc qdisc add dev eth0 root netem loss " + percent + "% && sleep " + period + " && tc qdisc del dev eth0 root netem"; ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd); pb.redirectErrorStream(true); Process p = null; try { p = pb.start(); } catch (IOException e) { System.err.println( "Executing network connection simulation catches IOException, enter VERBOSE mode to see the Stack Trace"); e.printStackTrace(); return false; } try { if (p.waitFor() != 0) { System.err.println("Non-zero return code (" + p.exitValue() + ") when executing: '" + cmd + "'"); ProcessBuilder tmp2 = new ProcessBuilder("bash", "-c", "tc qdisc del dev eth0 root netem"); Process ptmp = tmp2.start(); if (ptmp.waitFor() == 0) System.out.println("Connection resumed"); else { System.out.println("Connection resumed failed"); return false; } return false; } } catch (InterruptedException e1) { e1.printStackTrace(); return false; } return true; }
From source file:mitm.common.sms.transport.gnokii.Gnokii.java
/** * Sends the message to the number.//from w w w. j av a2s. co 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:com.jbrisbin.vpc.jobsched.exe.ExeMessageHandler.java
public ExeMessage handleMessage(final ExeMessage msg) throws Exception { log.debug("handling message: " + msg.toString()); List<String> args = msg.getArgs(); args.add(0, msg.getExe());/*from ww w.j a v a 2 s . c om*/ try { ProcessBuilder pb = new ProcessBuilder(args); pb.environment().putAll(msg.getEnv()); pb.directory(new File(msg.getDir())); pb.redirectErrorStream(true); Process p = pb.start(); BufferedInputStream stdout = new BufferedInputStream(p.getInputStream()); byte[] buff = new byte[4096]; for (int bytesRead = 0; bytesRead > -1; bytesRead = stdout.read(buff)) { msg.getOut().write(buff, 0, bytesRead); } p.waitFor(); } catch (Throwable t) { log.error(t.getMessage(), t); Object errmsg = t.getMessage(); if (null != errmsg) { msg.getOut().write(((String) errmsg).getBytes()); } } return msg; }
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 .ja v a 2s.c om * 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.st.symfony.Symfony.java
public void run(final String command, final long replyTimeout) throws Exception { String[] commands = command.split("\\s+"); ProcessBuilder pb = new ProcessBuilder(commands); File log = new File(this.logFilePath); pb.redirectErrorStream(true);/* w ww.j a v a2s .com*/ pb.redirectOutput(Redirect.appendTo(log)); Process p = pb.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; StringBuilder output = new StringBuilder(); while ((line = reader.readLine()) != null) { System.out.println(line + "\n"); output.append(line + "\n"); } p.waitFor(); }