All Downloads are FREE. Search and download functionalities are using the official Maven repository.

fi.evolver.basics.spring.status.component.ServerStatusReporter Maven / Gradle / Ivy

package fi.evolver.basics.spring.status.component;

import fi.evolver.basics.spring.status.model.ComponentStatus;
import fi.evolver.basics.spring.status.model.Reportable;
import fi.evolver.basics.spring.status.model.ReportableScope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.management.*;
import java.lang.management.ManagementFactory;
import java.util.List;
import java.util.Map;

/**
 * Report basic status info about the platform and system.
 */
@Component
public class ServerStatusReporter implements Reportable {
	private static final Logger LOG = LoggerFactory.getLogger(ServerStatusReporter.class);
	private final MBeanServer mbeanServer;

	public ServerStatusReporter() {
		this.mbeanServer = ManagementFactory.getPlatformMBeanServer();
	}

	@Override
	public List getStatus() {

		try {
			// Name and uptime
			ObjectName runtimeObjectName = new ObjectName("java.lang:type=Runtime");
			String name = (String) mbeanServer.getAttribute(runtimeObjectName, "Name");
			Long uptime = (Long) mbeanServer.getAttribute(runtimeObjectName, "Uptime");

			// System load
			ObjectName platformObjectName = new ObjectName("java.lang:type=OperatingSystem");
			Double systemLoad = (Double) mbeanServer.getAttribute(platformObjectName, "SystemLoadAverage");

			// Heap usage
			long totalMem = Runtime.getRuntime().totalMemory();
			long maxMem = Runtime.getRuntime().maxMemory();
			long freeMem = Runtime.getRuntime().freeMemory();
			long usedMem = totalMem - freeMem;

			return List.of(new ComponentStatus("ServerStatus", getClass().getSimpleName(), Map.of(
							"Name", name,
							"SystemLoadAverage", systemLoad,
							"MemUsed", usedMem,
							"MemMax", maxMem,
							"MemTotal", totalMem,
							"MemFree", freeMem,
							"Uptime", uptime)));

		} catch (ReflectionException | MalformedObjectNameException | AttributeNotFoundException |
				 InstanceNotFoundException | MBeanException e) {
			LOG.error("Failed to get status info", e);
			return List.of();
		}
	}

	@Override
	public ReportableScope getReportableScope() {
		return ReportableScope.INSTANCE;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy