Javaコードを使ってサーバの性能情報とローカルネットワーク内のホスト名を取得します。


最近のプロジェクトはcpuの占有率などのシステム情報を取得します。最初はダイナミックリンクライブラリを使うと思っていましたが、次のようにすることができます。jniを呼び出さないと、新しい技術を見る時間が少なくなります。∩)o…
Javaでは、全体の物理メモリ、残りの物理メモリ、使用済みの物理メモリなどの情報が得られ、以下の例ではこれらの情報が得られ、Windows下のメモリ使用率が得られる。
     まず、物理メモリ、残りの物理メモリ、使用済みの物理メモリ、メモリ使用率などのフィールドを含めて監視するためのMonitoInfoBenクラスを作成します。このクラスのコードは以下の通りです。

package com.amgkaka.performance; 
 
/** */ /** 
 *      JavaBean . 
 * @author amg 
 * @version 1.0  
 * Creation date: 2008-4-25 -   10:37:00 
 */  
public  class MonitorInfoBean { 
  /** */ /**      . */  
  private  long totalMemory; 
   
  /** */ /**     . */  
  private  long freeMemory; 
   
  /** */ /**        . */  
  private  long maxMemory; 
   
  /** */ /**     . */  
  private String osName; 
   
  /** */ /**       . */  
  private  long totalMemorySize; 
   
  /** */ /**        . */  
  private  long freePhysicalMemorySize; 
   
  /** */ /**         . */  
  private  long usedMemory; 
   
  /** */ /**     . */  
  private  int totalThread; 
   
  /** */ /** cpu   . */  
  private  double cpuRatio; 
 
  public  long getFreeMemory() { 
    return freeMemory; 
  } 
 
  public  void setFreeMemory( long freeMemory) { 
    this .freeMemory = freeMemory; 
  } 
 
  public  long getFreePhysicalMemorySize() { 
    return freePhysicalMemorySize; 
  } 
 
  public  void setFreePhysicalMemorySize( long freePhysicalMemorySize) { 
    this .freePhysicalMemorySize = freePhysicalMemorySize; 
  } 
 
  public  long getMaxMemory() { 
    return maxMemory; 
  } 
 
  public  void setMaxMemory( long maxMemory) { 
    this .maxMemory = maxMemory; 
  } 
 
  public String getOsName() { 
    return osName; 
  } 
 
  public  void setOsName(String osName) { 
    this .osName = osName; 
  } 
 
  public  long getTotalMemory() { 
    return totalMemory; 
  } 
 
  public  void setTotalMemory( long totalMemory) { 
    this .totalMemory = totalMemory; 
  } 
 
  public  long getTotalMemorySize() { 
    return totalMemorySize; 
  } 
 
  public  void setTotalMemorySize( long totalMemorySize) { 
    this .totalMemorySize = totalMemorySize; 
  } 
 
  public  int getTotalThread() { 
    return totalThread; 
  } 
 
  public  void setTotalThread( int totalThread) { 
    this .totalThread = totalThread; 
  } 
 
  public  long getUsedMemory() { 
    return usedMemory; 
  } 
 
  public  void setUsedMemory( long usedMemory) { 
    this .usedMemory = usedMemory; 
  } 
 
  public  double getCpuRatio() { 
    return cpuRatio; 
  } 
 
  public  void setCpuRatio( double cpuRatio) { 
    this .cpuRatio = cpuRatio; 
  } 
} 
 
次に、現在の監視情報を得るためのインターフェースを作成します。このクラスのコードは以下の通りです。

package com.amgkaka.performance; 
 
/** */ /** 
 *               . 
 * @author amg * @version 1.0  
 * Creation date: 2008-3-11 -   10:06:06 
 */  
public  interface IMonitorService { 
  /** */ /** 
   *          . 
   * @return            
   * @throws Exception 
   * @author amgkaka 
   * Creation date: 2008-4-25 -   10:45:08 
   */  
  public MonitorInfoBean getMonitorInfoBean() throws Exception; 
 
} 
  このクラスの実現タイプのMonitor ServiceImplは以下の通りです。

package com.amgkaka.performance; 
 
import java.io.InputStreamReader; 
import java.io.LineNumberReader; 
 
import sun.management.ManagementFactory; 
 
import com.sun.management.OperatingSystemMXBean; 
 
/** */ /** 
 *               . 
 * @author amg * @version 1.0 Creation date: 2008-3-11 -   10:06:06 
 */  
