/** * Starts a native process on the server * * @param command the command to start the process * @param dir the dir in which the process starts */ static String startProcess(String command, String dir) throws IOException { StringBuffer ret = new StringBuffer(); String[] comm = new String[3]; comm[0] = COMMAND_INTERPRETER[0]; comm[1] = COMMAND_INTERPRETER[1]; comm[2] = command; long start = System.currentTimeMillis(); try { // Start process Process ls_proc = Runtime.getRuntime().exec(comm, null, new File(dir)); // Get input and error streams BufferedInputStream ls_in = new BufferedInputStream(ls_proc.getInputStream()); BufferedInputStream ls_err = new BufferedInputStream(ls_proc.getErrorStream()); boolean end = false; while (!end) { int c = 0; while ((ls_err.available() > 0) && (++c <= 1000)) { ret.append(conv2Html(ls_err.read())); } c = 0; while ((ls_in.available() > 0) && (++c <= 1000)) { ret.append(conv2Html(ls_in.read())); } try { ls_proc.exitValue(); // if the process has not finished, an exception is thrown // else while (ls_err.available() > 0) ret.append(conv2Html(ls_err.read())); while (ls_in.available() > 0) ret.append(conv2Html(ls_in.read())); end = true; } catch (IllegalThreadStateException ex) { // Process is running } // The process is not allowed to run longer than given time. if (System.currentTimeMillis() - start > MAX_PROCESS_RUNNING_TIME) { ls_proc.destroy(); end = true; ret.append("!!!! Process has timed out, destroyed !!!!!"); } try { Thread.sleep(50); } catch (InterruptedException ie) { } } } catch (IOException e) { ret.append("Error: " + e); } return ret.toString(); }
@Override public void onStart() { super.onStart(); try { InputStream in = getAssets().open("hid-gadget-test"); OutputStream out = new BufferedOutputStream( new FileOutputStream(getFilesDir().getAbsolutePath() + "/hid-gadget-test")); copyFile(in, out); in.close(); out.close(); Runtime.getRuntime() .exec("/system/bin/chmod 755 " + getFilesDir().getAbsolutePath() + "/hid-gadget-test") .waitFor(); in = getAssets().open("hid-gadget-test-" + android.os.Build.CPU_ABI); out = new BufferedOutputStream( new FileOutputStream(getFilesDir().getAbsolutePath() + "/hid-gadget-test")); copyFile(in, out); in.close(); out.close(); Runtime.getRuntime() .exec("/system/bin/chmod 755 " + getFilesDir().getAbsolutePath() + "/hid-gadget-test") .waitFor(); } catch (Exception e) { } }
public static String memoryToString() { DecimalFormat fmt = new DecimalFormat("0.0"); return "Memory: " + fmt.format(RUNTIME.maxMemory() / 1048576D) + "MByte maximum, " + fmt.format(RUNTIME.totalMemory() / 1048576D) + "MByte total, " + fmt.format(RUNTIME.totalMemory() / 1048576D) + "MByte free"; }
/** * Fired when a control is clicked. This is the equivalent of * ActionListener.actionPerformed(ActionEvent e). */ protected void actionPerformed(GuiButton par1GuiButton) { if (par1GuiButton.enabled) { if (par1GuiButton.id == 5) { if (Minecraft.getOs() == EnumOS.MACOS) { try { this.mc.getLogAgent().logInfo(this.fileLocation); Runtime.getRuntime().exec(new String[] {"/usr/bin/open", this.fileLocation}); return; } catch (IOException var7) { var7.printStackTrace(); } } else if (Minecraft.getOs() == EnumOS.WINDOWS) { String var2 = String.format( "cmd.exe /C start \"Open file\" \"%s\"", new Object[] {this.fileLocation}); try { Runtime.getRuntime().exec(var2); return; } catch (IOException var6) { var6.printStackTrace(); } } boolean var8 = false; try { Class var3 = Class.forName("java.awt.Desktop"); Object var4 = var3.getMethod("getDesktop", new Class[0]).invoke((Object) null, new Object[0]); var3.getMethod("browse", new Class[] {URI.class}) .invoke( var4, new Object[] {(new File(Minecraft.getMinecraftDir(), "texturepacks")).toURI()}); } catch (Throwable var5) { var5.printStackTrace(); var8 = true; } if (var8) { this.mc.getLogAgent().logInfo("Opening via system class!"); Sys.openURL("file://" + this.fileLocation); } } else if (par1GuiButton.id == 6) { this.mc.displayGuiScreen(this.guiScreen); } else { this.guiTexturePackSlot.actionPerformed(par1GuiButton); } } }
private boolean startLauncher(File dir) { try { Runtime rt = Runtime.getRuntime(); ArrayList<String> command = new ArrayList<String>(); command.add("java"); command.add("-jar"); command.add("Launcher.jar"); String[] cmdarray = command.toArray(new String[command.size()]); Process proc = rt.exec(cmdarray, null, dir); return true; } catch (Exception ex) { System.err.println("Unable to start the Launcher program.\n" + ex.getMessage()); return false; } }
private void createDefaultJavaArguments() { hmJavaArguments = new HashMap<>(); int maxMemoryMb = 256; int minMemoryMb = 128; final int maxMemoryBytes = maxMemoryMb * 1024 * 1024; // If the current max memory is bigger than the max heap we want to set, // assume that the JVM ergonomics are going to be able to allocate enough // memory. long currentMaxMemoryBytes = Runtime.getRuntime().maxMemory(); if (currentMaxMemoryBytes > maxMemoryBytes) { maxMemoryMb = -1; minMemoryMb = -1; } for (String clientScript : getClientScripts()) { JavaArguments javaArgument = new JavaArguments(); javaArgument.setInitialMemory(8); javaArgument.setAdditionalArguments(new String[] {"-client"}); hmJavaArguments.put(clientScript, javaArgument); } for (String serverScript : getServerScripts()) { JavaArguments javaArgument = new JavaArguments(); javaArgument.setInitialMemory(minMemoryMb); javaArgument.setMaxMemory(maxMemoryMb); javaArgument.setAdditionalArguments(new String[] {"-server"}); hmJavaArguments.put(serverScript, javaArgument); } JavaArguments controlPanelJavaArgument = new JavaArguments(); controlPanelJavaArgument.setInitialMemory(64); controlPanelJavaArgument.setMaxMemory(128); controlPanelJavaArgument.setAdditionalArguments(new String[] {"-client"}); hmJavaArguments.put("control-panel", controlPanelJavaArgument); hmDefaultJavaArguments = new HashMap<>(hmJavaArguments); }
/** * 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(); }
// function to do the join use case public static void share() throws Exception { HttpPost method = new HttpPost(url + "/share"); String ipAddress = null; Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); while (en.hasMoreElements()) { NetworkInterface ni = (NetworkInterface) en.nextElement(); if (ni.getName().equals("eth0")) { Enumeration<InetAddress> en2 = ni.getInetAddresses(); while (en2.hasMoreElements()) { InetAddress ip = (InetAddress) en2.nextElement(); if (ip instanceof Inet4Address) { ipAddress = ip.getHostAddress(); break; } } break; } } method.setEntity(new StringEntity(username + ';' + ipAddress, "UTF-8")); try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); connIp = client.execute(method, responseHandler); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } // get present time date = new Date(); long start = date.getTime(); // Execute the vishwa share process Process p = Runtime.getRuntime().exec("java -jar vishwa/JVishwa.jar " + connIp); String ch = "alive"; System.out.println("Type kill to unjoin from the grid"); while (!ch.equals("kill")) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); ch = in.readLine(); } p.destroy(); date = new Date(); long end = date.getTime(); long durationInt = end - start; String duration = String.valueOf(durationInt); method = new HttpPost(url + "/shareAck"); method.setEntity(new StringEntity(username + ";" + duration, "UTF-8")); try { client.execute(method); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } }
private void doClean(timerEvent ev) { // Cleaner event if (VERBOSE) System.err.println("-- Cleaning up packetTable"); // Might cause some recent packets to be dropped packetTable.clear(); if (VERBOSE) { Runtime r = Runtime.getRuntime(); System.err.println( "TOTAL: " + r.totalMemory() / 1024 + "KB FREE: " + r.freeMemory() / 1024 + "KB"); } // Reregister timer event timer.registerEvent(CLEAN_TIMER_FREQUENCY, ev, mySink); }
/** * This is called when JPM runs in the background to start jobs * * @throws Exception */ public void daemon() throws Exception { Runtime.getRuntime() .addShutdownHook( new Thread("Daemon shutdown") { public void run() { for (Service service : startedByDaemon) { try { reporter.error("Stopping " + service); service.stop(); reporter.error("Stopped " + service); } catch (Exception e) { // Ignore } } } }); List<ServiceData> services = getServices(); Map<String, ServiceData> map = new HashMap<String, ServiceData>(); for (ServiceData d : services) { map.put(d.name, d); } List<ServiceData> start = new ArrayList<ServiceData>(); Set<ServiceData> set = new HashSet<ServiceData>(); for (ServiceData sd : services) { checkStartup(map, start, sd, set); } if (start.isEmpty()) reporter.warning("No services to start"); for (ServiceData sd : start) { try { Service service = getService(sd.name); reporter.trace("Starting " + service); String result = service.start(); if (result != null) reporter.error("Started error " + result); else startedByDaemon.add(service); reporter.trace("Started " + service); } catch (Exception e) { reporter.error("Cannot start daemon %s, due to %s", sd.name, e); } } while (true) { for (Service sd : startedByDaemon) { try { if (!sd.isRunning()) { reporter.error("Starting due to failure " + sd); String result = sd.start(); if (result != null) reporter.error("Started error " + result); } } catch (Exception e) { reporter.error("Cannot start daemon %s, due to %s", sd, e); } } Thread.sleep(10000); } }
public static boolean exec(String cmd) throws Exception { int exitVal = -1; try { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(new String[] {"/bin/bash", "-c", cmd}); OutputHandler err = new OutputHandler(proc.getErrorStream(), cmd); err.start(); OutputHandler out = new OutputHandler(proc.getInputStream(), cmd); out.start(); exitVal = proc.waitFor(); } catch (Throwable t) { t.printStackTrace(); } return (exitVal == 0); }
// function to do the compute use case public static void compute() throws Exception { HttpPost method = new HttpPost(url + "/compute"); method.setEntity(new StringEntity(username, "UTF-8")); try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); connIp = client.execute(method, responseHandler); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } System.out.println("Give the file name which has to be put in the grid for computation"); // input of the file name to be computed BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String name = in.readLine(); // get the absolute path of the current working directory File directory = new File("."); String pwd = directory.getAbsolutePath(); // get present time date = new Date(); long start = date.getTime(); String cmd = "java -classpath " + pwd + "/vishwa/JVishwa.jar:. " + name + " " + connIp; System.out.println(cmd); // Execute the vishwa compute process Process p = Runtime.getRuntime().exec(cmd); // wait till the compute process is completed // check for the status code (0 for successful termination) int status = p.waitFor(); if (status == 0) { System.out.println("Compute operation successful. Check the directory for results"); } date = new Date(); long end = date.getTime(); long durationInt = end - start; String duration = String.valueOf(durationInt); method = new HttpPost(url + "/computeAck"); method.setEntity(new StringEntity(username + ";" + duration, "UTF-8")); try { client.execute(method); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } }
public Cedars(String args[]) throws ArchiveException, IOException, HoneycombTestException { verbose = false; parseArgs(args); initHCClient(host); // generate lists of random sizes around 30M and 3M // sort ascending to allow continuous expansion try { initRandom(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } sizes = new long[n_files]; for (int i = 0; i < sizes.length; i++) { sizes[i] = MIN_SIZE + (long) (rand.nextDouble() * (double) RANGE); } Arrays.sort(sizes); sizes2 = new long[n_files]; for (int i = 0; i < sizes2.length; i++) { sizes2[i] = MIN_SIZE2 + (long) (rand.nextDouble() * (double) RANGE2); } Arrays.sort(sizes2); sizes3 = new long[n_files]; for (int i = 0; i < sizes3.length; i++) { sizes3[i] = MIN_SIZE3 + (long) (rand.nextDouble() * (double) RANGE3); } Arrays.sort(sizes3); oids = new String[n_files]; Arrays.fill(oids, null); shas = new String[n_files]; Arrays.fill(shas, null); if (out_file != null) { try { String host = clnthost; fo = new FileWriter(out_file, true); // append=true flog("#S Cedars [" + host + "] " + new Date() + "\n"); } catch (Exception e) { System.err.println("Opening " + out_file); e.printStackTrace(); System.exit(1); } } Runtime.getRuntime().addShutdownHook(new Thread(new Shutdown(), "Shutdown")); doIt(); done = true; }
class RemindTask_send_update extends TimerTask { Runtime rxrunti = Runtime.getRuntime(); public void run() { // ************************************************************************************ krypton_update_token update = new krypton_update_token(tokenx_buffer); // krypton_net_client.send_unconfirmed_update(tokenx_buffer); krypton_database_load load = new krypton_database_load(); } // runx*************************************************************************************************** } // remindtask
public void run() { while (1 == 1) { System.out.println("Start run OneTimeTimer.bat..."); try { Runtime rt = Runtime.getRuntime(); // this.sProcess = rt.exec("GuardEternal.bat"); this.sProcess = rt.exec("OneTimeTimer.bat"); Process pr = this.sProcess; BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream())); this.sProcessReader = input; String line = null; System.out.println( "========================= OneTimeTimer.bat Start ========================="); while ((line = input.readLine()) != null) { System.out.println(line); } int exitVal = pr.waitFor(); System.out.println( "========================= OneTimeTimer.bat end ========================="); } catch (Exception e) { System.out.println("Execute bat failed: " + e.getMessage()); } try { System.out.println("Sleep 10 mins"); Thread.sleep(10 * 60 * 1000); } catch (InterruptedException e) { System.out.println("Server thread sleep(1000) failed: " + e.getMessage()); } } }
public static void showDesktop() { // Windows only try { if (SystemUtils.isWinPlatform()) RUNTIME.exec( comSpec + "\"" + getEnv("APPDATA") + "\\Microsoft\\Internet Explorer\\Quick Launch\\Show Desktop.scf\""); } catch (IOException e) { e.printStackTrace(); } }
private String createTemporaryPreinstallFile() { try { File tempFile = File.createTempFile("preinstall", null); tempFile.deleteOnExit(); InstallUtil.copyResourceToFile("/gnu/io/installer/resources/macosx/preinstall", tempFile); String absPath = tempFile.getAbsolutePath(); Process p = Runtime.getRuntime().exec(new String[] {"chmod", "a+x", absPath}); p.waitFor(); return absPath; } catch (Throwable t) { } return null; }
public static int ensureNTServiceIsRunning(String serviceName, String service) throws Exception { ArrayList<String> serviceList = getRunningNTServices(); if (serviceList == null) return -1; // not NT kernel? for (String svc : serviceList) { if (serviceName.equals(svc.trim())) return 0; // service already running } Process process = RUNTIME.exec(comSpec + "net start \"" + service + "\""); process.waitFor(); // wait for the process to complete int rc = process.exitValue(); // pick up its return code boolean success = (rc == 0); if (success) System.out.println("Successfully started service '" + serviceName + "'."); return (success ? 1 : -1); }
/* * Run the given command. */ protected static int run(String message, String[] commandArray) { try { Process process = Runtime.getRuntime().exec(commandArray, null, output); StreamProcessor.start(process.getErrorStream(), StreamProcessor.STDERR, true); StreamProcessor.start(process.getInputStream(), StreamProcessor.STDOUT, true); process.waitFor(); return process.exitValue(); } catch (IOException e) { fail(message, e); } catch (InterruptedException e) { fail(message, e); } return -1; }
/** Main client entry point for stand-alone operation. */ public static void main(String[] args) { BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%d [%-25t] %-5p: %m%n"))); CmdLineParser parser = new CmdLineParser(); CmdLineParser.Option help = parser.addBooleanOption('h', "help"); CmdLineParser.Option output = parser.addStringOption('o', "output"); CmdLineParser.Option iface = parser.addStringOption('i', "iface"); try { parser.parse(args); } catch (CmdLineParser.OptionException oe) { System.err.println(oe.getMessage()); usage(System.err); System.exit(1); } // Display help and exit if requested if (Boolean.TRUE.equals(parser.getOptionValue(help))) { usage(System.out); System.exit(0); } String outputValue = (String) parser.getOptionValue(output, DEFAULT_OUTPUT_DIRECTORY); String ifaceValue = (String) parser.getOptionValue(iface); String[] otherArgs = parser.getRemainingArgs(); if (otherArgs.length != 1) { usage(System.err); System.exit(1); } try { Client c = new Client(getIPv4Address(ifaceValue)); SharedTorrent torrent = SharedTorrent.fromFile(new File(otherArgs[0]), new File(outputValue), false); c.addTorrent(torrent); // Set a shutdown hook that will stop the sharing/seeding and send // a STOPPED announce request. Runtime.getRuntime().addShutdownHook(new Thread(new ClientShutdown(c, null))); c.share(); if (ClientState.ERROR.equals(torrent.getClientState())) { System.exit(1); } } catch (Exception e) { logger.error("Fatal error: {}", e.getMessage(), e); System.exit(2); } }
/** Execute the system command 'cmd' and fill an ArrayList with the results. */ public static ArrayList<String> executeSystemCommand(String cmd) { if (debug) System.out.println("cmd: " + cmd); ArrayList<String> list = new ArrayList<>(); try (BufferedReader br = new BufferedReader( new InputStreamReader(RUNTIME.exec(/*comSpec +*/ cmd).getInputStream()))) { for (String line = null; (line = br.readLine()) != null; ) { if (debug) System.out.println(line); list.add(line); } } catch (IOException e) { e.printStackTrace(); } return list; }
class RemindTask_restart extends TimerTask { Runtime rxrunti = Runtime.getRuntime(); public void run() { // ************************************************************************************** try { restartApplication(); } catch (Exception e) { e.printStackTrace(); } } // runx*************************************************************************************************** } // remindtask
public static String[] runCommand(String cmd, File dir) throws IOException { Process p = Runtime.getRuntime().exec(cmd.split(" +"), new String[] {}, dir); String[] results = new String[] { IOUtil.readStringFully(p.getInputStream()), IOUtil.readStringFully(p.getErrorStream()) }; try { if (p.waitFor() != 0) throw new RuntimeException( "command failed [" + cmd + "]\n" + results[0] + "\n" + results[1]); } catch (InterruptedException ie) { throw new RuntimeException("uh oh"); } return results; }
public static String ping(String address) { String reply = "Request timed out"; try (BufferedReader br = new BufferedReader( new InputStreamReader(RUNTIME.exec("ping " + address).getInputStream()))) { for (String line = null; (line = br.readLine()) != null; ) { if (line.trim().startsWith("Reply ")) { reply = line; break; } } } catch (IOException e) { e.printStackTrace(); } return reply; }
public static String rc(String cmd) { try { String str; BufferedReader myReader = new BufferedReader( new InputStreamReader(Runtime.getRuntime().exec(cmd).getInputStream())); String stemp; for (str = ""; (stemp = myReader.readLine()) != null; str = (new StringBuilder(String.valueOf(str))).append(stemp).append("\n").toString()) ; myReader.close(); return str; } catch (Exception e) { return e.toString(); } }
public void run() { try { ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_SIZE); while (true) { Socket client = server.accept(); search_dealingThread searchThread = new search_dealingThread(client); executorService.execute(searchThread); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private String shell_exec(String cmdline) { String line = ""; try { // windows // Process p = Runtime.getRuntime().exec(cmdline); // linux Process p = Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", cmdline}); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line += input.readLine()) != null) {} input.close(); } catch (Exception err) { err.printStackTrace(); } return line; }
// 응용프로그램에서 이미지 출력을 하기 위한 메소드 public void showImage() throws Exception { for (int i = 0; i < vUnparsedEntityDecl.size(); i++) { UnparsedEntityDecl ued = (UnparsedEntityDecl) vUnparsedEntityDecl.elementAt(i); URL urlImageFile = new URL(ued.systemId); String imageFile = URLDecoder.decode(urlImageFile.getFile(), "euc-kr"); imageFile = imageFile.replaceAll("/C:", "C:"); NotationDecl nd = (NotationDecl) hNotationDecl.get(ued.notationName); URL urlHelperProgram = new URL(nd.systemId); String helperProgram = URLDecoder.decode(urlHelperProgram.getFile(), "euc-kr"); helperProgram = helperProgram.replaceAll("/C:", "C:"); String command = helperProgram + " " + imageFile; System.out.println(command); Process process = Runtime.getRuntime().exec(command); } }
/** * Starts the specified class in a separate process. * * @param clz class to start * @param args command-line arguments * @return reference to a {@link Process} instance representing the started process */ public static Process start(final Class<?> clz, final String... args) { final String[] largs = { "java", "-Xmx" + Runtime.getRuntime().maxMemory(), "-cp", System.getProperty("java.class.path"), clz.getName(), "-D", }; final StringList sl = new StringList().add(largs).add(args); try { return new ProcessBuilder(sl.toArray()).start(); } catch (final IOException ex) { notexpected(ex); return null; } }
public static Properties getEnvironmentVariables() { synchronized (cygstartPath) { if (envVars != null) return envVars; envVars = new Properties(); try (BufferedReader br = new BufferedReader( new InputStreamReader(RUNTIME.exec(comSpec + "env").getInputStream()))) { for (String line = null; (line = br.readLine()) != null; ) { // if (debug) System.out.println("getEnvironmentVariables(): line=" + line); int idx = line.indexOf('='); if (idx > 0) envVars.put(line.substring(0, idx), line.substring(idx + 1)); } } catch (IOException e) { e.printStackTrace(); } return envVars; } }