void doExeCommand() { PSlider slider; Runtime program = Runtime.getRuntime(); String currentCmd = new String(); String X = new String(); String Y = new String(); // Kill the current executing program pid.destroy(); // Setup the command parameters and run it slider = (PSlider) vSlider.elementAt(0); X = slider.getValue(); slider = (PSlider) vSlider.elementAt(1); Y = slider.getValue(); currentCmd = cmd + " " + X + " " + Y; try { pid = program.exec(currentCmd); if (isWindows == false) { Process pid2 = null; pid2 = program.exec("getpid WinSize"); } } catch (IOException ie) { System.err.println("Couldn't run " + ie); System.exit(-1); } // Update the new value in the source code of the program doSourceFileUpdate(); scrollPane.getViewport().setViewPosition(new Point(0, 20)); }
public static void openExternalURL(URL url) throws IOException { if (Util.isWindows()) { // Yes, this only works on windows final String systemBrowser = "explorer.exe"; final Runtime rt = Runtime.getRuntime(); final Process proc = rt.exec( new String[] { systemBrowser, "\"" + url.toString() + "\"", }); new StreamGobbler(proc.getErrorStream()); new StreamGobbler(proc.getInputStream()); } else if (Util.isMacOSX()) { // Yes, this only works on Mac OS X final Runtime rt = Runtime.getRuntime(); final Process proc = rt.exec( new String[] { "/usr/bin/open", url.toString(), }); new StreamGobbler(proc.getErrorStream()); new StreamGobbler(proc.getInputStream()); } else { throw new IOException("Only windows and Mac OS X browsers are yet supported"); } }
public void openUrl(String url) { String os = System.getProperty("os.name"); Runtime runtime = Runtime.getRuntime(); try { // Block for Windows Platform if (os.startsWith("Windows")) { String cmd = "rundll32 url.dll,FileProtocolHandler " + url; Process p = runtime.exec(cmd); // Block for Mac OS } else if (os.startsWith("Mac OS")) { Class fileMgr = Class.forName("com.apple.eio.FileManager"); Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] {String.class}); openURL.invoke(null, new Object[] {url}); // Block for UNIX Platform } else { String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape"}; String browser = null; for (int count = 0; count < browsers.length && browser == null; count++) if (runtime.exec(new String[] {"which", browsers[count]}).waitFor() == 0) browser = browsers[count]; if (browser == null) throw new Exception("Could not find web browser"); else runtime.exec(new String[] {browser, url}); } } catch (Exception x) { System.err.println("Exception occurd while invoking Browser!"); x.printStackTrace(); } }
/** * Rename a file natively; using REN on Windows and mv on *nix. * * @param from old name * @param to new name */ public static void rename(String from, String to) { Process p = null; Thread std = null; try { Runtime runTime = Runtime.getRuntime(); log.debug("Execute runtime"); // determine file system type if (File.separatorChar == '\\') { // we are windows p = runTime.exec("CMD /D /C \"REN " + from + ' ' + to + "\""); } else { // we are unix variant p = runTime.exec("mv -f " + from + ' ' + to); } // observe std out std = stdOut(p); // wait for the observer threads to finish while (std.isAlive()) { try { Thread.sleep(250); } catch (Exception e) { } } log.debug("Process threads wait exited"); } catch (Exception e) { log.error("Error running delete script", e); } finally { if (null != p) { log.debug("Destroying process"); p.destroy(); p = null; std = null; } } }
public String[] runJob(String command) { outputCatcher = null; try { String[] cmd = null; Process proc = null; Runtime rt = Runtime.getRuntime(); String os = getOsName(); System.out.println("OS = " + os); if (os.startsWith("Windows")) { cmd = new String[3]; cmd[0] = "cmd.exe"; cmd[1] = "/C"; cmd[2] = command; proc = rt.exec(cmd); } else if (os.startsWith("Linux")) { cmd = new String[1]; cmd[0] = command; proc = rt.exec(command.split(" ")); } System.out.println("command is:"); for (int i = 0; i < cmd.length; i++) { System.out.print(cmd[i] + " "); } System.out.println(); // any error message? errorCatcher = new StreamCatcher(proc.getErrorStream(), "ERROR"); // any output? outputCatcher = new StreamCatcher(proc.getInputStream(), "OUTPUT"); // kick them off errorCatcher.start(); outputCatcher.start(); // any error??? exitVal = proc.waitFor(); System.out.println("ExitValue: " + exitVal); if (exitVal != 0) System.out.println(errorCatcher.builder.toString()); } catch (Throwable t) { t.printStackTrace(); } // now return both the stdout and stderr streams // just use a String array for this -- not pretty but it works // stdout is at position [0], stderr is at [1] String[] outputs = new String[2]; outputs[0] = outputCatcher.builder.toString(); outputs[1] = errorCatcher.builder.toString(); return outputs; }
processDNSForWindowsIpv6(String dnsone, String dnstwo) throws SocketException, IOException { System.out.println("This is Windows"); // change ip configuration using netsh command if (uddhavcombobox.getSelectedItem().equals("wlan0")) { nameinterface = "Wireless Network Connection"; // netsh interface ip set dns "Local Area Connection" static // 192.168.0.200 // netsh dnsclient add dnsserver "Local Area Connection" // 192.168.137.202 1 // netsh dnsclient add dnsserver "Local Area Connection" // 192.168.137.200 2 // netsh interface ipv6 add dnsserver "Local Area Connection" // 2001:db8::99:4acd::8 // netsh interface ipv6 add dns "Ethernet" 2401:ddc0:60::1 // 2620:0:ccc::2 // 2620:0:ccd::2 // google-public-dns-a.google.com has IPv6 address // 2001:4860:4860::8888 command1 = "netsh interface ipv6 add dns \"" + nameinterface + "\" " + dnsone + " index=1"; command2 = "netsh interface ipv6 add dns \"" + nameinterface + "\" " + dnstwo + " index=2"; try { Runtime r = java.lang.Runtime.getRuntime(); Process p1 = r.exec(command1); Process p2 = r.exec(command2); System.out.println(command1); System.out.println(command2); } catch (IOException e1) { System.out.println(e1.getMessage()); } } if (uddhavcombobox.getSelectedItem().equals("eth0")) { nameinterface = "Local Area Connection"; // netsh interface ip set dns "Local Area Connection" static // 192.168.0.200 // netsh dnsclient add dnsserver "Local Area Connection" // 192.168.137.202 1 // netsh dnsclient add dnsserver "Local Area Connection" // 192.168.137.200 2 command1 = "netsh interface ipv6 add dns \"" + nameinterface + "\" " + dnsone + " index=1"; command2 = "netsh interface ipv6 add dns \"" + nameinterface + "\" " + dnstwo + " index=2"; try { Runtime r = java.lang.Runtime.getRuntime(); Process p1 = r.exec(command1); Process p2 = r.exec(command2); System.out.println(command1); System.out.println(command2); } catch (IOException e1) { System.out.println(e1.getMessage()); } } }
/** * Ouvre une url dans internet explorer specifiquement * * @param Adresse -String * @return vrai si Ok, faux sinon */ public static boolean OuvrePageInternetExplorer(String Adresse) { Properties sys = System.getProperties(); String os = sys.getProperty("os.name"); Runtime r = Runtime.getRuntime(); try { if (os.endsWith("NT") || os.endsWith("2000") || os.endsWith("XP")) r.exec("cmd /c start iexplore " + Adresse); else r.exec("cmd /c start iexplore " + Adresse); } catch (IOException ex) { ex.printStackTrace(); return false; } return true; }
public static void main(String[] args) { Runtime r = Runtime.getRuntime(); String comando = "gnome-calculator"; Process p, p1; try { p = r.exec(comando); p1 = r.exec("gedit"); p.waitFor(); p1.waitFor(); } catch (Exception e) { System.out.println("Error en:" + comando); e.printStackTrace(); } }
public void generateDiagram(String outputDirectory, File dotFile) { try { Runtime run = Runtime.getRuntime(); Process pr = run.exec( "dot " + dotFile.getAbsolutePath() + " -Tpng -o" + outputDirectory + FILE_SEPARATOR + "graph.png"); pr.waitFor(); // BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream())); // should the output be really printed? // String line; // while ( ( line = buf.readLine() ) != null ) // { // System.out.println(line) ; // } // FIXME how to handle exceptions in listener? } catch (IOException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (InterruptedException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } }
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = request.getHeader("foo"); String bar = new Test().doSomething(param); String a1 = ""; String a2 = ""; String osName = System.getProperty("os.name"); if (osName.indexOf("Windows") != -1) { a1 = "cmd.exe"; a2 = "/c"; } else { a1 = "sh"; a2 = "-c"; } String[] args = {a1, a2, "echo", bar}; String[] argsEnv = {"foo=bar"}; Runtime r = Runtime.getRuntime(); try { Process p = r.exec(args, argsEnv, new java.io.File(System.getProperty("user.dir"))); org.owasp.benchmark.helpers.Utils.printOSCommandResults(p); } catch (IOException e) { System.out.println("Problem executing cmdi - TestCase"); throw new ServletException(e); } } // end doPost
private String getSDKProperties(String javaPath, String path) throws IOException { Runtime runtime = Runtime.getRuntime(); try { String[] command = new String[5]; command[0] = javaPath; command[1] = "-classpath"; // NOI18N command[2] = InstalledFileLocator.getDefault() .locate( "modules/ext/org-netbeans-modules-visage-platform-probe.jar", "org.netbeans.modules.visage.platform", false) .getAbsolutePath(); // NOI18N command[3] = "org.netbeans.modules.visage.platform.wizard.SDKProbe"; // NOI18N command[4] = path; final Process process = runtime.exec(command); // PENDING -- this may be better done by using ExecEngine, since // it produces a cancellable task. process.waitFor(); int exitValue = process.exitValue(); if (exitValue != 0) throw new IOException(); return command[2]; } catch (InterruptedException ex) { IOException e = new IOException(); ErrorManager.getDefault().annotate(e, ex); throw e; } }
public boolean execute(GPLoadMeta meta, boolean wait) throws KettleException { Runtime rt = Runtime.getRuntime(); try { gploadProcess = rt.exec(createCommandLine(meta, true)); // any error message? StreamLogger errorLogger = new StreamLogger(gploadProcess.getErrorStream(), "ERROR"); // any output? StreamLogger outputLogger = new StreamLogger(gploadProcess.getInputStream(), "OUTPUT"); // kick them off errorLogger.start(); outputLogger.start(); if (wait) { // any error??? int exitVal = gploadProcess.waitFor(); logBasic( BaseMessages.getString( PKG, "GPLoad.Log.ExitValuePsqlPath", "" + exitVal)); // $NON-NLS-1$ } } catch (Exception ex) { // Don't throw the message upwards, the message contains the password. throw new KettleException("Error while executing \'" + createCommandLine(meta, false) + "\'"); } return true; }
public static void EjecutarNativo(String cmd) { Runtime aplicacion = Runtime.getRuntime(); try { aplicacion.exec(cmd); } catch (Exception e) { } }
// It executes external commands. public String runCommand(String cmd) { String result = ""; try { Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(cmd); BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line = null; while ((line = input.readLine()) != null) { result += line + "\n"; } int exitVal = pr.waitFor(); if (exitVal != 0) { System.out.println("Problem running external command!"); } } catch (Exception e) { System.out.println(e.toString()); e.printStackTrace(); } return result; }
public void actionPerformed(ActionEvent evt) { try { Runtime rt = Runtime.getRuntime(); String[] args = {"osascript", "-e", "tell app \"iTunes\" to playpause"}; // String[] args = { "osascript", "-e","tell app \"iTunes\" to artist of current track as // string"}; System.out.println("running: " + args[0] + " " + args[1] + " " + args[2]); final Process proc = rt.exec(args); /* new Thread(new Runnable() { public void run() { printStream(proc.getErrorStream()); } }).start(); new Thread(new Runnable() { public void run() { printStream(proc.getInputStream()); } }).start(); */ InputStream in = proc.getInputStream(); String str = new DataInputStream(in).readLine(); System.out.println("got: " + str); } catch (IOException ex) { System.out.println("exception : " + ex.getMessage()); ex.printStackTrace(); } }
private void callCMD() throws Throwable { StreamGobbler errorGobbler; StreamGobbler outputGobbler; // Execute args command... Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(this.cmd); // Check Error... errorGobbler = run(proc, "ERR", this.delay); // Check Output... outputGobbler = run(proc, "ICC", this.delay); // Any error??? proc.waitFor(); // Set Error List... List<String> tmp_linese = new ArrayList<String>(); tmp_linese = errorGobbler.getOs_lines(); // Set Output List... List<String> tmp_linesi = new ArrayList<String>(); tmp_linesi = outputGobbler.getOs_lines(); if (tmp_linesi.size() > 0) this.setGetOutList(tmp_linesi); else this.setGetOutList(tmp_linese); }
private void InstallFile(File f) { mProgress.dismiss(); if (f.length() < fileLength) { return; } try { String command = "chmod " + 777 + " " + f.getPath(); Runtime runtime = Runtime.getRuntime(); runtime.exec(command); } catch (IOException e) { e.printStackTrace(); } Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(android.content.Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(f), "application/vnd.android.package-archive"); myActivity.startActivity(intent); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // // 部分机型,安装过程中,要先退出自身进程,才能安装成功。 // BaseHelper.exitProcessSilently(myActivity); // 防止下载后安装,但用户单击取消情况下的问题 // application.destroy(); // myActivity.finish(); android.os.Process.killProcess(android.os.Process.myPid()); }
public static void main(String[] args) throws IOException, InterruptedException { System.out.println(args[0] + ":"); Runtime runtime = Runtime.getRuntime(); ColorScaling.main(new String[] {args[0], "/tmp/comp"}); for (int i = 0; i != 4; ++i) for (int j = 0; j != 4; ++j) if (i != j) { Process process = runtime.exec( "autopano-sift-c --maxmatches 0 --projection 0,0.05 /tmp/matches-" + i + "-" + j + " /tmp/comp-" + i + ".png /tmp/comp-" + j + ".png"); int err = process.waitFor(); if (err != 0) System.err.println("autopano exit code: " + err); System.out.println(i + "-" + j + ":"); ColorScalingCorrect.main(new String[] {"/tmp/matches-" + i + "-" + j, args[1]}); } }
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 static void main(String[] args) { String cmd = "cmd /c DIR"; Runtime rt = Runtime.getRuntime(); Process proc; try { proc = rt.exec(cmd); InputStream inputT = proc.getErrorStream(); // 해당 프로세스의 버퍼를 비우기 위한 행동.. byte[] buff = new byte[1000]; // System.out.println("출력전"); while (inputT.read(buff) != -1) { // System.out.println("출력"); String strBuff = new String(buff); System.out.println(strBuff); } inputT.close(); proc.waitFor(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void addUser( long companyId, long userId, String password, String firstName, String middleName, String lastName, String emailAddress) { try { CyrusServiceUtil.addUser(userId, emailAddress, password); // Expect String addUserCmd = PropsUtil.get(PropsKeys.MAIL_HOOK_CYRUS_ADD_USER); addUserCmd = StringUtil.replace(addUserCmd, "%1%", String.valueOf(userId)); Runtime rt = Runtime.getRuntime(); Process p = rt.exec(addUserCmd); ProcessUtil.close(p); } catch (Exception e) { _log.error(e, e); } }
/** * Get the dump database and export to to local * * @throws Exception the exception */ public final void export() throws Exception { String dumpCommand = "mysqldump " + database + " -h " + ip + " -u " + user + " -p" + pass; Runtime rt = Runtime.getRuntime(); PrintStream ps; Process child = rt.exec(dumpCommand); try { ps = new PrintStream(date + "-" + PATH + SQLEXT, "UTF-8"); } catch (FileNotFoundException fileEx) { File file = new File(""); throw new FileNotFoundException(fileEx.getMessage() + " / " + file.getPath()); } try { InputStream in = child.getInputStream(); int ch; while ((ch = in.read()) != -1) { ps.write(ch); } InputStream err = child.getErrorStream(); while ((ch = err.read()) != -1) { LOG.error(ch); } ps.close(); } catch (Exception exc) { throw new Exception(exc.getMessage(), exc); } }
public void speak(String txt) { try { Runtime rtime = Runtime.getRuntime(); // start unix shell Process child = rtime.exec("/bin/sh"); // or "/bin/sh set -t" to auto-exit after 1 command BufferedWriter outCommand = new BufferedWriter(new OutputStreamWriter(child.getOutputStream())); // run a command outCommand.write("echo '" + txt + "' | festival --tts\n"); outCommand.flush(); // exit the unix shell outCommand.write("exit" + "\n"); outCommand.flush(); int wait = child.waitFor(); System.out.println("exit code: " + wait); } catch (Exception e) { e.printStackTrace(); } }
public static void executeCommandWithoutExit(String command) throws IOException, InterruptedException { logger.info("Entering method executeCommand"); Runtime rt = Runtime.getRuntime(); String line = null; logger.info("Command to be executed = " + command); prcs = rt.exec(command); BufferedReader stdError = new BufferedReader(new InputStreamReader(prcs.getErrorStream())); logger.info("ERROR in the process - (if any)"); while ((line = stdError.readLine()) != null) { logger.info(line); } logger.info("End of error"); BufferedReader stdInput = new BufferedReader(new InputStreamReader(prcs.getInputStream())); logger.info("Output of the process - (if any)"); while ((line = stdInput.readLine()) != null) { logger.info(line); } logger.info("End of output"); logger.info("Exiting the method"); }
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = ""; java.util.Enumeration<String> headers = request.getHeaders("foo"); if (headers.hasMoreElements()) { param = headers.nextElement(); // just grab first element } String bar = doSomething(param); String cmd = org.owasp.benchmark.helpers.Utils.getOSCommandString("echo") + bar; String[] argsEnv = {"Foo=bar"}; Runtime r = Runtime.getRuntime(); try { Process p = r.exec(cmd, argsEnv); org.owasp.benchmark.helpers.Utils.printOSCommandResults(p); } catch (IOException e) { System.out.println("Problem executing cmdi - TestCase"); throw new ServletException(e); } } // end doPost
/** * Parses a script of AI programs with which to play, launching and connecting to each of them as * a new Player. * * @param launchFilename The formatted script containing the commands to run to be Players. Each * line must be a separate command. Each line must wrap the intended identifier with curly * braces and placehold the server port number with two percent signs ("%%"). * @throws FileNotFoundException * @throws IOException * @throws InterruptedException * @throws ProtocolViolation */ private void parseLaunchScript(String launchFilename) throws FileNotFoundException, IOException, InterruptedException, ProtocolViolation { int portNumber = accept.getLocalPort(); Pattern getIdentifier = Pattern.compile("\\{([^}]+)\\}"); Runtime r = Runtime.getRuntime(); String portString = String.valueOf(portNumber); try (BufferedReader br = new BufferedReader(new FileReader(launchFilename))) { String line; while ((line = br.readLine()) != null) { Matcher matcher = getIdentifier.matcher(line); if (!matcher.find()) { throw new IllegalStateException("The identifier must be wrapped with curly braces."); } String identifier = matcher.group(1); line = matcher.replaceAll(identifier); line = line.replaceAll("%%", portString); System.out.format("Starting \"%s\": %s\n", identifier, line); Process process = r.exec(line); Socket socket = accept.accept(); players.add(new Player(identifier, socket, process)); } } }
public static String getSDCardPath() { String cmd = "cat /proc/mounts"; Runtime run = Runtime.getRuntime(); // 返回与当前 Java 应用程序相关的运行时对象 try { Process p = run.exec(cmd); // 启动另一个进程来执行命令 BufferedInputStream in = new BufferedInputStream(p.getInputStream()); BufferedReader inBr = new BufferedReader(new InputStreamReader(in)); String lineStr; while ((lineStr = inBr.readLine()) != null) { // 获得命令执行后在控制台的输出信息 // Log.i("CommonUtil:getSDCardPath", lineStr); if (lineStr.contains("sdcard") && lineStr.contains(".android_secure")) { String[] strArray = lineStr.split(" "); if (strArray != null && strArray.length >= 5) { String result = strArray[1].replace("/.android_secure", ""); return result; } } // 检查命令是否执行失败。 if (p.waitFor() != 0 && p.exitValue() == 1) { // p.exitValue()==0表示正常结束,1:非正常结束 Log.e("CommonUtil:getSDCardPath", "命令执行失败!"); } } inBr.close(); in.close(); } catch (Exception e) { // Log.e("CommonUtil:getSDCardPath", e.toString()); return Environment.getExternalStorageDirectory().getPath(); } return Environment.getExternalStorageDirectory().getPath(); }
public ProccessManager(String command, boolean withReturn) { BufferedReader b; try { output = ""; error = ""; Runtime r = Runtime.getRuntime(); Process p = r.exec(command); if (withReturn) { p.waitFor(); } b = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = b.readLine()) != null) { output += line + System.getProperty("line.separator"); } b = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((line = b.readLine()) != null) { error += line + System.getProperty("line.separator"); } b.close(); } catch (Exception e) { GeneralReport.getInstance().reportError("Não foi possível executar o comando: " + command); } }
/** this void method runs the command created in the constructor. */ public void runTesseract() { LOGGER.info( "Trying to run command: " + command[0] + " " + command[1] + " " + command[2] + " " + command[3] + " " + command[4]); System.out.println("Trying to run command: " + Arrays.toString(command)); try { Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(command); BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line; while ((line = input.readLine()) != null) { System.out.println(line); } int exitVal = pr.waitFor(); System.out.println("Exited with error code " + exitVal); } catch (Exception e) { System.out.println(e.toString()); e.printStackTrace(); } }
private String execCmd(String cmd) { try { String ret = ""; Properties prop = new Properties(); prop.load( Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties")); String script = prop.getProperty("execScript"); String host = prop.getProperty("execHost"); String[] aCmdArgs = {script, "ssh root@" + host, cmd}; System.err.println("Running: " + script + " " + "ssh root@" + host + " " + cmd); Runtime oRuntime = Runtime.getRuntime(); // if(cmd.contains("getstate") || cmd.contains("mmls")) { //for testing Process oProcess = null; oProcess = oRuntime.exec(aCmdArgs); BufferedReader is = new BufferedReader(new InputStreamReader(oProcess.getInputStream())); String line; while ((line = is.readLine()) != null) ret += line + "\n"; oProcess.waitFor(); // } return ret; } catch (Exception e) { e.printStackTrace(); return "exec failure\n"; } }