protected void runScript(String[] cmd, JTextArea txaMsg) { String strg = ""; if (cmd == null) return; Process prcs = null; try { Messages.postDebug("Running script: " + cmd[2]); Runtime rt = Runtime.getRuntime(); prcs = rt.exec(cmd); if (prcs == null) return; InputStream istrm = prcs.getInputStream(); if (istrm == null) return; BufferedReader bfr = new BufferedReader(new InputStreamReader(istrm)); while ((strg = bfr.readLine()) != null) { // System.out.println(strg); strg = strg.trim(); // Messages.postDebug(strg); strg = strg.toLowerCase(); if (txaMsg != null) { txaMsg.append(strg); txaMsg.append("\n"); } } } catch (Exception e) { // e.printStackTrace(); Messages.writeStackTrace(e); Messages.postDebug(e.toString()); } finally { // It is my understanding that these streams are left // open sometimes depending on the garbage collector. // So, close them. try { if (prcs != null) { OutputStream os = prcs.getOutputStream(); if (os != null) os.close(); InputStream is = prcs.getInputStream(); if (is != null) is.close(); is = prcs.getErrorStream(); if (is != null) is.close(); } } catch (Exception ex) { Messages.writeStackTrace(ex); } } }
public static boolean testCommand( final Context context, final String command, final String contains, final List<String> arguments) { try { final List<String> commandAndArgs = new ArrayList<String>(); commandAndArgs.add(command); commandAndArgs.addAll(arguments); final ProcessBuilder pb = new ProcessBuilder(commandAndArgs); logCommand(context, pb); final Process compilation = pb.start(); final ConsumeStream result = ConsumeStream.start(compilation.getInputStream(), null); final ConsumeStream error = ConsumeStream.start(compilation.getErrorStream(), null); compilation.waitFor(); result.join(); error.join(); return error.output.toString().contains(contains) || result.output.toString().contains(contains); } catch (IOException ex) { context.log(ex.getMessage()); return false; } catch (InterruptedException ex) { context.log(ex.getMessage()); return false; } }
public static String getArchName() throws Exception { if (archName == null) { archName = "lin"; // bits Process process = Runtime.getRuntime().exec("uname -m"); process.waitFor(); if (process.exitValue() != 0) throw new Exception("Error arch"); BufferedReader inStream = new BufferedReader(new InputStreamReader(process.getInputStream())); String arch = inStream.readLine(); if (arch.equals("i686")) archName += "32"; else archName += "64"; process.destroy(); // SSE process = Runtime.getRuntime().exec("cat /proc/cpuinfo"); process.waitFor(); if (process.exitValue() != 0) throw new Exception("Error /proc/cpuinfo"); inStream = new BufferedReader(new InputStreamReader(process.getInputStream())); String line, cpuinfo = ""; while ((line = inStream.readLine()) != null) cpuinfo += line; String bestSSE = "sse"; String[] sses = {"sse2", "sse3", "ssse3", "sse4", "avx"}; for (int i = 0; i < sses.length; i++) { if (cpuinfo.indexOf(sses[i]) >= 0) bestSSE = sses[i]; } archName += bestSSE; process.destroy(); } return archName; }
@Override protected void startProcessHandler( DBRProgressMonitor monitor, final MySQLDatabaseExportInfo arg, ProcessBuilder processBuilder, Process process) { super.startProcessHandler(monitor, arg, processBuilder, process); String outFileName = GeneralUtils.replaceVariables( outputFilePattern, new GeneralUtils.IVariableResolver() { @Override public String get(String name) { switch (name) { case VARIABLE_DATABASE: return arg.getDatabase().getName(); case VARIABLE_HOST: return arg.getDatabase() .getDataSource() .getContainer() .getConnectionConfiguration() .getHostName(); case VARIABLE_TABLE: final Iterator<MySQLTableBase> iterator = arg.getTables() == null ? null : arg.getTables().iterator(); if (iterator != null && iterator.hasNext()) { return iterator.next().getName(); } else { return "null"; } case VARIABLE_TIMESTAMP: return RuntimeUtils.getCurrentTimeStamp(); default: System.getProperty(name); } return null; } }); File outFile = new File(outputFolder, outFileName); boolean isFiltering = removeDefiner; Thread job = isFiltering ? new DumpFilterJob(monitor, process.getInputStream(), outFile) : new DumpCopierJob( monitor, MySQLMessages.tools_db_export_wizard_monitor_export_db, process.getInputStream(), outFile); job.start(); }
// Uses adb commands to tap at relative coordinates. To be used when appium methods fail. Only // works on Android devices. public void tapAtRelativeCoordinatesADB(double x_offset, double y_offset) throws Exception { if (platformName.equalsIgnoreCase("iOS")) { tapAtRelativeCoordinates(x_offset, y_offset); } else { Dimension size = getScreenSizeADB(); log("Size of device as seen by ADB is - width: " + size.width + " height: " + size.height); String x = String.valueOf(size.width * x_offset); String y = String.valueOf(size.height * y_offset); log("ADB: x and y: " + x + ", " + y); String[] adbCommand = {"adb", "shell", "input", "tap", x, y}; // String[] adbCommand = {"adb", "shell", "input", "touchscreen", "swipe", x, y, x, // y, "2000"}; try { ProcessBuilder p = new ProcessBuilder(adbCommand); Process proc = p.start(); InputStream stdin = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) System.out.print(line); proc.waitFor(); } catch (Throwable t) { t.printStackTrace(); } } }
public static void command(String command) { boolean err = false; try { Process process = new ProcessBuilder(command.split(" ")).start(); BufferedReader results = new BufferedReader(new InputStreamReader(process.getInputStream())); String s; while ((s = results.readLine()) != null) { System.out.println(s); } BufferedReader errors = new BufferedReader(new InputStreamReader(process.getErrorStream())); while ((s = errors.readLine()) != null) { System.err.println(s); err = true; } } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } if (err) { throw new OSExecuteException("Errors executing " + command); } }
/** * Executes the command through a system 'exec'. This method will be used only if the supporting * Java Native Interface library could not be loaded. */ private synchronized void pure_exec(String[] cmd) throws IOException { if (null != this.environ.getExecutable()) { cmd[0] = this.environ.getExecutable(); } p = rt.exec(cmd, this.environ.getEnvp()); InputStream is = p.getInputStream(); Debug.verbose("P4Process.exec().is: " + is); InputStreamReader isr = new InputStreamReader(is); Debug.verbose("P4Process.exec().isr: " + isr); in = new BufferedReader(isr); InputStream es = p.getErrorStream(); Debug.verbose("P4Process.exec().es: " + es); InputStreamReader esr = new InputStreamReader(es); Debug.verbose("P4Process.exec().esr: " + esr); err = new BufferedReader(esr); OutputStream os = p.getOutputStream(); Debug.verbose("P4Process.exec().os: " + os); OutputStreamWriter osw = new OutputStreamWriter(os); Debug.verbose("P4Process.exec().osw: " + osw); out = new FilterWriter(new BufferedWriter(osw)) { public void write(String str) throws IOException { super.write(str); System.out.print("P4DebugOutput: " + str); } }; }
public static TByteArrayList transformByExternalCommand( final String command, final InputStream input) throws IOException { final Process process = Runtime.getRuntime().exec(command); final InputStream in = process.getInputStream(); final OutputStream out = process.getOutputStream(); final TByteArrayList bytes = new TByteArrayList(100500); final byte[] buffer = new byte[1024 * 1024]; try { int read; while ((read = input.read(buffer)) > 0) { out.write(buffer, 0, read); if (in.available() > 0) { read = in.read(buffer); bytes.add(buffer, 0, read); } } out.close(); while ((read = in.read(buffer)) > 0) { bytes.add(buffer, 0, read); } in.close(); } catch (IOException ioe) { System.err.println(readByteStream(process.getErrorStream())); LOG.error(ioe); throw ioe; } return bytes; }
public static int runA2sd(int mode) { String command = ""; if (mode == 0) // remove a2sd command = "echo \"n\" | /system/bin/a2sd remove"; else if (mode == 1) // a2sd command = "echo \"n\" | /system/bin/a2sd install"; else if (mode == 2) // dc2sd command = "echo \"y\" | /system/bin/a2sd install"; if (!command.equals("")) { try { Process process = Runtime.getRuntime().exec("su"); Log.e(TAG, "Executing: " + command); DataOutputStream outputStream = new DataOutputStream(process.getOutputStream()); DataInputStream inputStream = new DataInputStream(process.getInputStream()); outputStream.writeBytes(command + "\n"); outputStream.flush(); outputStream.writeBytes("exit\n"); outputStream.flush(); process.waitFor(); } catch (IOException e) { return -1; } catch (InterruptedException e) { return -2; } return 0; } return -3; }
/** * Creates a transcoded input stream by executing the given command. If <code>in</code> is not * null, data from it is copied to the command. * * @param command The command to execute. * @param in Data to feed to the command. May be <code>null</code>. * @throws IOException If an I/O error occurs. */ public TranscodeInputStream(String[] command, final InputStream in) throws IOException { StringBuffer buf = new StringBuffer("Starting transcoder: "); for (String s : command) { buf.append('[').append(s).append("] "); } LOG.debug(buf); process = Runtime.getRuntime().exec(command); processOutputStream = process.getOutputStream(); processInputStream = process.getInputStream(); // Must read stderr from the process, otherwise it may block. final String name = command[0]; new InputStreamReaderThread(process.getErrorStream(), name, true).start(); // Copy data in a separate thread if (in != null) { new Thread(name + " TranscodedInputStream copy thread") { public void run() { try { IOUtils.copy(in, processOutputStream); } catch (IOException x) { // Intentionally ignored. Will happen if the remote player closes the stream. } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(processOutputStream); } } }.start(); } }
/** * System command. Execute a command and insert the result. * * @param args * @param help * @param patterns * @param low * @param high */ public String system_internal(boolean allowFail, String args[]) throws Exception { verifyCommand( args, "${" + (allowFail ? "system-allow-fail" : "system") + ";<command>[;<in>]}, execute a system command", null, 2, 3); String command = args[1]; String input = null; if (args.length > 2) { input = args[2]; } Process process = Runtime.getRuntime().exec(command, null, domain.getBase()); if (input != null) { process.getOutputStream().write(input.getBytes("UTF-8")); } process.getOutputStream().close(); String s = IO.collect(process.getInputStream(), "UTF-8"); int exitValue = process.waitFor(); if (exitValue != 0) return exitValue + ""; if (!allowFail && (exitValue != 0)) { domain.error("System command " + command + " failed with " + exitValue); } return s.trim(); }
public static void processPSOutput(Process psProcess, Processor<String> processor) throws IOException { @SuppressWarnings({"IOResourceOpenedButNotSafelyClosed"}) BufferedReader stdOutput = new BufferedReader(new InputStreamReader(psProcess.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(psProcess.getErrorStream())); try { String s; stdOutput.readLine(); // ps output header while ((s = stdOutput.readLine()) != null) { processor.process(s); } StringBuilder errorStr = new StringBuilder(); while ((s = stdError.readLine()) != null) { errorStr.append(s).append("\n"); } if (errorStr.length() > 0) { throw new IllegalStateException("error:" + errorStr.toString()); } } finally { stdOutput.close(); stdError.close(); } }
public static String test123() { String r = ""; try { // System.setSecurityManager(null); // String[] callArgs = {"mkdir", "/home/alexis/test123"}; String[] callArgs = {"ls"}; ProcessBuilder pb = new ProcessBuilder(callArgs); pb.redirectErrorStream(true); Process p = pb.start(); p.waitFor(); // BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream() )); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; System.out.println("Start Output"); while ((line = br.readLine()) != null) r += line + "\n"; System.out.println("End Output"); /*Process p = Runtime.getRuntime().exec(callArgs); p.waitFor(); System.out.println("Test Complete");*/ r = line; } catch (IOException e) { System.out.println(e); r = "Test failed"; } catch (Exception e) { } return r; }
/** Redirect a VMs output and error streams to System.out and System.err */ protected void redirectStreams(VirtualMachine vm) { MessageSiphon ms = new MessageSiphon(process.getErrorStream(), this); errThread = ms.getThread(); outThread = new StreamRedirectThread("VM output reader", process.getInputStream(), System.out); errThread.start(); outThread.start(); }
private String getIPAndroid() { String host = "localhost"; try { ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "adb shell netcfg"); builder.redirectErrorStream(true); Process p = builder.start(); BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while (true) { line = r.readLine(); if (line == null) { break; } if (line.contains("0x00001043")) { // wlan0 UP 192.168.1.79/24 // 0x00001043 b4:52:7d:c5:8b:69 int index = line.indexOf("/24"); line = line.substring(0, index); index = line.lastIndexOf(" "); host = line.substring(index + 1); break; } } } catch (IOException e) { e.printStackTrace(); Notifications.Bus.notify( new Notification( Constant.GROUND_ID, "Error getIPAndroid", e.toString(), NotificationType.ERROR)); } return host; }
public static Either<CommandResult> runCommand( final Context context, final String command, final File path, final List<String> arguments) { try { final List<String> commandAndArgs = new ArrayList<String>(); commandAndArgs.add(command); commandAndArgs.addAll(arguments); final ProcessBuilder pb = new ProcessBuilder(commandAndArgs); if (path != null) { pb.directory(path); } logCommand(context, pb); final Process compilation = pb.start(); final ConsumeStream result = ConsumeStream.start(compilation.getInputStream(), context); final ConsumeStream error = ConsumeStream.start(compilation.getErrorStream(), context); final int exitCode = compilation.waitFor(); result.join(); error.join(); if (result.exception != null) { return Either.fail(result.exception); } if (error.exception != null) { return Either.fail(error.exception); } return Either.success( new CommandResult(result.output.toString(), error.output.toString(), exitCode)); } catch (IOException ex) { return Either.fail(ex); } catch (InterruptedException ex) { return Either.fail(ex); } }
/** * ====================================================================================== * TESSERACT GRAB TEXT FROM IMAGE * ====================================================================================== */ public String grabText(String image) throws Exception { findAndCropImageFromScreen(image); String imageInput = screenshotsFolder + getScreenshotsCounter() + "_" + image + "_screenshot" + getRetryCounter() + "_" + timeDifferenceStartTest + "sec" + ".png"; String[] tesseractCommand = {"tesseract", imageInput, "stdout"}; String value = ""; try { ProcessBuilder p = new ProcessBuilder(tesseractCommand); Process proc = p.start(); InputStream stdin = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); BufferedReader br = new BufferedReader(isr); String line; String[] size = null; String[] splitLines; while ((line = br.readLine()) != null) { value += line; } } catch (Throwable t) { t.printStackTrace(); } return value; }
// Creates a new thread, runs the program in that thread, and reports any errors as needed. private void run(String clazz) { try { // Makes sure the JVM resets if it's already running. if (JVMrunning) kill(); // Some String constants for java path and OS-specific separators. String separator = System.getProperty("file.separator"); String path = System.getProperty("java.home") + separator + "bin" + separator + "java"; // Tries to run compiled code. ProcessBuilder builder = new ProcessBuilder(path, clazz); // Should be good now! Everything past this is on you. Don't mess it up. println( "Build succeeded on " + java.util.Calendar.getInstance().getTime().toString(), progErr); println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", progErr); JVM = builder.start(); // Note that as of right now, there is no support for input. Only output. Reader errorReader = new InputStreamReader(JVM.getErrorStream()); Reader outReader = new InputStreamReader(JVM.getInputStream()); // Writer inReader = new OutputStreamWriter(JVM.getOutputStream()); redirectErr = redirectIOStream(errorReader, err); redirectOut = redirectIOStream(outReader, out); // redirectIn = redirectIOStream(null, inReader); } catch (Exception e) { // This catches any other errors we might get. println("Some error thrown", progErr); logError(e.toString()); displayLog(); return; } }
public boolean findDeviceTypeADB() throws Exception { log("trying to find device type ..."); log("------------------------------"); if (platformName.equalsIgnoreCase("iOS")) { // TO Be added } else { String adb = "adb"; String[] adbCommand = {adb, "shell", "getprop", "ro.build.characteristics"}; try { ProcessBuilder p = new ProcessBuilder(adbCommand); Process proc = p.start(); InputStream stdin = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); BufferedReader br = new BufferedReader(isr); String line = null; String[] size = null; while ((line = br.readLine()) != null) { if (line.contains("tablet")) { return true; } } } catch (Throwable t) { t.printStackTrace(); } } return false; }
public boolean executeFilter(@NotNull Editor editor, @NotNull TextRange range, String command) throws IOException { if (logger.isDebugEnabled()) logger.debug("command=" + command); CharSequence chars = editor.getDocument().getCharsSequence(); StringReader car = new StringReader( chars.subSequence(range.getStartOffset(), range.getEndOffset()).toString()); StringWriter sw = new StringWriter(); logger.debug("about to create filter"); Process filter = Runtime.getRuntime().exec(command); logger.debug("filter created"); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(filter.getOutputStream())); logger.debug("sending text"); copy(car, writer); writer.close(); logger.debug("sent"); BufferedReader reader = new BufferedReader(new InputStreamReader(filter.getInputStream())); logger.debug("getting result"); copy(reader, sw); sw.close(); logger.debug("received"); editor.getDocument().replaceString(range.getStartOffset(), range.getEndOffset(), sw.toString()); lastCommand = command; return true; }
public static void main(String args[]) { try { Runtime rt = Runtime.getRuntime(); // Process pr = rt.exec("cmd /c dir"); Process pr = rt.exec("python ciao.py"); BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line = null; while ((line = input.readLine()) != null) { System.out.println(line); } int exitVal = pr.waitFor(); if (exitVal == 0) { System.out.println("Exited without errors "); } else { System.out.println("Exited with error code " + exitVal); } } catch (Exception e) { System.out.println(e.toString()); e.printStackTrace(); } }
public String execRecognizer() { try { String inputFile = new File(tmpdir, "input").getAbsolutePath(); String[] args = new String[] {"java", "-classpath", tmpdir + pathSep + CLASSPATH, "Test", inputFile}; // String cmdLine = "java -classpath "+CLASSPATH+pathSep+tmpdir+" Test " + new File(tmpdir, // "input").getAbsolutePath(); // System.out.println("execParser: "+cmdLine); Process process = Runtime.getRuntime().exec(args, null, new File(tmpdir)); StreamVacuum stdoutVacuum = new StreamVacuum(process.getInputStream()); StreamVacuum stderrVacuum = new StreamVacuum(process.getErrorStream()); stdoutVacuum.start(); stderrVacuum.start(); process.waitFor(); stdoutVacuum.join(); stderrVacuum.join(); String output = null; output = stdoutVacuum.toString(); if (stderrVacuum.toString().length() > 0) { this.stderrDuringParse = stderrVacuum.toString(); System.err.println("exec stderrVacuum: " + stderrVacuum); } return output; } catch (Exception e) { System.err.println("can't exec recognizer"); e.printStackTrace(System.err); } return null; }
// Method: runTest // Runs the script specified in the test case object public void runTest() { try { Process p = Runtime.getRuntime().exec(this.execCommandLine); InputStreamReader esr = new InputStreamReader(p.getErrorStream()); BufferedReader ereader = new BufferedReader(esr); InputStreamReader isr = new InputStreamReader(p.getInputStream()); BufferedReader ireader = new BufferedReader(isr); String line = null; String line1 = null; while ((line = ireader.readLine()) != null) { // System.out.println("Output: " + line); System.out.println(line); } while ((line1 = ereader.readLine()) != null) { System.err.println("Error: " + line1); } int exitValue = p.waitFor(); tcInstanceTools.LogMessage('d', "Test Case exit value: " + exitValue); if (exitValue == 0) { setTestCaseResult(Result.Pass); } else { setTestCaseResult(Result.Fail); } } catch (IOException ioe) { System.out.println("Error: " + ioe.getMessage()); } catch (InterruptedException e) { System.out.println("Error: " + e.getMessage()); } }
/* Heck there's no getenv, we have to roll one ourselves! */ public static Hashtable getenv() throws Throwable { Process p; if (File.separator.equals("\\")) { p = Runtime.getRuntime().exec("cmd /c set"); } else { p = Runtime.getRuntime().exec("printenv"); } InputStream in = p.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; Hashtable table = new Hashtable(); while ((line = reader.readLine()) != null) { int i = line.indexOf('='); if (i > 0) { String name = line.substring(0, i); String value = line.substring(i + 1); table.put(name, value); } } in.close(); p.waitFor(); return table; }
public static int RefreshDatabase() { if (ERROR == SendHttp("http://" + HOST + ":" + REST_PORT + "/" + DATABASEINDEX, REQ_DELETE)) { System.out.println(PROMPT + "Delete log database index failed!"); return ERROR; } if (ERROR == SendHttp("http://" + HOST + ":" + REST_PORT + "/" + DATABASEINDEX, REQ_PUT)) { System.out.println(PROMPT + "Create log database index failed!"); return ERROR; } // Set mapping manually try { String cmd = "curl -XPUT " + HOST + ':' + REST_PORT + "/" + DATABASEINDEX + '/' + DATABASETYPE + "/_mapping --data-binary @./data/Log/map.json"; Process ps = Runtime.getRuntime().exec(cmd); ps.waitFor(); BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream())); String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (Exception e) { e.printStackTrace(); return ERROR; } return SUCCESS; }
public static void main(String[] Args) { // System.setProperty("KEY", "HNY81514525MALVIYA"); // Map<String, String> env = System.getenv(); // for (String envName : env.keySet()) // System.out.format("%s = %s%n", envName, env.get(envName)); // reg add HKCU\\Environment /v developer /d \"Honey Keny Malviya" /f" try { String PERSONAL_FOLDER_CMD = "reg query HKCU\\Environment /v developer"; String REGSTR_TOKEN = "REG_SZ"; Process process = Runtime.getRuntime().exec(PERSONAL_FOLDER_CMD); StreamReader reader = new StreamReader(process.getInputStream()); reader.start(); process.waitFor(); reader.join(); String result = reader.getResult(); int p = result.indexOf(REGSTR_TOKEN); if (p == -1) return; System.out.println(result.substring(p + REGSTR_TOKEN.length()).trim()); } catch (Exception e) { e.printStackTrace(); return; } }
// ## operation runReactor() public void runReactor() { // #[ operation runReactor() // run reactor String dir = System.getProperty("RMG.workingDirectory"); try { // system call for reactor String[] command = {dir + "/software/reactorModel/reactor.exe"}; File runningDir = new File("chemkin"); Process reactor = Runtime.getRuntime().exec(command, null, runningDir); InputStream ips = reactor.getInputStream(); InputStreamReader is = new InputStreamReader(ips); BufferedReader br = new BufferedReader(is); String line = null; while ((line = br.readLine()) != null) { // System.out.println(line); } int exitValue = reactor.waitFor(); } catch (Exception e) { System.out.println("Error in running reactor!"); System.out.println(e.getMessage()); System.exit(0); } // #] }
/** * Gives the same basic functionality of File.exists but can be used to look for removable media * without showing a system dialog if the media is not present. Workaround pulled from the <A * HREF="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4089199"> bug report</A> on * bugs.sun.com. This bug was fixed in Java 6, and we can remove the workaround when we start * requiring Java 6. */ protected static boolean fileExists(File file) { try { Process process = Runtime.getRuntime().exec(new String[] {"cmd.exe", "/c", "dir", file.getAbsolutePath()}); // We need to consume all available output or the process will block. boolean haveExitCode = false; int exitCode = -1; InputStream out = process.getInputStream(); InputStream err = process.getErrorStream(); while (!haveExitCode) { while (out.read() >= 0) {} while (err.read() >= 0) {} try { exitCode = process.exitValue(); haveExitCode = true; } catch (IllegalThreadStateException e) { // Not yet complete. Thread.sleep(100); } } // int exitCode = process.waitFor(); return exitCode == 0; } catch (IOException e) { System.out.println("Unable to check for file: " + file + " : " + e); return false; } catch (InterruptedException e) { System.out.println("Unable to check for file. Interrupted: " + file + " : " + e); return false; } }
/** * Gets the token. * * @param scope the scope * @return the token */ private String getToken(String scope) { Process curlProc; String outputString; DataInputStream curlIn = null; String access_token = null; String command = "curl -X POST -H Content-Type:application/x-www-form-urlencoded " + adminUrl + "/oauth2/token --insecure --data" + " client_id=" + client_id + "&" + "client_secret=" + client_secret + "&grant_type=client_credentials&scope=" + scope; try { curlProc = Runtime.getRuntime().exec(command); curlIn = new DataInputStream(curlProc.getInputStream()); while ((outputString = curlIn.readLine()) != null) { JSONObject obj = new JSONObject(outputString); access_token = obj.getString("access_token"); } } catch (IOException e1) { e1.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return access_token; }
public static String execute(String command) { StringBuilder sb = new StringBuilder(); String[] commands = new String[] {"/bin/bash", "-c", "export PATH=\"$PATH:/opt/local/bin\"; " + command}; try { Process proc = new ProcessBuilder(commands).start(); BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream())); String s = null; while ((s = stdInput.readLine()) != null) { sb.append(s); sb.append("\n"); } while ((s = stdError.readLine()) != null) { sb.append(s); sb.append("\n"); } } catch (IOException e) { e.printStackTrace(); } return sb.toString(); }