public  class MonitorServiceImpl implements IMonitorService { 
  //      ,              cpu   ,      
  private  static  final  int CPUTIME = 5000 ; 
 
  private  static  final  int PERCENT = 100 ; 
 
  private  static  final  int FAULTLENGTH = 10 ; 
 
  /** */ /** 
   *          . 
   * @return            
   * @throws Exception 
   * @author amg   * Creation date: 2008-4-25 -   10:45:08 
   */  
  public MonitorInfoBean getMonitorInfoBean() throws Exception { 
    int kb = 1024 ; 
     
    //        
    long totalMemory = Runtime.getRuntime().totalMemory() / kb; 
    //       
    long freeMemory = Runtime.getRuntime().freeMemory() / kb; 
    //          
    long maxMemory = Runtime.getRuntime().maxMemory() / kb; 
 
    OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory 
        .getOperatingSystemMXBean(); 
 
    //       
    String osName = System.getProperty("os.name" ); 
    //         
    long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb; 
    //          
    long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb; 
    //           
    long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb 
        .getFreePhysicalMemorySize()) 
        / kb; 
 
    //         
    ThreadGroup parentThread; 
    for (parentThread = Thread.currentThread().getThreadGroup(); parentThread 
        .getParent() != null ; parentThread = parentThread.getParent()) 
      ; 
    int totalThread = parentThread.activeCount(); 
 
    double cpuRatio = 0 ; 
    if (osName.toLowerCase().startsWith( "windows" )) { 
      cpuRatio = this .getCpuRatioForWindows(); 
    } 
     
    //         
    MonitorInfoBean infoBean = new MonitorInfoBean(); 
    infoBean.setFreeMemory(freeMemory); 
    infoBean.setFreePhysicalMemorySize(freePhysicalMemorySize); 
    infoBean.setMaxMemory(maxMemory); 
    infoBean.setOsName(osName); 
    infoBean.setTotalMemory(totalMemory); 
    infoBean.setTotalMemorySize(totalMemorySize); 
    infoBean.setTotalThread(totalThread); 
    infoBean.setUsedMemory(usedMemory); 
    infoBean.setCpuRatio(cpuRatio); 
    return infoBean; 
  } 
 
  /** */ /** 
   *   CPU   . 
   * @return   cpu    
   * @author amg   * Creation date: 2008-4-25 -   06:05:11 
   */  
  private  double getCpuRatioForWindows() { 
    try { 
      String procCmd = System.getenv("windir" ) 
          + "\\system32\\wbem\\wmic.exe process get Caption,CommandLine,"  
          + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount" ; 
      //        
      long [] c0 = readCpu(Runtime.getRuntime().exec(procCmd)); 
      Thread.sleep(CPUTIME); 
      long [] c1 = readCpu(Runtime.getRuntime().exec(procCmd)); 
      if (c0 != null && c1 != null ) { 
        long idletime = c1[ 0 ] - c0[ 0 ]; 
        long busytime = c1[ 1 ] - c0[ 1 ]; 
        return Double.valueOf( 
            PERCENT * (busytime) / (busytime + idletime)) 
            .doubleValue(); 
      } else { 
        return  0.0 ; 
      } 
    } catch (Exception ex) { 
      ex.printStackTrace(); 
      return  0.0 ; 
    } 
  } 
 
  /** */ /** 
   *   CPU  . 
   * @param proc 
   * @return 
   * @author amg   * Creation date: 2008-4-25 -   06:10:14 
   */  
  private  long [] readCpu( final Process proc) { 
    long [] retn = new  long [ 2 ]; 
    try { 
      proc.getOutputStream().close(); 
      InputStreamReader ir = new InputStreamReader(proc.getInputStream()); 
      LineNumberReader input = new LineNumberReader(ir); 
      String line = input.readLine(); 
      if (line == null || line.length() < FAULTLENGTH) { 
        return  null ; 
      } 
      int capidx = line.indexOf( "Caption" ); 
      int cmdidx = line.indexOf( "CommandLine" ); 
      int rocidx = line.indexOf( "ReadOperationCount" ); 
      int umtidx = line.indexOf( "UserModeTime" ); 
      int kmtidx = line.indexOf( "KernelModeTime" ); 
      int wocidx = line.indexOf( "WriteOperationCount" ); 
      long idletime = 0 ; 
      long kneltime = 0 ; 
      long usertime = 0 ; 
      while ((line = input.readLine()) != null ) { 
        if (line.length() < wocidx) { 
          continue ; 
        } 
        //       :Caption,CommandLine,KernelModeTime,ReadOperationCount,  
        // ThreadCount,UserModeTime,WriteOperation  
        String caption = Bytes.substring(line, capidx, cmdidx - 1 ) 
            .trim(); 
        String cmd = Bytes.substring(line, cmdidx, kmtidx - 1 ).trim(); 
        if (cmd.indexOf( "wmic.exe" ) >= 0 ) { 
          continue ; 
        } 
        // log.info("line="+line);  
        if (caption.equals( "System Idle Process" ) 
            || caption.equals("System" )) { 
          idletime += Long.valueOf( 
              Bytes.substring(line, kmtidx, rocidx - 1 ).trim()) 
              .longValue(); 
          idletime += Long.valueOf( 
              Bytes.substring(line, umtidx, wocidx - 1 ).trim()) 
              .longValue(); 
          continue ; 
        } 
 
        kneltime += Long.valueOf( 
            Bytes.substring(line, kmtidx, rocidx - 1 ).trim()) 
            .longValue(); 
        usertime += Long.valueOf( 
            Bytes.substring(line, umtidx, wocidx - 1 ).trim()) 
            .longValue(); 
      } 
      retn[0 ] = idletime; 
      retn[1 ] = kneltime + usertime; 
      return retn; 
    } catch (Exception ex) { 
      ex.printStackTrace(); 
    } finally { 
      try { 
        proc.getInputStream().close(); 
      } catch (Exception e) { 
        e.printStackTrace(); 
      } 
    } 
    return  null ; 
  } 
   
  /** */ /** 
   *     . 
   * @param args 
   * @throws Exception 
   * @author amg   * Creation date: 2008-4-30 -   04:47:29 
   */  
  public  static  void main(String[] args) throws Exception { 
    IMonitorService service = new MonitorServiceImpl(); 
    MonitorInfoBean monitorInfo = service.getMonitorInfoBean(); 
    System.out.println("cpu   =" + monitorInfo.getCpuRatio()); 
     
    System.out.println("     =" + monitorInfo.getTotalMemory()); 
    System.out.println("    =" + monitorInfo.getFreeMemory()); 
    System.out.println("       =" + monitorInfo.getMaxMemory()); 
     
    System.out.println("    =" + monitorInfo.getOsName()); 
    System.out.println("      =" + monitorInfo.getTotalMemorySize() + "kb" ); 
    System.out.println("       =" + monitorInfo.getFreeMemory() + "kb" ); 
    System.out.println("        =" + monitorInfo.getUsedMemory() + "kb" ); 
    System.out.println("    =" + monitorInfo.getTotalThread() + "kb" ); 
  } 
} 
 
