/*
 * Copyright 2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gradle.launcher.daemon.server.health;

import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.InvocationTargetException;

class MemoryInfo {

    private final long totalMemory; //this does not change

    MemoryInfo() {
        totalMemory = Runtime.getRuntime().maxMemory();
    }

    /**
     * Approx. time spent in gc. See {@link GarbageCollectorMXBean}
     */
    public long getCollectionTime() {
        long garbageCollectionTime = 0;
        for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
            long time = gc.getCollectionTime();
            if (time >= 0) {
                garbageCollectionTime += time;
            }
        }
        return garbageCollectionTime;
    }

    /**
     * Max memory that this process can commit in bytes. Always returns the same value because maximum memory is determined at jvm start.
     */
    public long getMaxMemory() {
        return totalMemory;
    }

    /**
     * Currently committed memory of this process in bytes. May return different value depending on how the heap has expanded. The returned value is <= {@link #getMaxMemory()}
     */
    public long getCommittedMemory() {
        //querying runtime for each invocation
        return Runtime.getRuntime().totalMemory();
    }

    /**
     * Retrieves the total physical memory size on the system in bytes. This value is independent of {@link #getMaxMemory()}, which is the total memory available to the JVM.
     *
     * @throws UnsupportedOperationException if the JVM doesn't support getting total physical memory.
     */
    public long getTotalPhysicalMemory() {
        return sunBean("getTotalPhysicalMemorySize");
    }

    /**
     * Retrieves the free physical memory on the system in bytes. This value is independent of {@link #getCommittedMemory()}, which is the memory reserved by the JVM.
     *
     * @throws UnsupportedOperationException if the JVM doesn't support getting free physical memory.
     */
    public long getFreePhysicalMemory() {
        return sunBean("getFreePhysicalMemorySize");
    }

    /**
     * Reflectively runs an Oracle JVM specific OS method if available.
     *
     * @throws UnsupportedOperationException if this method isn't available on this JVM.
     */
    private static long sunBean(String methodName) {
        OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean();

        Throwable rootCause = null;
        ClassLoader beanLoader = ClassLoader.getSystemClassLoader();
        try {
            Class<?> osbean = beanLoader.loadClass("com.sun.management.OperatingSystemMXBean");
            return (Long) osbean.getMethod(methodName).invoke(bean);
        } catch (IllegalAccessException e) {
            rootCause = e;
        } catch (InvocationTargetException e) {
            rootCause = e;
        } catch (NoSuchMethodException e) {
            rootCause = e;
        } catch (ClassNotFoundException e) {
            rootCause = e;
        }
        throw new UnsupportedOperationException(methodName + " is unsupported on this JVM.", rootCause);
    }
}

@@ -672,98 +672,311 @@
 ort 
-java.lang.management.GarbageCollectorMXBean;%0Aimport java.lang.management.ManagementFactory
+org.gradle.internal.Cast;%0A%0Aimport javax.management.AttributeNotFoundException;%0Aimport javax.management.InstanceNotFoundException;%0Aimport javax.management.MBeanException;%0Aimport javax.management.MalformedObjectNameException;%0Aimport javax.management.ObjectName;%0Aimport javax.management.ReflectionException
 ;%0Aim
@@ -997,39 +997,40 @@
 .management.
-OperatingSystem
+GarbageCollector
 MXBean;%0Aimpo
@@ -1046,41 +1046,36 @@
 ang.
-reflect.InvocationTargetException
+management.ManagementFactory
 ;%0A%0Ac
@@ -2597,28 +2597,69 @@
  return 
-sunBean(%22get
+getMbeanAttribute(%22java.lang:type=OperatingSystem%22, %22
 TotalPhy
@@ -2666,32 +2666,44 @@
 sicalMemorySize%22
+, Long.class
 );%0A    %7D%0A%0A    /*
@@ -3049,20 +3049,61 @@
 urn 
-sunBean(%22get
+getMbeanAttribute(%22java.lang:type=OperatingSystem%22, %22
 Free
@@ -3121,16 +3121,28 @@
 orySize%22
+, Long.class
 );%0A    %7D
@@ -3162,51 +3162,22 @@
   * 
-Reflectively runs an Oracle JVM specific OS
+Calls an mbean
  met
@@ -3321,245 +3321,191 @@
 tic 
-long sunBean(String methodName) %7B%0A        OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean();%0A%0A        Throwable rootCause = null;%0A        ClassLoader beanLoader = ClassLoader.getSystemClassLoader();%0A        try %7B%0A
+%3CT%3E T getMbeanAttribute(String mbean, final String attribute, Class%3CT%3E type) %7B%0A        Exception rootCause;%0A        try %7B%0A            ObjectName objectName = new ObjectName(mbean);%0A  
     
@@ -3514,161 +3514,185 @@
     
- 
+return
  C
-l
 as
-s%3C?%3E osbean = beanLoader.loadClass(%22com.sun.management.OperatingSystemMXBean%22);%0A            return (Long) osbean.getMethod(methodName).invoke(bean)
+t.cast(type, ManagementFactory.getPlatformMBeanServer().getAttribute(objectName, attribute));%0A        %7D catch (InstanceNotFoundException e) %7B%0A            rootCause = e
 ;%0A  
@@ -3710,21 +3710,18 @@
 ch (
-IllegalAccess
+Reflection
 Exce
@@ -3779,24 +3779,27 @@
 ch (
-InvocationTarget
+MalformedObjectName
 Exce
@@ -3857,20 +3857,13 @@
 ch (
-NoSuchMethod
+MBean
 Exce
@@ -3917,21 +3917,25 @@
  catch (
-Class
+Attribute
 NotFound
@@ -3941,33 +3941,32 @@
 dException e) %7B%0A
- 
            rootC
@@ -4037,17 +4037,37 @@
 ion(
-methodNam
+%22(%22 + mbean + %22).%22 + attribut
 e + 

Change OS memory calls to work around IBM JDK8 issues