package gov.va.med.esr.common.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.naming.Context;

import junit.framework.TestCase;

import org.apache.commons.logging.LogFactory;

import weblogic.jndi.Environment;
import weblogic.management.MBeanHome;
import weblogic.management.WebLogicMBean;
import weblogic.management.WebLogicObjectName;

public class TestWeblogicJMXGetMBeans extends TestCase {
	public void testGetAll() throws Exception {
		/*
		 * TODO: how do you override the default Weblogic t3 timeout?
		 */
		
		String url = "t3://localhost:7001";
		String username = "weblogic";
		String password = "weblogic";
		
		try {
			// Obtaining an MBeanHome Using JNDI
			Environment env = new Environment();
			env.setProviderUrl(url);
			env.setSecurityPrincipal(username);
			env.setSecurityCredentials(password);
			Context ctx = env.getInitialContext();
			MBeanHome home = (MBeanHome) ctx.lookup(MBeanHome.ADMIN_JNDI_NAME);

			Set allMBeans = home.getAllMBeans();
			System.out.println("Size: " + allMBeans.size());
			List list = new ArrayList();
			Map typeCounts =  new HashMap();
			for (Iterator itr = allMBeans.iterator(); itr.hasNext();) {
				WebLogicMBean mbean = (WebLogicMBean) itr.next();
				WebLogicObjectName objectName = mbean.getObjectName();
				Integer count = (Integer) typeCounts.get(mbean.getType());
				if(count == null) {
					typeCounts.put(mbean.getType(), new Integer(1));
				} else {
					typeCounts.put(mbean.getType(), new Integer(count.intValue() + 1));
				}
				list.add(objectName + "#" + mbean.getType());
			}
			Collections.sort(list);
			LogFactory.getLog(getClass()).error("Total Size: " + allMBeans.size());
			LogFactory.getLog(getClass()).error("JMSConnectionRuntime Size: " + typeCounts.get("JMSConnectionRuntime"));
			LogFactory.getLog(getClass()).error("JMSConsumerRuntime Size: " + typeCounts.get("JMSConsumerRuntime"));
			LogFactory.getLog(getClass()).error("JMSSessionRuntime Size: " + typeCounts.get("JMSSessionRuntime"));
			LogFactory.getLog(getClass()).error("JMSQueueConfig Size: " + typeCounts.get("JMSQueueConfig"));
			LogFactory.getLog(getClass()).error("ServletRuntime Size: " + typeCounts.get("ServletRuntime"));
			
			LogFactory.getLog(getClass()).error(typeCounts);
			for(Iterator itr = list.iterator() ; itr.hasNext();) {
				LogFactory.getLog(getClass()).error(itr.next());
			}
		} catch (Exception e) {
			System.out.println(e);
		}
	}
}
