/*

Copyright (C) 2009 NTT DATA INTELLILINK CORPORATION

This program is free software; you can redistribute it and/or
Modify it under the terms of the GNU General Public License 
as published by the Free Software Foundation, version 2.

This program is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied 
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
PURPOSE.  See the GNU General Public License for more details.

 */

package jp.co.intellilink.hinemos.jmx;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import jp.co.intellilink.hinemos.jmx.util.Config;
import jp.co.intellilink.hinemos.jmx.util.Messages;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * JMXTool メインクラス<br>
 * 
 * @version 1.0.0
 * @since 1.0.0
 */
public class JMXTool {
	// ログ出力
	private static Log log = LogFactory.getLog(JMXTool.class);
	
	protected Timer timer = new Timer(true);
	
	private HashMap<String, String> mbeanMap = new HashMap<String, String>();
	
	public JMXTool(){
		for(int i = 1; i <= 100; i++){
			String name = Config.getConfig("MBean.Name." + i);
			String fileName = Config.getConfig("MBean.FileName." + i);
			if(name.length() > 0 && fileName.length() > 0){
				mbeanMap.put(name, fileName);
			}
			else{
				break;
			}
		}
	}

	/**
	 * メイン
	 * 
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		// 実行ログを記載
		log.info(Messages.getMsg("JMXTool.Exec"));
		
		JMXTool jmxtool = new JMXTool();
		jmxtool.exec();
		
		//終了待ち
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		while (true) {
			try {
				String line = br.readLine();
				if (line.equals("quit") ) {
					break;
				}
			} catch (Exception e) {
			}
			synchronized (jmxtool) {
				jmxtool.wait();
            } 
		}
		
		jmxtool.terminate();

		// 正常終了
		log.info(Messages.getMsg("JMXTool.Exit"));
		System.exit(0);
	}
	
	/**
	 * 実行処理<BR>
	 */
	public void exec() {
		String intervalString = Config.getConfig("Interval");
		Long interval = Long.parseLong(intervalString);
		
		//タイマー開始
		timer.schedule(new CheckTask(), interval, interval);
	}
	
	/**
	 * 終了処理<BR>
	 */
	public void terminate() {
		timer.cancel();
	}
	
	/**
	 * JMX情報取得<BR>
	 */
	public void check() {
		OutputMBeanAttribute jms = new OutputMBeanAttribute();
		for(String name : mbeanMap.keySet()){
			jms.check(name, mbeanMap.get(name));
		}
	}
	
	/**
	 * JMX情報取得タイマータスク<BR>
	 */
	protected class CheckTask extends TimerTask {

		public void run() {
			check();
		}
	}
}
