1. 程式人生 > >tomcat jsp 列印 sigar

tomcat jsp 列印 sigar

<%@page session="false" contentType="text/html; charset=ISO-8859-1" %>
<%@page import="org.hyperic.sigar.*" %>
<%@page import="java.io.PrintWriter" %>
<%@page import="java.net.InetAddress" %>
<%@page import="java.net.UnknownHostException" %>
<%@page import="java.util.Map" %>
<%@page import="java.util.Properties" %>
<%
		Sigar sigar = new Sigar();
		// cpu 使用率
		CpuPerc cpuList[] = null;
        cpuList = sigar.getCpuPercList();
        double combined = 0.0;
        for (int i = 0; i < cpuList.length; i++) {
            combined += cpuList[i].getCombined();
        }
        combined = combined / cpuList.length;
		String p = String.valueOf(combined * 100.0D);
        int ix = p.indexOf(".") + 1;
        String cpu = p.substring(0, ix) + p.substring(ix, ix + 1);
		 // 當前記憶體使用量
		Mem mem = sigar.getMem();
        long memory = mem.getUsed()*100/mem.getTotal();
		// jvm當前使用率
		Runtime r = Runtime.getRuntime();
		long jvm = r.freeMemory()*100/r.totalMemory();
		// 磁碟使用率
		long total = 0;
        long totalFree = 0;
        long totalPercent = 0;
        FileSystem fslist[] = sigar.getFileSystemList();
        for (int i = 0; i < fslist.length; i++) {
            FileSystem fs = fslist[i];
            FileSystemUsage usage = null;
            usage = sigar.getFileSystemUsage(fs.getDirName());
            switch (fs.getType()) {
                case 0: // TYPE_UNKNOWN :未知
                    break;
                case 1: // TYPE_NONE
                    break;
                case 2: // TYPE_LOCAL_DISK : 本地硬碟
                    // 檔案系統總大小
                    total += usage.getTotal();
                    // 檔案系統剩餘大小
                    totalFree += usage.getFree();
                    // 檔案系統可用大小
                    // 檔案系統已經使用量
                    double usePercent = usage.getUsePercent() * 100D;
                    // 檔案系統資源的利用率
                    totalPercent += usePercent;
                    break;
                case 3:// TYPE_NETWORK :網路
                    break;
                case 4:// TYPE_RAM_DISK :快閃記憶體
                    break;
                case 5:// TYPE_CDROM :光碟機
                    break;
                case 6:// TYPE_SWAP :頁面交換
                    break;
            }
        }
        long disk = totalPercent/fslist.length;
		%>
<%out.print("{\"cpu\":\""+cpu+"\",\"jvm\":\""+jvm+"\",\"memory\":\""+memory+"\",\"disk\":\""+disk+"\"}");%>