List of usage examples for java.lang Runtime getRuntime
public static Runtime getRuntime()
From source file:Main.java
public static boolean getRootPermission(Context context) { String packageCodePath = context.getPackageCodePath(); Process process = null;/* w w w .j av a2s .c o m*/ DataOutputStream os = null; try { String cmd = "chmod 777 " + packageCodePath; process = Runtime.getRuntime().exec("su"); os = new DataOutputStream(process.getOutputStream()); os.writeBytes(cmd + "\n"); os.writeBytes("exit\n"); os.flush(); process.waitFor(); } catch (Exception e) { return false; } finally { try { if (os != null) { os.close(); } process.destroy(); } catch (Exception e) { e.printStackTrace(); } } return true; }
From source file:Main.java
/** * Run a command and return its output.//from ww w . j a v a2s . c om */ public static String systemOut(String command) throws Exception { int c; String[] cmd = new String[3]; cmd[0] = System.getProperty("SHELL", "/bin/sh"); cmd[1] = "-c"; cmd[2] = command; Process p = Runtime.getRuntime().exec(cmd); BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream())); StringBuilder s = new StringBuilder(); while ((c = r.read()) != -1) { s.append((char) c); } p.waitFor(); return s.toString(); }
From source file:Main.java
public static void execCmd(String szCmd, boolean bCatchLog) { try {//from w w w . j av a 2s .co m Log.d("PvTorrent_proc", "execCmd=" + szCmd); Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec(szCmd); if (bCatchLog) { InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; while (null != (line = br.readLine())) { Log.e("PvTorrent_proc", line); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block Log.d("PvTorrent_proc", e.toString()); } }
From source file:MainClass.java
public static void premain(final Instrumentation inst) { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { PrintWriter out = new PrintWriter(System.err); ThreadMXBean tb = ManagementFactory.getThreadMXBean(); out.printf("Current thread count: %d%n", tb.getThreadCount()); out.printf("Peak thread count: %d%n", tb.getPeakThreadCount()); List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans(); for (MemoryPoolMXBean pool : pools) { MemoryUsage peak = pool.getPeakUsage(); out.printf("Peak %s memory used: %,d%n", pool.getName(), peak.getUsed()); out.printf("Peak %s memory reserved: %,d%n", pool.getName(), peak.getCommitted()); }//from ww w .j a v a 2 s . co m Class[] loaded = inst.getAllLoadedClasses(); out.println("Loaded classes:"); for (Class c : loaded) out.println(c.getName()); out.close(); } catch (Throwable t) { System.err.println("Exception in agent: " + t); } } }); }
From source file:de.prozesskraft.pkraft.Merge.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { /*---------------------------- get options from ini-file//from w w w. j av a 2 s. c om ----------------------------*/ java.io.File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(Merge.class) + "/" + "../etc/pkraft-merge.ini"); if (inifile.exists()) { try { ini = new Ini(inifile); } catch (InvalidFileFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.err.println("ini file does not exist: " + inifile.getAbsolutePath()); System.exit(1); } /*---------------------------- create boolean options ----------------------------*/ Option ohelp = new Option("help", "print this message"); Option ov = new Option("v", "prints version and build-date"); /*---------------------------- create argument options ----------------------------*/ Option oinstance = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory] instance you want to merge another instance into.") // .isRequired() .create("instance"); Option oguest = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory] this instance will be merged into -instance.") // .isRequired() .create("guest"); Option obasedir = OptionBuilder.withArgName("DIR").hasArg().withDescription( "[optional] in this base-directory the result instance (merge of -instance and -guest) will be placed. this directory has to exist. omit to use the base-directory of -instance.") // .isRequired() .create("basedir"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(oinstance); options.addOption(oguest); options.addOption(obasedir); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); // parse the command line arguments commandline = parser.parse(options, args); /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("merge", options); System.exit(0); } if (commandline.hasOption("v")) { System.out.println("author: alexander.vogel@caegroup.de"); System.out.println("version: [% version %]"); System.out.println("date: [% date %]"); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ if (!(commandline.hasOption("instance"))) { System.err.println("option -instance is mandatory"); exiter(); } if (!(commandline.hasOption("guest"))) { System.err.println("at least one option -guest is mandatory"); exiter(); } /*---------------------------- die lizenz ueberpruefen und ggf abbrechen ----------------------------*/ // check for valid license ArrayList<String> allPortAtHost = new ArrayList<String>(); allPortAtHost.add(ini.get("license-server", "license-server-1")); allPortAtHost.add(ini.get("license-server", "license-server-2")); allPortAtHost.add(ini.get("license-server", "license-server-3")); MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1"); // lizenz-logging ausgeben for (String actLine : (ArrayList<String>) lic.getLog()) { System.err.println(actLine); } // abbruch, wenn lizenz nicht valide if (!lic.isValid()) { System.exit(1); } /*---------------------------- die eigentliche business logic ----------------------------*/ String pathToInstance = commandline.getOptionValue("instance"); java.io.File fileInstance = new java.io.File(pathToInstance); String[] pathToGuest = commandline.getOptionValues("guest"); String baseDir = null; if (commandline.hasOption("basedir")) { java.io.File fileBaseDir = new java.io.File(commandline.getOptionValue("basedir")); if (!fileBaseDir.exists()) { System.err.println("basedir does not exist: " + fileBaseDir.getAbsolutePath()); exiter(); } else if (!fileBaseDir.isDirectory()) { System.err.println("basedir is not a directory: " + fileBaseDir.getAbsolutePath()); exiter(); } baseDir = commandline.getOptionValue("basedir"); } // ueberpruefen ob die process.pmb files vorhanden sind // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen if (!fileInstance.exists()) { System.err.println("instance file does not exist: " + fileInstance.getAbsolutePath()); exiter(); } for (String pathGuest : pathToGuest) { java.io.File fileGuest = new java.io.File(pathGuest); // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen if (!fileGuest.exists()) { System.err.println("guest file does not exist: " + fileGuest.getAbsolutePath()); exiter(); } } // base - instance einlesen Process p1 = new Process(); p1.setInfilebinary(pathToInstance); p1.setOutfilebinary(pathToInstance); Process p2 = p1.readBinary(); // alle guests einlesen ArrayList<Process> alleGuests = new ArrayList<Process>(); for (String actPathGuest : pathToGuest) { Process p30 = new Process(); p30.setInfilebinary(actPathGuest); Process pGuest = p30.readBinary(); // testen ob base-instanz und aktuelle guestinstanz vom gleichen typ sind if (!p2.getName().equals(pGuest.getName())) { System.err.println("error: instances are not from the same type (-instance=" + p2.getName() + " != -guest=" + pGuest.getName()); exiter(); } // testen ob base-instanz und aktuelle guestinstanz von gleicher version sind if (!p2.getVersion().equals(pGuest.getVersion())) { System.err.println("error: instances are not from the same version (" + p2.getVersion() + "!=" + pGuest.getVersion()); exiter(); } alleGuests.add(pGuest); } // den main-prozess trotzdem nochmal einlesen um subprozesse extrahieren zu koennen Process p3 = new Process(); p3.setInfilebinary(pathToInstance); Process process = p3.readBinary(); // den main-prozess ueber die static function klonen // das anmelden bei pradar erfolgt erst ganz zum schluss, denn beim clonen werden nachfolgende steps resettet, die zu diesem zeitpunkt noch intakt sind Process clonedProcess = cloneProcess(process, null); // alle steps durchgehen und falls subprocesses existieren auch fuer diese ein cloning durchfuehren for (Step actStep : process.getStep()) { if (actStep.getSubprocess() != null) { Process pDummy = new Process(); pDummy.setInfilebinary(actStep.getAbsdir() + "/process.pmb"); Process processInSubprocess = pDummy.readBinary(); // System.err.println("info: reading process freshly from file: " + actStep.getAbsdir() + "/process.pmb"); if (processInSubprocess != null) { Process clonedSubprocess = cloneProcess(processInSubprocess, clonedProcess); // den prozess in pradar anmelden durch aufruf des tools: pradar-attend String call2 = ini.get("apps", "pradar-attend") + " -instance " + clonedSubprocess.getRootdir() + "/process.pmb"; System.err.println("info: calling: " + call2); try { java.lang.Process sysproc = Runtime.getRuntime().exec(call2); } catch (IOException e) { System.err.println("error: " + e.getMessage()); } } } } // alle dependent steps der zielinstanz einsammeln // dies wird zum resetten benoetigt, damit steps nicht doppelt resettet werden Map<Step, String> dependentSteps = new HashMap<Step, String>(); // alle guest prozesse merge durchfuehren for (Process actGuestProcess : alleGuests) { System.err.println("info: merging guest process " + actGuestProcess.getInfilebinary()); // alle fanned steps (ehemalige multisteps) des zu mergenden prozesses in die fanned multisteps des bestehenden prozesses integrieren for (Step actStep : actGuestProcess.getStep()) { if (actStep.isAFannedMultistep()) { System.err.println("info: merging from guest instance step " + actStep.getName()); Step clonedStepForIntegrationInClonedProcess = actStep.clone(); if (clonedProcess.integrateStep(clonedStepForIntegrationInClonedProcess)) { System.err.println("info: merging step successfully."); // die downstream steps vom merge-punkt merken for (Step actStepToResetBecauseOfDependency : clonedProcess .getStepDependent(actStep.getName())) { dependentSteps.put(actStepToResetBecauseOfDependency, "dummy"); } // der step einen subprocess enthaelt muss der subprocess nach der integration bei pradar gemeldet werden // den prozess in pradar anmelden durch aufruf des tools: pradar-attend if (clonedStepForIntegrationInClonedProcess.getSubprocess() != null && clonedStepForIntegrationInClonedProcess.getSubprocess().getProcess() != null) { String call5 = ini.get("apps", "pradar-attend") + " -instance " + clonedStepForIntegrationInClonedProcess.getAbsdir() + "/process.pmb"; System.err.println("info: calling: " + call5); try { java.lang.Process sysproc = Runtime.getRuntime().exec(call5); } catch (IOException e) { System.err.println("error: " + e.getMessage()); } } } else { System.err.println("error: merging step failed."); } } else { System.err.println("debug: because it's not a multistep, ignoring from guest instance step " + actStep.getName()); } } } // alle steps downstream der merge-positionen resetten for (Step actStep : dependentSteps.keySet()) { actStep.resetBecauseOfDependency(); } // speichern der ergebnis instanz clonedProcess.writeBinary(); // den prozess in pradar anmelden durch aufruf des tools: pradar-attend String call2 = ini.get("apps", "pradar-attend") + " -instance " + clonedProcess.getRootdir() + "/process.pmb"; System.err.println("info: calling: " + call2); try { java.lang.Process sysproc = Runtime.getRuntime().exec(call2); } catch (IOException e) { System.err.println("error: " + e.getMessage()); } }
From source file:Main.java
public static void createStorageFile(boolean flag) { try {// w w w .j a v a2 s . c om if (flag) { Runtime.getRuntime().exec(TOUCHONEFILE); } else { Runtime.getRuntime().exec(DELETEONEFILE); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:Main.java
public static List<String> execAsAdmin(String... commands) throws Exception { List<String> res = new ArrayList<String>(); Process process = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(process.getOutputStream()); for (String single : commands) { os.writeBytes(single + "\n"); os.flush();//from w w w . j a va2 s. com //res.add(osRes.readLine()); } os.writeBytes("exit\n"); os.flush(); //process.destroy(); process.waitFor(); return res; }
From source file:Main.java
public static void makeInternalCopy(Context c, String path, int resource) { InputStream is = c.getResources().openRawResource(resource); try {/*www .j a v a 2 s .co m*/ Process process = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(process.getOutputStream()); File sniff = new File(path); if (sniff.exists()) { os.writeBytes("rm " + path + "\n"); } byte[] bytes = new byte[is.available()]; FileOutputStream setdbOutStream = new FileOutputStream(path); DataInputStream dis = new DataInputStream(is); dis.readFully(bytes); setdbOutStream.write(bytes); setdbOutStream.close(); os.writeBytes("chmod 777 " + path + "\n"); os.writeBytes("exit\n"); os.flush(); } catch (Exception e) { // Toast.makeText(c, "Error Copying file: " + e.toString(),Toast.LENGTH_SHORT).show(); e.printStackTrace(); } }
From source file:com.kactech.otj.examples.Faucet.java
public static void main(String[] args) throws Exception { String channel = "#opentransactions" //"#kactech_test" ///*from ww w . ja v a 2 s. c o m*/ ; CommandLineParser parser = new GnuParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println("Command-line parsing error: " + e.getMessage()); help(); System.exit(-1); } if (cmd.hasOption('h')) { help(); System.exit(0); } if (cmd.hasOption('c')) channel = cmd.getOptionValue('c'); Utils.init(); client = new EClient(new File("faucet_client"), ExamplesUtils.findServer("OT 8coin") //ExamplesUtils.findServer("van") ); client.setAssetType(ExamplesUtils.findAsset("silver").assetID); client.init(); PircBotX bot = new PircBotX(); bot.setName("OTjFaucet"); bot.setLogin("fast"); bot.setVerbose(true); bot.setAutoNickChange(true); bot.setCapEnabled(true); final IrcListener listener = new IrcListener(bot, client); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { if (client == null) return; client.saveState(); try { client.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { client = null; } try { listener.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } })); bot.getListenerManager().addListener(listener); try { bot.connect("irc.freenode.net"); bot.joinChannel(channel); if (false) while (true) { Thread.sleep(1000); } //bot.quitServer("end of test"); while (bot.isConnected()) Thread.sleep(100); } catch (Exception ex) { ex.printStackTrace(); } finally { System.out.println("finally"); bot.disconnect(); client.saveState(); client.close(); client = null; } }
From source file:Main.java
static void execPrivileged(final String[] cmd_array) throws Exception { try {//from ww w . j a v a 2s . c o m Process process = AccessController.doPrivileged(new PrivilegedExceptionAction<Process>() { public Process run() throws Exception { return Runtime.getRuntime().exec(cmd_array); } }); // Close unused streams to make sure the child process won't hang process.getInputStream().close(); process.getOutputStream().close(); process.getErrorStream().close(); } catch (PrivilegedActionException e) { throw (Exception) e.getCause(); } }