import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * Check the CPU to find out if the page has finished loading.
 * @author JPR
 *
 */
public class CPUController {

	/**
	 * Constructor
	 */
	public CPUController() {
	}

	/**
	 * return the percentage of CPU usage
	 * @param page used in logs
	 * @return the percentage of CPU usage
	 */
	public float cpuController(int page) {
		Float temp = Float.valueOf(1.0F);
		Object value = null;
		OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
		Method amethod[];
		int j = (amethod = operatingSystemMXBean.getClass().getDeclaredMethods()).length;
		for (int i = 0; i < j; i++) {
			Method method = amethod[i];
			method.setAccessible(true);
			if (method.getName().startsWith("getSystemCpuLoad") && Modifier.isPublic(method.getModifiers()))
				try {
					value = method.invoke(operatingSystemMXBean, new Object[0]);
					// LoggerInfo li = new LoggerInfo((new StringBuilder(" - Page Number: ")).append(page).append(" CPU Value: ").append(value.toString()).toString());
					temp = Float.valueOf(value.toString());
					return temp.floatValue();
				} catch (Exception e) {
					value = e;
				}
		}

		if (value != null)
			temp = Float.valueOf(value.toString());
		return temp.floatValue();
	}
}