/** * Retrieve a JVM thread dump formatted using the given StringManager. * * @param requestedSm the StringManager to use * @return the formatted JVM thread dump */ private static String getThreadDump(StringManager requestedSm) { StringBuilder sb = new StringBuilder(); synchronized (timeformat) { sb.append(timeformat.format(new Date())); } sb.append(CRLF); sb.append(requestedSm.getString("diagnostics.threadDumpTitle")); sb.append(" "); sb.append(runtimeMXBean.getVmName()); sb.append(" ("); sb.append(runtimeMXBean.getVmVersion()); String vminfo = System.getProperty(vminfoSystemProperty); if (vminfo != null) { sb.append(" " + vminfo); } sb.append("):" + CRLF); sb.append(CRLF); ThreadInfo[] tis = threadMXBean.dumpAllThreads(true, true); sb.append(getThreadDump(tis)); sb.append(findDeadlock()); return sb.toString(); }
public String func_71487_a() { RuntimeMXBean runtimemxbean = ManagementFactory.getRuntimeMXBean(); List list = runtimemxbean.getInputArguments(); int i = 0; StringBuilder stringbuilder = new StringBuilder(); Iterator iterator = list.iterator(); do { if (!iterator.hasNext()) { break; } String s = (String) iterator.next(); if (s.startsWith("-X")) { if (i++ > 0) { stringbuilder.append(" "); } stringbuilder.append(s); } } while (true); return String.format( "%d total; %s", new Object[] {Integer.valueOf(i), stringbuilder.toString()}); }
@RequestMapping("/loadRuntimeInfo") @ResponseBody public JSONObject doLoadRuntimeInfo(HttpServletRequest request) { try { String app = request.getParameter("app"); RuntimeMXBean mBean = JMConnManager.getRuntimeMBean(app); ClassLoadingMXBean cBean = JMConnManager.getClassMbean(app); Map<String, String> props = mBean.getSystemProperties(); DateFormat format = DateFormat.getInstance(); List<String> input = mBean.getInputArguments(); Date date = new Date(mBean.getStartTime()); TreeMap<String, Object> data = new TreeMap<String, Object>(); data.put("apppid", mBean.getName()); data.put("startparam", input.toString()); data.put("starttime", format.format(date)); data.put("classLoadedNow", cBean.getLoadedClassCount()); data.put("classUnloadedAll", cBean.getUnloadedClassCount()); data.put("classLoadedAll", cBean.getTotalLoadedClassCount()); data.putAll(props); JSONObject json = new JSONObject(true); json.putAll(data); return json; } catch (IOException e) { throw new RuntimeException(e); } }
private void createRuntimeProps(MemberStateImpl memberState) { Runtime runtime = Runtime.getRuntime(); ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); ClassLoadingMXBean clMxBean = ManagementFactory.getClassLoadingMXBean(); MemoryMXBean memoryMxBean = ManagementFactory.getMemoryMXBean(); MemoryUsage heapMemory = memoryMxBean.getHeapMemoryUsage(); MemoryUsage nonHeapMemory = memoryMxBean.getNonHeapMemoryUsage(); Map<String, Long> map = new HashMap<String, Long>(); map.put( "runtime.availableProcessors", Integer.valueOf(runtime.availableProcessors()).longValue()); map.put("date.startTime", runtimeMxBean.getStartTime()); map.put("seconds.upTime", runtimeMxBean.getUptime()); map.put("memory.maxMemory", runtime.maxMemory()); map.put("memory.freeMemory", runtime.freeMemory()); map.put("memory.totalMemory", runtime.totalMemory()); map.put("memory.heapMemoryMax", heapMemory.getMax()); map.put("memory.heapMemoryUsed", heapMemory.getUsed()); map.put("memory.nonHeapMemoryMax", nonHeapMemory.getMax()); map.put("memory.nonHeapMemoryUsed", nonHeapMemory.getUsed()); map.put("runtime.totalLoadedClassCount", clMxBean.getTotalLoadedClassCount()); map.put( "runtime.loadedClassCount", Integer.valueOf(clMxBean.getLoadedClassCount()).longValue()); map.put("runtime.unloadedClassCount", clMxBean.getUnloadedClassCount()); map.put("runtime.totalStartedThreadCount", threadMxBean.getTotalStartedThreadCount()); map.put("runtime.threadCount", Integer.valueOf(threadMxBean.getThreadCount()).longValue()); map.put( "runtime.peakThreadCount", Integer.valueOf(threadMxBean.getPeakThreadCount()).longValue()); map.put( "runtime.daemonThreadCount", Integer.valueOf(threadMxBean.getDaemonThreadCount()).longValue()); memberState.setRuntimeProps(map); }
/** * Attach and load an agent class. * * @param log Log used if the agent cannot be loaded. * @param agentJar absolute path to the agent jar. * @param vmClass VirtualMachine.class from tools.jar. */ private static void loadAgent(Config config, Log log, String agentJar, Class<?> vmClass) { try { // addAttach(config,log); // first obtain the PID of the currently-running process // ### this relies on the undocumented convention of the // RuntimeMXBean's // ### name starting with the PID, but there appears to be no other // ### way to obtain the current process' id, which we need for // ### the attach process RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); String pid = runtime.getName(); if (pid.indexOf("@") != -1) pid = pid.substring(0, pid.indexOf("@")); log.info("Instrumentation", "pid:" + pid); // JDK1.6: now attach to the current VM so we can deploy a new agent // ### this is a Sun JVM specific feature; other JVMs may offer // ### this feature, but in an implementation-dependent way Object vm = vmClass .getMethod("attach", new Class<?>[] {String.class}) .invoke(null, new Object[] {pid}); // now deploy the actual agent, which will wind up calling // agentmain() vmClass .getMethod("loadAgent", new Class[] {String.class}) .invoke(vm, new Object[] {agentJar}); vmClass.getMethod("detach", new Class[] {}).invoke(vm, new Object[] {}); } catch (Throwable t) { // Log the message from the exception. Don't log the entire // stack as this is expected when running on a JDK that doesn't // support the Attach API. log.log(Log.LEVEL_ERROR, "Instrumentation", t); } }
/** * Returns object of class ‘"proc_time"’ which is a numeric vector of length 5, containing the * user, system, and total elapsed times for the currently running R process, and the cumulative * sum of user and system times of any child processes spawned by it on which it has waited. * * <p>_The ‘user time’ is the CPU time charged for the execution of user instructions of the * calling process. The ‘system time’ is the CPU time charged for execution by the system on * behalf of the calling process._ */ @Builtin("proc.time") public static DoubleVector procTime() { DoubleArrayVector.Builder result = new DoubleArrayVector.Builder(); StringVector.Builder names = new StringVector.Builder(); long totalCPUTime; long userCPUTime; long elapsedTime; // There doesn't seem to be any platform-independent way of accessing // CPU use for the whole JVM process, so we'll have to make do // with the timings for the thread we're running on. // // Additionally, the MX Beans may not be available in all environments, // so we need to fallback to app try { ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); totalCPUTime = threadMXBean.getCurrentThreadCpuTime(); userCPUTime = threadMXBean.getCurrentThreadUserTime(); RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); elapsedTime = runtimeMXBean.getUptime(); } catch (Error e) { // ThreadMXBean is not available in all environments // Specifically, AppEngine will throw variously SecurityErrors or // ClassNotFoundErrors if we try to access these classes userCPUTime = totalCPUTime = java.lang.System.nanoTime(); elapsedTime = new Date().getTime(); } // user.self names.add("user.self"); result.add(userCPUTime / NANOSECONDS_PER_SECOND); // sys.self names.add("sys.self"); result.add((totalCPUTime - userCPUTime) / NANOSECONDS_PER_SECOND); // elapsed // (wall clock time) names.add("elapsed"); result.add(elapsedTime); // AFAIK, we don't have any platform independent way of accessing // this info. // user.child names.add("user.child"); result.add(0); // sys.child names.add("sys.child"); result.add(0); result.setAttribute(Symbols.NAMES, names.build()); result.setAttribute(Symbols.CLASS, StringVector.valueOf("proc_time")); return result.build(); }
public static String getLibraryPath() { RuntimeMXBean r = ManagementFactory.getRuntimeMXBean(); if (r != null) { String cs = r.getLibraryPath(); return cs; } return ""; }
// This helper relies on RuntimeMXBean.getName() returning a string // that looks like this: 5436@mt-haku // // The testlibrary has tryFindJvmPid(), but that uses a separate // process which is much more expensive for finding out your own PID. // static String getPid() { RuntimeMXBean runtimebean = ManagementFactory.getRuntimeMXBean(); String vmname = runtimebean.getName(); int i = vmname.indexOf('@'); if (i != -1) { vmname = vmname.substring(0, i); } return vmname; }
/** * 获取当前JVM启动时间。 * * @return 当前JVM启动时间,单位(毫秒)。 */ public static long getJavaVMStartTime() { // throw new UnsupportedOperationException(); RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); if (runtimeMXBean != null) { return runtimeMXBean.getStartTime(); } // can't happen return -1; }
private String getVMArguments() { final StringBuilder result = new StringBuilder(1024); final RuntimeMXBean rmBean = ManagementFactory.getRuntimeMXBean(); final List<String> inputArguments = rmBean.getInputArguments(); for (String arg : inputArguments) { result.append(arg).append(" "); } return result.toString(); }
public static String getAllPaths() { String cs = ""; RuntimeMXBean r = ManagementFactory.getRuntimeMXBean(); if (r != null) { cs = "ClassPath=" + r.getClassPath(); cs += "; BootClassPath=" + r.getBootClassPath(); cs += "; LibraryPath=" + r.getLibraryPath(); return cs; } return ""; }
private JSONObject doRemoteDump(String app, String date, String host) throws IOException { RuntimeMXBean mBean = JMConnManager.getRuntimeMBean(app); String dir = mBean.getSystemProperties().get("user.dir"); String dumpFile = String.format("%s/%s_%s_heap.hprof", dir, app, date); JMConnManager.getHotspotBean(app).dumpHeap(dumpFile, false); JSONObject res = new JSONObject(); res.put("file", host + ":" + dumpFile); res.put("local", false); return res; }
private String getRuntimeFlagValue(String prefix) { RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); for (String param : runtime.getInputArguments()) { if (param.startsWith(prefix)) { return param.substring(prefix.length()).toUpperCase(); } } return null; }
private void writeSystemProperties() { try { Properties properties = System.getProperties(); int maxKeyLength = 1; List<String> keys = new ArrayList<String>(); for (Map.Entry<Object, Object> entry : properties.entrySet()) { Object objKey = entry.getKey(); Object objValue = entry.getValue(); // Filter out any bad non-String keys or values in system properties if (objKey instanceof String && objValue instanceof String) { String key = (String) objKey; keys.add(key); maxKeyLength = Math.max(maxKeyLength, key.length()); } } String inputArguments = null; try { RuntimeMXBean mxbean = ManagementFactory.getRuntimeMXBean(); inputArguments = mxbean.getInputArguments().toString(); } catch (SecurityException se) { inputArguments = "unknown"; } String nl = System.getProperty("line.separator"); StringBuffer data = new StringBuffer(); data.append("All Java System Properties for this Terracotta instance:"); data.append(nl); data.append("========================================================================"); data.append(nl); data.append("JVM arguments: " + inputArguments); data.append(nl); String[] sortedKeys = keys.toArray(new String[keys.size()]); Arrays.sort(sortedKeys); for (String key : sortedKeys) { data.append(key); for (int i = 0; i < maxKeyLength - key.length(); i++) { data.append(' '); } data.append(" : "); data.append(properties.get(key)); data.append(nl); } data.append("========================================================================"); getLogger(TCLoggingLog4J.class).info(data.toString()); } catch (Throwable t) { // don't let exceptions here be fatal t.printStackTrace(); } }
public Map<String, String> phoneHome(Node hazelcastNode, String version, boolean isEnterprise) { String downloadId = "source"; InputStream is = null; try { is = getClass().getClassLoader().getResourceAsStream("hazelcast-download.properties"); if (is != null) { final Properties properties = new Properties(); properties.load(is); downloadId = properties.getProperty("hazelcastDownloadId"); } } catch (IOException ignored) { EmptyStatement.ignore(ignored); } finally { IOUtil.closeResource(is); } // Calculate native memory usage from native memory config NativeMemoryConfig memoryConfig = hazelcastNode.getConfig().getNativeMemoryConfig(); final ClusterServiceImpl clusterService = hazelcastNode.getClusterService(); long totalNativeMemorySize = clusterService.getSize(DATA_MEMBER_SELECTOR) * memoryConfig.getSize().bytes(); String nativeMemoryParameter = (isEnterprise) ? Long.toString(MemoryUnit.BYTES.toGigaBytes(totalNativeMemorySize)) : "0"; // Calculate connected clients to the cluster. Map<ClientType, Integer> clusterClientStats = hazelcastNode.clientEngine.getConnectedClientStats(); RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); Long clusterUpTime = clusterService.getClusterClock().getClusterUpTime(); PhoneHomeParameterCreator parameterCreator = new PhoneHomeParameterCreator(); parameterCreator.addParam("version", version); parameterCreator.addParam("m", hazelcastNode.getLocalMember().getUuid()); parameterCreator.addParam("e", Boolean.toString(isEnterprise)); parameterCreator.addParam("l", MD5Util.toMD5String(hazelcastNode.getConfig().getLicenseKey())); parameterCreator.addParam("p", downloadId); parameterCreator.addParam("c", clusterService.getClusterId()); parameterCreator.addParam("crsz", convertToLetter(clusterService.getMembers().size())); parameterCreator.addParam( "cssz", convertToLetter(hazelcastNode.clientEngine.getClientEndpointCount())); parameterCreator.addParam("hdgb", nativeMemoryParameter); parameterCreator.addParam("ccpp", Integer.toString(clusterClientStats.get(ClientType.CPP))); parameterCreator.addParam("cdn", Integer.toString(clusterClientStats.get(ClientType.CSHARP))); parameterCreator.addParam("cjv", Integer.toString(clusterClientStats.get(ClientType.JAVA))); parameterCreator.addParam("cuptm", Long.toString(clusterUpTime)); parameterCreator.addParam("nuptm", Long.toString(runtimeMxBean.getUptime())); String urlStr = BASE_PHONE_HOME_URL + parameterCreator.build(); fetchWebService(urlStr); return parameterCreator.getParameters(); }
private void g() { RuntimeMXBean localRuntimeMXBean = ManagementFactory.getRuntimeMXBean(); List localList = localRuntimeMXBean.getInputArguments(); int i = 0; for (String str : localList) { if (str.startsWith("-X")) { a("jvm_arg[" + i++ + "]", str); } } a("jvm_args", Integer.valueOf(i)); }
private void func_76467_g() { RuntimeMXBean var1 = ManagementFactory.getRuntimeMXBean(); List var2 = var1.getInputArguments(); int var3 = 0; Iterator var4 = var2.iterator(); while (var4.hasNext()) { String var5 = (String) var4.next(); if (var5.startsWith("-X")) { this.func_76472_a("jvm_arg[" + var3++ + "]", var5); } } this.func_76472_a("jvm_args", Integer.valueOf(var3)); }
private void addJvmArgsToSnooper() { RuntimeMXBean runtimemxbean = ManagementFactory.getRuntimeMXBean(); List list = runtimemxbean.getInputArguments(); int i = 0; Iterator iterator = list.iterator(); while (iterator.hasNext()) { String s = (String) iterator.next(); if (s.startsWith("-X")) { this.addClientStat("jvm_arg[" + i++ + "]", s); } } this.addClientStat("jvm_args", Integer.valueOf(i)); }
/** * Prints the verbose GC log to System.out to list the memory usage of all memory pools as well as * the GC statistics. */ @Deprecated public String[] getVerboseGc() { String gcs = ""; StringBuilder sb = new StringBuilder(); sb.append("Uptime: " + StringFormatter.formatMillis(rmbean.getUptime())); for (GarbageCollectorMXBean gc : gcmbeans) { sb.append(" [" + gc.getName() + ": "); sb.append("Count=" + gc.getCollectionCount()); sb.append(" GCTime=" + StringFormatter.formatMillis(gc.getCollectionTime())); sb.append("]"); gcs += StringFormatter.formatMillisShort(gc.getCollectionTime()) + ":(" + gc.getCollectionCount() + ");"; } sb.append("\n"); for (MemoryPoolMXBean p : pools) { sb.append(" [" + p.getName() + ":"); MemoryUsage u = p.getUsage(); sb.append(" Used=" + StringFormatter.formatBytes(u.getUsed())); sb.append(" Committed=" + StringFormatter.formatBytes(u.getCommitted())); sb.append("]\n"); } return new String[] {sb.toString(), gcs}; }
private void jvmSummary() { OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); stdout.format( "JVM: %s %s %s\n", runtimeBean.getVmVendor(), runtimeBean.getVmName(), runtimeBean.getVmVersion()); stdout.format(" on %s %s %s\n", "", osBean.getName(), osBean.getVersion(), osBean.getArch()); try { stdout.format( " running as %s on %s\n", System.getProperty("user.name"), InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { } stdout.format(" cwd %s\n", path(new File(".").getAbsoluteFile().getParentFile())); stdout.format(" site %s\n", path(sitePath)); }
/** * Get the process id of the current running Java process * * @return Process id */ public static int getProcessId() throws Exception { // Get the current process id using a reflection hack RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); Field jvm = runtime.getClass().getDeclaredField("jvm"); jvm.setAccessible(true); VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime); Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId"); pid_method.setAccessible(true); int pid = (Integer) pid_method.invoke(mgmt); return pid; }
public static String getPid() { String name = runtimeMXBean.getName(); if (name != null && name.length() > 0 && name.indexOf("@") != -1) { return name.split("@")[0]; } return null; }
private static void writePid(String pidFile) { try { if (pidFile != null) { RuntimeMXBean rtb = ManagementFactory.getRuntimeMXBean(); String processName = rtb.getName(); Pattern pattern = Pattern.compile("^([0-9]+)@.+$", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(processName); if (matcher.matches()) { int pid = Integer.parseInt(matcher.group(1)); Writer w = new OutputStreamWriter(new FileOutputStream(pidFile)); w.write(Integer.toString(pid)); w.close(); } } } catch (Exception e) { e.printStackTrace(); } }
/** * Create the JVM information * * @return */ private JsonValue getJVMInformation() { JsonObject report = JsonValueBuilder.jsonValue(); // Arguments List<String> arguments = runtimeMxBean.getInputArguments(); JsonArray argumentsJson = report.array(JVM_ARGUMENTS_LABEL); for (String argument : arguments) { argumentsJson.add(argument); } // some useful jvm properties JsonObject propertiesJson = JsonValueBuilder.jsonValue(); propertiesJson.put("java.vm.info", System.getProperty("java.vm.info")); propertiesJson.put("java.vm.name", System.getProperty("java.vm.info")); propertiesJson.put( "java.vm.specification.name", System.getProperty("java.vm.specification.name")); propertiesJson.put( "java.vm.specification.vendor", System.getProperty("java.vm.specification.vendor")); propertiesJson.put( "java.vm.specification.version", System.getProperty("java.vm.specification.version")); propertiesJson.put("java.vm.vendor", System.getProperty("java.vm.vendor")); propertiesJson.put("java.vm.version", System.getProperty("java.vm.version")); report.put(JVM_PROPERTIES_LABEL, propertiesJson.build().asMap()); report.put(JVM_JAVA_VERSION_LABEL, System.getProperty("java.version")); // Memory JsonObject memoryJson = JsonValueBuilder.jsonValue(); memoryJson.put(JVM_UNIT_MEMORY_LABEL, FileSizeUnit.MB); // Getting the runtime reference from system Runtime runtime = Runtime.getRuntime(); // Print used memory memoryJson.put( JVM_USED_MEMORY_LABEL, FileSizeUnit.B.toMB(runtime.totalMemory() - runtime.freeMemory())); // Print free memory memoryJson.put(JVM_FREE_MEMORY_LABEL, FileSizeUnit.B.toMB(runtime.freeMemory())); // Print total available memory memoryJson.put(JVM_TOTAL_MEMORY_LABEL, FileSizeUnit.B.toMB(runtime.totalMemory())); // Print Maximum available memory memoryJson.put(JVM_MAX_MEMORY_LABEL, FileSizeUnit.B.toMB(runtime.maxMemory())); // GNU systems don't support the "sun.arch.data.model" property, so we print both memoryJson.put(JVM_BIT_SIZE_GNU_LABEL, System.getProperty("sun.arch.data.model")); memoryJson.put(JVM_BIT_SIZE_LABEL, System.getProperty("os.arch")); report.put(JVM_MEMORY_LABEL, memoryJson.build().asMap()); return report.build(); }
@Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { double tps = Main.getTps(); ChatColor color; if (tps >= 18.0 && tps <= 20.0) { color = ChatColor.GREEN; } else if (tps >= 15.0 && tps < 18.0) { color = ChatColor.YELLOW; } else { color = ChatColor.RED; } RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); long startTime = runtime.getStartTime(); long ramUsage = (Runtime.getRuntime().totalMemory() / 1024 / 1024); sender.sendMessage(Main.PREFIX + "Server performance:"); sender.sendMessage("§8§l» §7Current TPS: " + color + NumberUtils.convertDouble(tps)); if (!sender.hasPermission("uhc.tps")) { return true; } sender.sendMessage("§8§l» §7Uptime: §a" + DateUtils.formatDateDiff(startTime)); sender.sendMessage("§8§l» §7RAM Usage: §a" + ramUsage + " MB"); sender.sendMessage("§8§l» §7Max Memory: §a4096 MB"); int entities = 0; int chunks = 0; for (World world : Bukkit.getWorlds()) { entities = entities + world.getEntities().size(); chunks = chunks + world.getLoadedChunks().length; } entities = entities - PlayerUtils.getPlayers().size(); sender.sendMessage("§8§l» §7Entities: §a" + entities); sender.sendMessage("§8§l» §7Loaded chunks: §a" + chunks); return true; }
private void addJvmArgsToSnooper() { RuntimeMXBean runtimemxbean = ManagementFactory.getRuntimeMXBean(); List list = runtimemxbean.getInputArguments(); int i = 0; Iterator iterator = list.iterator(); do { if (!iterator.hasNext()) { break; } String s = (String) iterator.next(); if (s.startsWith("-X")) { addData((new StringBuilder()).append("jvm_arg[").append(i++).append("]").toString(), s); } } while (true); addData("jvm_args", Integer.valueOf(i)); }
private static void saveProcessID(String svrName, String runDir) { Log.info("Server Name is " + svrName + " Run Dir is " + runDir); RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean(); String pid = rt.getName(); if (Log.loggingDebug) { Log.info("PROCESS ID IS " + pid); Log.info("server name is " + svrName); } try { if (runDir != null) { File outFile = new File(runDir + "\\" + svrName + ".bat"); PrintWriter out = new PrintWriter(new FileWriter(outFile)); out.println("set pid=" + pid.substring(0, pid.indexOf("@"))); out.close(); } } catch (IOException e) { Log.exception("saveProcessID caught exception", e); } }
public static int currentPid() { RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); String runtimeMXBeanName = runtimeMXBean.getName(); Exception cause = null; if (StringUtils.hasText(runtimeMXBeanName)) { int atSignIndex = runtimeMXBeanName.indexOf('@'); if (atSignIndex > 0) { try { return Integer.parseInt(runtimeMXBeanName.substring(0, atSignIndex)); } catch (NumberFormatException e) { cause = e; } } } throw new PidUnavailableException( String.format("Process ID (PID) not available [%s]", runtimeMXBeanName), cause); }
// TODO public static void main(String[] args) { Libdiv livdiv = new Libdiv(); Pattern p = Pattern.compile("\\.div$|\\.div/$"); RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); String vmName = bean.getName(); long pid = Long.valueOf(vmName.split("@")[0]); for (int i = 0; i < args.length; i++) { Matcher m = p.matcher(args[i]); if (m.find() && !(new File(args[i]).exists())) { livdiv.divCreate(new File(args[i])); } else if (m.find()) { String tmp = args[i] + pid; File file = new File(tmp); livdiv.divChangeMtime(new File(args[i]), new File(tmp)); if (file.isFile()) { file.delete(); } } } }
@Test public void test() { final RuntimeMXBean runtime = createMock(RuntimeMXBean.class); expect(runtime.getUptime()).andReturn(69876000l); replay(runtime); Injector injector = Guice.createInjector( new ChefParserModule(), new GsonModule(), new JMXOhaiModule() { @Override protected RuntimeMXBean provideRuntimeMXBean() { return runtime; } }); Json json = injector.getInstance(Json.class); Ohai ohai = injector.getInstance(Ohai.class); assertEquals(json.toJson(ohai.ohai.get().get("uptime_seconds")), "69876"); }