この実装クラスでは、自分でbyteを作成するツールクラスが必要です。このクラスのコードは以下の通りです。

package com.amgkaka.performance; 
 
/** */ /** 
 * byte   . 
 * @author amg * @version 1.0  
 * Creation date: 2008-4-30 -   04:57:23 
 */  
public  class Bytes { 
  /** */ /** 
   *   String.subString         (           ),    
   *              ,     : 
   * @param src         
   * @param start_idx     (     ) 
   * @param end_idx      (     ) 
   * @return 
   */  
  public  static String substring(String src, int start_idx, int end_idx){ 
    byte [] b = src.getBytes(); 
    String tgt = "" ; 
    for ( int i=start_idx; i<=end_idx; i++){ 
      tgt +=(char )b[i]; 
    } 
    return tgt; 
  } 
} 
 
MonitorBenImpl類を実行すると、読者は現在のメモリ、cpuの利用率などの情報を見ることができます。
PS:LAN内のすべてのホスト名を取得する方法

import java.net.InetAddress;
import java.net.UnknownHostException;
public class A { 
 
 static public void main(String[] args) { 
 try {
   //        IP  
  InetAddress address = InetAddress.getByName("192.168.9.148");
  System.out.println("192.168.9.148"+": "+address.getHostAddress());
//    IP      
  String ips="192.168.9.",ip;
  InetAddress addip;
    for(int i=148;i<255;i++){
    ip=ips+i;  
    addip=InetAddress.getByName(ip); 
     System.out.println(ip+": "+addip.getHostName());
   
    }
  
   
   
  }
  catch(UnknownHostException uhe) {
  System.err.println("Unable to find: "+"192.168.9.148");
  }
 } 
 }