Sunday, November 25, 2012

CPU Monitor in Java - using SIGAR

Here is a small demo using SIGAR framework to display CPU statistics

File:Constants.java

package com.giri.cpu;


public class Constants {
 public static String USER_TIME = "UserTime";
 public static String SYS_TIME = "SysTime";
 public static String IDLE_TIME = "IdleTime";
 public static String WAIT_TIME = "WaitTime";
 public static String NICE_TIME = "NiceTime";
 public static String COMBINED_TIME = "CombinedTime";
 public static String IRQ_TIME = "IrqTime";
}


File:CpuInfo.java

package com.giri.cpu;


import java.util.HashMap;

import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarLoader;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.cmd.Shell;
import org.hyperic.sigar.cmd.SigarCommandBase;

public class CpuInfo extends SigarCommandBase {

    public boolean displayTimes = true;
    
    public CpuInfo(Shell shell) {
        super(shell);
    }

    public CpuInfo() {
        super();
    }

    public String getUsageShort() {
        return "Display cpu information";
    }
    
    public HashMap<String,String> getMap() throws SigarException {
     HashMap<String,String> hm = new HashMap<String,String>();
     CpuPerc cpu = this.sigar.getCpuPerc();
     
     hm.put("UserTime",CpuPerc.format(cpu.getUser()).substring(0, CpuPerc.format(cpu.getUser()).length()-1));
     hm.put("SysTime",CpuPerc.format(cpu.getSys()).substring(0, CpuPerc.format(cpu.getSys()).length()-1 ));
     hm.put("IdleTime",CpuPerc.format(cpu.getIdle()).substring(0, CpuPerc.format(cpu.getIdle()).length()-1));
     hm.put("WaitTime",CpuPerc.format(cpu.getWait()).substring(0, CpuPerc.format(cpu.getWait()).length()-1));
     hm.put("NiceTime",CpuPerc.format(cpu.getNice()).substring(0, CpuPerc.format(cpu.getNice()).length()-1));
     hm.put("CombinedTime",CpuPerc.format(cpu.getCombined()).substring(0, CpuPerc.format(cpu.getCombined()).length()-1));
     hm.put("IrqTime",CpuPerc.format(cpu.getIrq()).substring(0, CpuPerc.format(cpu.getIrq()).length()-1));
     if (SigarLoader.IS_LINUX) {
      hm.put("SoftIrqTime",CpuPerc.format(cpu.getSoftIrq()).substring(0, CpuPerc.format(cpu.getSoftIrq()).length()-1));
      hm.put("StolenTime",CpuPerc.format(cpu.getStolen()).substring(0, CpuPerc.format(cpu.getStolen()).length()-1));
     }
     
     return hm;
    }

    private void output(CpuPerc cpu) {
        println("User Time....." + CpuPerc.format(cpu.getUser()));
        println("Sys Time......" + CpuPerc.format(cpu.getSys()));
        println("Idle Time....." + CpuPerc.format(cpu.getIdle()));
        println("Wait Time....." + CpuPerc.format(cpu.getWait()));
        println("Nice Time....." + CpuPerc.format(cpu.getNice()));
        println("Combined......" + CpuPerc.format(cpu.getCombined()));
        println("Irq Time......" + CpuPerc.format(cpu.getIrq()));
        if (SigarLoader.IS_LINUX) {
            println("SoftIrq Time.." + CpuPerc.format(cpu.getSoftIrq()));
            println("Stolen Time...." + CpuPerc.format(cpu.getStolen()));
        }
        println("");
    }

    public void output(String[] args) throws SigarException {
        org.hyperic.sigar.CpuInfo[] infos = this.sigar.getCpuInfoList();

        CpuPerc[] cpus = this.sigar.getCpuPercList();

        org.hyperic.sigar.CpuInfo info = infos[0];
        long cacheSize = info.getCacheSize();
        println("Vendor........." + info.getVendor());
        println("Model.........." + info.getModel());
        println("Mhz............" + info.getMhz());
        println("Total CPUs....." + info.getTotalCores());
        if ((info.getTotalCores() != info.getTotalSockets()) || (info.getCoresPerSocket() > info.getTotalCores()))
        {
            println("Physical CPUs.." + info.getTotalSockets());
            println("Cores per CPU.." + info.getCoresPerSocket());
        }

        if (cacheSize != Sigar.FIELD_NOTIMPL) {
            println("Cache size...." + cacheSize);
        }
        
        println("");

        if (!this.displayTimes) {
            return;
        }

        for (int i=0; i<cpus.length; i++) {
            println("CPU " + i + ".........");
            output(cpus[i]);
        }

        println("Totals........");
        output(this.sigar.getCpuPerc());
    }
}

File:CpuStatsThread.java

package com.giri.cpu;

import java.util.HashMap;
import org.hyperic.sigar.SigarException;

public class CpuStatsThread implements Runnable {
 
 public CpuStatsThread() {
  
 }

