Created
September 30, 2014 14:50
-
-
Save Sythelux/5f407659d077e105f49f to your computer and use it in GitHub Desktop.
SystemInformationProvider will provide Information about for example jvm mem or cpu...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.lang.management.ManagementFactory; | |
import java.text.DecimalFormat; | |
import java.text.NumberFormat; | |
import java.util.Locale; | |
import java.util.concurrent.TimeUnit; | |
import org.apache.log4j.BasicConfigurator; | |
import org.apache.log4j.Logger; | |
import com.sun.management.OperatingSystemMXBean;//TODO: package could be removed in future relaeses | |
/** <p> | |
* This Class provides some Methods for easy access of System relevant informations like CPU, RAM, HDD usage. | |
* </p> | |
* <p> | |
* <b>Note, that this class uses the package: {@link com.sun.management.OperatingSystemMXBean } which is noted as to be removed in the Future:</b> | |
* </p> | |
* | |
* @see <a href="http://en.wikipedia.org/wiki/Binary_prefix">Binary prefix</a> for questions about this strange GiB, MiB instead of GB, MB | |
* @author Aron Schaub */ | |
public class SystemInformationProvider { | |
private static final Logger Log = Logger.getLogger(SystemInformationProvider.class); | |
private String infoSpacer = " / "; | |
private String newLine = "\n"; | |
private final OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class); | |
private final Runtime runtime = Runtime.getRuntime(); | |
/** returns the core count of CPUs | |
* | |
* @return */ | |
public String getCPUCount() { | |
return getCPUCountRaw() + ""; | |
} | |
/** returns the core count of CPUs | |
* | |
* @return */ | |
public long getCPUCountRaw() { | |
return runtime.availableProcessors(); | |
} | |
/** returns the free and the usable space of HDD. | |
* | |
* @param hdd | |
* @return */ | |
public String getHDDFree(File hdd) { | |
return formatBinaryByte(hdd.getFreeSpace()) + infoSpacer + formatBinaryByte(hdd.getUsableSpace()); | |
} | |
/** returns the Free Space of HDD. | |
* | |
* @param hdd | |
* @return */ | |
public long getHDDFreeRaw(File hdd) { | |
return hdd.getFreeSpace(); | |
} | |
/** returns the most important information of given HDDs. | |
* | |
* @param hdds | |
* @return */ | |
public String getHDDInfo(File... hdds) { | |
StringBuilder sb = new StringBuilder("Count: ").append(hdds.length).append(newLine).append("\t"); | |
for (File file : hdds) { | |
sb.append(getHDDInfo(file).replace(newLine, newLine + "\t")).append(newLine); | |
} | |
return sb.toString(); | |
} | |
/** builds an Informationstring of the given HDD. which are: hook path, free space, used space, total size. | |
* | |
* @param hdd | |
* @return String like: "absolutePath: /\nFree: 425,1GiB / 402,1GiB (total/usable)\nUsed: 27,8GiB\nSize: 452,9GiB" instead of \n it will use {@link #setNewLine(java.lang.String) } */ | |
public String getHDDInfo(File hdd) { | |
StringBuilder sb = new StringBuilder("absolutePath: ").append(hdd.getAbsolutePath()).append(newLine); | |
sb.append("Free: ").append(getHDDFree(hdd)).append(" (total/usable)").append(newLine); | |
sb.append("Used: ").append(getHDDUsed(hdd)).append(newLine); | |
sb.append("Size: ").append(getHDDTotal(hdd)).append(newLine); | |
return sb.toString(); | |
} | |
/** returns total Space of HDD. | |
* | |
* @param hdd | |
* @return */ | |
public String getHDDTotal(File hdd) { | |
long maxMemory = hdd.getTotalSpace(); | |
return maxMemory == Long.MAX_VALUE ? "no limit" : formatBinaryByte(maxMemory); | |
} | |
/** returns total Space of HDD. | |
* | |
* @param hdd | |
* @return */ | |
public long getHDDTotalRaw(File hdd) { | |
return hdd.getTotalSpace(); | |
} | |
/** returns the Usable Space of HDD. | |
* | |
* @param hdd | |
* @return */ | |
public long getHDDUsableRaw(File hdd) { | |
return hdd.getUsableSpace(); | |
} | |
/** returns used Space of HDD. | |
* | |
* @param hdd | |
* @return */ | |
public String getHDDUsed(File hdd) { | |
return formatBinaryByte(hdd.getTotalSpace() - hdd.getFreeSpace()); | |
} | |
/** returns used Space of HDD. | |
* | |
* @param hdd | |
* @return */ | |
public long getHDDUsedRaw(File hdd) { | |
return hdd.getTotalSpace() - hdd.getFreeSpace(); | |
} | |
/** returns free Memory allocated by JVM | |
* | |
* @return formatted free Memory */ | |
public String getJVMMemFree() { | |
return formatBinaryByte(getJVMMemFreeRaw()); | |
} | |
/** returns the free Memory allocated by JVM | |
* | |
* @return free memory in bytes */ | |
public long getJVMMemFreeRaw() { | |
return runtime.freeMemory(); | |
} | |
/** returns percentage formatted memoryload | |
* | |
* @return */ | |
public String getJVMMemLoad() { | |
return formatPercentage(getJVMMemLoadRaw()); | |
} | |
/** The JVM memory load of this programm it's basically max memory divided by used memory | |
* | |
* @return value between 0...1 or negativ value if not supported */ | |
public double getJVMMemLoadRaw() { | |
return ((float) getJVMMemUsedRaw() / (float) getJVMMemMaxRaw()); | |
} | |
/** returns the maximum Memory the JVM can allocate | |
* | |
* @return String like "65MiB" or "no limit" */ | |
public String getJVMMemMax() { | |
long maxMemory = getJVMMemMaxRaw(); | |
return maxMemory == Long.MAX_VALUE ? "no limit" : formatBinaryByte(maxMemory); | |
} | |
/** returns the maximum Memory the JVM can allocate | |
* | |
* @return */ | |
public long getJVMMemMaxRaw() { | |
return runtime.maxMemory(); | |
} | |
/** returns the Memory used within JVM | |
* | |
* @return */ | |
public String getJVMMemUsed() { | |
return formatBinaryByte(getJVMMemUsedRaw()); | |
} | |
/** returns the Memory used within JVM | |
* | |
* @return total memory - free memory in byte */ | |
public long getJVMMemUsedRaw() { | |
return runtime.totalMemory() - runtime.freeMemory(); | |
} | |
/** returns the Physical Memory the System has left. | |
* | |
* @return */ | |
public String getPhysMemFree() { | |
return formatBinaryByte(getPhysMemFreeRaw()); | |
} | |
/** returns the Physical Memory the System has left. | |
* | |
* @return */ | |
public long getPhysMemFreeRaw() { | |
return osBean.getFreePhysicalMemorySize(); | |
} | |
/** returns the total Physical memory. | |
* | |
* @return */ | |
public String getPhysMemTotal() { | |
return formatBinaryByte(getPhysMemTotalRaw()); | |
} | |
/** returns the total Physical Memory. | |
* | |
* @return */ | |
public long getPhysMemTotalRaw() { | |
return osBean.getTotalPhysicalMemorySize(); | |
} | |
/** returns how much CPU the Process needs. | |
* | |
* @return String like: "65%" or "not supported" */ | |
public String getProcessCPULoad() { // TODO: package could be removed in future relaeses. | |
double ret = getProcessCPULoadRaw(); | |
// double ret = -1; | |
if (ret < 0) { return "not supported"; } | |
return formatPercentage(ret); | |
} | |
/** returns how much CPU the Process needs. | |
* | |
* @return value between 0...1 or -1 if not supported */ | |
public double getProcessCPULoadRaw() { | |
return osBean.getProcessCpuLoad(); | |
} | |
/** returns the CPU of this Process. | |
* | |
* @return String like "800millis" or "not supported" */ | |
public String getProcessCPUTime() { | |
long ret = getProcessCPUTimeRaw(); | |
// long ret =-1; | |
if (ret < 0) { return "not supported"; } | |
return formatNanos(ret); | |
} | |
/** returns the CPU of this Process. | |
* | |
* @return value in nanos or -1 if not supported */ | |
public long getProcessCPUTimeRaw() { | |
return osBean.getProcessCpuTime(); | |
} | |
/** returns free percentage of CPU. | |
* | |
* @return String like: "65%" or "not supported" */ | |
public String getSystemCPUFree() { // TODO: package could be removed in future relaeses. | |
double ret = getSystemCPUFreeRaw(); | |
// double ret = -1; | |
if (ret > 1) { return "not supported"; } | |
return formatPercentage(getSystemCPUFreeRaw()); | |
} | |
/** returns free percentage of CPU. | |
* | |
* @return value between 0...{@link #getCPUCountRaw() } or negative if not supported. */ | |
public double getSystemCPUFreeRaw() { | |
double val = osBean.getSystemLoadAverage(); | |
if (val < 0) { return val; } | |
return getCPUCountRaw() - val; | |
} | |
/** percentage how much the CPU load currently is. | |
* | |
* @return String like "49%" or "not supported" */ | |
public String getSystemCPULoad() { // TODO: package could be removed in future relaeses. | |
double ret = getSystemCPULoadRaw(); | |
// double ret = -1; | |
if (ret < 0) { return "not supported"; } | |
return formatPercentage(ret); | |
} | |
/** percentage how much the CPU load currently is. | |
* | |
* @return 0...1.0 maybe above 1.0 if more than 1 core. can be -1 if not supported. */ | |
public double getSystemCPULoadRaw() { | |
return osBean.getSystemLoadAverage(); | |
} | |
/** Logs all informations to Logger. */ | |
public void logAllInformation() { | |
// Log.debug("Physical Memory(abs): "+osBean.getTotalPhysicalMemorySize()); | |
// Log.debug("Physical Memory(bin): "+formatBinaryByte(osBean.getTotalPhysicalMemorySize())); | |
// Log.debug("Physical Memory(dec): "+formatDecimalByte(osBean.getTotalPhysicalMemorySize())); | |
for (String s : returnAllInformation().split(newLine)) { | |
Log.debug(s); | |
} | |
} | |
/** builds a String with all Informations provided by all getters in this Class. | |
* | |
* @return */ | |
public String returnAllInformation() { | |
StringBuilder sb = new StringBuilder(getClass().getSimpleName()).append(newLine); | |
sb.append("CPU Core count: ").append(getCPUCount()).append(newLine); | |
sb.append("CPU Load(Processload/Systemload): ").append(getProcessCPULoad()).append(infoSpacer).append(getSystemCPULoad()).append(newLine); | |
sb.append("CPU Time: ").append(getProcessCPUTime()).append(newLine); | |
sb.append("MEM Usage(used/free/max/load): ").append(getJVMMemUsed()).append(infoSpacer).append(getJVMMemFree()).append(infoSpacer).append(getJVMMemMax()).append(infoSpacer).append(getJVMMemLoad()).append(newLine); | |
sb.append("HDDs: ").append(getHDDInfo(File.listRoots())); | |
if (sb.toString().endsWith("\t" + newLine)) { | |
return sb.toString().replace("\t" + newLine, ""); | |
} else if (sb.toString().endsWith(newLine)) { | |
return sb.toString().replace(newLine, ""); | |
} else { | |
return sb.toString(); | |
} | |
} | |
/** setter for new line... if you want for example <br /> instead of \n ... no problem. | |
* | |
* @param newLine */ | |
public void setNewLine(String newLine) { | |
this.newLine = newLine; | |
} | |
private static DecimalFormat provideDF() { | |
NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH); | |
return (DecimalFormat) nf; | |
} | |
/** formats given byte with 1024 exchange ratio. up to exabinary byte (EiB) | |
* | |
* @param size given value, that should be formatted. | |
* @return formatted byte. String like "638.2MiB". will consider regionspecific formatting ("."->"," for german). Negativ values will return "0" */ | |
public static String formatBinaryByte(long size) { | |
if (size <= 0) { return "0"; } | |
final String[] units = new String[] { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB" }; // http://physics.nist.gov/cuu/Units/binary.html | |
int digitGroups = (int) (Math.log10(size) / Math.log10(1024)); | |
return provideDF().format(size / Math.pow(1024, digitGroups)) + units[digitGroups]; | |
} | |
/** formats given byte with 1000 exchange ratio. up to exa byte (EiB) | |
* | |
* @param size given value, that should be formatted. | |
* @return formatted byte. String like "638.2MiB". will consider regionspecific formatting ("."->"," for german). Negativ values will return "0" */ | |
public static String formatDecimalByte(long size) { | |
if (size <= 0) { return "0"; } | |
final String[] units = new String[] { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; // http://physics.nist.gov/cuu/Units/binary.html | |
int digitGroups = (int) (Math.log10(size) / Math.log10(1000)); | |
return provideDF().format(size / Math.pow(1000, digitGroups)) + units[digitGroups]; | |
} | |
/** formats given nanoSeconds up to Seconds. | |
* | |
* @param nanos | |
* @return String like: "100millis" */ | |
public static String formatNanos(long nanos) { | |
if (nanos <= 0) { return "0"; } | |
final String[] units = new String[] { "nanos", "micros", "millis", "s" }; | |
int digitGroups = (int) (Math.log10(nanos) / Math.log10(1000)); | |
if (digitGroups > 3) { | |
long millis = nanos / 1000000; | |
return String.format("%dd %02dh %02dm %02ds", TimeUnit.MILLISECONDS.toDays(millis), TimeUnit.MILLISECONDS.toHours(millis) - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(millis)), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); | |
} | |
return provideDF().format(nanos / Math.pow(1000, digitGroups)) + units[digitGroups]; | |
} | |
/** multiplies value with 100 and adds a "%" | |
* | |
* @param floated a value between 0...1 | |
* @return String like: "95%" */ | |
public static String formatPercentage(double floated) { | |
return provideDF().format(Math.round(floated * 10000.0) / 100.0) + "%"; | |
} | |
/** this main provides an example, how this class could be used. | |
* | |
* @param args won't be used. | |
* @throws InterruptedException */ | |
public static void main(String[] args) throws InterruptedException { | |
// DOMConfigurator.configure("log4jdatalog.xml"); | |
BasicConfigurator.configure(); | |
SystemInformationProvider si = new SystemInformationProvider(); | |
// si.setNewLine("<br />"); | |
si.logAllInformation(); | |
int maxloopTime = 60 + 1; | |
long deltaT = 0; | |
StringBuilder sb = new StringBuilder(); | |
for (int i = 0; i < maxloopTime; i++) { | |
deltaT = System.currentTimeMillis(); | |
sb.append("CPU Load(Processload/Systemload): ").append(si.getProcessCPULoad()).append(si.infoSpacer).append(si.getSystemCPULoad()).append(si.newLine); | |
sb.append("CPU Time: ").append(si.getProcessCPUTime()).append(si.newLine); | |
sb.append("MEM Usage(used/free/max/load): ").append(si.getJVMMemUsed()).append(si.infoSpacer).append(si.getJVMMemFree()).append(si.infoSpacer).append(si.getJVMMemMax()).append(si.infoSpacer).append(si.getJVMMemLoad()).append(si.newLine); | |
for (String s : sb.toString().split(si.newLine)) { | |
Log.debug(s); | |
} | |
sb.delete(0, sb.length()); | |
deltaT = Math.max(1000l - (System.currentTimeMillis() - deltaT), 0l); | |
Log.debug("sleeping for " + deltaT + " Milliseconds (" + (i + 1) + "/" + maxloopTime + ", in loop)"); | |
Thread.sleep(deltaT); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment