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); } } }
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)); }
String[] getMedkit( String[] availableResources, String[] requiredResources, String[] missions, double P, double C) { try { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(exec); OutputStream os = proc.getOutputStream(); InputStream is = proc.getInputStream(); new ErrorReader(proc.getErrorStream()).start(); StringBuffer sb = new StringBuffer(); append(sb, availableResources); append(sb, requiredResources); append(sb, missions); sb.append(P).append('\n'); sb.append(C).append('\n'); os.write(sb.toString().getBytes()); BufferedReader br = new BufferedReader(new InputStreamReader(is)); int N = Integer.parseInt(br.readLine().trim()); String[] ret = new String[N]; for (int i = 0; i < N; i++) ret[i] = br.readLine().trim(); return ret; } catch (Exception e) { System.err.println("An error occurred while executing your program"); e.printStackTrace(); return null; } }
/** print out some info about the system and JVM etc. */ public static void show() { Properties prop = System.getProperties(); JDDConsole.out.println( "Using JDD build " + jdd.Version.build + " on " + (new Date()).toString() + "\n"); JDDConsole.out.print( "Using " + prop.getProperty("java.vendor") + " JRE " + prop.getProperty("java.version")); String jit = prop.getProperty("java.compiler"); if (jit != null) JDDConsole.out.print(", " + jit + " JIT in"); JDDConsole.out.println(" " + prop.getProperty("java.vm.name")); JDDConsole.out.println( "OS " + prop.getProperty("os.name") + " on " + rt.availableProcessors() + " " + prop.getProperty("os.arch") + " CPU(s)"); JDDConsole.out.print("Total JRE memory: "); Digits.printNumber1024(rt.maxMemory()); JDDConsole.out.print(", memory currently reserved by the JRE: "); Digits.printNumber1024(usedMemory()); JDDConsole.out.println("\n"); }
public static String getGCStats() { long totalGC = 0; long gcTime = 0; for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) { long count = gc.getCollectionCount(); if (count >= 0) { totalGC += count; } long time = gc.getCollectionTime(); if (time >= 0) { gcTime += time; } } StringBuilder sb = new StringBuilder(); sb.append(banner("memory stats")); sb.append("\n- total collections: " + totalGC); sb.append("\n- total collection time: " + formatTime(gcTime)); Runtime runtime = Runtime.getRuntime(); sb.append("\n- total memory: " + _.printMem(runtime.totalMemory())); return sb.toString(); }
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. } }
public void addMemoryStatsToSnooper() { addData("memory_total", Long.valueOf(Runtime.getRuntime().totalMemory())); addData("memory_max", Long.valueOf(Runtime.getRuntime().maxMemory())); addData("memory_free", Long.valueOf(Runtime.getRuntime().freeMemory())); addData("cpu_cores", Integer.valueOf(Runtime.getRuntime().availableProcessors())); playerStatsCollector.addServerStatsToSnooper(this); }
/* 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; }
/** * Constructor. Initialises the servlet, reading the ontology model from static files and creating * a cleaner thread that removes obsolete sessions. */ public LiberServletImpl() { System.out.println("Starting up"); try { ontology = new OntologyReader(); // reads PolicyGrid ontologies // ontology = new GeographyOntologyReader(); //reads geography ontology clean = new TimerTask() { public void run() { // Removes obsolete sessions from the map, running every 10 min. long time = new GregorianCalendar().getTimeInMillis(); synchronized (userMap) { Iterator it = userMap.keySet().iterator(); List<String> obsolete = new ArrayList<String>(); while (it.hasNext()) { String key = (String) it.next(); long timeDif = time - userMap.get(key).getLastUpdated(); if ((timeDif < 0) || (timeDif > 3600000)) // if an hour has lapsed, or the next day has started obsolete.add(key); // (let's just hope no-one starts using the tool at midnight) } for (int i = 0; i < obsolete.size(); i++) // then remove that session userMap.remove(obsolete.get(i)); } } }; Timer timer = new Timer(); timer.schedule(clean, 0, 600000); Runtime r = Runtime.getRuntime(); r.gc(); // FORCES GARBAGE COLLECTION r.runFinalization(); } catch (Exception e) { e.printStackTrace(); } }
@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) { } }
private void killUNIXProcess() { Runtime program = Runtime.getRuntime(); try { pid = program.exec("trigger WinSize"); } catch (IOException ie) { System.err.println("Error in killing process " + ie); System.exit(-1); } }
/** * Runs executable command * * @param command * @param config the configuration setting * @exception IOException */ private Process run(String[] command, String[] config) throws IOException { try { Runtime rt = Runtime.getRuntime(); return rt.exec(command, config); } catch (Exception e) { throw new IOException("Run process error: " + e.getMessage()); } }
/** * processes the input String and produces an output String. * * @param input the String to input to the underlying process * @throws java.lang.Exception exceptions from Runtime and Process that this class uses * @return the output from the underlying process */ public String process(String input) throws Exception { String returnValue = new String(); StringBuffer buffer = new StringBuffer(); if (socketServer == true) { returnValue = client.process(input); ServerThread current = getServer(); if (current != null) { if (!current.isDaemon()) { current.getProcess().destroy(); } current.interrupt(); } } else { // not a socket server Runtime rt = Runtime.getRuntime(); String output = ""; String errors = ""; try { p = rt.exec(getCodeCall() + " " + getParams()); PrintStream processInputStream = new PrintStream(p.getOutputStream(), true, "utf-8"); processInputStream.println(input + "\n\u0003"); // put in garbage to kill Bikel's loop StreamConsumer errorConsumer = new StreamConsumer(p.getErrorStream(), "error", 1); StreamConsumer outputConsumer = new StreamConsumer(p.getInputStream(), "output", 10); outputConsumer.start(); errorConsumer.start(); int countloops = 0; int time = 0; String message = ""; while (!outputConsumer.isComplete()) { // wait Thread.sleep(100); countloops++; time += 100; // one tenth of a second if (time > waittime) { // just wait 5 minutes message = "exceeded waittime of " + waittime + " milliseconds"; break; } } errors = errorConsumer.getOutput(); output = outputConsumer.getOutput(); if (!message.equals("")) { errors = message; } } catch (IOException ioe) { System.err.println("Module error: " + getModuleName()); ioe.printStackTrace(); System.exit(0); } p.destroy(); if (errors.equals("")) { returnValue = output; } else { returnValue = errors; } } return returnValue; }
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"; }
void doExeCommand() { JViewport viewport = scrollPane.getViewport(); String strContent = new String(); PSlider slider; int i; File fp = new File(dataFile); RandomAccessFile access = null; Runtime program = Runtime.getRuntime(); String cmdTrigger = "trigger"; boolean delete = fp.delete(); try { fp.createNewFile(); } catch (IOException ie) { System.err.println("Couldn't create the new file " + ie); // System.exit(-1);; } try { access = new RandomAccessFile(fp, "rw"); } catch (IOException ie) { System.err.println("Error in accessing the file " + ie); // System.exit(-1);; } for (i = 0; i < COMPONENTS; i++) { slider = (PSlider) vSlider.elementAt(i); /* Modified on March 20th to satisfy advisors' new request */ if (slider.isString == true) strContent = strContent + slider.getRealStringValue() + " "; else strContent = strContent + slider.getValue() + " "; } // Get value of the radio button group if (firstBox.isSelected() == true) strContent = strContent + "1"; else strContent = strContent + "0"; try { access.writeBytes(strContent); access.close(); } catch (IOException ie) { System.err.println("Error in writing to file " + ie); // System.exit(-1);; } // Trigger the OpenGL program to update with new values try { Process pid = program.exec(cmdTrigger); } catch (IOException ie) { System.err.println("Couldn't run " + ie); // System.exit(-1);; } doSourceFileUpdate(); }
private void doExpire() { M_log.info( "doExpire(): About to evict expired elements free memory: " + Runtime.getRuntime().freeMemory()); final List<Ehcache> allCaches = getAllCaches(false); for (Ehcache ehcache : allCaches) { ehcache.evictExpiredElements(); } M_log.info("doExpire(): free memory now " + Runtime.getRuntime().freeMemory()); }
/** Plot the currently selected output buffer */ protected void plotOutput() { try { StringBuffer sb = m_History.getSelectedBuffer(); if (sb != null) { // dump the output into a temporary file File tempDirFile = new File("/tmp"); final File bufferFile = File.createTempFile("buffer", "", tempDirFile); bufferFile.deleteOnExit(); PrintWriter writer = new PrintWriter(new BufferedOutputStream(new FileOutputStream(bufferFile))); writer.print(sb); writer.close(); // launch the perl script to process the file // Process proc = Runtime.getRuntime().exec("perl weka/gui/experiment/plot.pl " + // bufferFile.getPath()); Process proc = Runtime.getRuntime() .exec( "perl /u/ml/software/weka-latest/weka/gui/experiment/plot.pl " + bufferFile.getPath()); proc.waitFor(); // get a list of generated gnuplot scripts String[] scriptList = tempDirFile.list( new FilenameFilter() { public boolean accept(File f, String s) { return (s.endsWith(".gplot") && s.startsWith(bufferFile.getName())); } }); for (int i = 0; i < scriptList.length; i++) { // launch gnuplot scriptList[i] = tempDirFile.getPath() + "/" + scriptList[i]; System.out.println(scriptList[i]); proc = Runtime.getRuntime().exec("gnuplot -persist " + scriptList[i]); File plotFile = new File(scriptList[i]); plotFile.deleteOnExit(); File dataFile = new File(scriptList[i].replaceAll(".gplot", ".dat")); dataFile.deleteOnExit(); } } else { m_PlotBut.setEnabled(false); } } catch (Exception e) { System.out.println("Problems plotting: " + e); e.printStackTrace(); } }
/** * Creates a new session for the editing tool. * * @param user user id * @param project Project ID * @param resource Resource ID * @return String[] with user id and name */ public String[] newSession(String user, String project, String resource) { try { LiberSession session = new LiberSession(ontology, user, project, resource, LiberSession.EDIT); userMap.put(user, session); Runtime r = Runtime.getRuntime(); r.gc(); // FORCES GARBAGE COLLECTION r.runFinalization(); return session.getUserDetails(); } catch (Exception e) { e.printStackTrace(); return null; } }
public static void main(String argv[]) { BMDriver bmt = new BMDriver(); boolean dbstatus; dbstatus = bmt.runTests(); if (dbstatus != true) { System.err.println("Error encountered during buffer manager tests:\n"); Runtime.getRuntime().exit(1); } Runtime.getRuntime().exit(0); }
/** * Called when the users asks to show or hide all known information about a certain object from * the database. * * @param user User ID * @param anchor Unique ID of Anchor * @param show If true, show more information, if false, hide information * @param type Session type (edit, query, browse) * @param key browsing session id (null if session type is EDIT) * @return AnchorInfo[] with serialisable version of feedback text, empty if the user's session is * expired or null if an error occurred */ public AnchorInfo[] changeTextContent( String user, String anchor, boolean show, int type, String key) { if (!userMap.containsKey(user)) return new AnchorInfo[0]; LiberSession session = userMap.get(user); Runtime r = Runtime.getRuntime(); r.gc(); // FORCES GARBAGE COLLECTION r.runFinalization(); synchronized (session) { session.setLastUpdated(); return session.changeTextContent(anchor, show, type, key); } }
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; } }
public void run() { Runtime run = Runtime.getRuntime(); Process ps; try { ps = run.exec(execomm); Scanner in = new Scanner(ps.getInputStream()); while (in.hasNext()) commOut += in.nextLine() + "\n"; in.close(); logging(new StringReader(commOut)); } catch (Exception e) { e.printStackTrace(); } }
/** Compute a status report on all memory users */ public String getStatus() { final StringBuilder buf = new StringBuilder(); buf.append("** Memory report\n"); buf.append("freeMemory: " + Runtime.getRuntime().freeMemory()); buf.append(" totalMemory: "); buf.append(Runtime.getRuntime().totalMemory()); buf.append(" maxMemory: "); buf.append(Runtime.getRuntime().maxMemory()); buf.append("\n\n"); List<Ehcache> allCaches = getAllCaches(true); // summary for (Ehcache cache : allCaches) { final long hits = cache.getStatistics().getCacheHits(); final long misses = cache.getStatistics().getCacheMisses(); final long total = hits + misses; final long hitRatio = ((total > 0) ? ((100l * hits) / total) : 0); // Even when we're not collecting statistics ehcache knows how // many objects are in the cache buf.append(cache.getName() + ": " + " count:" + cache.getStatistics().getObjectCount()); if (cache.isStatisticsEnabled()) { buf.append(" hits:" + hits + " misses:" + misses + " hit%:" + hitRatio); } else { buf.append(" NO statistics (not enabled for cache)"); } buf.append("\n"); } // extended report buf.append("\n** Extended Cache Report\n"); for (Object ehcache : allCaches) { buf.append(ehcache.toString()); buf.append("\n"); } // Iterator<Cacher> it = m_cachers.iterator(); // while (it.hasNext()) // { // Cacher cacher = (Cacher) it.next(); // buf.append(cacher.getSize() + " in " + cacher.getDescription() + "\n"); // } final String rv = buf.toString(); M_log.info(rv); return rv; }
private static void showUsage() { if (!usagePrinted) { outputPrintStream.print(USAGE); runtime.exit(1); usagePrinted = true; } }
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; }
public void close() { if (shutdownCloseThread != null) { Runtime.getRuntime().removeShutdownHook(shutdownCloseThread); shutdownCloseThread.dbToClose = null; shutdownCloseThread = null; } }
public TaggedImageStorageMultipageTiff( String dir, boolean newDataSet, JSONObject summaryMetadata, boolean seperateMDFile, boolean seperateFilesForPositions) throws IOException { omeTiff_ = true; seperateMetadataFile_ = seperateMDFile; splitByXYPosition_ = seperateFilesForPositions; newDataSet_ = newDataSet; directory_ = dir; tiffReadersByLabel_ = new TreeMap<String, MultipageTiffReader>(new ImageLabelComparator()); cached_ = new CachedImages(); setSummaryMetadata(summaryMetadata); // TODO: throw error if no existing dataset if (!newDataSet_) { openExistingDataSet(); } // add shutdown hook --> thread to be run when JVM shuts down shutdownHook_ = new Thread() { @Override public void run() { finished(); writeDisplaySettings(); } }; Runtime.getRuntime().addShutdownHook(this.shutdownHook_); }
/** * Creates a java process that executes the given main class and waits for the process to * terminate. * * @return a {@link ProcessOutputReader} that can be used to get the exit code and stdout+stderr * of the terminated process. */ public static ProcessOutputReader fg(Class main, String[] vmArgs, String[] mainArgs) throws IOException { File javabindir = new File(System.getProperty("java.home"), "bin"); File javaexe = new File(javabindir, "java"); int bits = Integer.getInteger("sun.arch.data.model", 0).intValue(); String vmKindArg = (bits == 64) ? "-d64" : null; ArrayList argList = new ArrayList(); argList.add(javaexe.getPath()); if (vmKindArg != null) { argList.add(vmKindArg); } // argList.add("-Dgemfire.systemDirectory=" + // GemFireConnectionFactory.getDefaultSystemDirectory()); argList.add("-Djava.class.path=" + System.getProperty("java.class.path")); argList.add("-Djava.library.path=" + System.getProperty("java.library.path")); if (vmArgs != null) { argList.addAll(Arrays.asList(vmArgs)); } argList.add(main.getName()); if (mainArgs != null) { argList.addAll(Arrays.asList(mainArgs)); } String[] cmd = (String[]) argList.toArray(new String[argList.size()]); return new ProcessOutputReader(Runtime.getRuntime().exec(cmd)); }
/** * 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 main(String[] args) { // set argument: // start lat, start lon, end lat, end lon, start time index, start day index setParam(34.199705, -117.3663704, 34.38999, -119.159022, 10, 0); // config OSMParam.paramConfig(); // input OSMInput.readNodeFile(); OSMInput.readEdgeFile(); // for both adjListHashMap and adjReverseListHashMap OSMInput.readAdjList(); OSMInput.readNodeLocationGrid(); OSMInput.addOnEdgeToNode(); // JVM memory usage System.out.println( "JVM total memory usage: " + Runtime.getRuntime().totalMemory() / (1024 * 1024) + " megabytes"); // test // OSMOutput.generateHighwayKML(edgeHashMap, nodeHashMap); // initial hierarchy level OSMParam.initialHierarchy(); // routing, turn by turn tdsp(); }