List of usage examples for java.lang ProcessBuilder ProcessBuilder
ProcessBuilder
From source file:kr.ac.kaist.wala.hybridroid.analysis.resource.AndroidDecompiler.java
private static void permission(String path) { String[] cmd = { "chmod", "755", path }; ProcessBuilder pb = new ProcessBuilder(); pb.command(cmd);/* ww w.j a va2 s . com*/ Process p = null; try { p = pb.start(); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader bre = new BufferedReader(new InputStreamReader(p.getErrorStream())); String r = null; while ((r = br.readLine()) != null) { System.out.println(r); } while ((r = bre.readLine()) != null) { System.err.println(r); } int res = p.waitFor(); if (res != 0) { throw new InternalError("failed to decompile: " + path); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.junoyoon.BullsUtil.java
/** * Run command and//from w w w. j a v a2s. c o m * * @param cmd * @return * @throws IOException */ public static String getCmdOutput(List<String> cmd) throws IOException { ProcessBuilder builder = new ProcessBuilder(); builder.command().addAll(cmd); builder.redirectErrorStream(true); StringBuilder result = new StringBuilder(1024); Process proc = builder.start(); boolean firstLine = true; for (Object eachLineObject : IOUtils.readLines(proc.getInputStream())) { String eachLine = (String) eachLineObject; if (firstLine) { eachLine = eachLine.replace("charset=us-ascii", "charset=" + Constant.DEFAULT_ENCODING); firstLine = false; } result.append(eachLine).append("\n"); } return result.toString(); }
From source file:com.smash.revolance.ui.materials.CmdlineHelper.java
public CmdlineHelper exec() throws InterruptedException, IOException { ProcessBuilder pb = new ProcessBuilder(); if (dir != null) { pb.directory(dir);// w ww . j a va 2 s . com } pb.command(cmd); pb.redirectError(ProcessBuilder.Redirect.to(err)); pb.redirectOutput(ProcessBuilder.Redirect.to(out)); pb.redirectInput(ProcessBuilder.Redirect.from(in)); System.out.println("Executing cmd: " + cmd[0] + " from dir: " + dir); System.out.println("Redirecting out to: " + out.getAbsolutePath()); System.out.println("Redirecting err to: " + err.getAbsolutePath()); Process process = pb.start(); if (sync) { process.waitFor(); } this.process = process; return this; }
From source file:com.frederikam.fredboat.bootloader.Bootloader.java
private static Process boot() throws IOException { //Check that we are not booting too quick (we could be stuck in a login loop) if (System.currentTimeMillis() - lastBoot > 3000 * 1000) { recentBoots = 0;/*from ww w . j a v a 2 s . com*/ } recentBoots++; lastBoot = System.currentTimeMillis(); if (recentBoots >= 4) { System.out.println("[BOOTLOADER] Failed to restart 3 times, probably due to login errors. Exiting..."); System.exit(-1); } //ProcessBuilder pb = new ProcessBuilder(System.getProperty("java.home") + "/bin/java -jar "+new File("FredBoat-1.0.jar").getAbsolutePath()) ProcessBuilder pb = new ProcessBuilder().inheritIO(); ArrayList<String> list = new ArrayList<>(); command.forEach((Object str) -> { list.add((String) str); }); pb.command(list); Process process = pb.start(); return process; }
From source file:com.netflix.genie.agent.execution.services.impl.LaunchJobServiceImpl.java
/** * {@inheritDoc}/* ww w.ja va 2s.c o m*/ */ @Override public void launchProcess(final File jobDirectory, final Map<String, String> environmentVariablesMap, final List<String> commandLine, final boolean interactive) throws JobLaunchException { if (!launched.compareAndSet(false, true)) { throw new IllegalStateException("Job already launched"); } final ProcessBuilder processBuilder = new ProcessBuilder(); // Validate job running directory if (jobDirectory == null) { throw new JobLaunchException("Job directory is null"); } else if (!jobDirectory.exists()) { throw new JobLaunchException("Job directory does not exist: " + jobDirectory); } else if (!jobDirectory.isDirectory()) { throw new JobLaunchException("Job directory is not a directory: " + jobDirectory); } else if (!jobDirectory.canWrite()) { throw new JobLaunchException("Job directory is not writable: " + jobDirectory); } final Map<String, String> currentEnvironmentVariables = processBuilder.environment(); if (environmentVariablesMap == null) { throw new JobLaunchException("Job environment variables map is null"); } // Merge job environment variables into process inherited environment environmentVariablesMap.forEach((key, value) -> { final String replacedValue = currentEnvironmentVariables.put(key, value); if (StringUtils.isBlank(replacedValue)) { log.debug("Added job environment variable: {}={}", key, value); } else if (!replacedValue.equals(value)) { log.debug("Set job environment variable: {}={} (previous value: {})", key, value, replacedValue); } }); // Validate arguments if (commandLine == null) { throw new JobLaunchException("Job command-line arguments is null"); } else if (commandLine.isEmpty()) { throw new JobLaunchException("Job command-line arguments are empty"); } // Configure arguments log.info("Job command-line: {}", Arrays.toString(commandLine.toArray())); final List<String> expandedCommandLine; try { expandedCommandLine = expandCommandLineVariables(commandLine, Collections.unmodifiableMap(currentEnvironmentVariables)); } catch (final EnvUtils.VariableSubstitutionException e) { throw new JobLaunchException("Job command-line arguments variables could not be expanded"); } if (!commandLine.equals(expandedCommandLine)) { log.info("Job command-line with variables expanded: {}", Arrays.toString(expandedCommandLine.toArray())); } processBuilder.command(expandedCommandLine); if (interactive) { processBuilder.inheritIO(); } else { processBuilder.redirectError(PathUtils.jobStdErrPath(jobDirectory).toFile()); processBuilder.redirectOutput(PathUtils.jobStdOutPath(jobDirectory).toFile()); } if (killed.get()) { log.info("Job aborted, skipping launch"); } else { log.info("Launching job"); try { processReference.set(processBuilder.start()); } catch (final IOException | SecurityException e) { throw new JobLaunchException("Failed to launch job: ", e); } log.info("Process launched (pid: {})", getPid(processReference.get())); } }
From source file:com.cisco.dvbu.cmdline.vcs.spi.AbstractLifecycleListener.java
protected AbstractLifecycleListener() { processBuilder = new ProcessBuilder(); }
From source file:com.thinkbiganalytics.spark.shell.SparkClientUtil.java
/** * Gets the Spark version string by executing {@code spark-submit}. * * @throws IOException if the version string cannot be obtained *///from www. j a va 2 s . c om private static String getVersion() throws IOException { // Build spark-submit process final String sparkSubmitCommand = new StringJoiner(File.separator).add(getSparkHome()).add("bin") .add("spark-submit").toString(); final Process process = new ProcessBuilder().command(sparkSubmitCommand, "--version") .redirectErrorStream(true).start(); // Wait for process to complete boolean exited; try { exited = process.waitFor(10, TimeUnit.SECONDS); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); exited = !process.isAlive(); } if (!exited) { throw new IOException("Timeout waiting for Spark version"); } // Read stdout final byte[] bytes = new byte[1024]; final int length = process.getInputStream().read(bytes); final String output = new String(bytes, 0, length, "UTF-8"); final Matcher matcher = Pattern.compile("version ([\\d+.]+)").matcher(output); if (matcher.find()) { return matcher.group(1); } else { throw new IllegalStateException("Unable to determine version from Spark Submit"); } }
From source file:io.cloudslang.content.utilities.util.ProcessExecutor.java
public ProcessResponseEntity execute(String commandLine, int timeout) throws IOException, ExecutionException, InterruptedException, TimeoutException { Process process = new ProcessBuilder().command(processCommand(commandLine)).start(); ProcessStreamConsumer processStreamConsumer = new ProcessStreamConsumer(process); ExecutorService executor = Executors.newFixedThreadPool(1); Future<ProcessResponseEntity> futureResult = executor.submit(processStreamConsumer); try {//from ww w.j a va 2 s . c o m return futureResult.get(timeout, MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { stopProcess(process, futureResult); throw e; } finally { executor.shutdownNow(); } }
From source file:de.tudarmstadt.ukp.dkpro.core.RSTAnnotator.java
@Override public void initialize(UimaContext context) throws ResourceInitializationException { super.initialize(context); // perform sanity check if (sanityCheckOnInit) { File rstParserSrcDir = new File(rstParserSrcDirPath); // create process ProcessBuilder processBuilder = new ProcessBuilder().inheritIO(); // working dir must be set to the src dir of RST parser processBuilder.directory(rstParserSrcDir); // run the command processBuilder.command("python", new File(rstParserSrcDir, "sanity_check.py").getAbsolutePath()); try {//from ww w .j a v a 2 s . c om Process process = processBuilder.start(); // and wait int returnValue = process.waitFor(); if (returnValue != 0) { throw new RuntimeException("Process exited with code " + returnValue); } } catch (IOException | InterruptedException e) { throw new ResourceInitializationException(e); } } }
From source file:net.dv8tion.jda.player.source.LocalSource.java
@Override public synchronized AudioInfo getInfo() { if (audioInfo != null) return audioInfo; audioInfo = new AudioInfo(); try {// w w w . jav a2 s . c o m List<String> infoArgs = new LinkedList<>(); infoArgs.addAll(FFPROBE_INFO_ARGS); infoArgs.add("-i"); infoArgs.add(file.getCanonicalPath()); Process infoProcess = new ProcessBuilder().command(infoArgs).start(); byte[] infoData = IOUtils.readFully(infoProcess.getInputStream(), -1, false); if (infoData == null || infoData.length == 0) throw new NullPointerException("The FFprobe process resulted in a null or zero-length INFO!"); System.out.println(new String(infoData)); JSONObject info = new JSONObject(new String(infoData)); JSONObject format = info.getJSONObject("format"); JSONObject tags = format.optJSONObject("tags"); audioInfo.jsonInfo = info; audioInfo.origin = file.getCanonicalPath(); audioInfo.extractor = "LocalSource"; if (tags != null) { audioInfo.title = !tags.optString("title", "").isEmpty() ? tags.getString("title") : null; audioInfo.description = "Title: " + (tags.has("title") ? tags.getString("title") : "N/A") + "\n" + "Artist: " + (tags.has("artist") ? tags.getString("artist") : "N/A") + "\n" + "Album: " + (tags.has("album") ? tags.getString("album") : "N/A") + "\n" + "Genre: " + (tags.has("genre") ? tags.getString("genre") : "N/A") + "\n"; } audioInfo.encoding = !format.optString("format_name", "").isEmpty() ? format.getString("format_name") : !format.optString("format_long_name", "").isEmpty() ? format.getString("format_long_name") : null; audioInfo.duration = format.has("duration") ? AudioTimestamp.fromSeconds((int) format.getDouble("duration")) : null; } catch (IOException e) { audioInfo.error = e.getMessage(); e.printStackTrace(); } catch (JSONException e) { audioInfo.error = e.getMessage(); e.printStackTrace(); } return audioInfo; }