 @Override
 public void run() {
  HashMap hmap  = null;
  while(true) {
   try {
    hmap = new CpuInfo().getMap();
    
    Frame.updateProgressGivenMap(hmap);
   } catch (SigarException e) {
    e.printStackTrace();
   }
   
   try {
    Thread.sleep(100);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }

 }

}

File:Frame.java

package com.giri.cpu;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.swing.JProgressBar;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Frame extends JFrame {

 private static final long serialVersionUID = 1L;

 private JPanel contentPane;
  
 private static JProgressBar pb_usertime = new JProgressBar();
 
 private static JProgressBar pb_systime = new JProgressBar();
 
 private static JProgressBar pb_idletime = new JProgressBar();
 
 private static JProgressBar pb_waittime = new JProgressBar();
 
 private static JProgressBar pb_nicetime = new JProgressBar();
 
 private static JProgressBar pb_combinedtime = new JProgressBar();
 
 private static JProgressBar pb_irqtime = new JProgressBar();
 
 public static void updateProgressGivenMap(HashMap<String,String> map) {
  Set<Map.Entry<String, String>> entries = map.entrySet();
  
        for(Map.Entry<String, String> entry : entries) {
            String strKey = entry.getKey();
            String strVal = entry.getValue();
            
            if(strKey.equals(Constants.COMBINED_TIME)) {
             pb_combinedtime.setValue((int) Float.parseFloat(strVal)); 
   }
   
   if(strKey.equals(Constants.IDLE_TIME)) {
    pb_idletime.setValue((int) Float.parseFloat(strVal));
   }
   
   if(strKey.equals(Constants.IRQ_TIME)) {
    pb_irqtime.setValue((int) Float.parseFloat(strVal));
   }
   
   if(strKey.equals(Constants.NICE_TIME)) {
    pb_nicetime.setValue((int) Float.parseFloat(strVal));
   }
   
   if(strKey.equals(Constants.SYS_TIME)) {
    pb_systime.setValue((int) Float.parseFloat(strVal));
   }
   
   if(strKey.equals(Constants.USER_TIME)) {
    pb_usertime.setValue((int) Float.parseFloat(strVal));    
   }
   
   if(strKey.equals(Constants.WAIT_TIME)) {
    pb_waittime.setValue((int) Float.parseFloat(strVal));
   }
        }
 }

 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     Frame frame = new Frame();
     frame.setVisible(true);
     Thread t = new Thread(new CpuStatsThread());
     t.start();
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }

 /**
  * Create the frame.
  */
 public Frame() {
  setTitle("CPU Monitor (Author: Giridhar Bhujanga)");
  setResizable(false);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setBounds(100, 100, 780, 590);
  contentPane = new JPanel();
  contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  setContentPane(contentPane);
  contentPane.setLayout(null);
  
  JLabel lblNewLabel = new JLabel("User Time");
  lblNewLabel.setBounds(53, 33, 666, 16);
  contentPane.add(lblNewLabel);
  
  JLabel lblSystemTime = new JLabel("System Time");
  lblSystemTime.setBounds(53, 101, 666, 16);
  contentPane.add(lblSystemTime);
  
  JLabel lblIdleTime = new JLabel("Idle Time");
  lblIdleTime.setBounds(53, 169, 666, 16);
  contentPane.add(lblIdleTime);
  
  JLabel lblWaitTime = new JLabel("Wait Time");
  lblWaitTime.setBounds(53, 237, 666, 16);
  contentPane.add(lblWaitTime);
  
  JLabel lblCombinedTime = new JLabel("Nice Time");
  lblCombinedTime.setBounds(53, 305, 666, 16);
  contentPane.add(lblCombinedTime);
  
  JLabel lblIrqTime = new JLabel("Combined Time\n");
  lblIrqTime.setBounds(53, 373, 666, 16);
  contentPane.add(lblIrqTime);
  
  JLabel lblIrqTime_1 = new JLabel("IRQ Time");
  lblIrqTime_1.setBounds(53, 441, 666, 16);
  contentPane.add(lblIrqTime_1);
  
  pb_usertime.setBounds(53, 61, 666, 20);
  contentPane.add(pb_usertime);

  pb_systime.setBounds(53, 129, 666, 20);
  contentPane.add(pb_systime);
  

  pb_idletime.setBounds(53, 192, 666, 20);
  contentPane.add(pb_idletime);
  

  pb_waittime.setBounds(53, 265, 666, 20);
  contentPane.add(pb_waittime);
  

  pb_nicetime.setBounds(53, 333, 666, 20);
  contentPane.add(pb_nicetime);
  

  pb_combinedtime.setBounds(53, 401, 666, 20);
  contentPane.add(pb_combinedtime);
  

  pb_irqtime.setBounds(53, 469, 666, 20);
  contentPane.add(pb_irqtime);
  
  JLabel lblCpuMonitor = new JLabel("CPU Monitor");
  lblCpuMonitor.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
  lblCpuMonitor.setHorizontalAlignment(SwingConstants.RIGHT);
  lblCpuMonitor.setBounds(408, 19, 311, 16);
  contentPane.add(lblCpuMonitor);
  
  JButton btnExit = new JButton("Exit");
  btnExit.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    System.exit(0);
   }
  });
  btnExit.setBounds(513, 516, 206, 29);
  contentPane.add(btnExit);
 }
}

No comments :

Post a Comment