proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/mac/MacLogicalVolumeGroup.java
MacLogicalVolumeGroup
getLogicalVolumeGroups
class MacLogicalVolumeGroup extends AbstractLogicalVolumeGroup { private static final String DISKUTIL_CS_LIST = "diskutil cs list"; private static final String LOGICAL_VOLUME_GROUP = "Logical Volume Group"; private static final String PHYSICAL_VOLUME = "Physical Volume"; private static final String LOGICAL_VOLUME = "Logical Volume"; MacLogicalVolumeGroup(String name, Map<String, Set<String>> lvMap, Set<String> pvSet) { super(name, lvMap, pvSet); } static List<LogicalVolumeGroup> getLogicalVolumeGroups() {<FILL_FUNCTION_BODY>} }
Map<String, Map<String, Set<String>>> logicalVolumesMap = new HashMap<>(); Map<String, Set<String>> physicalVolumesMap = new HashMap<>(); String currentVolumeGroup = null; boolean lookForVGName = false; boolean lookForPVName = false; int indexOf; // Parse `diskutil cs list` to populate logical volume map for (String line : ExecutingCommand.runNative(DISKUTIL_CS_LIST)) { if (line.contains(LOGICAL_VOLUME_GROUP)) { // Disks that follow should be attached to this VG lookForVGName = true; } else if (lookForVGName) { indexOf = line.indexOf("Name:"); if (indexOf >= 0) { currentVolumeGroup = line.substring(indexOf + 5).trim(); lookForVGName = false; } } else if (line.contains(PHYSICAL_VOLUME)) { lookForPVName = true; } else if (line.contains(LOGICAL_VOLUME)) { lookForPVName = false; } else { indexOf = line.indexOf("Disk:"); if (indexOf >= 0) { if (lookForPVName) { physicalVolumesMap.computeIfAbsent(currentVolumeGroup, k -> new HashSet<>()) .add(line.substring(indexOf + 5).trim()); } else { logicalVolumesMap.computeIfAbsent(currentVolumeGroup, k -> new HashMap<>()) .put(line.substring(indexOf + 5).trim(), Collections.emptySet()); } } } } return logicalVolumesMap.entrySet().stream() .map(e -> new MacLogicalVolumeGroup(e.getKey(), e.getValue(), physicalVolumesMap.get(e.getKey()))) .collect(Collectors.toList());
180
490
670
<methods>public Map<java.lang.String,Set<java.lang.String>> getLogicalVolumes() ,public java.lang.String getName() ,public Set<java.lang.String> getPhysicalVolumes() ,public java.lang.String toString() <variables>private final non-sealed Map<java.lang.String,Set<java.lang.String>> lvMap,private final non-sealed java.lang.String name,private final non-sealed Set<java.lang.String> pvSet
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/mac/MacNetworkIF.java
MacNetworkIF
getNetworks
class MacNetworkIF extends AbstractNetworkIF { private static final Logger LOG = LoggerFactory.getLogger(MacNetworkIF.class); private int ifType; private long bytesRecv; private long bytesSent; private long packetsRecv; private long packetsSent; private long inErrors; private long outErrors; private long inDrops; private long collisions; private long speed; private long timeStamp; public MacNetworkIF(NetworkInterface netint, Map<Integer, IFdata> data) throws InstantiationException { super(netint, queryIfDisplayName(netint)); updateNetworkStats(data); } private static String queryIfDisplayName(NetworkInterface netint) { String name = netint.getName(); CFArrayRef ifArray = SystemConfiguration.INSTANCE.SCNetworkInterfaceCopyAll(); if (ifArray != null) { try { int count = ifArray.getCount(); for (int i = 0; i < count; i++) { Pointer pNetIf = ifArray.getValueAtIndex(i); SCNetworkInterfaceRef scNetIf = new SCNetworkInterfaceRef(pNetIf); CFStringRef cfName = SystemConfiguration.INSTANCE.SCNetworkInterfaceGetBSDName(scNetIf); if (cfName != null && name.equals(cfName.stringValue())) { CFStringRef cfDisplayName = SystemConfiguration.INSTANCE .SCNetworkInterfaceGetLocalizedDisplayName(scNetIf); return cfDisplayName.stringValue(); } } } finally { ifArray.release(); } } return name; } /** * Gets all network interfaces on this machine * * @param includeLocalInterfaces include local interfaces in the result * @return A list of {@link NetworkIF} objects representing the interfaces */ public static List<NetworkIF> getNetworks(boolean includeLocalInterfaces) {<FILL_FUNCTION_BODY>} @Override public int getIfType() { return this.ifType; } @Override public long getBytesRecv() { return this.bytesRecv; } @Override public long getBytesSent() { return this.bytesSent; } @Override public long getPacketsRecv() { return this.packetsRecv; } @Override public long getPacketsSent() { return this.packetsSent; } @Override public long getInErrors() { return this.inErrors; } @Override public long getOutErrors() { return this.outErrors; } @Override public long getInDrops() { return this.inDrops; } @Override public long getCollisions() { return this.collisions; } @Override public long getSpeed() { return this.speed; } @Override public long getTimeStamp() { return this.timeStamp; } @Override public boolean updateAttributes() { int index = queryNetworkInterface().getIndex(); return updateNetworkStats(NetStat.queryIFdata(index)); } /** * Updates interface network statistics on the given interface. Statistics include packets and bytes sent and * received, and interface speed. * * @param data A map of network interface statistics with the index as the key * @return {@code true} if the update was successful, {@code false} otherwise. */ private boolean updateNetworkStats(Map<Integer, IFdata> data) { int index = queryNetworkInterface().getIndex(); if (data.containsKey(index)) { IFdata ifData = data.get(index); // Update data this.ifType = ifData.getIfType(); this.bytesSent = ifData.getOBytes(); this.bytesRecv = ifData.getIBytes(); this.packetsSent = ifData.getOPackets(); this.packetsRecv = ifData.getIPackets(); this.outErrors = ifData.getOErrors(); this.inErrors = ifData.getIErrors(); this.collisions = ifData.getCollisions(); this.inDrops = ifData.getIDrops(); this.speed = ifData.getSpeed(); this.timeStamp = ifData.getTimeStamp(); return true; } return false; } }
// One time fetch of stats final Map<Integer, IFdata> data = NetStat.queryIFdata(-1); List<NetworkIF> ifList = new ArrayList<>(); for (NetworkInterface ni : getNetworkInterfaces(includeLocalInterfaces)) { try { ifList.add(new MacNetworkIF(ni, data)); } catch (InstantiationException e) { LOG.debug("Network Interface Instantiation failed: {}", e.getMessage()); } } return ifList;
1,144
128
1,272
<methods>public java.lang.String getDisplayName() ,public java.lang.String[] getIPv4addr() ,public java.lang.String[] getIPv6addr() ,public int getIndex() ,public long getMTU() ,public java.lang.String getMacaddr() ,public java.lang.String getName() ,public java.lang.Short[] getPrefixLengths() ,public java.lang.Short[] getSubnetMasks() ,public boolean isKnownVmMacAddr() ,public java.net.NetworkInterface queryNetworkInterface() ,public java.lang.String toString() <variables>private static final org.slf4j.Logger LOG,private static final java.lang.String OSHI_VM_MAC_ADDR_PROPERTIES,private java.lang.String displayName,private int index,private java.lang.String[] ipv4,private java.lang.String[] ipv6,private java.lang.String mac,private long mtu,private java.lang.String name,private java.net.NetworkInterface networkInterface,private java.lang.Short[] prefixLengths,private java.lang.Short[] subnetMasks,private final Supplier<java.util.Properties> vmMacAddrProps
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/mac/MacSensors.java
MacSensors
queryCpuVoltage
class MacSensors extends AbstractSensors { // This shouldn't change once determined private int numFans = 0; @Override public double queryCpuTemperature() { IOConnect conn = SmcUtil.smcOpen(); double temp = SmcUtil.smcGetFloat(conn, SmcUtil.SMC_KEY_CPU_TEMP); SmcUtil.smcClose(conn); if (temp > 0d) { return temp; } return 0d; } @Override public int[] queryFanSpeeds() { // If we don't have fan # try to get it IOConnect conn = SmcUtil.smcOpen(); if (this.numFans == 0) { this.numFans = (int) SmcUtil.smcGetLong(conn, SmcUtil.SMC_KEY_FAN_NUM); } int[] fanSpeeds = new int[this.numFans]; for (int i = 0; i < this.numFans; i++) { fanSpeeds[i] = (int) SmcUtil.smcGetFloat(conn, String.format(Locale.ROOT, SmcUtil.SMC_KEY_FAN_SPEED, i)); } SmcUtil.smcClose(conn); return fanSpeeds; } @Override public double queryCpuVoltage() {<FILL_FUNCTION_BODY>} }
IOConnect conn = SmcUtil.smcOpen(); double volts = SmcUtil.smcGetFloat(conn, SmcUtil.SMC_KEY_CPU_VOLTAGE) / 1000d; SmcUtil.smcClose(conn); return volts;
375
74
449
<methods>public non-sealed void <init>() ,public double getCpuTemperature() ,public double getCpuVoltage() ,public int[] getFanSpeeds() ,public java.lang.String toString() <variables>private final Supplier<java.lang.Double> cpuTemperature,private final Supplier<java.lang.Double> cpuVoltage,private final Supplier<int[]> fanSpeeds
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/mac/MacSoundCard.java
MacSoundCard
getSoundCards
class MacSoundCard extends AbstractSoundCard { private static final String APPLE = "Apple Inc."; /** * Constructor for MacSoundCard. * * @param kernelVersion The version * @param name The name * @param codec The codec */ MacSoundCard(String kernelVersion, String name, String codec) { super(kernelVersion, name, codec); } /** * public method used by {@link oshi.hardware.common.AbstractHardwareAbstractionLayer} to access the sound cards. * * @return List of {@link oshi.hardware.platform.mac.MacSoundCard} objects. */ public static List<SoundCard> getSoundCards() {<FILL_FUNCTION_BODY>} }
List<SoundCard> soundCards = new ArrayList<>(); // /System/Library/Extensions/AppleHDA.kext/Contents/Info.plist // ..... snip .... // <dict> // <key>com.apple.driver.AppleHDAController</key> // <string>1.7.2a1</string> String manufacturer = APPLE; String kernelVersion = "AppleHDAController"; String codec = "AppleHDACodec"; boolean version = false; String versionMarker = "<key>com.apple.driver.AppleHDAController</key>"; for (final String checkLine : FileUtil .readFile("/System/Library/Extensions/AppleHDA.kext/Contents/Info.plist")) { if (checkLine.contains(versionMarker)) { version = true; continue; } if (version) { kernelVersion = "AppleHDAController " + ParseUtil.getTextBetweenStrings(checkLine, "<string>", "</string>"); version = false; } } soundCards.add(new MacSoundCard(kernelVersion, manufacturer, codec)); return soundCards;
205
315
520
<methods>public java.lang.String getCodec() ,public java.lang.String getDriverVersion() ,public java.lang.String getName() ,public java.lang.String toString() <variables>private java.lang.String codec,private java.lang.String kernelVersion,private java.lang.String name
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/mac/MacVirtualMemory.java
MacVirtualMemory
querySwapUsage
class MacVirtualMemory extends AbstractVirtualMemory { private static final Logger LOG = LoggerFactory.getLogger(MacVirtualMemory.class); private final MacGlobalMemory global; private final Supplier<Pair<Long, Long>> usedTotal = memoize(MacVirtualMemory::querySwapUsage, defaultExpiration()); private final Supplier<Pair<Long, Long>> inOut = memoize(MacVirtualMemory::queryVmStat, defaultExpiration()); /** * Constructor for MacVirtualMemory. * * @param macGlobalMemory The parent global memory class instantiating this */ MacVirtualMemory(MacGlobalMemory macGlobalMemory) { this.global = macGlobalMemory; } @Override public long getSwapUsed() { return usedTotal.get().getA(); } @Override public long getSwapTotal() { return usedTotal.get().getB(); } @Override public long getVirtualMax() { return this.global.getTotal() + getSwapTotal(); } @Override public long getVirtualInUse() { return this.global.getTotal() - this.global.getAvailable() + getSwapUsed(); } @Override public long getSwapPagesIn() { return inOut.get().getA(); } @Override public long getSwapPagesOut() { return inOut.get().getB(); } private static Pair<Long, Long> querySwapUsage() {<FILL_FUNCTION_BODY>} private static Pair<Long, Long> queryVmStat() { long swapPagesIn = 0L; long swapPagesOut = 0L; try (CloseableVMStatistics vmStats = new CloseableVMStatistics(); CloseableIntByReference size = new CloseableIntByReference(vmStats.size() / SystemB.INT_SIZE)) { if (0 == SystemB.INSTANCE.host_statistics(SystemB.INSTANCE.mach_host_self(), SystemB.HOST_VM_INFO, vmStats, size)) { swapPagesIn = ParseUtil.unsignedIntToLong(vmStats.pageins); swapPagesOut = ParseUtil.unsignedIntToLong(vmStats.pageouts); } else { LOG.error("Failed to get host VM info. Error code: {}", Native.getLastError()); } } return new Pair<>(swapPagesIn, swapPagesOut); } }
long swapUsed = 0L; long swapTotal = 0L; try (CloseableXswUsage xswUsage = new CloseableXswUsage()) { if (SysctlUtil.sysctl("vm.swapusage", xswUsage)) { swapUsed = xswUsage.xsu_used; swapTotal = xswUsage.xsu_total; } } return new Pair<>(swapUsed, swapTotal);
630
112
742
<methods>public non-sealed void <init>() ,public java.lang.String toString() <variables>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/BsdNetworkIF.java
BsdNetworkIF
updateAttributes
class BsdNetworkIF extends AbstractNetworkIF { private static final Logger LOG = LoggerFactory.getLogger(BsdNetworkIF.class); private long bytesRecv; private long bytesSent; private long packetsRecv; private long packetsSent; private long inErrors; private long outErrors; private long inDrops; private long collisions; private long timeStamp; public BsdNetworkIF(NetworkInterface netint) throws InstantiationException { super(netint); updateAttributes(); } /** * Gets all network interfaces on this machine * * @param includeLocalInterfaces include local interfaces in the result * @return A list of {@link NetworkIF} objects representing the interfaces */ public static List<NetworkIF> getNetworks(boolean includeLocalInterfaces) { List<NetworkIF> ifList = new ArrayList<>(); for (NetworkInterface ni : getNetworkInterfaces(includeLocalInterfaces)) { try { ifList.add(new BsdNetworkIF(ni)); } catch (InstantiationException e) { LOG.debug("Network Interface Instantiation failed: {}", e.getMessage()); } } return ifList; } @Override public long getBytesRecv() { return this.bytesRecv; } @Override public long getBytesSent() { return this.bytesSent; } @Override public long getPacketsRecv() { return this.packetsRecv; } @Override public long getPacketsSent() { return this.packetsSent; } @Override public long getInErrors() { return this.inErrors; } @Override public long getOutErrors() { return this.outErrors; } @Override public long getInDrops() { return this.inDrops; } @Override public long getCollisions() { return this.collisions; } @Override public long getSpeed() { return 0; } @Override public long getTimeStamp() { return this.timeStamp; } @Override public boolean updateAttributes() {<FILL_FUNCTION_BODY>} }
String stats = ExecutingCommand.getAnswerAt("netstat -bI " + getName(), 1); this.timeStamp = System.currentTimeMillis(); String[] split = ParseUtil.whitespaces.split(stats); if (split.length < 12) { // No update return false; } this.bytesSent = ParseUtil.parseUnsignedLongOrDefault(split[10], 0L); this.bytesRecv = ParseUtil.parseUnsignedLongOrDefault(split[7], 0L); this.packetsSent = ParseUtil.parseUnsignedLongOrDefault(split[8], 0L); this.packetsRecv = ParseUtil.parseUnsignedLongOrDefault(split[4], 0L); this.outErrors = ParseUtil.parseUnsignedLongOrDefault(split[9], 0L); this.inErrors = ParseUtil.parseUnsignedLongOrDefault(split[5], 0L); this.collisions = ParseUtil.parseUnsignedLongOrDefault(split[11], 0L); this.inDrops = ParseUtil.parseUnsignedLongOrDefault(split[6], 0L); return true;
593
316
909
<methods>public java.lang.String getDisplayName() ,public java.lang.String[] getIPv4addr() ,public java.lang.String[] getIPv6addr() ,public int getIndex() ,public long getMTU() ,public java.lang.String getMacaddr() ,public java.lang.String getName() ,public java.lang.Short[] getPrefixLengths() ,public java.lang.Short[] getSubnetMasks() ,public boolean isKnownVmMacAddr() ,public java.net.NetworkInterface queryNetworkInterface() ,public java.lang.String toString() <variables>private static final org.slf4j.Logger LOG,private static final java.lang.String OSHI_VM_MAC_ADDR_PROPERTIES,private java.lang.String displayName,private int index,private java.lang.String[] ipv4,private java.lang.String[] ipv6,private java.lang.String mac,private long mtu,private java.lang.String name,private java.net.NetworkInterface networkInterface,private java.lang.Short[] prefixLengths,private java.lang.Short[] subnetMasks,private final Supplier<java.util.Properties> vmMacAddrProps
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixComputerSystem.java
AixComputerSystem
readLsattr
class AixComputerSystem extends AbstractComputerSystem { private final Supplier<LsattrStrings> lsattrStrings = memoize(AixComputerSystem::readLsattr); private final Supplier<List<String>> lscfg; AixComputerSystem(Supplier<List<String>> lscfg) { this.lscfg = lscfg; } @Override public String getManufacturer() { return lsattrStrings.get().manufacturer; } @Override public String getModel() { return lsattrStrings.get().model; } @Override public String getSerialNumber() { return lsattrStrings.get().serialNumber; } @Override public String getHardwareUUID() { return lsattrStrings.get().uuid; } @Override public Firmware createFirmware() { return new AixFirmware(lsattrStrings.get().biosVendor, lsattrStrings.get().biosPlatformVersion, lsattrStrings.get().biosVersion); } @Override public Baseboard createBaseboard() { return new AixBaseboard(lscfg); } private static LsattrStrings readLsattr() {<FILL_FUNCTION_BODY>} private static final class LsattrStrings { private final String biosVendor; private final String biosPlatformVersion; private final String biosVersion; private final String manufacturer; private final String model; private final String serialNumber; private final String uuid; private LsattrStrings(String biosVendor, String biosPlatformVersion, String biosVersion, String manufacturer, String model, String serialNumber, String uuid) { this.biosVendor = Util.isBlank(biosVendor) ? Constants.UNKNOWN : biosVendor; this.biosPlatformVersion = Util.isBlank(biosPlatformVersion) ? Constants.UNKNOWN : biosPlatformVersion; this.biosVersion = Util.isBlank(biosVersion) ? Constants.UNKNOWN : biosVersion; this.manufacturer = Util.isBlank(manufacturer) ? Constants.UNKNOWN : manufacturer; this.model = Util.isBlank(model) ? Constants.UNKNOWN : model; this.serialNumber = Util.isBlank(serialNumber) ? Constants.UNKNOWN : serialNumber; this.uuid = Util.isBlank(uuid) ? Constants.UNKNOWN : uuid; } } }
String fwVendor = "IBM"; String fwVersion = null; String fwPlatformVersion = null; String manufacturer = fwVendor; String model = null; String serialNumber = null; String uuid = null; /*- fwversion IBM,RG080425_d79e22_r Firmware version and revision levels False modelname IBM,9114-275 Machine name False os_uuid 789f930f-b15c-4639-b842-b42603862704 N/A True rtasversion 1 Open Firmware RTAS version False systemid IBM,0110ACFDE Hardware system identifier False */ final String fwVersionMarker = "fwversion"; final String modelMarker = "modelname"; final String systemIdMarker = "systemid"; final String uuidMarker = "os_uuid"; final String fwPlatformVersionMarker = "Platform Firmware level is"; for (final String checkLine : ExecutingCommand.runNative("lsattr -El sys0")) { if (checkLine.startsWith(fwVersionMarker)) { fwVersion = checkLine.split(fwVersionMarker)[1].trim(); int comma = fwVersion.indexOf(','); if (comma > 0 && fwVersion.length() > comma) { fwVendor = fwVersion.substring(0, comma); fwVersion = fwVersion.substring(comma + 1); } fwVersion = ParseUtil.whitespaces.split(fwVersion)[0]; } else if (checkLine.startsWith(modelMarker)) { model = checkLine.split(modelMarker)[1].trim(); int comma = model.indexOf(','); if (comma > 0 && model.length() > comma) { manufacturer = model.substring(0, comma); model = model.substring(comma + 1); } model = ParseUtil.whitespaces.split(model)[0]; } else if (checkLine.startsWith(systemIdMarker)) { serialNumber = checkLine.split(systemIdMarker)[1].trim(); serialNumber = ParseUtil.whitespaces.split(serialNumber)[0]; } else if (checkLine.startsWith(uuidMarker)) { uuid = checkLine.split(uuidMarker)[1].trim(); uuid = ParseUtil.whitespaces.split(uuid)[0]; } } for (final String checkLine : ExecutingCommand.runNative("lsmcode -c")) { /*- Platform Firmware level is 3F080425 System Firmware level is RG080425_d79e22_regatta */ if (checkLine.startsWith(fwPlatformVersionMarker)) { fwPlatformVersion = checkLine.split(fwPlatformVersionMarker)[1].trim(); break; } } return new LsattrStrings(fwVendor, fwPlatformVersion, fwVersion, manufacturer, model, serialNumber, uuid);
673
817
1,490
<methods>public non-sealed void <init>() ,public oshi.hardware.Baseboard getBaseboard() ,public oshi.hardware.Firmware getFirmware() ,public java.lang.String toString() <variables>private final Supplier<oshi.hardware.Baseboard> baseboard,private final Supplier<oshi.hardware.Firmware> firmware
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixGlobalMemory.java
AixGlobalMemory
getPhysicalMemory
class AixGlobalMemory extends AbstractGlobalMemory { private final Supplier<perfstat_memory_total_t> perfstatMem = memoize(AixGlobalMemory::queryPerfstat, defaultExpiration()); private final Supplier<List<String>> lscfg; // AIX has multiple page size units, but for purposes of "pages" in perfstat, // the docs specify 4KB pages so we hardcode this private static final long PAGESIZE = 4096L; private final Supplier<VirtualMemory> vm = memoize(this::createVirtualMemory); AixGlobalMemory(Supplier<List<String>> lscfg) { this.lscfg = lscfg; } @Override public long getAvailable() { return perfstatMem.get().real_avail * PAGESIZE; } @Override public long getTotal() { return perfstatMem.get().real_total * PAGESIZE; } @Override public long getPageSize() { return PAGESIZE; } @Override public VirtualMemory getVirtualMemory() { return vm.get(); } @Override public List<PhysicalMemory> getPhysicalMemory() {<FILL_FUNCTION_BODY>} private static perfstat_memory_total_t queryPerfstat() { return PerfstatMemory.queryMemoryTotal(); } private VirtualMemory createVirtualMemory() { return new AixVirtualMemory(perfstatMem); } }
List<PhysicalMemory> pmList = new ArrayList<>(); boolean isMemModule = false; boolean isMemoryDIMM = false; String bankLabel = Constants.UNKNOWN; String locator = ""; String partNumber = Constants.UNKNOWN; long capacity = 0L; for (String line : lscfg.get()) { String s = line.trim(); if (s.endsWith("memory-module")) { isMemModule = true; } else if (s.startsWith("Memory DIMM")) { isMemoryDIMM = true; } else if (isMemModule) { if (s.startsWith("Node:")) { bankLabel = s.substring(5).trim(); if (bankLabel.startsWith("IBM,")) { bankLabel = bankLabel.substring(4); } } else if (s.startsWith("Physical Location:")) { locator = "/" + s.substring(18).trim(); } else if (s.startsWith("Size")) { capacity = ParseUtil.parseLongOrDefault(ParseUtil.removeLeadingDots(s.substring(4).trim()), 0L) << 20; } else if (s.startsWith("Hardware Location Code")) { // Save previous bank if (capacity > 0) { pmList.add(new PhysicalMemory(bankLabel + locator, capacity, 0L, "IBM", Constants.UNKNOWN, Constants.UNKNOWN)); } bankLabel = Constants.UNKNOWN; locator = ""; capacity = 0L; isMemModule = false; } } else if (isMemoryDIMM) { if (s.startsWith("Hardware Location Code")) { locator = ParseUtil.removeLeadingDots(s.substring(23).trim()); } else if (s.startsWith("Size")) { capacity = ParseUtil.parseLongOrDefault(ParseUtil.removeLeadingDots(s.substring(4).trim()), 0L) << 20; } else if (s.startsWith("Part Number") || s.startsWith("FRU Number")) { partNumber = ParseUtil.removeLeadingDots(s.substring(11).trim()); } else if (s.startsWith("Physical Location:")) { // Save previous bank if (capacity > 0) { pmList.add(new PhysicalMemory(locator, capacity, 0L, "IBM", Constants.UNKNOWN, partNumber)); } partNumber = Constants.UNKNOWN; locator = ""; capacity = 0L; isMemoryDIMM = false; } } } return pmList;
398
719
1,117
<methods>public non-sealed void <init>() ,public List<oshi.hardware.PhysicalMemory> getPhysicalMemory() ,public java.lang.String toString() <variables>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixGraphicsCard.java
AixGraphicsCard
getGraphicsCards
class AixGraphicsCard extends AbstractGraphicsCard { /** * Constructor for AixGraphicsCard * * @param name The name * @param deviceId The device ID * @param vendor The vendor * @param versionInfo The version info * @param vram The VRAM */ AixGraphicsCard(String name, String deviceId, String vendor, String versionInfo, long vram) { super(name, deviceId, vendor, versionInfo, vram); } /** * Gets graphics cards * * @param lscfg A memoized lscfg list * * @return List of graphics cards */ public static List<GraphicsCard> getGraphicsCards(Supplier<List<String>> lscfg) {<FILL_FUNCTION_BODY>} }
List<GraphicsCard> cardList = new ArrayList<>(); boolean display = false; String name = null; String vendor = null; List<String> versionInfo = new ArrayList<>(); for (String line : lscfg.get()) { String s = line.trim(); if (s.startsWith("Name:") && s.contains("display")) { display = true; } else if (display && s.toLowerCase(Locale.ROOT).contains("graphics")) { name = s; } else if (display && name != null) { if (s.startsWith("Manufacture ID")) { vendor = ParseUtil.removeLeadingDots(s.substring(14)); } else if (s.contains("Level")) { versionInfo.add(s.replaceAll("\\.\\.+", "=")); } else if (s.startsWith("Hardware Location Code")) { cardList.add(new AixGraphicsCard(name, Constants.UNKNOWN, Util.isBlank(vendor) ? Constants.UNKNOWN : vendor, versionInfo.isEmpty() ? Constants.UNKNOWN : String.join(",", versionInfo), 0L)); display = false; } } } return cardList;
209
328
537
<methods>public java.lang.String getDeviceId() ,public java.lang.String getName() ,public long getVRam() ,public java.lang.String getVendor() ,public java.lang.String getVersionInfo() ,public java.lang.String toString() <variables>private final non-sealed java.lang.String deviceId,private final non-sealed java.lang.String name,private final non-sealed java.lang.String vendor,private final non-sealed java.lang.String versionInfo,private long vram
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixHWDiskStore.java
AixHWDiskStore
updateAttributes
class AixHWDiskStore extends AbstractHWDiskStore { private final Supplier<perfstat_disk_t[]> diskStats; private long reads = 0L; private long readBytes = 0L; private long writes = 0L; private long writeBytes = 0L; private long currentQueueLength = 0L; private long transferTime = 0L; private long timeStamp = 0L; private List<HWPartition> partitionList; private AixHWDiskStore(String name, String model, String serial, long size, Supplier<perfstat_disk_t[]> diskStats) { super(name, model, serial, size); this.diskStats = diskStats; } @Override public synchronized long getReads() { return reads; } @Override public synchronized long getReadBytes() { return readBytes; } @Override public synchronized long getWrites() { return writes; } @Override public synchronized long getWriteBytes() { return writeBytes; } @Override public synchronized long getCurrentQueueLength() { return currentQueueLength; } @Override public synchronized long getTransferTime() { return transferTime; } @Override public synchronized long getTimeStamp() { return timeStamp; } @Override public List<HWPartition> getPartitions() { return this.partitionList; } @Override public synchronized boolean updateAttributes() {<FILL_FUNCTION_BODY>} /** * Gets the disks on this machine * * @param diskStats Memoized supplier of disk statistics * * @return a list of {@link HWDiskStore} objects representing the disks */ public static List<HWDiskStore> getDisks(Supplier<perfstat_disk_t[]> diskStats) { Map<String, Pair<Integer, Integer>> majMinMap = Ls.queryDeviceMajorMinor(); List<AixHWDiskStore> storeList = new ArrayList<>(); for (perfstat_disk_t disk : diskStats.get()) { String storeName = Native.toString(disk.name); Pair<String, String> ms = Lscfg.queryModelSerial(storeName); String model = ms.getA() == null ? Native.toString(disk.description) : ms.getA(); String serial = ms.getB() == null ? Constants.UNKNOWN : ms.getB(); storeList.add(createStore(storeName, model, serial, disk.size << 20, diskStats, majMinMap)); } return storeList.stream() .sorted(Comparator.comparingInt( s -> s.getPartitions().isEmpty() ? Integer.MAX_VALUE : s.getPartitions().get(0).getMajor())) .collect(Collectors.toList()); } private static AixHWDiskStore createStore(String diskName, String model, String serial, long size, Supplier<perfstat_disk_t[]> diskStats, Map<String, Pair<Integer, Integer>> majMinMap) { AixHWDiskStore store = new AixHWDiskStore(diskName, model.isEmpty() ? Constants.UNKNOWN : model, serial, size, diskStats); store.partitionList = Lspv.queryLogicalVolumes(diskName, majMinMap); store.updateAttributes(); return store; } }
long now = System.currentTimeMillis(); for (perfstat_disk_t stat : diskStats.get()) { String name = Native.toString(stat.name); if (name.equals(this.getName())) { // we only have total transfers so estimate read/write ratio from blocks long blks = stat.rblks + stat.wblks; if (blks == 0L) { this.reads = stat.xfers; this.writes = 0L; } else { long approximateReads = Math.round(stat.xfers * stat.rblks / (double) blks); long approximateWrites = stat.xfers - approximateReads; // Enforce monotonic increase if (approximateReads > this.reads) { this.reads = approximateReads; } if (approximateWrites > this.writes) { this.writes = approximateWrites; } } this.readBytes = stat.rblks * stat.bsize; this.writeBytes = stat.wblks * stat.bsize; this.currentQueueLength = stat.qdepth; this.transferTime = stat.time; this.timeStamp = now; return true; } } return false;
901
333
1,234
<methods>public java.lang.String getModel() ,public java.lang.String getName() ,public java.lang.String getSerial() ,public long getSize() ,public java.lang.String toString() <variables>private final non-sealed java.lang.String model,private final non-sealed java.lang.String name,private final non-sealed java.lang.String serial,private final non-sealed long size
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixNetworkIF.java
AixNetworkIF
updateAttributes
class AixNetworkIF extends AbstractNetworkIF { private static final Logger LOG = LoggerFactory.getLogger(AixNetworkIF.class); private long bytesRecv; private long bytesSent; private long packetsRecv; private long packetsSent; private long inErrors; private long outErrors; private long inDrops; private long collisions; private long speed; private long timeStamp; private Supplier<perfstat_netinterface_t[]> netstats; public AixNetworkIF(NetworkInterface netint, Supplier<perfstat_netinterface_t[]> netstats) throws InstantiationException { super(netint); this.netstats = netstats; updateAttributes(); } /** * Gets all network interfaces on this machine * * @param includeLocalInterfaces include local interfaces in the result * @return A list of {@link NetworkIF} objects representing the interfaces */ public static List<NetworkIF> getNetworks(boolean includeLocalInterfaces) { Supplier<perfstat_netinterface_t[]> netstats = memoize(PerfstatNetInterface::queryNetInterfaces, defaultExpiration()); List<NetworkIF> ifList = new ArrayList<>(); for (NetworkInterface ni : getNetworkInterfaces(includeLocalInterfaces)) { try { ifList.add(new AixNetworkIF(ni, netstats)); } catch (InstantiationException e) { LOG.debug("Network Interface Instantiation failed: {}", e.getMessage()); } } return ifList; } @Override public long getBytesRecv() { return this.bytesRecv; } @Override public long getBytesSent() { return this.bytesSent; } @Override public long getPacketsRecv() { return this.packetsRecv; } @Override public long getPacketsSent() { return this.packetsSent; } @Override public long getInErrors() { return this.inErrors; } @Override public long getOutErrors() { return this.outErrors; } @Override public long getInDrops() { return this.inDrops; } @Override public long getCollisions() { return this.collisions; } @Override public long getSpeed() { return this.speed; } @Override public long getTimeStamp() { return this.timeStamp; } @Override public boolean updateAttributes() {<FILL_FUNCTION_BODY>} }
perfstat_netinterface_t[] stats = netstats.get(); long now = System.currentTimeMillis(); for (perfstat_netinterface_t stat : stats) { String name = Native.toString(stat.name); if (name.equals(this.getName())) { this.bytesSent = stat.obytes; this.bytesRecv = stat.ibytes; this.packetsSent = stat.opackets; this.packetsRecv = stat.ipackets; this.outErrors = stat.oerrors; this.inErrors = stat.ierrors; this.collisions = stat.collisions; this.inDrops = stat.if_iqdrops; this.speed = stat.bitrate; this.timeStamp = now; return true; } } return false;
687
218
905
<methods>public java.lang.String getDisplayName() ,public java.lang.String[] getIPv4addr() ,public java.lang.String[] getIPv6addr() ,public int getIndex() ,public long getMTU() ,public java.lang.String getMacaddr() ,public java.lang.String getName() ,public java.lang.Short[] getPrefixLengths() ,public java.lang.Short[] getSubnetMasks() ,public boolean isKnownVmMacAddr() ,public java.net.NetworkInterface queryNetworkInterface() ,public java.lang.String toString() <variables>private static final org.slf4j.Logger LOG,private static final java.lang.String OSHI_VM_MAC_ADDR_PROPERTIES,private java.lang.String displayName,private int index,private java.lang.String[] ipv4,private java.lang.String[] ipv6,private java.lang.String mac,private long mtu,private java.lang.String name,private java.net.NetworkInterface networkInterface,private java.lang.Short[] prefixLengths,private java.lang.Short[] subnetMasks,private final Supplier<java.util.Properties> vmMacAddrProps
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixSensors.java
AixSensors
queryCpuVoltage
class AixSensors extends AbstractSensors { private final Supplier<List<String>> lscfg; AixSensors(Supplier<List<String>> lscfg) { this.lscfg = lscfg; } @Override public double queryCpuTemperature() { // Not available in general without specialized software return 0d; } @Override public int[] queryFanSpeeds() { // Speeds are not available in general without specialized software // We can count fans from lscfg and return an appropriate sized array of zeroes. int fans = 0; for (String s : lscfg.get()) { if (s.contains("Air Mover")) { fans++; } } return new int[fans]; } @Override public double queryCpuVoltage() {<FILL_FUNCTION_BODY>} }
// Not available in general without specialized software return 0d;
237
20
257
<methods>public non-sealed void <init>() ,public double getCpuTemperature() ,public double getCpuVoltage() ,public int[] getFanSpeeds() ,public java.lang.String toString() <variables>private final Supplier<java.lang.Double> cpuTemperature,private final Supplier<java.lang.Double> cpuVoltage,private final Supplier<int[]> fanSpeeds
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixSoundCard.java
AixSoundCard
getSoundCards
class AixSoundCard extends AbstractSoundCard { /** * Constructor for AixSoundCard. * * @param kernelVersion The version * @param name The name * @param codec The codec */ AixSoundCard(String kernelVersion, String name, String codec) { super(kernelVersion, name, codec); } /** * Gets sound cards * * @param lscfg a memoized lscfg object * * @return sound cards */ public static List<SoundCard> getSoundCards(Supplier<List<String>> lscfg) {<FILL_FUNCTION_BODY>} }
List<SoundCard> soundCards = new ArrayList<>(); for (String line : lscfg.get()) { String s = line.trim(); if (s.startsWith("paud")) { String[] split = ParseUtil.whitespaces.split(s, 3); if (split.length == 3) { soundCards.add(new AixSoundCard(Constants.UNKNOWN, split[2], Constants.UNKNOWN)); } } } return soundCards;
174
135
309
<methods>public java.lang.String getCodec() ,public java.lang.String getDriverVersion() ,public java.lang.String getName() ,public java.lang.String toString() <variables>private java.lang.String codec,private java.lang.String kernelVersion,private java.lang.String name
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/aix/AixUsbDevice.java
AixUsbDevice
getUsbDevices
class AixUsbDevice extends AbstractUsbDevice { public AixUsbDevice(String name, String vendor, String vendorId, String productId, String serialNumber, String uniqueDeviceId, List<UsbDevice> connectedDevices) { super(name, vendor, vendorId, productId, serialNumber, uniqueDeviceId, connectedDevices); } /** * Instantiates a list of {@link oshi.hardware.UsbDevice} objects, representing devices connected via a usb port * (including internal devices). * <p> * If the value of {@code tree} is true, the top level devices returned from this method are the USB Controllers; * connected hubs and devices in its device tree share that controller's bandwidth. If the value of {@code tree} is * false, USB devices (not controllers) are listed in a single flat list. * * @param tree If true, returns a list of controllers, which requires recursive iteration of connected devices. If * false, returns a flat list of devices excluding controllers. * @param lscfg A memoized lscfg list * @return a list of {@link oshi.hardware.UsbDevice} objects. */ public static List<UsbDevice> getUsbDevices(boolean tree, Supplier<List<String>> lscfg) {<FILL_FUNCTION_BODY>} }
List<UsbDevice> deviceList = new ArrayList<>(); for (String line : lscfg.get()) { String s = line.trim(); if (s.startsWith("usb")) { String[] split = ParseUtil.whitespaces.split(s, 3); if (split.length == 3) { deviceList.add(new AixUsbDevice(split[2], Constants.UNKNOWN, Constants.UNKNOWN, Constants.UNKNOWN, Constants.UNKNOWN, split[0], Collections.emptyList())); } } } if (tree) { return Arrays.asList(new AixUsbDevice("USB Controller", "", "0000", "0000", "", "", deviceList)); } return deviceList;
344
208
552
<methods>public int compareTo(oshi.hardware.UsbDevice) ,public List<oshi.hardware.UsbDevice> getConnectedDevices() ,public java.lang.String getName() ,public java.lang.String getProductId() ,public java.lang.String getSerialNumber() ,public java.lang.String getUniqueDeviceId() ,public java.lang.String getVendor() ,public java.lang.String getVendorId() ,public java.lang.String toString() <variables>private final non-sealed List<oshi.hardware.UsbDevice> connectedDevices,private final non-sealed java.lang.String name,private final non-sealed java.lang.String productId,private final non-sealed java.lang.String serialNumber,private final non-sealed java.lang.String uniqueDeviceId,private final non-sealed java.lang.String vendor,private final non-sealed java.lang.String vendorId
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdComputerSystem.java
FreeBsdComputerSystem
readDmiDecode
class FreeBsdComputerSystem extends AbstractComputerSystem { private final Supplier<Quintet<String, String, String, String, String>> manufModelSerialUuidVers = memoize( FreeBsdComputerSystem::readDmiDecode); @Override public String getManufacturer() { return manufModelSerialUuidVers.get().getA(); } @Override public String getModel() { return manufModelSerialUuidVers.get().getB(); } @Override public String getSerialNumber() { return manufModelSerialUuidVers.get().getC(); } @Override public String getHardwareUUID() { return manufModelSerialUuidVers.get().getD(); } @Override public Firmware createFirmware() { return new FreeBsdFirmware(); } @Override public Baseboard createBaseboard() { return new UnixBaseboard(manufModelSerialUuidVers.get().getA(), manufModelSerialUuidVers.get().getB(), manufModelSerialUuidVers.get().getC(), manufModelSerialUuidVers.get().getE()); } private static Quintet<String, String, String, String, String> readDmiDecode() {<FILL_FUNCTION_BODY>} private static String querySystemSerialNumber() { String marker = "system.hardware.serial ="; for (String checkLine : ExecutingCommand.runNative("lshal")) { if (checkLine.contains(marker)) { return ParseUtil.getSingleQuoteStringValue(checkLine); } } return Constants.UNKNOWN; } }
String manufacturer = null; String model = null; String serialNumber = null; String uuid = null; String version = null; // $ sudo dmidecode -t system // # dmidecode 3.0 // Scanning /dev/mem for entry point. // SMBIOS 2.7 present. // // Handle 0x0001, DMI type 1, 27 bytes // System Information // Manufacturer: Parallels Software International Inc. // Product Name: Parallels Virtual Platform // Version: None // Serial Number: Parallels-47 EC 38 2A 33 1B 4C 75 94 0F F7 AF 86 63 C0 // C4 // UUID: 2A38EC47-1B33-854C-940F-F7AF8663C0C4 // Wake-up Type: Power Switch // SKU Number: Undefined // Family: Parallels VM // // Handle 0x0016, DMI type 32, 20 bytes // System Boot Information // Status: No errors detected final String manufacturerMarker = "Manufacturer:"; final String productNameMarker = "Product Name:"; final String serialNumMarker = "Serial Number:"; final String uuidMarker = "UUID:"; final String versionMarker = "Version:"; // Only works with root permissions but it's all we've got for (final String checkLine : ExecutingCommand.runNative("dmidecode -t system")) { if (checkLine.contains(manufacturerMarker)) { manufacturer = checkLine.split(manufacturerMarker)[1].trim(); } else if (checkLine.contains(productNameMarker)) { model = checkLine.split(productNameMarker)[1].trim(); } else if (checkLine.contains(serialNumMarker)) { serialNumber = checkLine.split(serialNumMarker)[1].trim(); } else if (checkLine.contains(uuidMarker)) { uuid = checkLine.split(uuidMarker)[1].trim(); } else if (checkLine.contains(versionMarker)) { version = checkLine.split(versionMarker)[1].trim(); } } // If we get to end and haven't assigned, use fallback if (Util.isBlank(serialNumber)) { serialNumber = querySystemSerialNumber(); } if (Util.isBlank(uuid)) { uuid = BsdSysctlUtil.sysctl("kern.hostuuid", Constants.UNKNOWN); } return new Quintet<>(Util.isBlank(manufacturer) ? Constants.UNKNOWN : manufacturer, Util.isBlank(model) ? Constants.UNKNOWN : model, Util.isBlank(serialNumber) ? Constants.UNKNOWN : serialNumber, Util.isBlank(uuid) ? Constants.UNKNOWN : uuid, Util.isBlank(version) ? Constants.UNKNOWN : version);
443
791
1,234
<methods>public non-sealed void <init>() ,public oshi.hardware.Baseboard getBaseboard() ,public oshi.hardware.Firmware getFirmware() ,public java.lang.String toString() <variables>private final Supplier<oshi.hardware.Baseboard> baseboard,private final Supplier<oshi.hardware.Firmware> firmware
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdFirmware.java
FreeBsdFirmware
readDmiDecode
class FreeBsdFirmware extends AbstractFirmware { private final Supplier<Triplet<String, String, String>> manufVersRelease = memoize(FreeBsdFirmware::readDmiDecode); @Override public String getManufacturer() { return manufVersRelease.get().getA(); } @Override public String getVersion() { return manufVersRelease.get().getB(); } @Override public String getReleaseDate() { return manufVersRelease.get().getC(); } /* * Name and Description not set */ private static Triplet<String, String, String> readDmiDecode() {<FILL_FUNCTION_BODY>} }
String manufacturer = null; String version = null; String releaseDate = ""; // $ sudo dmidecode -t bios // # dmidecode 3.0 // Scanning /dev/mem for entry point. // SMBIOS 2.7 present. // // Handle 0x0000, DMI type 0, 24 bytes // BIOS Information // Vendor: Parallels Software International Inc. // Version: 11.2.1 (32626) // Release Date: 07/15/2016 // ... <snip> ... // BIOS Revision: 11.2 // Firmware Revision: 11.2 final String manufacturerMarker = "Vendor:"; final String versionMarker = "Version:"; final String releaseDateMarker = "Release Date:"; // Only works with root permissions but it's all we've got for (final String checkLine : ExecutingCommand.runNative("dmidecode -t bios")) { if (checkLine.contains(manufacturerMarker)) { manufacturer = checkLine.split(manufacturerMarker)[1].trim(); } else if (checkLine.contains(versionMarker)) { version = checkLine.split(versionMarker)[1].trim(); } else if (checkLine.contains(releaseDateMarker)) { releaseDate = checkLine.split(releaseDateMarker)[1].trim(); } } releaseDate = ParseUtil.parseMmDdYyyyToYyyyMmDD(releaseDate); return new Triplet<>(Util.isBlank(manufacturer) ? Constants.UNKNOWN : manufacturer, Util.isBlank(version) ? Constants.UNKNOWN : version, Util.isBlank(releaseDate) ? Constants.UNKNOWN : releaseDate);
195
475
670
<methods>public non-sealed void <init>() ,public java.lang.String getDescription() ,public java.lang.String getName() ,public java.lang.String getReleaseDate() ,public java.lang.String toString() <variables>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdGlobalMemory.java
FreeBsdGlobalMemory
queryVmStats
class FreeBsdGlobalMemory extends AbstractGlobalMemory { private final Supplier<Long> available = memoize(this::queryVmStats, defaultExpiration()); private final Supplier<Long> total = memoize(FreeBsdGlobalMemory::queryPhysMem); private final Supplier<Long> pageSize = memoize(FreeBsdGlobalMemory::queryPageSize); private final Supplier<VirtualMemory> vm = memoize(this::createVirtualMemory); @Override public long getAvailable() { return available.get(); } @Override public long getTotal() { return total.get(); } @Override public long getPageSize() { return pageSize.get(); } @Override public VirtualMemory getVirtualMemory() { return vm.get(); } private long queryVmStats() {<FILL_FUNCTION_BODY>} private static long queryPhysMem() { return BsdSysctlUtil.sysctl("hw.physmem", 0L); } private static long queryPageSize() { // sysctl hw.pagesize doesn't work on FreeBSD 13 return ParseUtil.parseLongOrDefault(ExecutingCommand.getFirstAnswer("sysconf PAGESIZE"), 4096L); } private VirtualMemory createVirtualMemory() { return new FreeBsdVirtualMemory(this); } }
// cached removed in FreeBSD 12 but was always set to 0 int inactive = BsdSysctlUtil.sysctl("vm.stats.vm.v_inactive_count", 0); int free = BsdSysctlUtil.sysctl("vm.stats.vm.v_free_count", 0); return (inactive + free) * getPageSize();
369
98
467
<methods>public non-sealed void <init>() ,public List<oshi.hardware.PhysicalMemory> getPhysicalMemory() ,public java.lang.String toString() <variables>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdGraphicsCard.java
FreeBsdGraphicsCard
getGraphicsCards
class FreeBsdGraphicsCard extends AbstractGraphicsCard { private static final String PCI_CLASS_DISPLAY = "0x03"; /** * Constructor for FreeBsdGraphicsCard * * @param name The name * @param deviceId The device ID * @param vendor The vendor * @param versionInfo The version info * @param vram The VRAM */ FreeBsdGraphicsCard(String name, String deviceId, String vendor, String versionInfo, long vram) { super(name, deviceId, vendor, versionInfo, vram); } /** * public method used by {@link oshi.hardware.common.AbstractHardwareAbstractionLayer} to access the graphics cards. * * @return List of {@link oshi.hardware.platform.unix.freebsd.FreeBsdGraphicsCard} objects. */ public static List<GraphicsCard> getGraphicsCards() {<FILL_FUNCTION_BODY>} }
List<GraphicsCard> cardList = new ArrayList<>(); // Enumerate all devices and add if required List<String> devices = ExecutingCommand.runNative("pciconf -lv"); if (devices.isEmpty()) { return Collections.emptyList(); } String name = Constants.UNKNOWN; String vendorId = Constants.UNKNOWN; String productId = Constants.UNKNOWN; String classCode = ""; String versionInfo = Constants.UNKNOWN; for (String line : devices) { if (line.contains("class=0x")) { // Identifies start of a new device. Save previous if it's a graphics card if (PCI_CLASS_DISPLAY.equals(classCode)) { cardList.add(new FreeBsdGraphicsCard(name.isEmpty() ? Constants.UNKNOWN : name, productId.isEmpty() ? Constants.UNKNOWN : productId, vendorId.isEmpty() ? Constants.UNKNOWN : vendorId, versionInfo.isEmpty() ? Constants.UNKNOWN : versionInfo, 0L)); } // Parse this line String[] split = ParseUtil.whitespaces.split(line); for (String s : split) { String[] keyVal = s.split("="); if (keyVal.length > 1) { if (keyVal[0].equals("class") && keyVal[1].length() >= 4) { // class=0x030000 classCode = keyVal[1].substring(0, 4); } else if (keyVal[0].equals("chip") && keyVal[1].length() >= 10) { // chip=0x3ea08086 productId = keyVal[1].substring(0, 6); vendorId = "0x" + keyVal[1].substring(6, 10); } else if (keyVal[0].contains("rev")) { // rev=0x00 versionInfo = s; } } } // Reset name name = Constants.UNKNOWN; } else { String[] split = line.trim().split("=", 2); if (split.length == 2) { String key = split[0].trim(); if (key.equals("vendor")) { vendorId = ParseUtil.getSingleQuoteStringValue(line) + (vendorId.equals(Constants.UNKNOWN) ? "" : " (" + vendorId + ")"); } else if (key.equals("device")) { name = ParseUtil.getSingleQuoteStringValue(line); } } } } // In case we reached end before saving if (PCI_CLASS_DISPLAY.equals(classCode)) { cardList.add(new FreeBsdGraphicsCard(name.isEmpty() ? Constants.UNKNOWN : name, productId.isEmpty() ? Constants.UNKNOWN : productId, vendorId.isEmpty() ? Constants.UNKNOWN : vendorId, versionInfo.isEmpty() ? Constants.UNKNOWN : versionInfo, 0L)); } return cardList;
256
818
1,074
<methods>public java.lang.String getDeviceId() ,public java.lang.String getName() ,public long getVRam() ,public java.lang.String getVendor() ,public java.lang.String getVersionInfo() ,public java.lang.String toString() <variables>private final non-sealed java.lang.String deviceId,private final non-sealed java.lang.String name,private final non-sealed java.lang.String vendor,private final non-sealed java.lang.String versionInfo,private long vram
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdHWDiskStore.java
FreeBsdHWDiskStore
getDisks
class FreeBsdHWDiskStore extends AbstractHWDiskStore { private long reads = 0L; private long readBytes = 0L; private long writes = 0L; private long writeBytes = 0L; private long currentQueueLength = 0L; private long transferTime = 0L; private long timeStamp = 0L; private List<HWPartition> partitionList; private FreeBsdHWDiskStore(String name, String model, String serial, long size) { super(name, model, serial, size); } @Override public long getReads() { return reads; } @Override public long getReadBytes() { return readBytes; } @Override public long getWrites() { return writes; } @Override public long getWriteBytes() { return writeBytes; } @Override public long getCurrentQueueLength() { return currentQueueLength; } @Override public long getTransferTime() { return transferTime; } @Override public long getTimeStamp() { return timeStamp; } @Override public List<HWPartition> getPartitions() { return this.partitionList; } @Override public boolean updateAttributes() { List<String> output = ExecutingCommand.runNative("iostat -Ix " + getName()); long now = System.currentTimeMillis(); boolean diskFound = false; for (String line : output) { String[] split = ParseUtil.whitespaces.split(line); if (split.length < 7 || !split[0].equals(getName())) { continue; } diskFound = true; this.reads = (long) ParseUtil.parseDoubleOrDefault(split[1], 0d); this.writes = (long) ParseUtil.parseDoubleOrDefault(split[2], 0d); // In KB this.readBytes = (long) (ParseUtil.parseDoubleOrDefault(split[3], 0d) * 1024); this.writeBytes = (long) (ParseUtil.parseDoubleOrDefault(split[4], 0d) * 1024); // # transactions this.currentQueueLength = ParseUtil.parseLongOrDefault(split[5], 0L); // In seconds, multiply for ms this.transferTime = (long) (ParseUtil.parseDoubleOrDefault(split[6], 0d) * 1000); this.timeStamp = now; } return diskFound; } /** * Gets the disks on this machine * * @return a list of {@link HWDiskStore} objects representing the disks */ public static List<HWDiskStore> getDisks() {<FILL_FUNCTION_BODY>} }
// Result List<HWDiskStore> diskList = new ArrayList<>(); // Get map of disk names to partitions Map<String, List<HWPartition>> partitionMap = GeomPartList.queryPartitions(); // Get map of disk names to disk info Map<String, Triplet<String, String, Long>> diskInfoMap = GeomDiskList.queryDisks(); // Get list of disks from sysctl List<String> devices = Arrays.asList(ParseUtil.whitespaces.split(BsdSysctlUtil.sysctl("kern.disks", ""))); // Run iostat -Ix to enumerate disks by name and get kb r/w List<String> iostat = ExecutingCommand.runNative("iostat -Ix"); long now = System.currentTimeMillis(); for (String line : iostat) { String[] split = ParseUtil.whitespaces.split(line); if (split.length > 6 && devices.contains(split[0])) { Triplet<String, String, Long> storeInfo = diskInfoMap.get(split[0]); FreeBsdHWDiskStore store = (storeInfo == null) ? new FreeBsdHWDiskStore(split[0], Constants.UNKNOWN, Constants.UNKNOWN, 0L) : new FreeBsdHWDiskStore(split[0], storeInfo.getA(), storeInfo.getB(), storeInfo.getC()); store.reads = (long) ParseUtil.parseDoubleOrDefault(split[1], 0d); store.writes = (long) ParseUtil.parseDoubleOrDefault(split[2], 0d); // In KB store.readBytes = (long) (ParseUtil.parseDoubleOrDefault(split[3], 0d) * 1024); store.writeBytes = (long) (ParseUtil.parseDoubleOrDefault(split[4], 0d) * 1024); // # transactions store.currentQueueLength = ParseUtil.parseLongOrDefault(split[5], 0L); // In seconds, multiply for ms store.transferTime = (long) (ParseUtil.parseDoubleOrDefault(split[6], 0d) * 1000); store.partitionList = Collections .unmodifiableList(partitionMap.getOrDefault(split[0], Collections.emptyList()).stream() .sorted(Comparator.comparing(HWPartition::getName)).collect(Collectors.toList())); store.timeStamp = now; diskList.add(store); } } return diskList;
746
669
1,415
<methods>public java.lang.String getModel() ,public java.lang.String getName() ,public java.lang.String getSerial() ,public long getSize() ,public java.lang.String toString() <variables>private final non-sealed java.lang.String model,private final non-sealed java.lang.String name,private final non-sealed java.lang.String serial,private final non-sealed long size
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSource.java
FreeBsdPowerSource
getPowerSource
class FreeBsdPowerSource extends AbstractPowerSource { public FreeBsdPowerSource(String psName, String psDeviceName, double psRemainingCapacityPercent, double psTimeRemainingEstimated, double psTimeRemainingInstant, double psPowerUsageRate, double psVoltage, double psAmperage, boolean psPowerOnLine, boolean psCharging, boolean psDischarging, CapacityUnits psCapacityUnits, int psCurrentCapacity, int psMaxCapacity, int psDesignCapacity, int psCycleCount, String psChemistry, LocalDate psManufactureDate, String psManufacturer, String psSerialNumber, double psTemperature) { super(psName, psDeviceName, psRemainingCapacityPercent, psTimeRemainingEstimated, psTimeRemainingInstant, psPowerUsageRate, psVoltage, psAmperage, psPowerOnLine, psCharging, psDischarging, psCapacityUnits, psCurrentCapacity, psMaxCapacity, psDesignCapacity, psCycleCount, psChemistry, psManufactureDate, psManufacturer, psSerialNumber, psTemperature); } /** * Gets Battery Information * * @return A list of PowerSource objects representing batteries, etc. */ public static List<PowerSource> getPowerSources() { return Arrays.asList(getPowerSource("BAT0")); } private static FreeBsdPowerSource getPowerSource(String name) {<FILL_FUNCTION_BODY>} }
String psName = name; double psRemainingCapacityPercent = 1d; double psTimeRemainingEstimated = -1d; // -1 = unknown, -2 = unlimited double psPowerUsageRate = 0d; int psVoltage = -1; double psAmperage = 0d; boolean psPowerOnLine = false; boolean psCharging = false; boolean psDischarging = false; CapacityUnits psCapacityUnits = CapacityUnits.RELATIVE; int psCurrentCapacity = 0; int psMaxCapacity = 1; int psDesignCapacity = 1; int psCycleCount = -1; LocalDate psManufactureDate = null; double psTemperature = 0d; // state 0=full, 1=discharging, 2=charging int state = BsdSysctlUtil.sysctl("hw.acpi.battery.state", 0); if (state == 2) { psCharging = true; } else { int time = BsdSysctlUtil.sysctl("hw.acpi.battery.time", -1); // time is in minutes psTimeRemainingEstimated = time < 0 ? -1d : 60d * time; if (state == 1) { psDischarging = true; } } // life is in percent int life = BsdSysctlUtil.sysctl("hw.acpi.battery.life", -1); if (life > 0) { psRemainingCapacityPercent = life / 100d; } List<String> acpiconf = ExecutingCommand.runNative("acpiconf -i 0"); Map<String, String> psMap = new HashMap<>(); for (String line : acpiconf) { String[] split = line.split(":", 2); if (split.length > 1) { String value = split[1].trim(); if (!value.isEmpty()) { psMap.put(split[0], value); } } } String psDeviceName = psMap.getOrDefault("Model number", Constants.UNKNOWN); String psSerialNumber = psMap.getOrDefault("Serial number", Constants.UNKNOWN); String psChemistry = psMap.getOrDefault("Type", Constants.UNKNOWN); String psManufacturer = psMap.getOrDefault("OEM info", Constants.UNKNOWN); String cap = psMap.get("Design capacity"); if (cap != null) { psDesignCapacity = ParseUtil.getFirstIntValue(cap); if (cap.toLowerCase(Locale.ROOT).contains("mah")) { psCapacityUnits = CapacityUnits.MAH; } else if (cap.toLowerCase(Locale.ROOT).contains("mwh")) { psCapacityUnits = CapacityUnits.MWH; } } cap = psMap.get("Last full capacity"); if (cap != null) { psMaxCapacity = ParseUtil.getFirstIntValue(cap); } else { psMaxCapacity = psDesignCapacity; } double psTimeRemainingInstant = psTimeRemainingEstimated; String time = psMap.get("Remaining time"); if (time != null) { String[] hhmm = time.split(":"); if (hhmm.length == 2) { psTimeRemainingInstant = 3600d * ParseUtil.parseIntOrDefault(hhmm[0], 0) + 60d * ParseUtil.parseIntOrDefault(hhmm[1], 0); } } String rate = psMap.get("Present rate"); if (rate != null) { psPowerUsageRate = ParseUtil.getFirstIntValue(rate); } String volts = psMap.get("Present voltage"); if (volts != null) { psVoltage = ParseUtil.getFirstIntValue(volts); if (psVoltage != 0) { psAmperage = psPowerUsageRate / psVoltage; } } return new FreeBsdPowerSource(psName, psDeviceName, psRemainingCapacityPercent, psTimeRemainingEstimated, psTimeRemainingInstant, psPowerUsageRate, psVoltage, psAmperage, psPowerOnLine, psCharging, psDischarging, psCapacityUnits, psCurrentCapacity, psMaxCapacity, psDesignCapacity, psCycleCount, psChemistry, psManufactureDate, psManufacturer, psSerialNumber, psTemperature);
387
1,205
1,592
<methods>public double getAmperage() ,public oshi.hardware.PowerSource.CapacityUnits getCapacityUnits() ,public java.lang.String getChemistry() ,public int getCurrentCapacity() ,public int getCycleCount() ,public int getDesignCapacity() ,public java.lang.String getDeviceName() ,public java.time.LocalDate getManufactureDate() ,public java.lang.String getManufacturer() ,public int getMaxCapacity() ,public java.lang.String getName() ,public double getPowerUsageRate() ,public double getRemainingCapacityPercent() ,public java.lang.String getSerialNumber() ,public double getTemperature() ,public double getTimeRemainingEstimated() ,public double getTimeRemainingInstant() ,public double getVoltage() ,public boolean isCharging() ,public boolean isDischarging() ,public boolean isPowerOnLine() ,public java.lang.String toString() ,public boolean updateAttributes() <variables>private double amperage,private oshi.hardware.PowerSource.CapacityUnits capacityUnits,private boolean charging,private java.lang.String chemistry,private int currentCapacity,private int cycleCount,private int designCapacity,private java.lang.String deviceName,private boolean discharging,private java.time.LocalDate manufactureDate,private java.lang.String manufacturer,private int maxCapacity,private java.lang.String name,private boolean powerOnLine,private double powerUsageRate,private double remainingCapacityPercent,private java.lang.String serialNumber,private double temperature,private double timeRemainingEstimated,private double timeRemainingInstant,private double voltage
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdSensors.java
FreeBsdSensors
queryKldloadCoretemp
class FreeBsdSensors extends AbstractSensors { @Override public double queryCpuTemperature() { return queryKldloadCoretemp(); } /* * If user has loaded coretemp module via kldload coretemp, sysctl call will return temperature * * @return Temperature if successful, otherwise NaN */ private static double queryKldloadCoretemp() {<FILL_FUNCTION_BODY>} @Override public int[] queryFanSpeeds() { // Nothing known on FreeBSD for this. return new int[0]; } @Override public double queryCpuVoltage() { // Nothing known on FreeBSD for this. return 0d; } }
String name = "dev.cpu.%d.temperature"; try (CloseableSizeTByReference size = new CloseableSizeTByReference(FreeBsdLibc.INT_SIZE)) { int cpu = 0; double sumTemp = 0d; try (Memory p = new Memory(size.longValue())) { while (0 == FreeBsdLibc.INSTANCE.sysctlbyname(String.format(Locale.ROOT, name, cpu), p, size, null, size_t.ZERO)) { sumTemp += p.getInt(0) / 10d - 273.15; cpu++; } } return cpu > 0 ? sumTemp / cpu : Double.NaN; }
194
194
388
<methods>public non-sealed void <init>() ,public double getCpuTemperature() ,public double getCpuVoltage() ,public int[] getFanSpeeds() ,public java.lang.String toString() <variables>private final Supplier<java.lang.Double> cpuTemperature,private final Supplier<java.lang.Double> cpuVoltage,private final Supplier<int[]> fanSpeeds
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdSoundCard.java
FreeBsdSoundCard
getSoundCards
class FreeBsdSoundCard extends AbstractSoundCard { private static final String LSHAL = "lshal"; /** * Constructor for FreeBsdSoundCard. * * @param kernelVersion The version * @param name The name * @param codec The codec */ FreeBsdSoundCard(String kernelVersion, String name, String codec) { super(kernelVersion, name, codec); } /** * <p> * getSoundCards. * </p> * * @return a {@link java.util.List} object. */ public static List<SoundCard> getSoundCards() {<FILL_FUNCTION_BODY>} }
Map<String, String> vendorMap = new HashMap<>(); Map<String, String> productMap = new HashMap<>(); vendorMap.clear(); productMap.clear(); List<String> sounds = new ArrayList<>(); String key = ""; for (String line : ExecutingCommand.runNative(LSHAL)) { line = line.trim(); if (line.startsWith("udi =")) { // we have the key. key = ParseUtil.getSingleQuoteStringValue(line); } else if (!key.isEmpty() && !line.isEmpty()) { if (line.contains("freebsd.driver =") && "pcm".equals(ParseUtil.getSingleQuoteStringValue(line))) { sounds.add(key); } else if (line.contains("info.product")) { productMap.put(key, ParseUtil.getStringBetween(line, '\'')); } else if (line.contains("info.vendor")) { vendorMap.put(key, ParseUtil.getStringBetween(line, '\'')); } } } List<SoundCard> soundCards = new ArrayList<>(); for (String s : sounds) { soundCards.add(new FreeBsdSoundCard(productMap.get(s), vendorMap.get(s) + " " + productMap.get(s), productMap.get(s))); } return soundCards;
189
360
549
<methods>public java.lang.String getCodec() ,public java.lang.String getDriverVersion() ,public java.lang.String getName() ,public java.lang.String toString() <variables>private java.lang.String codec,private java.lang.String kernelVersion,private java.lang.String name
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdUsbDevice.java
FreeBsdUsbDevice
getUsbDevices
class FreeBsdUsbDevice extends AbstractUsbDevice { public FreeBsdUsbDevice(String name, String vendor, String vendorId, String productId, String serialNumber, String uniqueDeviceId, List<UsbDevice> connectedDevices) { super(name, vendor, vendorId, productId, serialNumber, uniqueDeviceId, connectedDevices); } /** * Instantiates a list of {@link oshi.hardware.UsbDevice} objects, representing devices connected via a usb port * (including internal devices). * <p> * If the value of {@code tree} is true, the top level devices returned from this method are the USB Controllers; * connected hubs and devices in its device tree share that controller's bandwidth. If the value of {@code tree} is * false, USB devices (not controllers) are listed in a single flat list. * * @param tree If true, returns a list of controllers, which requires recursive iteration of connected devices. If * false, returns a flat list of devices excluding controllers. * @return a list of {@link oshi.hardware.UsbDevice} objects. */ public static List<UsbDevice> getUsbDevices(boolean tree) { List<UsbDevice> devices = getUsbDevices(); if (tree) { return devices; } List<UsbDevice> deviceList = new ArrayList<>(); // Top level is controllers; they won't be added to the list, but all // their connected devices will be for (UsbDevice device : devices) { deviceList.add(new FreeBsdUsbDevice(device.getName(), device.getVendor(), device.getVendorId(), device.getProductId(), device.getSerialNumber(), device.getUniqueDeviceId(), Collections.emptyList())); addDevicesToList(deviceList, device.getConnectedDevices()); } return deviceList; } private static List<UsbDevice> getUsbDevices() {<FILL_FUNCTION_BODY>} private static void addDevicesToList(List<UsbDevice> deviceList, List<UsbDevice> list) { for (UsbDevice device : list) { deviceList.add(device); addDevicesToList(deviceList, device.getConnectedDevices()); } } /** * Recursively creates FreeBsdUsbDevices by fetching information from maps to populate fields * * @param devPath The device node path. * @param vid The default (parent) vendor ID * @param pid The default (parent) product ID * @param nameMap the map of names * @param vendorMap the map of vendors * @param vendorIdMap the map of vendorIds * @param productIdMap the map of productIds * @param serialMap the map of serial numbers * @param hubMap the map of hubs * @return A SolarisUsbDevice corresponding to this device */ private static FreeBsdUsbDevice getDeviceAndChildren(String devPath, String vid, String pid, Map<String, String> nameMap, Map<String, String> vendorMap, Map<String, String> vendorIdMap, Map<String, String> productIdMap, Map<String, String> serialMap, Map<String, List<String>> hubMap) { String vendorId = vendorIdMap.getOrDefault(devPath, vid); String productId = productIdMap.getOrDefault(devPath, pid); List<String> childPaths = hubMap.getOrDefault(devPath, new ArrayList<>()); List<UsbDevice> usbDevices = new ArrayList<>(); for (String path : childPaths) { usbDevices.add(getDeviceAndChildren(path, vendorId, productId, nameMap, vendorMap, vendorIdMap, productIdMap, serialMap, hubMap)); } Collections.sort(usbDevices); return new FreeBsdUsbDevice(nameMap.getOrDefault(devPath, vendorId + ":" + productId), vendorMap.getOrDefault(devPath, ""), vendorId, productId, serialMap.getOrDefault(devPath, ""), devPath, usbDevices); } }
// Maps to store information using node # as the key Map<String, String> nameMap = new HashMap<>(); Map<String, String> vendorMap = new HashMap<>(); Map<String, String> vendorIdMap = new HashMap<>(); Map<String, String> productIdMap = new HashMap<>(); Map<String, String> serialMap = new HashMap<>(); Map<String, String> parentMap = new HashMap<>(); Map<String, List<String>> hubMap = new HashMap<>(); // Enumerate all devices and build information maps. This will build the // entire device tree; we will identify the controllers as the parents // of the usbus entries and eventually only populate the returned // results with those List<String> devices = ExecutingCommand.runNative("lshal"); if (devices.isEmpty()) { return Collections.emptyList(); } // For each item enumerated, store information in the maps String key = ""; List<String> usBuses = new ArrayList<>(); for (String line : devices) { // udi = ... identifies start of a new tree if (line.startsWith("udi =")) { // Remove indent for key key = ParseUtil.getSingleQuoteStringValue(line); } else if (!key.isEmpty()) { // We are currently processing for node identified by key. Save // approrpriate variables to maps. line = line.trim(); if (!line.isEmpty()) { if (line.startsWith("freebsd.driver =") && "usbus".equals(ParseUtil.getSingleQuoteStringValue(line))) { usBuses.add(key); } else if (line.contains(".parent =")) { String parent = ParseUtil.getSingleQuoteStringValue(line); // If this is interface of parent, skip if (key.replace(parent, "").startsWith("_if")) { continue; } // Store parent for later usbus-skipping parentMap.put(key, parent); // Add this key to the parent's hubmap list hubMap.computeIfAbsent(parent, x -> new ArrayList<>()).add(key); } else if (line.contains(".product =")) { nameMap.put(key, ParseUtil.getSingleQuoteStringValue(line)); } else if (line.contains(".vendor =")) { vendorMap.put(key, ParseUtil.getSingleQuoteStringValue(line)); } else if (line.contains(".serial =")) { String serial = ParseUtil.getSingleQuoteStringValue(line); serialMap.put(key, serial.startsWith("0x") ? ParseUtil.hexStringToString(serial.replace("0x", "")) : serial); } else if (line.contains(".vendor_id =")) { vendorIdMap.put(key, String.format(Locale.ROOT, "%04x", ParseUtil.getFirstIntValue(line))); } else if (line.contains(".product_id =")) { productIdMap.put(key, String.format(Locale.ROOT, "%04x", ParseUtil.getFirstIntValue(line))); } } } } // Build tree and return List<UsbDevice> controllerDevices = new ArrayList<>(); for (String usbus : usBuses) { // Skip the usbuses: make their parents the controllers and replace // parents' children with the buses' children String parent = parentMap.get(usbus); hubMap.put(parent, hubMap.get(usbus)); controllerDevices.add(getDeviceAndChildren(parent, "0000", "0000", nameMap, vendorMap, vendorIdMap, productIdMap, serialMap, hubMap)); } return controllerDevices;
1,073
974
2,047
<methods>public int compareTo(oshi.hardware.UsbDevice) ,public List<oshi.hardware.UsbDevice> getConnectedDevices() ,public java.lang.String getName() ,public java.lang.String getProductId() ,public java.lang.String getSerialNumber() ,public java.lang.String getUniqueDeviceId() ,public java.lang.String getVendor() ,public java.lang.String getVendorId() ,public java.lang.String toString() <variables>private final non-sealed List<oshi.hardware.UsbDevice> connectedDevices,private final non-sealed java.lang.String name,private final non-sealed java.lang.String productId,private final non-sealed java.lang.String serialNumber,private final non-sealed java.lang.String uniqueDeviceId,private final non-sealed java.lang.String vendor,private final non-sealed java.lang.String vendorId
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdVirtualMemory.java
FreeBsdVirtualMemory
querySwapUsed
class FreeBsdVirtualMemory extends AbstractVirtualMemory { private final FreeBsdGlobalMemory global; private final Supplier<Long> used = memoize(FreeBsdVirtualMemory::querySwapUsed, defaultExpiration()); private final Supplier<Long> total = memoize(FreeBsdVirtualMemory::querySwapTotal, defaultExpiration()); private final Supplier<Long> pagesIn = memoize(FreeBsdVirtualMemory::queryPagesIn, defaultExpiration()); private final Supplier<Long> pagesOut = memoize(FreeBsdVirtualMemory::queryPagesOut, defaultExpiration()); FreeBsdVirtualMemory(FreeBsdGlobalMemory freeBsdGlobalMemory) { this.global = freeBsdGlobalMemory; } @Override public long getSwapUsed() { return used.get(); } @Override public long getSwapTotal() { return total.get(); } @Override public long getVirtualMax() { return this.global.getTotal() + getSwapTotal(); } @Override public long getVirtualInUse() { return this.global.getTotal() - this.global.getAvailable() + getSwapUsed(); } @Override public long getSwapPagesIn() { return pagesIn.get(); } @Override public long getSwapPagesOut() { return pagesOut.get(); } private static long querySwapUsed() {<FILL_FUNCTION_BODY>} private static long querySwapTotal() { return BsdSysctlUtil.sysctl("vm.swap_total", 0L); } private static long queryPagesIn() { return BsdSysctlUtil.sysctl("vm.stats.vm.v_swappgsin", 0L); } private static long queryPagesOut() { return BsdSysctlUtil.sysctl("vm.stats.vm.v_swappgsout", 0L); } }
String swapInfo = ExecutingCommand.getAnswerAt("swapinfo -k", 1); String[] split = ParseUtil.whitespaces.split(swapInfo); if (split.length < 5) { return 0L; } return ParseUtil.parseLongOrDefault(split[2], 0L) << 10;
515
90
605
<methods>public non-sealed void <init>() ,public java.lang.String toString() <variables>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdFirmware.java
OpenBsdFirmware
readDmesg
class OpenBsdFirmware extends AbstractFirmware { private final Supplier<Triplet<String, String, String>> manufVersRelease = memoize(OpenBsdFirmware::readDmesg); @Override public String getManufacturer() { return manufVersRelease.get().getA(); } @Override public String getVersion() { return manufVersRelease.get().getB(); } @Override public String getReleaseDate() { return manufVersRelease.get().getC(); } private static Triplet<String, String, String> readDmesg() {<FILL_FUNCTION_BODY>} }
String version = null; String vendor = null; String releaseDate = ""; List<String> dmesg = ExecutingCommand.runNative("dmesg"); for (String line : dmesg) { // bios0 at mainbus0: SMBIOS rev. 2.7 @ 0xdcc0e000 (67 entries) // bios0: vendor LENOVO version "GLET90WW (2.44 )" date 09/13/2017 // bios0: LENOVO 20AWA08J00 if (line.startsWith("bios0: vendor")) { version = ParseUtil.getStringBetween(line, '"'); releaseDate = ParseUtil.parseMmDdYyyyToYyyyMmDD(ParseUtil.parseLastString(line)); vendor = line.split("vendor")[1].trim(); } } return new Triplet<>(Util.isBlank(vendor) ? Constants.UNKNOWN : vendor, Util.isBlank(version) ? Constants.UNKNOWN : version, Util.isBlank(releaseDate) ? Constants.UNKNOWN : releaseDate);
177
312
489
<methods>public non-sealed void <init>() ,public java.lang.String getDescription() ,public java.lang.String getName() ,public java.lang.String getReleaseDate() ,public java.lang.String toString() <variables>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdGlobalMemory.java
OpenBsdGlobalMemory
queryAvailable
class OpenBsdGlobalMemory extends AbstractGlobalMemory { private final Supplier<Long> available = memoize(OpenBsdGlobalMemory::queryAvailable, defaultExpiration()); private final Supplier<Long> total = memoize(OpenBsdGlobalMemory::queryPhysMem); private final Supplier<Long> pageSize = memoize(OpenBsdGlobalMemory::queryPageSize); private final Supplier<VirtualMemory> vm = memoize(this::createVirtualMemory); @Override public long getAvailable() { return available.get() * getPageSize(); } @Override public long getTotal() { return total.get(); } @Override public long getPageSize() { return pageSize.get(); } @Override public VirtualMemory getVirtualMemory() { return vm.get(); } private static long queryAvailable() {<FILL_FUNCTION_BODY>} private static long queryPhysMem() { return OpenBsdSysctlUtil.sysctl("hw.physmem", 0L); } private static long queryPageSize() { return OpenBsdSysctlUtil.sysctl("hw.pagesize", 4096L); } private VirtualMemory createVirtualMemory() { return new OpenBsdVirtualMemory(this); } }
long free = 0L; long inactive = 0L; for (String line : ExecutingCommand.runNative("vmstat -s")) { if (line.endsWith("pages free")) { free = ParseUtil.getFirstIntValue(line); } else if (line.endsWith("pages inactive")) { inactive = ParseUtil.getFirstIntValue(line); } } int[] mib = new int[3]; mib[0] = CTL_VFS; mib[1] = VFS_GENERIC; mib[2] = VFS_BCACHESTAT; try (Memory m = OpenBsdSysctlUtil.sysctl(mib)) { Bcachestats cache = new Bcachestats(m); return (cache.numbufpages + free + inactive); }
345
217
562
<methods>public non-sealed void <init>() ,public List<oshi.hardware.PhysicalMemory> getPhysicalMemory() ,public java.lang.String toString() <variables>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdGraphicsCard.java
OpenBsdGraphicsCard
getGraphicsCards
class OpenBsdGraphicsCard extends AbstractGraphicsCard { private static final String PCI_CLASS_DISPLAY = "Class: 03 Display"; private static final Pattern PCI_DUMP_HEADER = Pattern.compile(" \\d+:\\d+:\\d+: (.+)"); /** * Constructor for OpenBsdGraphicsCard * * @param name The name * @param deviceId The device ID * @param vendor The vendor * @param versionInfo The version info * @param vram The VRAM */ OpenBsdGraphicsCard(String name, String deviceId, String vendor, String versionInfo, long vram) { super(name, deviceId, vendor, versionInfo, vram); } /** * public method used by {@link oshi.hardware.common.AbstractHardwareAbstractionLayer} to access the graphics cards. * * @return List of {@link oshi.hardware.platform.unix.freebsd.OpenBsdGraphicsCard} objects. */ public static List<GraphicsCard> getGraphicsCards() {<FILL_FUNCTION_BODY>} }
List<GraphicsCard> cardList = new ArrayList<>(); // Enumerate all devices and add if required List<String> devices = ExecutingCommand.runNative("pcidump -v"); if (devices.isEmpty()) { return Collections.emptyList(); } String name = ""; String vendorId = ""; String productId = ""; boolean classCodeFound = false; String versionInfo = ""; for (String line : devices) { Matcher m = PCI_DUMP_HEADER.matcher(line); if (m.matches()) { // Identifies start of a new device. Save previous if it's a graphics card if (classCodeFound) { cardList.add(new OpenBsdGraphicsCard(name.isEmpty() ? Constants.UNKNOWN : name, productId.isEmpty() ? "0x0000" : productId, vendorId.isEmpty() ? "0x0000" : vendorId, versionInfo.isEmpty() ? Constants.UNKNOWN : versionInfo, 0L)); } // Device name is the captured pattern name = m.group(1); // Reset values vendorId = ""; productId = ""; classCodeFound = false; versionInfo = ""; } else { int idx; // Look for: // 0x0000: Vendor ID: 1ab8, Product ID: 4005 // 0x0008: Class: 03 Display, Subclass: 00 VGA // ....... Interface: 00, Revision: 00 if (!classCodeFound) { idx = line.indexOf("Vendor ID: "); if (idx >= 0 && line.length() >= idx + 15) { vendorId = "0x" + line.substring(idx + 11, idx + 15); } idx = line.indexOf("Product ID: "); if (idx >= 0 && line.length() >= idx + 16) { productId = "0x" + line.substring(idx + 12, idx + 16); } if (line.contains(PCI_CLASS_DISPLAY)) { classCodeFound = true; } } else if (versionInfo.isEmpty()) { idx = line.indexOf("Revision: "); if (idx >= 0) { versionInfo = line.substring(idx); } } } } // In case we reached end before saving if (classCodeFound) { cardList.add(new OpenBsdGraphicsCard(name.isEmpty() ? Constants.UNKNOWN : name, productId.isEmpty() ? "0x0000" : productId, vendorId.isEmpty() ? "0x0000" : vendorId, versionInfo.isEmpty() ? Constants.UNKNOWN : versionInfo, 0L)); } return cardList;
294
737
1,031
<methods>public java.lang.String getDeviceId() ,public java.lang.String getName() ,public long getVRam() ,public java.lang.String getVendor() ,public java.lang.String getVersionInfo() ,public java.lang.String toString() <variables>private final non-sealed java.lang.String deviceId,private final non-sealed java.lang.String name,private final non-sealed java.lang.String vendor,private final non-sealed java.lang.String versionInfo,private long vram
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdHWDiskStore.java
OpenBsdHWDiskStore
getDisks
class OpenBsdHWDiskStore extends AbstractHWDiskStore { private final Supplier<List<String>> iostat = memoize(OpenBsdHWDiskStore::querySystatIostat, defaultExpiration()); private long reads = 0L; private long readBytes = 0L; private long writes = 0L; private long writeBytes = 0L; private long currentQueueLength = 0L; private long transferTime = 0L; private long timeStamp = 0L; private List<HWPartition> partitionList; private OpenBsdHWDiskStore(String name, String model, String serial, long size) { super(name, model, serial, size); } /** * Gets the disks on this machine. * * @return a list of {@link HWDiskStore} objects representing the disks */ public static List<HWDiskStore> getDisks() {<FILL_FUNCTION_BODY>} @Override public long getReads() { return reads; } @Override public long getReadBytes() { return readBytes; } @Override public long getWrites() { return writes; } @Override public long getWriteBytes() { return writeBytes; } @Override public long getCurrentQueueLength() { return currentQueueLength; } @Override public long getTransferTime() { return transferTime; } @Override public long getTimeStamp() { return timeStamp; } @Override public List<HWPartition> getPartitions() { return this.partitionList; } @Override public boolean updateAttributes() { /*- └─ $ ▶ systat -b iostat 0 users Load 2.04 4.02 3.96 thinkpad.local 00:14:35 DEVICE READ WRITE RTPS WTPS SEC STATS sd0 49937M 25774M 1326555 1695370 945.9 cd0 0 0 0 0 0.0 sd1 1573888 204 29 0 0.1 Totals 49939M 25774M 1326585 1695371 946.0 126568 total pages 126568 dma pages 100 dirty pages 14 delwri bufs 0 busymap bufs 6553 avail kvaslots 6553 kvaslots 0 pending writes 12 pending reads 0 cache hits 0 high flips 0 high flops 0 dma flips */ long now = System.currentTimeMillis(); boolean diskFound = false; for (String line : iostat.get()) { String[] split = ParseUtil.whitespaces.split(line); if (split.length < 7 && split[0].equals(getName())) { diskFound = true; this.readBytes = ParseUtil.parseMultipliedToLongs(split[1]); this.writeBytes = ParseUtil.parseMultipliedToLongs(split[2]); this.reads = (long) ParseUtil.parseDoubleOrDefault(split[3], 0d); this.writes = (long) ParseUtil.parseDoubleOrDefault(split[4], 0d); // In seconds, multiply for ms this.transferTime = (long) (ParseUtil.parseDoubleOrDefault(split[5], 0d) * 1000); this.timeStamp = now; } } return diskFound; } private static List<String> querySystatIostat() { return ExecutingCommand.runNative("systat -ab iostat"); } }
List<HWDiskStore> diskList = new ArrayList<>(); List<String> dmesg = null; // Lazily fetch in loop if needed // Get list of disks from sysctl // hw.disknames=sd0:2cf69345d371cd82,cd0:,sd1: String[] devices = OpenBsdSysctlUtil.sysctl("hw.disknames", "").split(","); OpenBsdHWDiskStore store; String diskName; for (String device : devices) { diskName = device.split(":")[0]; // get partitions using disklabel command (requires root) Quartet<String, String, Long, List<HWPartition>> diskdata = Disklabel.getDiskParams(diskName); String model = diskdata.getA(); long size = diskdata.getC(); if (size <= 1) { if (dmesg == null) { dmesg = ExecutingCommand.runNative("dmesg"); } Pattern diskAt = Pattern.compile(diskName + " at .*<(.+)>.*"); Pattern diskMB = Pattern .compile(diskName + ":.* (\\d+)MB, (?:(\\d+) bytes\\/sector, )?(?:(\\d+) sectors).*"); for (String line : dmesg) { Matcher m = diskAt.matcher(line); if (m.matches()) { model = m.group(1); } m = diskMB.matcher(line); if (m.matches()) { // Group 3 is sectors long sectors = ParseUtil.parseLongOrDefault(m.group(3), 0L); // Group 2 is optional capture of bytes per sector long bytesPerSector = ParseUtil.parseLongOrDefault(m.group(2), 0L); if (bytesPerSector == 0 && sectors > 0) { // if we don't have bytes per sector guess at it based on total size and number // of sectors // Group 1 is size in MB, which may round size = ParseUtil.parseLongOrDefault(m.group(1), 0L) << 20; // Estimate bytes per sector. Should be "near" a power of 2 bytesPerSector = size / sectors; // Multiply by 1.5 and round down to nearest power of 2: bytesPerSector = Long.highestOneBit(bytesPerSector + bytesPerSector >> 1); } size = bytesPerSector * sectors; break; } } } store = new OpenBsdHWDiskStore(diskName, model, diskdata.getB(), size); store.partitionList = diskdata.getD(); store.updateAttributes(); diskList.add(store); } return diskList;
1,057
730
1,787
<methods>public java.lang.String getModel() ,public java.lang.String getName() ,public java.lang.String getSerial() ,public long getSize() ,public java.lang.String toString() <variables>private final non-sealed java.lang.String model,private final non-sealed java.lang.String name,private final non-sealed java.lang.String serial,private final non-sealed long size
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdPowerSource.java
OpenBsdPowerSource
getPowerSource
class OpenBsdPowerSource extends AbstractPowerSource { public OpenBsdPowerSource(String psName, String psDeviceName, double psRemainingCapacityPercent, double psTimeRemainingEstimated, double psTimeRemainingInstant, double psPowerUsageRate, double psVoltage, double psAmperage, boolean psPowerOnLine, boolean psCharging, boolean psDischarging, CapacityUnits psCapacityUnits, int psCurrentCapacity, int psMaxCapacity, int psDesignCapacity, int psCycleCount, String psChemistry, LocalDate psManufactureDate, String psManufacturer, String psSerialNumber, double psTemperature) { super(psName, psDeviceName, psRemainingCapacityPercent, psTimeRemainingEstimated, psTimeRemainingInstant, psPowerUsageRate, psVoltage, psAmperage, psPowerOnLine, psCharging, psDischarging, psCapacityUnits, psCurrentCapacity, psMaxCapacity, psDesignCapacity, psCycleCount, psChemistry, psManufactureDate, psManufacturer, psSerialNumber, psTemperature); } /** * Gets Battery Information * * @return An array of PowerSource objects representing batteries, etc. */ public static List<PowerSource> getPowerSources() { Set<String> psNames = new HashSet<>(); for (String line : ExecutingCommand.runNative("systat -ab sensors")) { if (line.contains(".amphour") || line.contains(".watthour")) { int dot = line.indexOf('.'); psNames.add(line.substring(0, dot)); } } List<PowerSource> psList = new ArrayList<>(); for (String name : psNames) { psList.add(getPowerSource(name)); } return psList; } private static OpenBsdPowerSource getPowerSource(String name) {<FILL_FUNCTION_BODY>} }
String psName = name.startsWith("acpi") ? name.substring(4) : name; double psRemainingCapacityPercent = 1d; double psTimeRemainingEstimated = -1d; // -1 = unknown, -2 = unlimited double psPowerUsageRate = 0d; double psVoltage = -1d; double psAmperage = 0d; boolean psPowerOnLine = false; boolean psCharging = false; boolean psDischarging = false; CapacityUnits psCapacityUnits = CapacityUnits.RELATIVE; int psCurrentCapacity = 0; int psMaxCapacity = 1; int psDesignCapacity = 1; int psCycleCount = -1; LocalDate psManufactureDate = null; double psTemperature = 0d; for (String line : ExecutingCommand.runNative("systat -ab sensors")) { String[] split = ParseUtil.whitespaces.split(line); if (split.length > 1 && split[0].startsWith(name)) { if (split[0].contains("volt0") || split[0].contains("volt") && line.contains("current")) { psVoltage = ParseUtil.parseDoubleOrDefault(split[1], -1d); } else if (split[0].contains("current0")) { psAmperage = ParseUtil.parseDoubleOrDefault(split[1], 0d); } else if (split[0].contains("temp0")) { psTemperature = ParseUtil.parseDoubleOrDefault(split[1], 0d); } else if (split[0].contains("watthour") || split[0].contains("amphour")) { psCapacityUnits = split[0].contains("watthour") ? CapacityUnits.MWH : CapacityUnits.MAH; if (line.contains("remaining")) { psCurrentCapacity = (int) (1000d * ParseUtil.parseDoubleOrDefault(split[1], 0d)); } else if (line.contains("full")) { psMaxCapacity = (int) (1000d * ParseUtil.parseDoubleOrDefault(split[1], 0d)); } else if (line.contains("new") || line.contains("design")) { psDesignCapacity = (int) (1000d * ParseUtil.parseDoubleOrDefault(split[1], 0d)); } } } } int state = ParseUtil.parseIntOrDefault(ExecutingCommand.getFirstAnswer("apm -b"), 255); // state 0=high, 1=low, 2=critical, 3=charging, 4=absent, 255=unknown if (state < 4) { psPowerOnLine = true; if (state == 3) { psCharging = true; } else { int time = ParseUtil.parseIntOrDefault(ExecutingCommand.getFirstAnswer("apm -m"), -1); // time is in minutes psTimeRemainingEstimated = time < 0 ? -1d : 60d * time; psDischarging = true; } } // life is in percent int life = ParseUtil.parseIntOrDefault(ExecutingCommand.getFirstAnswer("apm -l"), -1); if (life > 0) { psRemainingCapacityPercent = life / 100d; } if (psMaxCapacity < psDesignCapacity && psMaxCapacity < psCurrentCapacity) { psMaxCapacity = psDesignCapacity; } else if (psDesignCapacity < psMaxCapacity && psDesignCapacity < psCurrentCapacity) { psDesignCapacity = psMaxCapacity; } String psDeviceName = Constants.UNKNOWN; String psSerialNumber = Constants.UNKNOWN; String psChemistry = Constants.UNKNOWN; String psManufacturer = Constants.UNKNOWN; double psTimeRemainingInstant = psTimeRemainingEstimated; if (psVoltage > 0) { if (psAmperage > 0 && psPowerUsageRate == 0) { psPowerUsageRate = psAmperage * psVoltage; } else if (psAmperage == 0 && psPowerUsageRate > 0) { psAmperage = psPowerUsageRate / psVoltage; } } return new OpenBsdPowerSource(psName, psDeviceName, psRemainingCapacityPercent, psTimeRemainingEstimated, psTimeRemainingInstant, psPowerUsageRate, psVoltage, psAmperage, psPowerOnLine, psCharging, psDischarging, psCapacityUnits, psCurrentCapacity, psMaxCapacity, psDesignCapacity, psCycleCount, psChemistry, psManufactureDate, psManufacturer, psSerialNumber, psTemperature);
507
1,266
1,773
<methods>public double getAmperage() ,public oshi.hardware.PowerSource.CapacityUnits getCapacityUnits() ,public java.lang.String getChemistry() ,public int getCurrentCapacity() ,public int getCycleCount() ,public int getDesignCapacity() ,public java.lang.String getDeviceName() ,public java.time.LocalDate getManufactureDate() ,public java.lang.String getManufacturer() ,public int getMaxCapacity() ,public java.lang.String getName() ,public double getPowerUsageRate() ,public double getRemainingCapacityPercent() ,public java.lang.String getSerialNumber() ,public double getTemperature() ,public double getTimeRemainingEstimated() ,public double getTimeRemainingInstant() ,public double getVoltage() ,public boolean isCharging() ,public boolean isDischarging() ,public boolean isPowerOnLine() ,public java.lang.String toString() ,public boolean updateAttributes() <variables>private double amperage,private oshi.hardware.PowerSource.CapacityUnits capacityUnits,private boolean charging,private java.lang.String chemistry,private int currentCapacity,private int cycleCount,private int designCapacity,private java.lang.String deviceName,private boolean discharging,private java.time.LocalDate manufactureDate,private java.lang.String manufacturer,private int maxCapacity,private java.lang.String name,private boolean powerOnLine,private double powerUsageRate,private double remainingCapacityPercent,private java.lang.String serialNumber,private double temperature,private double timeRemainingEstimated,private double timeRemainingInstant,private double voltage
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdSensors.java
OpenBsdSensors
querySensors
class OpenBsdSensors extends AbstractSensors { private final Supplier<Triplet<Double, int[], Double>> tempFanVolts = memoize(OpenBsdSensors::querySensors, defaultExpiration()); @Override public double queryCpuTemperature() { return tempFanVolts.get().getA(); } @Override public int[] queryFanSpeeds() { return tempFanVolts.get().getB(); } @Override public double queryCpuVoltage() { return tempFanVolts.get().getC(); } private static Triplet<Double, int[], Double> querySensors() {<FILL_FUNCTION_BODY>} private static double listAverage(List<Double> doubles) { double sum = 0d; int count = 0; for (Double d : doubles) { if (!d.isNaN()) { sum += d; count++; } } return count > 0 ? sum / count : 0d; } }
double volts = 0d; List<Double> cpuTemps = new ArrayList<>(); List<Double> allTemps = new ArrayList<>(); List<Integer> fanRPMs = new ArrayList<>(); for (String line : ExecutingCommand.runNative("systat -ab sensors")) { String[] split = ParseUtil.whitespaces.split(line); if (split.length > 1) { if (split[0].contains("cpu")) { if (split[0].contains("temp0")) { cpuTemps.add(ParseUtil.parseDoubleOrDefault(split[1], Double.NaN)); } else if (split[0].contains("volt0")) { volts = ParseUtil.parseDoubleOrDefault(split[1], 0d); } } else if (split[0].contains("temp0")) { allTemps.add(ParseUtil.parseDoubleOrDefault(split[1], Double.NaN)); } else if (split[0].contains("fan")) { fanRPMs.add(ParseUtil.parseIntOrDefault(split[1], 0)); } } } // Prefer cpu temps double temp = cpuTemps.isEmpty() ? listAverage(allTemps) : listAverage(cpuTemps); // Collect all fans int[] fans = new int[fanRPMs.size()]; for (int i = 0; i < fans.length; i++) { fans[i] = fanRPMs.get(i); } return new Triplet<>(temp, fans, volts);
287
410
697
<methods>public non-sealed void <init>() ,public double getCpuTemperature() ,public double getCpuVoltage() ,public int[] getFanSpeeds() ,public java.lang.String toString() <variables>private final Supplier<java.lang.Double> cpuTemperature,private final Supplier<java.lang.Double> cpuVoltage,private final Supplier<int[]> fanSpeeds
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdSoundCard.java
OpenBsdSoundCard
getSoundCards
class OpenBsdSoundCard extends AbstractSoundCard { private static final Pattern AUDIO_AT = Pattern.compile("audio\\d+ at (.+)"); private static final Pattern PCI_AT = Pattern .compile("(.+) at pci\\d+ dev \\d+ function \\d+ \"(.*)\" (rev .+):.*"); /** * Constructor for OpenBsdSoundCard. * * @param kernelVersion The version * @param name The name * @param codec The codec */ OpenBsdSoundCard(String kernelVersion, String name, String codec) { super(kernelVersion, name, codec); } /** * <p> * getSoundCards. * </p> * * @return a {@link java.util.List} object. */ public static List<SoundCard> getSoundCards() {<FILL_FUNCTION_BODY>} }
List<String> dmesg = ExecutingCommand.runNative("dmesg"); // Iterate dmesg once to collect location of audioN Set<String> names = new HashSet<>(); for (String line : dmesg) { Matcher m = AUDIO_AT.matcher(line); if (m.matches()) { names.add(m.group(1)); } } // Iterate again and add cards when they match the name Map<String, String> nameMap = new HashMap<>(); Map<String, String> codecMap = new HashMap<>(); Map<String, String> versionMap = new HashMap<>(); String key = ""; for (String line : dmesg) { Matcher m = PCI_AT.matcher(line); if (m.matches() && names.contains(m.group(1))) { key = m.group(1); nameMap.put(key, m.group(2)); versionMap.put(key, m.group(3)); } else if (!key.isEmpty()) { // Codec is on the next line int idx = line.indexOf("codec"); if (idx >= 0) { idx = line.indexOf(':'); codecMap.put(key, line.substring(idx + 1).trim()); } // clear key so we don't keep looking key = ""; } } List<SoundCard> soundCards = new ArrayList<>(); for (Entry<String, String> entry : nameMap.entrySet()) { soundCards.add(new OpenBsdSoundCard(versionMap.get(entry.getKey()), entry.getValue(), codecMap.get(entry.getKey()))); } return soundCards;
248
451
699
<methods>public java.lang.String getCodec() ,public java.lang.String getDriverVersion() ,public java.lang.String getName() ,public java.lang.String toString() <variables>private java.lang.String codec,private java.lang.String kernelVersion,private java.lang.String name
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdUsbDevice.java
OpenBsdUsbDevice
getUsbDevices
class OpenBsdUsbDevice extends AbstractUsbDevice { public OpenBsdUsbDevice(String name, String vendor, String vendorId, String productId, String serialNumber, String uniqueDeviceId, List<UsbDevice> connectedDevices) { super(name, vendor, vendorId, productId, serialNumber, uniqueDeviceId, connectedDevices); } /** * Instantiates a list of {@link oshi.hardware.UsbDevice} objects, representing devices connected via a usb port * (including internal devices). * <p> * If the value of {@code tree} is true, the top level devices returned from this method are the USB Controllers; * connected hubs and devices in its device tree share that controller's bandwidth. If the value of {@code tree} is * false, USB devices (not controllers) are listed in a single flat list. * * @param tree If true, returns a list of controllers, which requires recursive iteration of connected devices. If * false, returns a flat list of devices excluding controllers. * @return a list of {@link oshi.hardware.UsbDevice} objects. */ public static List<UsbDevice> getUsbDevices(boolean tree) { List<UsbDevice> devices = getUsbDevices(); if (tree) { return devices; } List<UsbDevice> deviceList = new ArrayList<>(); // Top level is controllers; they won't be added to the list, but all // their connected devices will be for (UsbDevice device : devices) { deviceList.add(new OpenBsdUsbDevice(device.getName(), device.getVendor(), device.getVendorId(), device.getProductId(), device.getSerialNumber(), device.getUniqueDeviceId(), Collections.emptyList())); addDevicesToList(deviceList, device.getConnectedDevices()); } return deviceList; } private static List<UsbDevice> getUsbDevices() {<FILL_FUNCTION_BODY>} private static void addDevicesToList(List<UsbDevice> deviceList, List<UsbDevice> list) { for (UsbDevice device : list) { deviceList.add(device); addDevicesToList(deviceList, device.getConnectedDevices()); } } /** * Recursively creates OpenBsdUsbDevices by fetching information from maps to populate fields * * @param devPath The device node path. * @param vid The default (parent) vendor ID * @param pid The default (parent) product ID * @param nameMap the map of names * @param vendorMap the map of vendors * @param vendorIdMap the map of vendorIds * @param productIdMap the map of productIds * @param serialMap the map of serial numbers * @param hubMap the map of hubs * @return A SolarisUsbDevice corresponding to this device */ private static OpenBsdUsbDevice getDeviceAndChildren(String devPath, String vid, String pid, Map<String, String> nameMap, Map<String, String> vendorMap, Map<String, String> vendorIdMap, Map<String, String> productIdMap, Map<String, String> serialMap, Map<String, List<String>> hubMap) { String vendorId = vendorIdMap.getOrDefault(devPath, vid); String productId = productIdMap.getOrDefault(devPath, pid); List<String> childPaths = hubMap.getOrDefault(devPath, new ArrayList<>()); List<UsbDevice> usbDevices = new ArrayList<>(); for (String path : childPaths) { usbDevices.add(getDeviceAndChildren(path, vendorId, productId, nameMap, vendorMap, vendorIdMap, productIdMap, serialMap, hubMap)); } Collections.sort(usbDevices); return new OpenBsdUsbDevice(nameMap.getOrDefault(devPath, vendorId + ":" + productId), vendorMap.getOrDefault(devPath, ""), vendorId, productId, serialMap.getOrDefault(devPath, ""), devPath, usbDevices); } }
// Maps to store information using node # as the key // Node is controller+addr (+port+addr etc.) Map<String, String> nameMap = new HashMap<>(); Map<String, String> vendorMap = new HashMap<>(); Map<String, String> vendorIdMap = new HashMap<>(); Map<String, String> productIdMap = new HashMap<>(); Map<String, String> serialMap = new HashMap<>(); Map<String, List<String>> hubMap = new HashMap<>(); List<String> rootHubs = new ArrayList<>(); // For each item enumerated, store information in the maps String key = ""; // Addresses repeat for each controller: // prepend the controller /dev/usb* for the key String parent = ""; // Enumerate all devices and build information maps. // This will build the entire device tree in hubMap for (String line : ExecutingCommand.runNative("usbdevs -v")) { if (line.startsWith("Controller ")) { parent = line.substring(11); } else if (line.startsWith("addr ")) { // addr 01: 8086:0000 Intel, EHCI root hub if (line.indexOf(':') == 7 && line.indexOf(',') >= 18) { key = parent + line.substring(0, 7); String[] split = line.substring(8).trim().split(","); if (split.length > 1) { // 0 = vid:pid vendor String vendorStr = split[0].trim(); int idx1 = vendorStr.indexOf(':'); int idx2 = vendorStr.indexOf(' '); if (idx1 >= 0 && idx2 >= 0) { vendorIdMap.put(key, vendorStr.substring(0, idx1)); productIdMap.put(key, vendorStr.substring(idx1 + 1, idx2)); vendorMap.put(key, vendorStr.substring(idx2 + 1)); } // 1 = product nameMap.put(key, split[1].trim()); // Add this key to the parent's hubmap list hubMap.computeIfAbsent(parent, x -> new ArrayList<>()).add(key); // For the first addr in a controller, make it the parent if (!parent.contains("addr")) { parent = key; rootHubs.add(parent); } } } } else if (!key.isEmpty()) { // Continuing to read for the previous key // CSV is speed, power, config, rev, optional iSerial // Since all we need is the serial... int idx = line.indexOf("iSerial "); if (idx >= 0) { serialMap.put(key, line.substring(idx + 8).trim()); } key = ""; } } // Build tree and return List<UsbDevice> controllerDevices = new ArrayList<>(); for (String devusb : rootHubs) { controllerDevices.add(getDeviceAndChildren(devusb, "0000", "0000", nameMap, vendorMap, vendorIdMap, productIdMap, serialMap, hubMap)); } return controllerDevices;
1,073
825
1,898
<methods>public int compareTo(oshi.hardware.UsbDevice) ,public List<oshi.hardware.UsbDevice> getConnectedDevices() ,public java.lang.String getName() ,public java.lang.String getProductId() ,public java.lang.String getSerialNumber() ,public java.lang.String getUniqueDeviceId() ,public java.lang.String getVendor() ,public java.lang.String getVendorId() ,public java.lang.String toString() <variables>private final non-sealed List<oshi.hardware.UsbDevice> connectedDevices,private final non-sealed java.lang.String name,private final non-sealed java.lang.String productId,private final non-sealed java.lang.String serialNumber,private final non-sealed java.lang.String uniqueDeviceId,private final non-sealed java.lang.String vendor,private final non-sealed java.lang.String vendorId
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdVirtualMemory.java
OpenBsdVirtualMemory
queryVmstat
class OpenBsdVirtualMemory extends AbstractVirtualMemory { private final OpenBsdGlobalMemory global; private final Supplier<Triplet<Integer, Integer, Integer>> usedTotalPgin = memoize( OpenBsdVirtualMemory::queryVmstat, defaultExpiration()); private final Supplier<Integer> pgout = memoize(OpenBsdVirtualMemory::queryUvm, defaultExpiration()); OpenBsdVirtualMemory(OpenBsdGlobalMemory freeBsdGlobalMemory) { this.global = freeBsdGlobalMemory; } @Override public long getSwapUsed() { return usedTotalPgin.get().getA() * global.getPageSize(); } @Override public long getSwapTotal() { return usedTotalPgin.get().getB() * global.getPageSize(); } @Override public long getVirtualMax() { return this.global.getTotal() + getSwapTotal(); } @Override public long getVirtualInUse() { return this.global.getTotal() - this.global.getAvailable() + getSwapUsed(); } @Override public long getSwapPagesIn() { return usedTotalPgin.get().getC() * global.getPageSize(); } @Override public long getSwapPagesOut() { return pgout.get() * global.getPageSize(); } private static Triplet<Integer, Integer, Integer> queryVmstat() {<FILL_FUNCTION_BODY>} private static int queryUvm() { for (String line : ExecutingCommand.runNative("systat -ab uvm")) { if (line.contains("pdpageouts")) { // First column is non-numeric "Constants" header return ParseUtil.getFirstIntValue(line); } } return 0; } }
int used = 0; int total = 0; int swapIn = 0; for (String line : ExecutingCommand.runNative("vmstat -s")) { if (line.contains("swap pages in use")) { used = ParseUtil.getFirstIntValue(line); } else if (line.contains("swap pages")) { total = ParseUtil.getFirstIntValue(line); } else if (line.contains("pagein operations")) { swapIn = ParseUtil.getFirstIntValue(line); } } return new Triplet<>(used, total, swapIn);
483
156
639
<methods>public non-sealed void <init>() ,public java.lang.String toString() <variables>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisGraphicsCard.java
SolarisGraphicsCard
getGraphicsCards
class SolarisGraphicsCard extends AbstractGraphicsCard { private static final String PCI_CLASS_DISPLAY = "0003"; /** * Constructor for SolarisGraphicsCard * * @param name The name * @param deviceId The device ID * @param vendor The vendor * @param versionInfo The version info * @param vram The VRAM */ SolarisGraphicsCard(String name, String deviceId, String vendor, String versionInfo, long vram) { super(name, deviceId, vendor, versionInfo, vram); } /** * public method used by {@link oshi.hardware.common.AbstractHardwareAbstractionLayer} to access the graphics cards. * * @return List of {@link oshi.hardware.platform.unix.solaris.SolarisGraphicsCard} objects. */ public static List<GraphicsCard> getGraphicsCards() {<FILL_FUNCTION_BODY>} }
List<GraphicsCard> cardList = new ArrayList<>(); // Enumerate all devices and add if required List<String> devices = ExecutingCommand.runNative("prtconf -pv"); if (devices.isEmpty()) { return cardList; } String name = ""; String vendorId = ""; String productId = ""; String classCode = ""; List<String> versionInfoList = new ArrayList<>(); for (String line : devices) { // Node 0x... identifies start of a new device. Save previous if it's a graphics // card if (line.contains("Node 0x")) { if (PCI_CLASS_DISPLAY.equals(classCode)) { cardList.add(new SolarisGraphicsCard(name.isEmpty() ? Constants.UNKNOWN : name, productId.isEmpty() ? Constants.UNKNOWN : productId, vendorId.isEmpty() ? Constants.UNKNOWN : vendorId, versionInfoList.isEmpty() ? Constants.UNKNOWN : String.join(", ", versionInfoList), 0L)); } // Reset strings name = ""; vendorId = Constants.UNKNOWN; productId = Constants.UNKNOWN; classCode = ""; versionInfoList.clear(); } else { String[] split = line.trim().split(":", 2); if (split.length == 2) { if (split[0].equals("model")) { // This is preferred, always set it name = ParseUtil.getSingleQuoteStringValue(line); } else if (split[0].equals("name")) { // Name is backup for model if model doesn't exist, so only // put if name blank if (name.isEmpty()) { name = ParseUtil.getSingleQuoteStringValue(line); } } else if (split[0].equals("vendor-id")) { // Format: vendor-id: 00008086 vendorId = "0x" + line.substring(line.length() - 4); } else if (split[0].equals("device-id")) { // Format: device-id: 00002440 productId = "0x" + line.substring(line.length() - 4); } else if (split[0].equals("revision-id")) { // Format: revision-id: 00000002 versionInfoList.add(line.trim()); } else if (split[0].equals("class-code")) { // Format: 00030000 // Display class is 0003xx, first 6 bytes of this code classCode = line.substring(line.length() - 8, line.length() - 4); } } } } // In case we reached end before saving if (PCI_CLASS_DISPLAY.equals(classCode)) { cardList.add(new SolarisGraphicsCard(name.isEmpty() ? Constants.UNKNOWN : name, productId.isEmpty() ? Constants.UNKNOWN : productId, vendorId.isEmpty() ? Constants.UNKNOWN : vendorId, versionInfoList.isEmpty() ? Constants.UNKNOWN : String.join(", ", versionInfoList), 0L)); } return cardList;
251
860
1,111
<methods>public java.lang.String getDeviceId() ,public java.lang.String getName() ,public long getVRam() ,public java.lang.String getVendor() ,public java.lang.String getVersionInfo() ,public java.lang.String toString() <variables>private final non-sealed java.lang.String deviceId,private final non-sealed java.lang.String name,private final non-sealed java.lang.String vendor,private final non-sealed java.lang.String versionInfo,private long vram
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisHWDiskStore.java
SolarisHWDiskStore
updateAttributes
class SolarisHWDiskStore extends AbstractHWDiskStore { private long reads = 0L; private long readBytes = 0L; private long writes = 0L; private long writeBytes = 0L; private long currentQueueLength = 0L; private long transferTime = 0L; private long timeStamp = 0L; private List<HWPartition> partitionList; private SolarisHWDiskStore(String name, String model, String serial, long size) { super(name, model, serial, size); } @Override public long getReads() { return reads; } @Override public long getReadBytes() { return readBytes; } @Override public long getWrites() { return writes; } @Override public long getWriteBytes() { return writeBytes; } @Override public long getCurrentQueueLength() { return currentQueueLength; } @Override public long getTransferTime() { return transferTime; } @Override public long getTimeStamp() { return timeStamp; } @Override public List<HWPartition> getPartitions() { return this.partitionList; } @Override public boolean updateAttributes() {<FILL_FUNCTION_BODY>} private boolean updateAttributes2() { String fullName = getName(); String alpha = fullName; String numeric = ""; for (int c = 0; c < fullName.length(); c++) { if (fullName.charAt(c) >= '0' && fullName.charAt(c) <= '9') { alpha = fullName.substring(0, c); numeric = fullName.substring(c); break; } } // Try device style notation Object[] results = KstatUtil.queryKstat2("kstat:/disk/" + alpha + "/" + getName() + "/0", "reads", "writes", "nread", "nwritten", "wcnt", "rcnt", "rtime", "snaptime"); // If failure try io notation if (results[results.length - 1] == null) { results = KstatUtil.queryKstat2("kstat:/disk/" + alpha + "/" + numeric + "/io", "reads", "writes", "nread", "nwritten", "wcnt", "rcnt", "rtime", "snaptime"); } if (results[results.length - 1] == null) { return false; } this.reads = results[0] == null ? 0L : (long) results[0]; this.writes = results[1] == null ? 0L : (long) results[1]; this.readBytes = results[2] == null ? 0L : (long) results[2]; this.writeBytes = results[3] == null ? 0L : (long) results[3]; this.currentQueueLength = results[4] == null ? 0L : (long) results[4]; this.currentQueueLength += results[5] == null ? 0L : (long) results[5]; // rtime and snaptime are nanoseconds, convert to millis this.transferTime = results[6] == null ? 0L : (long) results[6] / 1_000_000L; this.timeStamp = (long) results[7] / 1_000_000L; return true; } /** * Gets the disks on this machine * * @return a list of {@link HWDiskStore} objects representing the disks */ public static List<HWDiskStore> getDisks() { // Create map to correlate disk name with block device mount point for // later use in partition info Map<String, String> deviceMap = Iostat.queryPartitionToMountMap(); // Create map to correlate disk name with block device mount point for // later use in partition info. Run lshal, if available, to get block device // major (we'll use partition # for minor) Map<String, Integer> majorMap = Lshal.queryDiskToMajorMap(); // Create map of model, vendor, product, serial, size // We'll use Model if available, otherwise Vendor+Product Map<String, Quintet<String, String, String, String, Long>> deviceStringMap = Iostat .queryDeviceStrings(deviceMap.keySet()); List<HWDiskStore> storeList = new ArrayList<>(); for (Entry<String, Quintet<String, String, String, String, Long>> entry : deviceStringMap.entrySet()) { String storeName = entry.getKey(); Quintet<String, String, String, String, Long> val = entry.getValue(); storeList.add(createStore(storeName, val.getA(), val.getB(), val.getC(), val.getD(), val.getE(), deviceMap.getOrDefault(storeName, ""), majorMap.getOrDefault(storeName, 0))); } return storeList; } private static SolarisHWDiskStore createStore(String diskName, String model, String vendor, String product, String serial, long size, String mount, int major) { SolarisHWDiskStore store = new SolarisHWDiskStore(diskName, model.isEmpty() ? (vendor + " " + product).trim() : model, serial, size); store.partitionList = Collections.unmodifiableList(Prtvtoc.queryPartitions(mount, major).stream() .sorted(Comparator.comparing(HWPartition::getName)).collect(Collectors.toList())); store.updateAttributes(); return store; } }
this.timeStamp = System.currentTimeMillis(); if (HAS_KSTAT2) { // Use Kstat2 implementation return updateAttributes2(); } try (KstatChain kc = KstatUtil.openChain()) { Kstat ksp = kc.lookup(null, 0, getName()); if (ksp != null && kc.read(ksp)) { KstatIO data = new KstatIO(ksp.ks_data); this.reads = data.reads; this.writes = data.writes; this.readBytes = data.nread; this.writeBytes = data.nwritten; this.currentQueueLength = (long) data.wcnt + data.rcnt; // rtime and snaptime are nanoseconds, convert to millis this.transferTime = data.rtime / 1_000_000L; this.timeStamp = ksp.ks_snaptime / 1_000_000L; return true; } } return false;
1,483
284
1,767
<methods>public java.lang.String getModel() ,public java.lang.String getName() ,public java.lang.String getSerial() ,public long getSize() ,public java.lang.String toString() <variables>private final non-sealed java.lang.String model,private final non-sealed java.lang.String name,private final non-sealed java.lang.String serial,private final non-sealed long size
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisNetworkIF.java
SolarisNetworkIF
updateAttributes2
class SolarisNetworkIF extends AbstractNetworkIF { private static final Logger LOG = LoggerFactory.getLogger(SolarisNetworkIF.class); private long bytesRecv; private long bytesSent; private long packetsRecv; private long packetsSent; private long inErrors; private long outErrors; private long inDrops; private long collisions; private long speed; private long timeStamp; public SolarisNetworkIF(NetworkInterface netint) throws InstantiationException { super(netint); updateAttributes(); } /** * Gets all network interfaces on this machine * * @param includeLocalInterfaces include local interfaces in the result * @return A list of {@link NetworkIF} objects representing the interfaces */ public static List<NetworkIF> getNetworks(boolean includeLocalInterfaces) { List<NetworkIF> ifList = new ArrayList<>(); for (NetworkInterface ni : getNetworkInterfaces(includeLocalInterfaces)) { try { ifList.add(new SolarisNetworkIF(ni)); } catch (InstantiationException e) { LOG.debug("Network Interface Instantiation failed: {}", e.getMessage()); } } return ifList; } @Override public long getBytesRecv() { return this.bytesRecv; } @Override public long getBytesSent() { return this.bytesSent; } @Override public long getPacketsRecv() { return this.packetsRecv; } @Override public long getPacketsSent() { return this.packetsSent; } @Override public long getInErrors() { return this.inErrors; } @Override public long getOutErrors() { return this.outErrors; } @Override public long getInDrops() { return this.inDrops; } @Override public long getCollisions() { return this.collisions; } @Override public long getSpeed() { return this.speed; } @Override public long getTimeStamp() { return this.timeStamp; } @Override public boolean updateAttributes() { // Initialize to a sane default value this.timeStamp = System.currentTimeMillis(); if (HAS_KSTAT2) { // Use Kstat2 implementation return updateAttributes2(); } try (KstatChain kc = KstatUtil.openChain()) { Kstat ksp = kc.lookup("link", -1, getName()); if (ksp == null) { // Solaris 10 compatibility ksp = kc.lookup(null, -1, getName()); } if (ksp != null && kc.read(ksp)) { this.bytesSent = KstatUtil.dataLookupLong(ksp, "obytes64"); this.bytesRecv = KstatUtil.dataLookupLong(ksp, "rbytes64"); this.packetsSent = KstatUtil.dataLookupLong(ksp, "opackets64"); this.packetsRecv = KstatUtil.dataLookupLong(ksp, "ipackets64"); this.outErrors = KstatUtil.dataLookupLong(ksp, "oerrors"); this.inErrors = KstatUtil.dataLookupLong(ksp, "ierrors"); this.collisions = KstatUtil.dataLookupLong(ksp, "collisions"); this.inDrops = KstatUtil.dataLookupLong(ksp, "dl_idrops"); this.speed = KstatUtil.dataLookupLong(ksp, "ifspeed"); // Snap time in ns; convert to ms this.timeStamp = ksp.ks_snaptime / 1_000_000L; return true; } } return false; } private boolean updateAttributes2() {<FILL_FUNCTION_BODY>} }
Object[] results = KstatUtil.queryKstat2("kstat:/net/link/" + getName() + "/0", "obytes64", "rbytes64", "opackets64", "ipackets64", "oerrors", "ierrors", "collisions", "dl_idrops", "ifspeed", "snaptime"); if (results[results.length - 1] == null) { return false; } this.bytesSent = results[0] == null ? 0L : (long) results[0]; this.bytesRecv = results[1] == null ? 0L : (long) results[1]; this.packetsSent = results[2] == null ? 0L : (long) results[2]; this.packetsRecv = results[3] == null ? 0L : (long) results[3]; this.outErrors = results[4] == null ? 0L : (long) results[4]; this.collisions = results[5] == null ? 0L : (long) results[5]; this.inDrops = results[6] == null ? 0L : (long) results[6]; this.speed = results[7] == null ? 0L : (long) results[7]; // Snap time in ns; convert to ms this.timeStamp = (long) results[8] / 1_000_000L; return true;
1,044
360
1,404
<methods>public java.lang.String getDisplayName() ,public java.lang.String[] getIPv4addr() ,public java.lang.String[] getIPv6addr() ,public int getIndex() ,public long getMTU() ,public java.lang.String getMacaddr() ,public java.lang.String getName() ,public java.lang.Short[] getPrefixLengths() ,public java.lang.Short[] getSubnetMasks() ,public boolean isKnownVmMacAddr() ,public java.net.NetworkInterface queryNetworkInterface() ,public java.lang.String toString() <variables>private static final org.slf4j.Logger LOG,private static final java.lang.String OSHI_VM_MAC_ADDR_PROPERTIES,private java.lang.String displayName,private int index,private java.lang.String[] ipv4,private java.lang.String[] ipv6,private java.lang.String mac,private long mtu,private java.lang.String name,private java.net.NetworkInterface networkInterface,private java.lang.Short[] prefixLengths,private java.lang.Short[] subnetMasks,private final Supplier<java.util.Properties> vmMacAddrProps
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisPowerSource.java
SolarisPowerSource
getPowerSource
class SolarisPowerSource extends AbstractPowerSource { // One-time lookup to see which kstat module to use private static final String[] KSTAT_BATT_MOD = { null, "battery", "acpi_drv" }; private static final int KSTAT_BATT_IDX; static { try (KstatChain kc = KstatUtil.openChain()) { if (kc.lookup(KSTAT_BATT_MOD[1], 0, null) != null) { KSTAT_BATT_IDX = 1; } else if (kc.lookup(KSTAT_BATT_MOD[2], 0, null) != null) { KSTAT_BATT_IDX = 2; } else { KSTAT_BATT_IDX = 0; } } } public SolarisPowerSource(String psName, String psDeviceName, double psRemainingCapacityPercent, double psTimeRemainingEstimated, double psTimeRemainingInstant, double psPowerUsageRate, double psVoltage, double psAmperage, boolean psPowerOnLine, boolean psCharging, boolean psDischarging, CapacityUnits psCapacityUnits, int psCurrentCapacity, int psMaxCapacity, int psDesignCapacity, int psCycleCount, String psChemistry, LocalDate psManufactureDate, String psManufacturer, String psSerialNumber, double psTemperature) { super(psName, psDeviceName, psRemainingCapacityPercent, psTimeRemainingEstimated, psTimeRemainingInstant, psPowerUsageRate, psVoltage, psAmperage, psPowerOnLine, psCharging, psDischarging, psCapacityUnits, psCurrentCapacity, psMaxCapacity, psDesignCapacity, psCycleCount, psChemistry, psManufactureDate, psManufacturer, psSerialNumber, psTemperature); } /** * Gets Battery Information * * @return A list of PowerSource objects representing batteries, etc. */ public static List<PowerSource> getPowerSources() { return Arrays.asList(getPowerSource("BAT0")); } private static SolarisPowerSource getPowerSource(String name) {<FILL_FUNCTION_BODY>} }
String psName = name; String psDeviceName = Constants.UNKNOWN; double psRemainingCapacityPercent = 1d; double psTimeRemainingEstimated = -1d; // -1 = unknown, -2 = unlimited double psTimeRemainingInstant = 0d; double psPowerUsageRate = 0d; double psVoltage = -1d; double psAmperage = 0d; boolean psPowerOnLine = false; boolean psCharging = false; boolean psDischarging = false; CapacityUnits psCapacityUnits = CapacityUnits.RELATIVE; int psCurrentCapacity = 0; int psMaxCapacity = 1; int psDesignCapacity = 1; int psCycleCount = -1; String psChemistry = Constants.UNKNOWN; LocalDate psManufactureDate = null; String psManufacturer = Constants.UNKNOWN; String psSerialNumber = Constants.UNKNOWN; double psTemperature = 0d; // If no kstat info, return empty if (KSTAT_BATT_IDX > 0) { // Get kstat for the battery information try (KstatChain kc = KstatUtil.openChain()) { Kstat ksp = kc.lookup(KSTAT_BATT_MOD[KSTAT_BATT_IDX], 0, "battery BIF0"); if (ksp != null && kc.read(ksp)) { // Predicted battery capacity when fully charged. long energyFull = KstatUtil.dataLookupLong(ksp, "bif_last_cap"); if (energyFull == 0xffffffff || energyFull <= 0) { energyFull = KstatUtil.dataLookupLong(ksp, "bif_design_cap"); } if (energyFull != 0xffffffff && energyFull > 0) { psMaxCapacity = (int) energyFull; } long unit = KstatUtil.dataLookupLong(ksp, "bif_unit"); if (unit == 0) { psCapacityUnits = CapacityUnits.MWH; } else if (unit == 1) { psCapacityUnits = CapacityUnits.MAH; } psDeviceName = KstatUtil.dataLookupString(ksp, "bif_model"); psSerialNumber = KstatUtil.dataLookupString(ksp, "bif_serial"); psChemistry = KstatUtil.dataLookupString(ksp, "bif_type"); psManufacturer = KstatUtil.dataLookupString(ksp, "bif_oem_info"); } // Get kstat for the battery state ksp = kc.lookup(KSTAT_BATT_MOD[KSTAT_BATT_IDX], 0, "battery BST0"); if (ksp != null && kc.read(ksp)) { // estimated remaining battery capacity long energyNow = KstatUtil.dataLookupLong(ksp, "bst_rem_cap"); if (energyNow >= 0) { psCurrentCapacity = (int) energyNow; } // power or current supplied at battery terminal long powerNow = KstatUtil.dataLookupLong(ksp, "bst_rate"); if (powerNow == 0xFFFFFFFF) { powerNow = 0L; } // Battery State: // bit 0 = discharging // bit 1 = charging // bit 2 = critical energy state boolean isCharging = (KstatUtil.dataLookupLong(ksp, "bst_state") & 0x10) > 0; if (!isCharging) { psTimeRemainingEstimated = powerNow > 0 ? 3600d * energyNow / powerNow : -1d; } long voltageNow = KstatUtil.dataLookupLong(ksp, "bst_voltage"); if (voltageNow > 0) { psVoltage = voltageNow / 1000d; psAmperage = psPowerUsageRate * 1000d / voltageNow; } } } } return new SolarisPowerSource(psName, psDeviceName, psRemainingCapacityPercent, psTimeRemainingEstimated, psTimeRemainingInstant, psPowerUsageRate, psVoltage, psAmperage, psPowerOnLine, psCharging, psDischarging, psCapacityUnits, psCurrentCapacity, psMaxCapacity, psDesignCapacity, psCycleCount, psChemistry, psManufactureDate, psManufacturer, psSerialNumber, psTemperature);
591
1,205
1,796
<methods>public double getAmperage() ,public oshi.hardware.PowerSource.CapacityUnits getCapacityUnits() ,public java.lang.String getChemistry() ,public int getCurrentCapacity() ,public int getCycleCount() ,public int getDesignCapacity() ,public java.lang.String getDeviceName() ,public java.time.LocalDate getManufactureDate() ,public java.lang.String getManufacturer() ,public int getMaxCapacity() ,public java.lang.String getName() ,public double getPowerUsageRate() ,public double getRemainingCapacityPercent() ,public java.lang.String getSerialNumber() ,public double getTemperature() ,public double getTimeRemainingEstimated() ,public double getTimeRemainingInstant() ,public double getVoltage() ,public boolean isCharging() ,public boolean isDischarging() ,public boolean isPowerOnLine() ,public java.lang.String toString() ,public boolean updateAttributes() <variables>private double amperage,private oshi.hardware.PowerSource.CapacityUnits capacityUnits,private boolean charging,private java.lang.String chemistry,private int currentCapacity,private int cycleCount,private int designCapacity,private java.lang.String deviceName,private boolean discharging,private java.time.LocalDate manufactureDate,private java.lang.String manufacturer,private int maxCapacity,private java.lang.String name,private boolean powerOnLine,private double powerUsageRate,private double remainingCapacityPercent,private java.lang.String serialNumber,private double temperature,private double timeRemainingEstimated,private double timeRemainingInstant,private double voltage
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisSensors.java
SolarisSensors
queryFanSpeeds
class SolarisSensors extends AbstractSensors { @Override public double queryCpuTemperature() { double maxTemp = 0d; // Return max found temp for (String line : ExecutingCommand.runNative("/usr/sbin/prtpicl -v -c temperature-sensor")) { if (line.trim().startsWith("Temperature:")) { int temp = ParseUtil.parseLastInt(line, 0); if (temp > maxTemp) { maxTemp = temp; } } } // If it's in millidegrees: if (maxTemp > 1000) { maxTemp /= 1000; } return maxTemp; } @Override public int[] queryFanSpeeds() {<FILL_FUNCTION_BODY>} @Override public double queryCpuVoltage() { double voltage = 0d; for (String line : ExecutingCommand.runNative("/usr/sbin/prtpicl -v -c voltage-sensor")) { if (line.trim().startsWith("Voltage:")) { voltage = ParseUtil.parseDoubleOrDefault(line.replace("Voltage:", "").trim(), 0d); break; } } return voltage; } }
List<Integer> speedList = new ArrayList<>(); // Return max found temp for (String line : ExecutingCommand.runNative("/usr/sbin/prtpicl -v -c fan")) { if (line.trim().startsWith("Speed:")) { speedList.add(ParseUtil.parseLastInt(line, 0)); } } int[] fans = new int[speedList.size()]; for (int i = 0; i < speedList.size(); i++) { fans[i] = speedList.get(i); } return fans;
336
149
485
<methods>public non-sealed void <init>() ,public double getCpuTemperature() ,public double getCpuVoltage() ,public int[] getFanSpeeds() ,public java.lang.String toString() <variables>private final Supplier<java.lang.Double> cpuTemperature,private final Supplier<java.lang.Double> cpuVoltage,private final Supplier<int[]> fanSpeeds
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisSoundCard.java
SolarisSoundCard
getSoundCards
class SolarisSoundCard extends AbstractSoundCard { private static final String LSHAL = "lshal"; private static final String DEFAULT_AUDIO_DRIVER = "audio810"; /** * Constructor for SolarisSoundCard. * * @param kernelVersion The version * @param name The name * @param codec The codec */ SolarisSoundCard(String kernelVersion, String name, String codec) { super(kernelVersion, name, codec); } /** * <p> * getSoundCards. * </p> * * @return a {@link java.util.List} object. */ public static List<SoundCard> getSoundCards() {<FILL_FUNCTION_BODY>} }
Map<String, String> vendorMap = new HashMap<>(); Map<String, String> productMap = new HashMap<>(); List<String> sounds = new ArrayList<>(); String key = ""; for (String line : ExecutingCommand.runNative(LSHAL)) { line = line.trim(); if (line.startsWith("udi =")) { // we have the key. key = ParseUtil.getSingleQuoteStringValue(line); } else if (!key.isEmpty() && !line.isEmpty()) { if (line.contains("info.solaris.driver =") && DEFAULT_AUDIO_DRIVER.equals(ParseUtil.getSingleQuoteStringValue(line))) { sounds.add(key); } else if (line.contains("info.product")) { productMap.put(key, ParseUtil.getStringBetween(line, '\'')); } else if (line.contains("info.vendor")) { vendorMap.put(key, ParseUtil.getStringBetween(line, '\'')); } } } List<SoundCard> soundCards = new ArrayList<>(); for (String s : sounds) { soundCards.add(new SolarisSoundCard(productMap.get(s) + " " + DEFAULT_AUDIO_DRIVER, vendorMap.get(s) + " " + productMap.get(s), productMap.get(s))); } return soundCards;
208
368
576
<methods>public java.lang.String getCodec() ,public java.lang.String getDriverVersion() ,public java.lang.String getName() ,public java.lang.String toString() <variables>private java.lang.String codec,private java.lang.String kernelVersion,private java.lang.String name
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisUsbDevice.java
SolarisUsbDevice
getUsbDevices
class SolarisUsbDevice extends AbstractUsbDevice { private static final String PCI_TYPE_USB = "000c"; public SolarisUsbDevice(String name, String vendor, String vendorId, String productId, String serialNumber, String uniqueDeviceId, List<UsbDevice> connectedDevices) { super(name, vendor, vendorId, productId, serialNumber, uniqueDeviceId, connectedDevices); } /** * Instantiates a list of {@link oshi.hardware.UsbDevice} objects, representing devices connected via a usb port * (including internal devices). * <p> * If the value of {@code tree} is true, the top level devices returned from this method are the USB Controllers; * connected hubs and devices in its device tree share that controller's bandwidth. If the value of {@code tree} is * false, USB devices (not controllers) are listed in a single flat list. * * @param tree If true, returns a list of controllers, which requires recursive iteration of connected devices. If * false, returns a flat list of devices excluding controllers. * @return a list of {@link oshi.hardware.UsbDevice} objects. */ public static List<UsbDevice> getUsbDevices(boolean tree) { List<UsbDevice> devices = getUsbDevices(); if (tree) { return devices; } List<UsbDevice> deviceList = new ArrayList<>(); // Top level is controllers; they won't be added to the list, but all // their connected devices will be for (UsbDevice device : devices) { deviceList.add(new SolarisUsbDevice(device.getName(), device.getVendor(), device.getVendorId(), device.getProductId(), device.getSerialNumber(), device.getUniqueDeviceId(), Collections.emptyList())); addDevicesToList(deviceList, device.getConnectedDevices()); } return deviceList; } private static List<UsbDevice> getUsbDevices() {<FILL_FUNCTION_BODY>} private static void addDevicesToList(List<UsbDevice> deviceList, List<UsbDevice> list) { for (UsbDevice device : list) { deviceList.add(device); addDevicesToList(deviceList, device.getConnectedDevices()); } } /** * Recursively creates SolarisUsbDevices by fetching information from maps to populate fields * * @param devPath The device node path. * @param vid The default (parent) vendor ID * @param pid The default (parent) product ID * @param nameMap the map of names * @param vendorIdMap the map of vendorIds * @param productIdMap the map of productIds * @param hubMap the map of hubs * @return A SolarisUsbDevice corresponding to this device */ private static SolarisUsbDevice getDeviceAndChildren(String devPath, String vid, String pid, Map<String, String> nameMap, Map<String, String> vendorIdMap, Map<String, String> productIdMap, Map<String, List<String>> hubMap) { String vendorId = vendorIdMap.getOrDefault(devPath, vid); String productId = productIdMap.getOrDefault(devPath, pid); List<String> childPaths = hubMap.getOrDefault(devPath, new ArrayList<>()); List<UsbDevice> usbDevices = new ArrayList<>(); for (String path : childPaths) { usbDevices.add(getDeviceAndChildren(path, vendorId, productId, nameMap, vendorIdMap, productIdMap, hubMap)); } Collections.sort(usbDevices); return new SolarisUsbDevice(nameMap.getOrDefault(devPath, vendorId + ":" + productId), "", vendorId, productId, "", devPath, usbDevices); } }
Map<String, String> nameMap = new HashMap<>(); Map<String, String> vendorIdMap = new HashMap<>(); Map<String, String> productIdMap = new HashMap<>(); Map<String, List<String>> hubMap = new HashMap<>(); Map<String, String> deviceTypeMap = new HashMap<>(); // Enumerate all usb devices and build information maps List<String> devices = ExecutingCommand.runNative("prtconf -pv"); if (devices.isEmpty()) { return Collections.emptyList(); } // For each item enumerated, store information in the maps Map<Integer, String> lastParent = new HashMap<>(); String key = ""; int indent = 0; List<String> usbControllers = new ArrayList<>(); for (String line : devices) { // Node 0x... identifies start of a new tree if (line.contains("Node 0x")) { // Remove indent for key key = line.replaceFirst("^\\s*", ""); // Calculate indent and store as last parent at this depth int depth = line.length() - key.length(); // Store first indent for future use if (indent == 0) { indent = depth; } // Store this Node ID as parent at this depth lastParent.put(depth, key); // Add as child to appropriate parent if (depth > indent) { // Has a parent. Get parent and add this node to child list hubMap.computeIfAbsent(lastParent.get(depth - indent), x -> new ArrayList<>()).add(key); } else { // No parent, add to controllers list usbControllers.add(key); } } else if (!key.isEmpty()) { // We are currently processing for node identified by key. Save // approrpriate variables to maps. line = line.trim(); if (line.startsWith("model:")) { nameMap.put(key, ParseUtil.getSingleQuoteStringValue(line)); } else if (line.startsWith("name:")) { // Name is backup for model if model doesn't exist, so only // put if key doesn't yet exist nameMap.putIfAbsent(key, ParseUtil.getSingleQuoteStringValue(line)); } else if (line.startsWith("vendor-id:")) { // Format: vendor-id: 00008086 vendorIdMap.put(key, line.substring(line.length() - 4)); } else if (line.startsWith("device-id:")) { // Format: device-id: 00002440 productIdMap.put(key, line.substring(line.length() - 4)); } else if (line.startsWith("class-code:")) { // USB devices are 000cxxxx deviceTypeMap.putIfAbsent(key, line.substring(line.length() - 8, line.length() - 4)); } else if (line.startsWith("device_type:")) { // USB devices are 000cxxxx deviceTypeMap.putIfAbsent(key, ParseUtil.getSingleQuoteStringValue(line)); } } } // Build tree and return List<UsbDevice> controllerDevices = new ArrayList<>(); for (String controller : usbControllers) { // Only do controllers that are USB device type if (PCI_TYPE_USB.equals(deviceTypeMap.getOrDefault(controller, "")) || "usb".equals(deviceTypeMap.getOrDefault(controller, ""))) { controllerDevices.add( getDeviceAndChildren(controller, "0000", "0000", nameMap, vendorIdMap, productIdMap, hubMap)); } } return controllerDevices;
1,011
989
2,000
<methods>public int compareTo(oshi.hardware.UsbDevice) ,public List<oshi.hardware.UsbDevice> getConnectedDevices() ,public java.lang.String getName() ,public java.lang.String getProductId() ,public java.lang.String getSerialNumber() ,public java.lang.String getUniqueDeviceId() ,public java.lang.String getVendor() ,public java.lang.String getVendorId() ,public java.lang.String toString() <variables>private final non-sealed List<oshi.hardware.UsbDevice> connectedDevices,private final non-sealed java.lang.String name,private final non-sealed java.lang.String productId,private final non-sealed java.lang.String serialNumber,private final non-sealed java.lang.String uniqueDeviceId,private final non-sealed java.lang.String vendor,private final non-sealed java.lang.String vendorId
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/unix/solaris/SolarisVirtualMemory.java
SolarisVirtualMemory
queryPagesOut
class SolarisVirtualMemory extends AbstractVirtualMemory { private static final Pattern SWAP_INFO = Pattern.compile(".+\\s(\\d+)K\\s+(\\d+)K$"); private final SolarisGlobalMemory global; // Physical private final Supplier<Pair<Long, Long>> availTotal = memoize(SystemPages::queryAvailableTotal, defaultExpiration()); // Swap private final Supplier<Pair<Long, Long>> usedTotal = memoize(SolarisVirtualMemory::querySwapInfo, defaultExpiration()); private final Supplier<Long> pagesIn = memoize(SolarisVirtualMemory::queryPagesIn, defaultExpiration()); private final Supplier<Long> pagesOut = memoize(SolarisVirtualMemory::queryPagesOut, defaultExpiration()); /** * Constructor for SolarisVirtualMemory. * * @param solarisGlobalMemory The parent global memory class instantiating this */ SolarisVirtualMemory(SolarisGlobalMemory solarisGlobalMemory) { this.global = solarisGlobalMemory; } @Override public long getSwapUsed() { return usedTotal.get().getA(); } @Override public long getSwapTotal() { return usedTotal.get().getB(); } @Override public long getVirtualMax() { return this.global.getPageSize() * availTotal.get().getB() + getSwapTotal(); } @Override public long getVirtualInUse() { return this.global.getPageSize() * (availTotal.get().getB() - availTotal.get().getA()) + getSwapUsed(); } @Override public long getSwapPagesIn() { return pagesIn.get(); } @Override public long getSwapPagesOut() { return pagesOut.get(); } private static long queryPagesIn() { long swapPagesIn = 0L; for (String s : ExecutingCommand.runNative("kstat -p cpu_stat:::pgswapin")) { swapPagesIn += ParseUtil.parseLastLong(s, 0L); } return swapPagesIn; } private static long queryPagesOut() {<FILL_FUNCTION_BODY>} private static Pair<Long, Long> querySwapInfo() { long swapTotal = 0L; long swapUsed = 0L; String swap = ExecutingCommand.getAnswerAt("swap -lk", 1); Matcher m = SWAP_INFO.matcher(swap); if (m.matches()) { swapTotal = ParseUtil.parseLongOrDefault(m.group(1), 0L) << 10; swapUsed = swapTotal - (ParseUtil.parseLongOrDefault(m.group(2), 0L) << 10); } return new Pair<>(swapUsed, swapTotal); } }
long swapPagesOut = 0L; for (String s : ExecutingCommand.runNative("kstat -p cpu_stat:::pgswapout")) { swapPagesOut += ParseUtil.parseLastLong(s, 0L); } return swapPagesOut;
750
72
822
<methods>public non-sealed void <init>() ,public java.lang.String toString() <variables>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsBaseboard.java
WindowsBaseboard
queryManufModelVersSerial
class WindowsBaseboard extends AbstractBaseboard { private final Supplier<Quartet<String, String, String, String>> manufModelVersSerial = memoize( WindowsBaseboard::queryManufModelVersSerial); @Override public String getManufacturer() { return manufModelVersSerial.get().getA(); } @Override public String getModel() { return manufModelVersSerial.get().getB(); } @Override public String getVersion() { return manufModelVersSerial.get().getC(); } @Override public String getSerialNumber() { return manufModelVersSerial.get().getD(); } private static Quartet<String, String, String, String> queryManufModelVersSerial() {<FILL_FUNCTION_BODY>} }
String manufacturer = null; String model = null; String version = null; String serialNumber = null; WmiResult<BaseBoardProperty> win32BaseBoard = Win32BaseBoard.queryBaseboardInfo(); if (win32BaseBoard.getResultCount() > 0) { manufacturer = WmiUtil.getString(win32BaseBoard, BaseBoardProperty.MANUFACTURER, 0); model = WmiUtil.getString(win32BaseBoard, BaseBoardProperty.MODEL, 0); version = WmiUtil.getString(win32BaseBoard, BaseBoardProperty.VERSION, 0); serialNumber = WmiUtil.getString(win32BaseBoard, BaseBoardProperty.SERIALNUMBER, 0); } return new Quartet<>(Util.isBlank(manufacturer) ? Constants.UNKNOWN : manufacturer, Util.isBlank(model) ? Constants.UNKNOWN : model, Util.isBlank(version) ? Constants.UNKNOWN : version, Util.isBlank(serialNumber) ? Constants.UNKNOWN : serialNumber);
214
294
508
<methods>public non-sealed void <init>() ,public java.lang.String toString() <variables>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsComputerSystem.java
WindowsComputerSystem
queryManufacturerModel
class WindowsComputerSystem extends AbstractComputerSystem { private final Supplier<Pair<String, String>> manufacturerModel = memoize( WindowsComputerSystem::queryManufacturerModel); private final Supplier<Pair<String, String>> serialNumberUUID = memoize( WindowsComputerSystem::querySystemSerialNumberUUID); @Override public String getManufacturer() { return manufacturerModel.get().getA(); } @Override public String getModel() { return manufacturerModel.get().getB(); } @Override public String getSerialNumber() { return serialNumberUUID.get().getA(); } @Override public String getHardwareUUID() { return serialNumberUUID.get().getB(); } @Override public Firmware createFirmware() { return new WindowsFirmware(); } @Override public Baseboard createBaseboard() { return new WindowsBaseboard(); } private static Pair<String, String> queryManufacturerModel() {<FILL_FUNCTION_BODY>} private static Pair<String, String> querySystemSerialNumberUUID() { String serialNumber = null; String uuid = null; WmiResult<ComputerSystemProductProperty> win32ComputerSystemProduct = Win32ComputerSystemProduct .queryIdentifyingNumberUUID(); if (win32ComputerSystemProduct.getResultCount() > 0) { serialNumber = WmiUtil.getString(win32ComputerSystemProduct, ComputerSystemProductProperty.IDENTIFYINGNUMBER, 0); uuid = WmiUtil.getString(win32ComputerSystemProduct, ComputerSystemProductProperty.UUID, 0); } if (Util.isBlank(serialNumber)) { serialNumber = querySerialFromBios(); } if (Util.isBlank(serialNumber)) { serialNumber = Constants.UNKNOWN; } if (Util.isBlank(uuid)) { uuid = Constants.UNKNOWN; } return new Pair<>(serialNumber, uuid); } private static String querySerialFromBios() { WmiResult<BiosSerialProperty> serialNum = Win32Bios.querySerialNumber(); if (serialNum.getResultCount() > 0) { return WmiUtil.getString(serialNum, BiosSerialProperty.SERIALNUMBER, 0); } return null; } }
String manufacturer = null; String model = null; WmiResult<ComputerSystemProperty> win32ComputerSystem = Win32ComputerSystem.queryComputerSystem(); if (win32ComputerSystem.getResultCount() > 0) { manufacturer = WmiUtil.getString(win32ComputerSystem, ComputerSystemProperty.MANUFACTURER, 0); model = WmiUtil.getString(win32ComputerSystem, ComputerSystemProperty.MODEL, 0); } return new Pair<>(Util.isBlank(manufacturer) ? Constants.UNKNOWN : manufacturer, Util.isBlank(model) ? Constants.UNKNOWN : model);
634
177
811
<methods>public non-sealed void <init>() ,public oshi.hardware.Baseboard getBaseboard() ,public oshi.hardware.Firmware getFirmware() ,public java.lang.String toString() <variables>private final Supplier<oshi.hardware.Baseboard> baseboard,private final Supplier<oshi.hardware.Firmware> firmware
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsDisplay.java
WindowsDisplay
getDisplays
class WindowsDisplay extends AbstractDisplay { private static final Logger LOG = LoggerFactory.getLogger(WindowsDisplay.class); private static final SetupApi SU = SetupApi.INSTANCE; private static final Advapi32 ADV = Advapi32.INSTANCE; private static final Guid.GUID GUID_DEVINTERFACE_MONITOR = new Guid.GUID("E6F07B5F-EE97-4a90-B076-33F57BF4EAA7"); /** * Constructor for WindowsDisplay. * * @param edid a byte array representing a display EDID */ WindowsDisplay(byte[] edid) { super(edid); LOG.debug("Initialized WindowsDisplay"); } /** * Gets Display Information * * @return An array of Display objects representing monitors, etc. */ public static List<Display> getDisplays() {<FILL_FUNCTION_BODY>} }
List<Display> displays = new ArrayList<>(); HANDLE hDevInfo = SU.SetupDiGetClassDevs(GUID_DEVINTERFACE_MONITOR, null, null, SetupApi.DIGCF_PRESENT | SetupApi.DIGCF_DEVICEINTERFACE); if (!hDevInfo.equals(WinBase.INVALID_HANDLE_VALUE)) { try (CloseableSpDeviceInterfaceData deviceInterfaceData = new CloseableSpDeviceInterfaceData(); CloseableSpDevinfoData info = new CloseableSpDevinfoData()) { deviceInterfaceData.cbSize = deviceInterfaceData.size(); for (int memberIndex = 0; SU.SetupDiEnumDeviceInfo(hDevInfo, memberIndex, info); memberIndex++) { HKEY key = SU.SetupDiOpenDevRegKey(hDevInfo, info, SetupApi.DICS_FLAG_GLOBAL, 0, SetupApi.DIREG_DEV, WinNT.KEY_QUERY_VALUE); byte[] edid = new byte[1]; try (CloseableIntByReference pType = new CloseableIntByReference(); CloseableIntByReference lpcbData = new CloseableIntByReference()) { if (ADV.RegQueryValueEx(key, "EDID", 0, pType, edid, lpcbData) == WinError.ERROR_MORE_DATA) { edid = new byte[lpcbData.getValue()]; if (ADV.RegQueryValueEx(key, "EDID", 0, pType, edid, lpcbData) == WinError.ERROR_SUCCESS) { Display display = new WindowsDisplay(edid); displays.add(display); } } } Advapi32.INSTANCE.RegCloseKey(key); } } SU.SetupDiDestroyDeviceInfoList(hDevInfo); } return displays;
258
481
739
<methods>public byte[] getEdid() ,public java.lang.String toString() <variables>private final non-sealed byte[] edid
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsFirmware.java
WindowsFirmware
queryManufNameDescVersRelease
class WindowsFirmware extends AbstractFirmware { private final Supplier<Quintet<String, String, String, String, String>> manufNameDescVersRelease = memoize( WindowsFirmware::queryManufNameDescVersRelease); @Override public String getManufacturer() { return manufNameDescVersRelease.get().getA(); } @Override public String getName() { return manufNameDescVersRelease.get().getB(); } @Override public String getDescription() { return manufNameDescVersRelease.get().getC(); } @Override public String getVersion() { return manufNameDescVersRelease.get().getD(); } @Override public String getReleaseDate() { return manufNameDescVersRelease.get().getE(); } private static Quintet<String, String, String, String, String> queryManufNameDescVersRelease() {<FILL_FUNCTION_BODY>} }
String manufacturer = null; String name = null; String description = null; String version = null; String releaseDate = null; WmiResult<BiosProperty> win32BIOS = Win32Bios.queryBiosInfo(); if (win32BIOS.getResultCount() > 0) { manufacturer = WmiUtil.getString(win32BIOS, BiosProperty.MANUFACTURER, 0); name = WmiUtil.getString(win32BIOS, BiosProperty.NAME, 0); description = WmiUtil.getString(win32BIOS, BiosProperty.DESCRIPTION, 0); version = WmiUtil.getString(win32BIOS, BiosProperty.VERSION, 0); releaseDate = WmiUtil.getDateString(win32BIOS, BiosProperty.RELEASEDATE, 0); } return new Quintet<>(Util.isBlank(manufacturer) ? Constants.UNKNOWN : manufacturer, Util.isBlank(name) ? Constants.UNKNOWN : name, Util.isBlank(description) ? Constants.UNKNOWN : description, Util.isBlank(version) ? Constants.UNKNOWN : version, Util.isBlank(releaseDate) ? Constants.UNKNOWN : releaseDate);
260
340
600
<methods>public non-sealed void <init>() ,public java.lang.String getDescription() ,public java.lang.String getName() ,public java.lang.String getReleaseDate() ,public java.lang.String toString() <variables>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java
WindowsGraphicsCard
getGraphicsCardsFromWmi
class WindowsGraphicsCard extends AbstractGraphicsCard { private static final Logger LOG = LoggerFactory.getLogger(WindowsGraphicsCard.class); private static final boolean IS_VISTA_OR_GREATER = VersionHelpers.IsWindowsVistaOrGreater(); public static final String ADAPTER_STRING = "HardwareInformation.AdapterString"; public static final String DRIVER_DESC = "DriverDesc"; public static final String DRIVER_VERSION = "DriverVersion"; public static final String VENDOR = "ProviderName"; public static final String QW_MEMORY_SIZE = "HardwareInformation.qwMemorySize"; public static final String MEMORY_SIZE = "HardwareInformation.MemorySize"; public static final String DISPLAY_DEVICES_REGISTRY_PATH = "SYSTEM\\CurrentControlSet\\Control\\Class\\{4d36e968-e325-11ce-bfc1-08002be10318}\\"; /** * Constructor for WindowsGraphicsCard * * @param name The name * @param deviceId The device ID * @param vendor The vendor * @param versionInfo The version info * @param vram The VRAM */ WindowsGraphicsCard(String name, String deviceId, String vendor, String versionInfo, long vram) { super(name, deviceId, vendor, versionInfo, vram); } /** * public method used by {@link oshi.hardware.common.AbstractHardwareAbstractionLayer} to access the graphics cards. * * @return List of {@link oshi.hardware.platform.windows.WindowsGraphicsCard} objects. */ public static List<GraphicsCard> getGraphicsCards() { List<GraphicsCard> cardList = new ArrayList<>(); int index = 1; String[] keys = Advapi32Util.registryGetKeys(WinReg.HKEY_LOCAL_MACHINE, DISPLAY_DEVICES_REGISTRY_PATH); for (String key : keys) { if (!key.startsWith("0")) { continue; } try { String fullKey = DISPLAY_DEVICES_REGISTRY_PATH + key; if (!Advapi32Util.registryValueExists(WinReg.HKEY_LOCAL_MACHINE, fullKey, ADAPTER_STRING)) { continue; } String name = Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, fullKey, DRIVER_DESC); String deviceId = "VideoController" + index++; String vendor = Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, fullKey, VENDOR); String versionInfo = Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, fullKey, DRIVER_VERSION); long vram = 0L; if (Advapi32Util.registryValueExists(WinReg.HKEY_LOCAL_MACHINE, fullKey, QW_MEMORY_SIZE)) { vram = Advapi32Util.registryGetLongValue(WinReg.HKEY_LOCAL_MACHINE, fullKey, QW_MEMORY_SIZE); } else if (Advapi32Util.registryValueExists(WinReg.HKEY_LOCAL_MACHINE, fullKey, MEMORY_SIZE)) { Object genericValue = Advapi32Util.registryGetValue(WinReg.HKEY_LOCAL_MACHINE, fullKey, MEMORY_SIZE); if (genericValue instanceof Long) { vram = (long) genericValue; } else if (genericValue instanceof Integer) { vram = Integer.toUnsignedLong((int) genericValue); } else if (genericValue instanceof byte[]) { byte[] bytes = (byte[]) genericValue; vram = ParseUtil.byteArrayToLong(bytes, bytes.length, false); } } cardList.add(new WindowsGraphicsCard( Util.isBlank(name) ? Constants.UNKNOWN : name, Util.isBlank(deviceId) ? Constants.UNKNOWN : deviceId, Util.isBlank(vendor) ? Constants.UNKNOWN : vendor, Util.isBlank(versionInfo) ? Constants.UNKNOWN : versionInfo, vram)); } catch (Win32Exception e) { if (e.getErrorCode() != WinError.ERROR_ACCESS_DENIED) { // Ignore access denied errors, re-throw others throw e; } } } if (cardList.isEmpty()) { return getGraphicsCardsFromWmi(); } return cardList; } // fall back if something went wrong private static List<GraphicsCard> getGraphicsCardsFromWmi() {<FILL_FUNCTION_BODY>} }
List<GraphicsCard> cardList = new ArrayList<>(); if (IS_VISTA_OR_GREATER) { WmiResult<VideoControllerProperty> cards = Win32VideoController.queryVideoController(); for (int index = 0; index < cards.getResultCount(); index++) { String name = WmiUtil.getString(cards, VideoControllerProperty.NAME, index); Triplet<String, String, String> idPair = ParseUtil.parseDeviceIdToVendorProductSerial( WmiUtil.getString(cards, VideoControllerProperty.PNPDEVICEID, index)); String deviceId = idPair == null ? Constants.UNKNOWN : idPair.getB(); String vendor = WmiUtil.getString(cards, VideoControllerProperty.ADAPTERCOMPATIBILITY, index); if (idPair != null) { if (Util.isBlank(vendor)) { deviceId = idPair.getA(); } else { vendor = vendor + " (" + idPair.getA() + ")"; } } String versionInfo = WmiUtil.getString(cards, VideoControllerProperty.DRIVERVERSION, index); if (!Util.isBlank(versionInfo)) { versionInfo = "DriverVersion=" + versionInfo; } else { versionInfo = Constants.UNKNOWN; } long vram = WmiUtil.getUint32asLong(cards, VideoControllerProperty.ADAPTERRAM, index); cardList.add(new WindowsGraphicsCard(Util.isBlank(name) ? Constants.UNKNOWN : name, deviceId, Util.isBlank(vendor) ? Constants.UNKNOWN : vendor, versionInfo, vram)); } } return cardList;
1,270
447
1,717
<methods>public java.lang.String getDeviceId() ,public java.lang.String getName() ,public long getVRam() ,public java.lang.String getVendor() ,public java.lang.String getVersionInfo() ,public java.lang.String toString() <variables>private final non-sealed java.lang.String deviceId,private final non-sealed java.lang.String name,private final non-sealed java.lang.String vendor,private final non-sealed java.lang.String versionInfo,private long vram
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsLogicalVolumeGroup.java
WindowsLogicalVolumeGroup
getLogicalVolumeGroups
class WindowsLogicalVolumeGroup extends AbstractLogicalVolumeGroup { private static final Logger LOG = LoggerFactory.getLogger(WindowsLogicalVolumeGroup.class); private static final Pattern SP_OBJECT_ID = Pattern.compile(".*ObjectId=.*SP:(\\{.*\\}).*"); private static final Pattern PD_OBJECT_ID = Pattern.compile(".*ObjectId=.*PD:(\\{.*\\}).*"); private static final Pattern VD_OBJECT_ID = Pattern.compile(".*ObjectId=.*VD:(\\{.*\\})(\\{.*\\}).*"); private static final boolean IS_WINDOWS8_OR_GREATER = VersionHelpers.IsWindows8OrGreater(); WindowsLogicalVolumeGroup(String name, Map<String, Set<String>> lvMap, Set<String> pvSet) { super(name, lvMap, pvSet); } static List<LogicalVolumeGroup> getLogicalVolumeGroups() {<FILL_FUNCTION_BODY>} }
// Storage Spaces requires Windows 8 or Server 2012 if (!IS_WINDOWS8_OR_GREATER) { return Collections.emptyList(); } WmiQueryHandler h = Objects.requireNonNull(WmiQueryHandler.createInstance()); boolean comInit = false; try { comInit = h.initCOM(); // Query Storage Pools first, so we can skip other queries if we have no pools WmiResult<StoragePoolProperty> sp = MSFTStorage.queryStoragePools(h); int count = sp.getResultCount(); if (count == 0) { return Collections.emptyList(); } // We have storage pool(s) but now need to gather other info // Get all the Virtual Disks Map<String, String> vdMap = new HashMap<>(); WmiResult<VirtualDiskProperty> vds = MSFTStorage.queryVirtualDisks(h); count = vds.getResultCount(); for (int i = 0; i < count; i++) { String vdObjectId = WmiUtil.getString(vds, VirtualDiskProperty.OBJECTID, i); Matcher m = VD_OBJECT_ID.matcher(vdObjectId); if (m.matches()) { vdObjectId = m.group(2) + " " + m.group(1); } // Store key with SP|VD vdMap.put(vdObjectId, WmiUtil.getString(vds, VirtualDiskProperty.FRIENDLYNAME, i)); } // Get all the Physical Disks Map<String, Pair<String, String>> pdMap = new HashMap<>(); WmiResult<PhysicalDiskProperty> pds = MSFTStorage.queryPhysicalDisks(h); count = pds.getResultCount(); for (int i = 0; i < count; i++) { String pdObjectId = WmiUtil.getString(pds, PhysicalDiskProperty.OBJECTID, i); Matcher m = PD_OBJECT_ID.matcher(pdObjectId); if (m.matches()) { pdObjectId = m.group(1); } // Store key with PD pdMap.put(pdObjectId, new Pair<>(WmiUtil.getString(pds, PhysicalDiskProperty.FRIENDLYNAME, i), WmiUtil.getString(pds, PhysicalDiskProperty.PHYSICALLOCATION, i))); } // Get the Storage Pool to Physical Disk mappping Map<String, String> sppdMap = new HashMap<>(); WmiResult<StoragePoolToPhysicalDiskProperty> sppd = MSFTStorage.queryStoragePoolPhysicalDisks(h); count = sppd.getResultCount(); for (int i = 0; i < count; i++) { // Ref string contains object id, will do partial match later String spObjectId = WmiUtil.getRefString(sppd, StoragePoolToPhysicalDiskProperty.STORAGEPOOL, i); Matcher m = SP_OBJECT_ID.matcher(spObjectId); if (m.matches()) { spObjectId = m.group(1); } String pdObjectId = WmiUtil.getRefString(sppd, StoragePoolToPhysicalDiskProperty.PHYSICALDISK, i); m = PD_OBJECT_ID.matcher(pdObjectId); if (m.matches()) { pdObjectId = m.group(1); } sppdMap.put(spObjectId + " " + pdObjectId, pdObjectId); } // Finally process the storage pools List<LogicalVolumeGroup> lvgList = new ArrayList<>(); count = sp.getResultCount(); for (int i = 0; i < count; i++) { // Name String name = WmiUtil.getString(sp, StoragePoolProperty.FRIENDLYNAME, i); // Parse object ID to match String spObjectId = WmiUtil.getString(sp, StoragePoolProperty.OBJECTID, i); Matcher m = SP_OBJECT_ID.matcher(spObjectId); if (m.matches()) { spObjectId = m.group(1); } // find matching physical and logical volumes Set<String> physicalVolumeSet = new HashSet<>(); for (Entry<String, String> entry : sppdMap.entrySet()) { if (entry.getKey().contains(spObjectId)) { String pdObjectId = entry.getValue(); Pair<String, String> nameLoc = pdMap.get(pdObjectId); if (nameLoc != null) { physicalVolumeSet.add(nameLoc.getA() + " @ " + nameLoc.getB()); } } } // find matching logical volume Map<String, Set<String>> logicalVolumeMap = new HashMap<>(); for (Entry<String, String> entry : vdMap.entrySet()) { if (entry.getKey().contains(spObjectId)) { String vdObjectId = ParseUtil.whitespaces.split(entry.getKey())[0]; logicalVolumeMap.put(entry.getValue() + " " + vdObjectId, physicalVolumeSet); } } // Add to list lvgList.add(new WindowsLogicalVolumeGroup(name, logicalVolumeMap, physicalVolumeSet)); } return lvgList; } catch (COMException e) { LOG.warn("COM exception: {}", e.getMessage()); return Collections.emptyList(); } finally { if (comInit) { h.unInitCOM(); } }
261
1,445
1,706
<methods>public Map<java.lang.String,Set<java.lang.String>> getLogicalVolumes() ,public java.lang.String getName() ,public Set<java.lang.String> getPhysicalVolumes() ,public java.lang.String toString() <variables>private final non-sealed Map<java.lang.String,Set<java.lang.String>> lvMap,private final non-sealed java.lang.String name,private final non-sealed Set<java.lang.String> pvSet
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsNetworkIF.java
WindowsNetworkIF
getNetworks
class WindowsNetworkIF extends AbstractNetworkIF { private static final Logger LOG = LoggerFactory.getLogger(WindowsNetworkIF.class); private static final boolean IS_VISTA_OR_GREATER = VersionHelpers.IsWindowsVistaOrGreater(); private static final byte CONNECTOR_PRESENT_BIT = 0b00000100; private int ifType; private int ndisPhysicalMediumType; private boolean connectorPresent; private long bytesRecv; private long bytesSent; private long packetsRecv; private long packetsSent; private long inErrors; private long outErrors; private long inDrops; private long collisions; private long speed; private long timeStamp; private String ifAlias; private IfOperStatus ifOperStatus; public WindowsNetworkIF(NetworkInterface netint) throws InstantiationException { super(netint); updateAttributes(); } /** * Gets all network interfaces on this machine * * @param includeLocalInterfaces include local interfaces in the result * @return A list of {@link NetworkIF} objects representing the interfaces */ public static List<NetworkIF> getNetworks(boolean includeLocalInterfaces) {<FILL_FUNCTION_BODY>} @Override public int getIfType() { return this.ifType; } @Override public int getNdisPhysicalMediumType() { return this.ndisPhysicalMediumType; } @Override public boolean isConnectorPresent() { return this.connectorPresent; } @Override public long getBytesRecv() { return this.bytesRecv; } @Override public long getBytesSent() { return this.bytesSent; } @Override public long getPacketsRecv() { return this.packetsRecv; } @Override public long getPacketsSent() { return this.packetsSent; } @Override public long getInErrors() { return this.inErrors; } @Override public long getOutErrors() { return this.outErrors; } @Override public long getInDrops() { return this.inDrops; } @Override public long getCollisions() { return this.collisions; } @Override public long getSpeed() { return this.speed; } @Override public long getTimeStamp() { return this.timeStamp; } @Override public String getIfAlias() { return ifAlias; } @Override public IfOperStatus getIfOperStatus() { return ifOperStatus; } @Override public boolean updateAttributes() { // MIB_IFROW2 requires Vista (6.0) or later. if (IS_VISTA_OR_GREATER) { // Create new MIB_IFROW2 and set index to this interface index try (CloseableMibIfRow2 ifRow = new CloseableMibIfRow2()) { ifRow.InterfaceIndex = queryNetworkInterface().getIndex(); if (0 != IPHlpAPI.INSTANCE.GetIfEntry2(ifRow)) { // Error, abort LOG.error("Failed to retrieve data for interface {}, {}", queryNetworkInterface().getIndex(), getName()); return false; } this.ifType = ifRow.Type; this.ndisPhysicalMediumType = ifRow.PhysicalMediumType; this.connectorPresent = (ifRow.InterfaceAndOperStatusFlags & CONNECTOR_PRESENT_BIT) > 0; this.bytesSent = ifRow.OutOctets; this.bytesRecv = ifRow.InOctets; this.packetsSent = ifRow.OutUcastPkts; this.packetsRecv = ifRow.InUcastPkts; this.outErrors = ifRow.OutErrors; this.inErrors = ifRow.InErrors; this.collisions = ifRow.OutDiscards; // closest proxy this.inDrops = ifRow.InDiscards; // closest proxy this.speed = ifRow.ReceiveLinkSpeed; this.ifAlias = Native.toString(ifRow.Alias); this.ifOperStatus = IfOperStatus.byValue(ifRow.OperStatus); } } else { // Create new MIB_IFROW and set index to this interface index try (CloseableMibIfRow ifRow = new CloseableMibIfRow()) { ifRow.dwIndex = queryNetworkInterface().getIndex(); if (0 != IPHlpAPI.INSTANCE.GetIfEntry(ifRow)) { // Error, abort LOG.error("Failed to retrieve data for interface {}, {}", queryNetworkInterface().getIndex(), getName()); return false; } this.ifType = ifRow.dwType; // These are unsigned ints. Widen them to longs. this.bytesSent = ParseUtil.unsignedIntToLong(ifRow.dwOutOctets); this.bytesRecv = ParseUtil.unsignedIntToLong(ifRow.dwInOctets); this.packetsSent = ParseUtil.unsignedIntToLong(ifRow.dwOutUcastPkts); this.packetsRecv = ParseUtil.unsignedIntToLong(ifRow.dwInUcastPkts); this.outErrors = ParseUtil.unsignedIntToLong(ifRow.dwOutErrors); this.inErrors = ParseUtil.unsignedIntToLong(ifRow.dwInErrors); this.collisions = ParseUtil.unsignedIntToLong(ifRow.dwOutDiscards); // closest proxy this.inDrops = ParseUtil.unsignedIntToLong(ifRow.dwInDiscards); // closest proxy this.speed = ParseUtil.unsignedIntToLong(ifRow.dwSpeed); this.ifAlias = ""; // not supported by MIB_IFROW this.ifOperStatus = IfOperStatus.UNKNOWN; // not supported } } this.timeStamp = System.currentTimeMillis(); return true; } }
List<NetworkIF> ifList = new ArrayList<>(); for (NetworkInterface ni : getNetworkInterfaces(includeLocalInterfaces)) { try { ifList.add(new WindowsNetworkIF(ni)); } catch (InstantiationException e) { LOG.debug("Network Interface Instantiation failed: {}", e.getMessage()); } } return ifList;
1,610
97
1,707
<methods>public java.lang.String getDisplayName() ,public java.lang.String[] getIPv4addr() ,public java.lang.String[] getIPv6addr() ,public int getIndex() ,public long getMTU() ,public java.lang.String getMacaddr() ,public java.lang.String getName() ,public java.lang.Short[] getPrefixLengths() ,public java.lang.Short[] getSubnetMasks() ,public boolean isKnownVmMacAddr() ,public java.net.NetworkInterface queryNetworkInterface() ,public java.lang.String toString() <variables>private static final org.slf4j.Logger LOG,private static final java.lang.String OSHI_VM_MAC_ADDR_PROPERTIES,private java.lang.String displayName,private int index,private java.lang.String[] ipv4,private java.lang.String[] ipv6,private java.lang.String mac,private long mtu,private java.lang.String name,private java.net.NetworkInterface networkInterface,private java.lang.Short[] prefixLengths,private java.lang.Short[] subnetMasks,private final Supplier<java.util.Properties> vmMacAddrProps
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsSoundCard.java
WindowsSoundCard
getSoundCards
class WindowsSoundCard extends AbstractSoundCard { private static final String REGISTRY_SOUNDCARDS = "SYSTEM\\CurrentControlSet\\Control\\Class\\{4d36e96c-e325-11ce-bfc1-08002be10318}\\"; /** * Constructor for WindowsSoundCard. * * @param kernelVersion The version * @param name The name * @param codec The codec */ WindowsSoundCard(String kernelVersion, String name, String codec) { super(kernelVersion, name, codec); } /** * Returns Windows audio device driver information, which represents the closest proxy we have to sound cards. * <p> * NOTE : The reason why the codec name is same as the card name is because windows does not provide the name of the * codec chip but sometimes the name of the card returned is infact the name of the codec chip also. Example : * Realtek ALC887 HD Audio Device * * @return List of sound cards */ public static List<SoundCard> getSoundCards() {<FILL_FUNCTION_BODY>} }
List<SoundCard> soundCards = new ArrayList<>(); String[] keys = Advapi32Util.registryGetKeys(WinReg.HKEY_LOCAL_MACHINE, REGISTRY_SOUNDCARDS); for (String key : keys) { String fullKey = REGISTRY_SOUNDCARDS + key; try { if (Advapi32Util.registryValueExists(WinReg.HKEY_LOCAL_MACHINE, fullKey, "Driver")) { soundCards.add(new WindowsSoundCard( Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, fullKey, "Driver") + " " + Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, fullKey, "DriverVersion"), Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, fullKey, "ProviderName") + " " + Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, fullKey, "DriverDesc"), Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, fullKey, "DriverDesc"))); } } catch (Win32Exception e) { if (e.getErrorCode() != WinError.ERROR_ACCESS_DENIED) { // Ignore access denied errors, re-throw others throw e; } } } return soundCards;
304
401
705
<methods>public java.lang.String getCodec() ,public java.lang.String getDriverVersion() ,public java.lang.String getName() ,public java.lang.String toString() <variables>private java.lang.String codec,private java.lang.String kernelVersion,private java.lang.String name
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsUsbDevice.java
WindowsUsbDevice
getUsbDevices
class WindowsUsbDevice extends AbstractUsbDevice { private static final GUID GUID_DEVINTERFACE_USB_HOST_CONTROLLER = new GUID( "{3ABF6F2D-71C4-462A-8A92-1E6861E6AF27}"); public WindowsUsbDevice(String name, String vendor, String vendorId, String productId, String serialNumber, String uniqueDeviceId, List<UsbDevice> connectedDevices) { super(name, vendor, vendorId, productId, serialNumber, uniqueDeviceId, connectedDevices); } /** * Instantiates a list of {@link oshi.hardware.UsbDevice} objects, representing devices connected via a usb port * (including internal devices). * <p> * If the value of {@code tree} is true, the top level devices returned from this method are the USB Controllers; * connected hubs and devices in its device tree share that controller's bandwidth. If the value of {@code tree} is * false, USB devices (not controllers) are listed in a single flat list. * * @param tree If true, returns a list of controllers, which requires recursive iteration of connected devices. If * false, returns a flat list of devices excluding controllers. * @return a list of {@link oshi.hardware.UsbDevice} objects. */ public static List<UsbDevice> getUsbDevices(boolean tree) {<FILL_FUNCTION_BODY>} private static void addDevicesToList(List<UsbDevice> deviceList, List<UsbDevice> list) { for (UsbDevice device : list) { deviceList.add(new WindowsUsbDevice(device.getName(), device.getVendor(), device.getVendorId(), device.getProductId(), device.getSerialNumber(), device.getUniqueDeviceId(), Collections.emptyList())); addDevicesToList(deviceList, device.getConnectedDevices()); } } private static List<UsbDevice> queryUsbDevices() { Quintet<Set<Integer>, Map<Integer, Integer>, Map<Integer, String>, Map<Integer, String>, Map<Integer, String>> controllerDevices = DeviceTree .queryDeviceTree(GUID_DEVINTERFACE_USB_HOST_CONTROLLER); Map<Integer, Integer> parentMap = controllerDevices.getB(); Map<Integer, String> nameMap = controllerDevices.getC(); Map<Integer, String> deviceIdMap = controllerDevices.getD(); Map<Integer, String> mfgMap = controllerDevices.getE(); List<UsbDevice> usbDevices = new ArrayList<>(); // recursively build results for (Integer controllerDevice : controllerDevices.getA()) { WindowsUsbDevice deviceAndChildren = queryDeviceAndChildren(controllerDevice, parentMap, nameMap, deviceIdMap, mfgMap, "0000", "0000", ""); if (deviceAndChildren != null) { usbDevices.add(deviceAndChildren); } } return usbDevices; } private static WindowsUsbDevice queryDeviceAndChildren(Integer device, Map<Integer, Integer> parentMap, Map<Integer, String> nameMap, Map<Integer, String> deviceIdMap, Map<Integer, String> mfgMap, String vid, String pid, String parentSerial) { // Parse vendor and product IDs from the device ID // If this doesn't work, use the IDs from the parent String vendorId = vid; String productId = pid; String serial = parentSerial; Triplet<String, String, String> idsAndSerial = ParseUtil .parseDeviceIdToVendorProductSerial(deviceIdMap.get(device)); if (idsAndSerial != null) { vendorId = idsAndSerial.getA(); productId = idsAndSerial.getB(); serial = idsAndSerial.getC(); if (serial.isEmpty() && vendorId.equals(vid) && productId.equals(pid)) { serial = parentSerial; } } // Iterate the parent map looking for children Set<Integer> childDeviceSet = parentMap.entrySet().stream().filter(e -> e.getValue().equals(device)) .map(Entry::getKey).collect(Collectors.toSet()); // Recursively find those children and put in a list List<UsbDevice> childDevices = new ArrayList<>(); for (Integer child : childDeviceSet) { WindowsUsbDevice deviceAndChildren = queryDeviceAndChildren(child, parentMap, nameMap, deviceIdMap, mfgMap, vendorId, productId, serial); if (deviceAndChildren != null) { childDevices.add(deviceAndChildren); } } Collections.sort(childDevices); // Finally construct the object and return if (nameMap.containsKey(device)) { String name = nameMap.get(device); if (name.isEmpty()) { name = vendorId + ":" + productId; } String deviceId = deviceIdMap.get(device); String mfg = mfgMap.get(device); return new WindowsUsbDevice(name, mfg, vendorId, productId, serial, deviceId, childDevices); } return null; } }
List<UsbDevice> devices = queryUsbDevices(); if (tree) { return devices; } List<UsbDevice> deviceList = new ArrayList<>(); // Top level is controllers; they won't be added to the list, but all // their connected devices will be for (UsbDevice device : devices) { // Recursively add all child devices addDevicesToList(deviceList, device.getConnectedDevices()); } return deviceList;
1,370
128
1,498
<methods>public int compareTo(oshi.hardware.UsbDevice) ,public List<oshi.hardware.UsbDevice> getConnectedDevices() ,public java.lang.String getName() ,public java.lang.String getProductId() ,public java.lang.String getSerialNumber() ,public java.lang.String getUniqueDeviceId() ,public java.lang.String getVendor() ,public java.lang.String getVendorId() ,public java.lang.String toString() <variables>private final non-sealed List<oshi.hardware.UsbDevice> connectedDevices,private final non-sealed java.lang.String name,private final non-sealed java.lang.String productId,private final non-sealed java.lang.String serialNumber,private final non-sealed java.lang.String uniqueDeviceId,private final non-sealed java.lang.String vendor,private final non-sealed java.lang.String vendorId
oshi_oshi
oshi/oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsVirtualMemory.java
WindowsVirtualMemory
querySwapTotalVirtMaxVirtUsed
class WindowsVirtualMemory extends AbstractVirtualMemory { private static final Logger LOG = LoggerFactory.getLogger(WindowsVirtualMemory.class); private final WindowsGlobalMemory global; private final Supplier<Long> used = memoize(WindowsVirtualMemory::querySwapUsed, defaultExpiration()); private final Supplier<Triplet<Long, Long, Long>> totalVmaxVused = memoize( WindowsVirtualMemory::querySwapTotalVirtMaxVirtUsed, defaultExpiration()); private final Supplier<Pair<Long, Long>> swapInOut = memoize(WindowsVirtualMemory::queryPageSwaps, defaultExpiration()); /** * Constructor for WindowsVirtualMemory. * * @param windowsGlobalMemory The parent global memory class instantiating this */ WindowsVirtualMemory(WindowsGlobalMemory windowsGlobalMemory) { this.global = windowsGlobalMemory; } @Override public long getSwapUsed() { return this.global.getPageSize() * used.get(); } @Override public long getSwapTotal() { return this.global.getPageSize() * totalVmaxVused.get().getA(); } @Override public long getVirtualMax() { return this.global.getPageSize() * totalVmaxVused.get().getB(); } @Override public long getVirtualInUse() { return this.global.getPageSize() * totalVmaxVused.get().getC(); } @Override public long getSwapPagesIn() { return swapInOut.get().getA(); } @Override public long getSwapPagesOut() { return swapInOut.get().getB(); } private static long querySwapUsed() { return PagingFile.querySwapUsed().getOrDefault(PagingPercentProperty.PERCENTUSAGE, 0L); } private static Triplet<Long, Long, Long> querySwapTotalVirtMaxVirtUsed() {<FILL_FUNCTION_BODY>} private static Pair<Long, Long> queryPageSwaps() { Map<PageSwapProperty, Long> valueMap = MemoryInformation.queryPageSwaps(); return new Pair<>(valueMap.getOrDefault(PageSwapProperty.PAGESINPUTPERSEC, 0L), valueMap.getOrDefault(PageSwapProperty.PAGESOUTPUTPERSEC, 0L)); } }
try (CloseablePerformanceInformation perfInfo = new CloseablePerformanceInformation()) { if (!Psapi.INSTANCE.GetPerformanceInfo(perfInfo, perfInfo.size())) { LOG.error("Failed to get Performance Info. Error code: {}", Kernel32.INSTANCE.GetLastError()); return new Triplet<>(0L, 0L, 0L); } return new Triplet<>(perfInfo.CommitLimit.longValue() - perfInfo.PhysicalTotal.longValue(), perfInfo.CommitLimit.longValue(), perfInfo.CommitTotal.longValue()); }
630
155
785
<methods>public non-sealed void <init>() ,public java.lang.String toString() <variables>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/common/AbstractNetworkParams.java
AbstractNetworkParams
getDnsServers
class AbstractNetworkParams implements NetworkParams { private static final String NAMESERVER = "nameserver"; @Override public String getDomainName() { InetAddress localHost; try { localHost = InetAddress.getLocalHost(); } catch (UnknownHostException e) { localHost = InetAddress.getLoopbackAddress(); } return localHost.getCanonicalHostName(); } @Override public String getHostName() { InetAddress localHost; try { localHost = InetAddress.getLocalHost(); } catch (UnknownHostException e) { localHost = InetAddress.getLoopbackAddress(); } String hn = localHost.getHostName(); int dot = hn.indexOf('.'); if (dot == -1) { return hn; } return hn.substring(0, dot); } @Override public String[] getDnsServers() {<FILL_FUNCTION_BODY>} /** * Convenience method to parse the output of the `route` command. While the command arguments vary between OS's the * output is consistently parsable. * * @param lines output of OS-specific route command * @return default gateway */ protected static String searchGateway(List<String> lines) { for (String line : lines) { String leftTrimmed = line.replaceFirst("^\\s+", ""); if (leftTrimmed.startsWith("gateway:")) { String[] split = ParseUtil.whitespaces.split(leftTrimmed); if (split.length < 2) { return ""; } return split[1].split("%")[0]; } } return ""; } @Override public String toString() { return String.format(Locale.ROOT, "Host name: %s, Domain name: %s, DNS servers: %s, IPv4 Gateway: %s, IPv6 Gateway: %s", this.getHostName(), this.getDomainName(), Arrays.toString(this.getDnsServers()), this.getIpv4DefaultGateway(), this.getIpv6DefaultGateway()); } }
List<String> resolv = FileUtil.readFile("/etc/resolv.conf"); String key = NAMESERVER; int maxNameServer = 3; List<String> servers = new ArrayList<>(); for (int i = 0; i < resolv.size() && servers.size() < maxNameServer; i++) { String line = resolv.get(i); if (line.startsWith(key)) { String value = line.substring(key.length()).replaceFirst("^[ \t]+", ""); if (value.length() != 0 && value.charAt(0) != '#' && value.charAt(0) != ';') { String val = value.split("[ \t#;]", 2)[0]; servers.add(val); } } } return servers.toArray(new String[0]);
583
225
808
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/common/AbstractOSFileStore.java
AbstractOSFileStore
toString
class AbstractOSFileStore implements OSFileStore { private String name; private String volume; private String label; private String mount; private String options; private String uuid; protected AbstractOSFileStore(String name, String volume, String label, String mount, String options, String uuid) { this.name = name; this.volume = volume; this.label = label; this.mount = mount; this.options = options; this.uuid = uuid; } protected AbstractOSFileStore() { } @Override public String getName() { return this.name; } @Override public String getVolume() { return this.volume; } @Override public String getLabel() { return this.label; } @Override public String getMount() { return this.mount; } @Override public String getOptions() { return options; } @Override public String getUUID() { return this.uuid; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "OSFileStore [name=" + getName() + ", volume=" + getVolume() + ", label=" + getLabel() + ", logicalVolume=" + getLogicalVolume() + ", mount=" + getMount() + ", description=" + getDescription() + ", fsType=" + getType() + ", options=\"" + getOptions() + "\", uuid=" + getUUID() + ", freeSpace=" + getFreeSpace() + ", usableSpace=" + getUsableSpace() + ", totalSpace=" + getTotalSpace() + ", freeInodes=" + getFreeInodes() + ", totalInodes=" + getTotalInodes() + "]";
306
170
476
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/common/AbstractOSProcess.java
AbstractOSProcess
queryCumulativeCpuLoad
class AbstractOSProcess implements OSProcess { private final Supplier<Double> cumulativeCpuLoad = memoize(this::queryCumulativeCpuLoad, defaultExpiration()); private int processID; protected AbstractOSProcess(int pid) { this.processID = pid; } @Override public int getProcessID() { return this.processID; } @Override public double getProcessCpuLoadCumulative() { return cumulativeCpuLoad.get(); } private double queryCumulativeCpuLoad() {<FILL_FUNCTION_BODY>} @Override public double getProcessCpuLoadBetweenTicks(OSProcess priorSnapshot) { if (priorSnapshot != null && this.processID == priorSnapshot.getProcessID() && getUpTime() > priorSnapshot.getUpTime()) { return (getUserTime() - priorSnapshot.getUserTime() + getKernelTime() - priorSnapshot.getKernelTime()) / (double) (getUpTime() - priorSnapshot.getUpTime()); } return getProcessCpuLoadCumulative(); } @Override public String toString() { StringBuilder builder = new StringBuilder("OSProcess@"); builder.append(Integer.toHexString(hashCode())); builder.append("[processID=").append(this.processID); builder.append(", name=").append(getName()).append(']'); return builder.toString(); } }
return getUpTime() > 0d ? (getKernelTime() + getUserTime()) / (double) getUpTime() : 0d;
379
37
416
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/common/AbstractOSThread.java
AbstractOSThread
getThreadCpuLoadBetweenTicks
class AbstractOSThread implements OSThread { private final Supplier<Double> cumulativeCpuLoad = memoize(this::queryCumulativeCpuLoad, defaultExpiration()); private final int owningProcessId; protected AbstractOSThread(int processId) { this.owningProcessId = processId; } @Override public int getOwningProcessId() { return this.owningProcessId; } @Override public double getThreadCpuLoadCumulative() { return cumulativeCpuLoad.get(); } private double queryCumulativeCpuLoad() { return getUpTime() > 0d ? (getKernelTime() + getUserTime()) / (double) getUpTime() : 0d; } @Override public double getThreadCpuLoadBetweenTicks(OSThread priorSnapshot) {<FILL_FUNCTION_BODY>} @Override public String toString() { return "OSThread [threadId=" + getThreadId() + ", owningProcessId=" + getOwningProcessId() + ", name=" + getName() + ", state=" + getState() + ", kernelTime=" + getKernelTime() + ", userTime=" + getUserTime() + ", upTime=" + getUpTime() + ", startTime=" + getStartTime() + ", startMemoryAddress=0x" + String.format(Locale.ROOT, "%x", getStartMemoryAddress()) + ", contextSwitches=" + getContextSwitches() + ", minorFaults=" + getMinorFaults() + ", majorFaults=" + getMajorFaults() + "]"; } }
if (priorSnapshot != null && owningProcessId == priorSnapshot.getOwningProcessId() && getThreadId() == priorSnapshot.getThreadId() && getUpTime() > priorSnapshot.getUpTime()) { return (getUserTime() - priorSnapshot.getUserTime() + getKernelTime() - priorSnapshot.getKernelTime()) / (double) (getUpTime() - priorSnapshot.getUpTime()); } return getThreadCpuLoadCumulative();
432
120
552
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/common/AbstractOperatingSystem.java
AbstractOperatingSystem
getProcesses
class AbstractOperatingSystem implements OperatingSystem { protected static final boolean USE_WHO_COMMAND = GlobalConfig.get(GlobalConfig.OSHI_OS_UNIX_WHOCOMMAND, false); private final Supplier<String> manufacturer = memoize(this::queryManufacturer); private final Supplier<Pair<String, OSVersionInfo>> familyVersionInfo = memoize(this::queryFamilyVersionInfo); private final Supplier<Integer> bitness = memoize(this::queryPlatformBitness); @Override public String getManufacturer() { return manufacturer.get(); } protected abstract String queryManufacturer(); @Override public String getFamily() { return familyVersionInfo.get().getA(); } @Override public OSVersionInfo getVersionInfo() { return familyVersionInfo.get().getB(); } protected abstract Pair<String, OSVersionInfo> queryFamilyVersionInfo(); @Override public int getBitness() { return bitness.get(); } private int queryPlatformBitness() { if (Platform.is64Bit()) { return 64; } // Initialize based on JVM Bitness. Individual OS implementations will test // if 32-bit JVM running on 64-bit OS int jvmBitness = System.getProperty("os.arch").contains("64") ? 64 : 32; return queryBitness(jvmBitness); } /** * Backup OS-specific query to determine bitness if previous checks fail * * @param jvmBitness The bitness of the JVM * @return The operating system bitness */ protected abstract int queryBitness(int jvmBitness); @Override public List<OSProcess> getProcesses(Predicate<OSProcess> filter, Comparator<OSProcess> sort, int limit) {<FILL_FUNCTION_BODY>} protected abstract List<OSProcess> queryAllProcesses(); @Override public List<OSProcess> getChildProcesses(int parentPid, Predicate<OSProcess> filter, Comparator<OSProcess> sort, int limit) { // Get this pid and its children List<OSProcess> childProcs = queryChildProcesses(parentPid); // Extract the parent from the list OSProcess parent = childProcs.stream().filter(p -> p.getProcessID() == parentPid).findAny().orElse(null); // Get the parent's start time long parentStartTime = parent == null ? 0 : parent.getStartTime(); // Get children after parent return queryChildProcesses(parentPid).stream().filter(filter == null ? ALL_PROCESSES : filter) .filter(p -> p.getProcessID() != parentPid && p.getStartTime() >= parentStartTime) .sorted(sort == null ? NO_SORTING : sort).limit(limit > 0 ? limit : Long.MAX_VALUE) .collect(Collectors.toList()); } protected abstract List<OSProcess> queryChildProcesses(int parentPid); @Override public List<OSProcess> getDescendantProcesses(int parentPid, Predicate<OSProcess> filter, Comparator<OSProcess> sort, int limit) { // Get this pid and its descendants List<OSProcess> descendantProcs = queryDescendantProcesses(parentPid); // Extract the parent from the list OSProcess parent = descendantProcs.stream().filter(p -> p.getProcessID() == parentPid).findAny().orElse(null); // Get the parent's start time long parentStartTime = parent == null ? 0 : parent.getStartTime(); // Get descendants after parent return queryDescendantProcesses(parentPid).stream().filter(filter == null ? ALL_PROCESSES : filter) .filter(p -> p.getProcessID() != parentPid && p.getStartTime() >= parentStartTime) .sorted(sort == null ? NO_SORTING : sort).limit(limit > 0 ? limit : Long.MAX_VALUE) .collect(Collectors.toList()); } protected abstract List<OSProcess> queryDescendantProcesses(int parentPid); /** * Utility method for subclasses to take a full process list as input and return the children or descendants of a * particular process. The process itself is also returned to more efficiently extract its start time for filtering * * @param allProcs A collection of all processes * @param parentPid The process ID whose children or descendants to return * @param allDescendants If false, only gets immediate children of this process. If true, gets all descendants. * @return Set of children or descendants of parentPid */ protected static Set<Integer> getChildrenOrDescendants(Collection<OSProcess> allProcs, int parentPid, boolean allDescendants) { Map<Integer, Integer> parentPidMap = allProcs.stream() .collect(Collectors.toMap(OSProcess::getProcessID, OSProcess::getParentProcessID)); return getChildrenOrDescendants(parentPidMap, parentPid, allDescendants); } /** * Utility method for subclasses to take a map of pid to parent as input and return the children or descendants of a * particular process. * * @param parentPidMap a map of all processes with processID as key and parentProcessID as value * @param parentPid The process ID whose children or descendants to return * @param allDescendants If false, only gets immediate children of this process. If true, gets all descendants. * @return Set of children or descendants of parentPid, including the parent */ protected static Set<Integer> getChildrenOrDescendants(Map<Integer, Integer> parentPidMap, int parentPid, boolean allDescendants) { // Set to hold results Set<Integer> descendantPids = new HashSet<>(); descendantPids.add(parentPid); // Queue for BFS algorithm Queue<Integer> queue = new ArrayDeque<>(); queue.add(parentPid); // Add children, repeating if recursive do { for (int pid : getChildren(parentPidMap, queue.poll())) { if (!descendantPids.contains(pid)) { descendantPids.add(pid); queue.add(pid); } } } while (allDescendants && !queue.isEmpty()); return descendantPids; } private static Set<Integer> getChildren(Map<Integer, Integer> parentPidMap, int parentPid) { return parentPidMap.entrySet().stream() .filter(e -> e.getValue().equals(parentPid) && !e.getKey().equals(parentPid)).map(Entry::getKey) .collect(Collectors.toSet()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getManufacturer()).append(' ').append(getFamily()).append(' ').append(getVersionInfo()); return sb.toString(); } }
return queryAllProcesses().stream().filter(filter == null ? ALL_PROCESSES : filter) .sorted(sort == null ? NO_SORTING : sort).limit(limit > 0 ? limit : Long.MAX_VALUE) .collect(Collectors.toList());
1,841
72
1,913
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/OSDesktopWindow.java
OSDesktopWindow
toString
class OSDesktopWindow { private final long windowId; private final String title; private final String command; private final Rectangle locAndSize; private final long owningProcessId; private final int order; private final boolean visible; public OSDesktopWindow(long windowId, String title, String command, Rectangle locAndSize, long owningProcessId, int order, boolean visible) { super(); this.windowId = windowId; this.title = title; this.command = command; this.locAndSize = locAndSize; this.owningProcessId = owningProcessId; this.order = order; this.visible = visible; } /** * Gets the operating system's handle, window ID, or other unique identifier for this window. * <p> * On Winodws, this can be converted to a {@link HWND} using {@code new HWND(new Pointer(windowId))}. On macOS, this * is the Core Graphics Window ID. On Unix-like systems, this is the X11 Window ID. * * @return the windowId */ public long getWindowId() { return windowId; } /** * Gets the Window title, if any. * * @return the title, which may be an empty string if the window has no title. */ public String getTitle() { return title; } /** * Gets the command name (possibly the full file path) of the window's executable program, if known. * * @return the command */ public String getCommand() { return command; } /** * Gets a {@link Rectangle} representing the window's location and size. * * @return the location and size */ public Rectangle getLocAndSize() { return locAndSize; } /** * Gets the process ID of the process which owns this window, if known. * * @return the owningProcessId */ public long getOwningProcessId() { return owningProcessId; } /** * Makes a best effort to get the order in which this window appears on the desktop. Higher values are more in the * foreground. * <p> * On Windows, this represents the Z Order of the window, and is not guaranteed to be atomic, as it could be * impacted by race conditions. * <p> * On macOS this is the window layer. Note that multiple windows may share the same layer. * <p> * On X11 this represents the stacking order of the windows. * * @return a best effort identification of the window's Z order relative to other windows */ public int getOrder() { return order; } /** * Makes a best effort to report whether the window is visible to the user. A "visible" window may be completely * transparent. * * @return {@code true} if the window is visible to users or if visibility can not be determined, {@code false} * otherwise. */ public boolean isVisible() { return visible; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "OSDesktopWindow [windowId=" + windowId + ", title=" + title + ", command=" + command + ", locAndSize=" + locAndSize.toString() + ", owningProcessId=" + owningProcessId + ", order=" + order + ", visible=" + visible + "]";
838
81
919
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/OSSession.java
OSSession
toString
class OSSession { private static final DateTimeFormatter LOGIN_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm", Locale.ROOT); private final String userName; private final String terminalDevice; private final long loginTime; private final String host; public OSSession(String userName, String terminalDevice, long loginTime, String host) { this.userName = userName; this.terminalDevice = terminalDevice; this.loginTime = loginTime; this.host = host; } /** * Gets the login name of the user * * @return the userName */ public String getUserName() { return userName; } /** * Gets the terminal device (such as tty, pts, etc.) the user used to log in * * @return the terminalDevice */ public String getTerminalDevice() { return terminalDevice; } /** * Gets the time the user logged in * * @return the loginTime, in milliseconds since the 1970 epoch */ public long getLoginTime() { return loginTime; } /** * Gets the remote host from which the user logged in * * @return the host as either an IPv4 or IPv6 representation. If the host is unspecified, may also be an empty * string, depending on the platform. */ public String getHost() { return host; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
String loginStr = loginTime == 0 ? "No login" : LocalDateTime.ofInstant(Instant.ofEpochMilli(loginTime), ZoneId.systemDefault()).format(LOGIN_FORMAT); String hostStr = ""; if (!host.isEmpty() && !host.equals("::") && !host.equals("0.0.0.0")) { hostStr = ", (" + host + ")"; } return String.format(Locale.ROOT, "%s, %s, %s%s", userName, terminalDevice, loginStr, hostStr);
413
142
555
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/linux/LinuxInternetProtocolStats.java
LinuxInternetProtocolStats
parseIpAddr
class LinuxInternetProtocolStats extends AbstractInternetProtocolStats { @Override public TcpStats getTCPv4Stats() { return NetStat.queryTcpStats("netstat -st4"); } @Override public UdpStats getUDPv4Stats() { return NetStat.queryUdpStats("netstat -su4"); } @Override public UdpStats getUDPv6Stats() { return NetStat.queryUdpStats("netstat -su6"); } @Override public List<IPConnection> getConnections() { List<IPConnection> conns = new ArrayList<>(); Map<Integer, Integer> pidMap = ProcessStat.querySocketToPidMap(); conns.addAll(queryConnections("tcp", 4, pidMap)); conns.addAll(queryConnections("tcp", 6, pidMap)); conns.addAll(queryConnections("udp", 4, pidMap)); conns.addAll(queryConnections("udp", 6, pidMap)); return conns; } private static List<IPConnection> queryConnections(String protocol, int ipver, Map<Integer, Integer> pidMap) { List<IPConnection> conns = new ArrayList<>(); for (String s : FileUtil.readFile(ProcPath.NET + "/" + protocol + (ipver == 6 ? "6" : ""))) { if (s.indexOf(':') >= 0) { String[] split = ParseUtil.whitespaces.split(s.trim()); if (split.length > 9) { Pair<byte[], Integer> lAddr = parseIpAddr(split[1]); Pair<byte[], Integer> fAddr = parseIpAddr(split[2]); TcpState state = stateLookup(ParseUtil.hexStringToInt(split[3], 0)); Pair<Integer, Integer> txQrxQ = parseHexColonHex(split[4]); int inode = ParseUtil.parseIntOrDefault(split[9], 0); conns.add(new IPConnection(protocol + ipver, lAddr.getA(), lAddr.getB(), fAddr.getA(), fAddr.getB(), state, txQrxQ.getA(), txQrxQ.getB(), pidMap.getOrDefault(inode, -1))); } } } return conns; } private static Pair<byte[], Integer> parseIpAddr(String s) {<FILL_FUNCTION_BODY>} private static Pair<Integer, Integer> parseHexColonHex(String s) { int colon = s.indexOf(':'); if (colon > 0 && colon < s.length()) { int first = ParseUtil.hexStringToInt(s.substring(0, colon), 0); int second = ParseUtil.hexStringToInt(s.substring(colon + 1), 0); return new Pair<>(first, second); } return new Pair<>(0, 0); } private static TcpState stateLookup(int state) { switch (state) { case 0x01: return ESTABLISHED; case 0x02: return SYN_SENT; case 0x03: return SYN_RECV; case 0x04: return FIN_WAIT_1; case 0x05: return FIN_WAIT_2; case 0x06: return TIME_WAIT; case 0x07: return CLOSED; case 0x08: return CLOSE_WAIT; case 0x09: return LAST_ACK; case 0x0A: return LISTEN; case 0x0B: return CLOSING; case 0x00: default: return UNKNOWN; } } }
int colon = s.indexOf(':'); if (colon > 0 && colon < s.length()) { byte[] first = ParseUtil.hexStringToByteArray(s.substring(0, colon)); // Bytes are in __be32 endianness. we must invert each set of 4 bytes for (int i = 0; i + 3 < first.length; i += 4) { byte tmp = first[i]; first[i] = first[i + 3]; first[i + 3] = tmp; tmp = first[i + 1]; first[i + 1] = first[i + 2]; first[i + 2] = tmp; } int second = ParseUtil.hexStringToInt(s.substring(colon + 1), 0); return new Pair<>(first, second); } return new Pair<>(new byte[0], 0);
1,028
229
1,257
<methods>public non-sealed void <init>() ,public List<oshi.software.os.InternetProtocolStats.IPConnection> getConnections() ,public oshi.software.os.InternetProtocolStats.TcpStats getTCPv6Stats() ,public oshi.software.os.InternetProtocolStats.UdpStats getUDPv6Stats() <variables>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/linux/LinuxNetworkParams.java
LinuxNetworkParams
getIpv4DefaultGateway
class LinuxNetworkParams extends AbstractNetworkParams { private static final Logger LOG = LoggerFactory.getLogger(LinuxNetworkParams.class); private static final LinuxLibc LIBC = LinuxLibc.INSTANCE; private static final String IPV4_DEFAULT_DEST = "0.0.0.0"; // NOSONAR private static final String IPV6_DEFAULT_DEST = "::/0"; @Override public String getDomainName() { try (Addrinfo hint = new Addrinfo()) { hint.ai_flags = CLibrary.AI_CANONNAME; String hostname = ""; try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { LOG.warn("Unknown host exception when getting address of local host: {}", e.getMessage()); return ""; } try (CloseablePointerByReference ptr = new CloseablePointerByReference()) { int res = LIBC.getaddrinfo(hostname, null, hint, ptr); if (res > 0) { if (LOG.isErrorEnabled()) { LOG.error("Failed getaddrinfo(): {}", LIBC.gai_strerror(res)); } return ""; } try (Addrinfo info = new Addrinfo(ptr.getValue())) { return info.ai_canonname == null ? hostname : info.ai_canonname.trim(); } } } } @Override public String getHostName() { byte[] hostnameBuffer = new byte[HOST_NAME_MAX + 1]; if (0 != LibC.INSTANCE.gethostname(hostnameBuffer, hostnameBuffer.length)) { return super.getHostName(); } return Native.toString(hostnameBuffer); } @Override public String getIpv4DefaultGateway() {<FILL_FUNCTION_BODY>} @Override public String getIpv6DefaultGateway() { List<String> routes = ExecutingCommand.runNative("route -A inet6 -n"); if (routes.size() <= 2) { return ""; } String gateway = ""; int minMetric = Integer.MAX_VALUE; for (int i = 2; i < routes.size(); i++) { String[] fields = ParseUtil.whitespaces.split(routes.get(i)); if (fields.length > 3 && fields[0].equals(IPV6_DEFAULT_DEST)) { boolean isGateway = fields[2].indexOf('G') != -1; int metric = ParseUtil.parseIntOrDefault(fields[3], Integer.MAX_VALUE); if (isGateway && metric < minMetric) { minMetric = metric; gateway = fields[1]; } } } return gateway; } }
List<String> routes = ExecutingCommand.runNative("route -A inet -n"); if (routes.size() <= 2) { return ""; } String gateway = ""; int minMetric = Integer.MAX_VALUE; for (int i = 2; i < routes.size(); i++) { String[] fields = ParseUtil.whitespaces.split(routes.get(i)); if (fields.length > 4 && fields[0].equals(IPV4_DEFAULT_DEST)) { boolean isGateway = fields[3].indexOf('G') != -1; int metric = ParseUtil.parseIntOrDefault(fields[4], Integer.MAX_VALUE); if (isGateway && metric < minMetric) { minMetric = metric; gateway = fields[1]; } } } return gateway;
737
225
962
<methods>public non-sealed void <init>() ,public java.lang.String[] getDnsServers() ,public java.lang.String getDomainName() ,public java.lang.String getHostName() ,public java.lang.String toString() <variables>private static final java.lang.String NAMESERVER
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/linux/LinuxOSFileStore.java
LinuxOSFileStore
updateAttributes
class LinuxOSFileStore extends AbstractOSFileStore { private String logicalVolume; private String description; private String fsType; private long freeSpace; private long usableSpace; private long totalSpace; private long freeInodes; private long totalInodes; public LinuxOSFileStore(String name, String volume, String label, String mount, String options, String uuid, String logicalVolume, String description, String fsType, long freeSpace, long usableSpace, long totalSpace, long freeInodes, long totalInodes) { super(name, volume, label, mount, options, uuid); this.logicalVolume = logicalVolume; this.description = description; this.fsType = fsType; this.freeSpace = freeSpace; this.usableSpace = usableSpace; this.totalSpace = totalSpace; this.freeInodes = freeInodes; this.totalInodes = totalInodes; } @Override public String getLogicalVolume() { return this.logicalVolume; } @Override public String getDescription() { return this.description; } @Override public String getType() { return this.fsType; } @Override public long getFreeSpace() { return this.freeSpace; } @Override public long getUsableSpace() { return this.usableSpace; } @Override public long getTotalSpace() { return this.totalSpace; } @Override public long getFreeInodes() { return this.freeInodes; } @Override public long getTotalInodes() { return this.totalInodes; } @Override public boolean updateAttributes() {<FILL_FUNCTION_BODY>} }
for (OSFileStore fileStore : LinuxFileSystem.getFileStoreMatching(getName(), null)) { if (getVolume().equals(fileStore.getVolume()) && getMount().equals(fileStore.getMount())) { this.logicalVolume = fileStore.getLogicalVolume(); this.description = fileStore.getDescription(); this.fsType = fileStore.getType(); this.freeSpace = fileStore.getFreeSpace(); this.usableSpace = fileStore.getUsableSpace(); this.totalSpace = fileStore.getTotalSpace(); this.freeInodes = fileStore.getFreeInodes(); this.totalInodes = fileStore.getTotalInodes(); return true; } } return false;
476
189
665
<methods>public java.lang.String getLabel() ,public java.lang.String getMount() ,public java.lang.String getName() ,public java.lang.String getOptions() ,public java.lang.String getUUID() ,public java.lang.String getVolume() ,public java.lang.String toString() <variables>private java.lang.String label,private java.lang.String mount,private java.lang.String name,private java.lang.String options,private java.lang.String uuid,private java.lang.String volume
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/linux/LinuxOSThread.java
LinuxOSThread
updateAttributes
class LinuxOSThread extends AbstractOSThread { private static final int[] PROC_TASK_STAT_ORDERS = new int[LinuxOSThread.ThreadPidStat.values().length]; static { for (LinuxOSThread.ThreadPidStat stat : LinuxOSThread.ThreadPidStat.values()) { // The PROC_PID_STAT enum indices are 1-indexed. // Subtract one to get a zero-based index PROC_TASK_STAT_ORDERS[stat.ordinal()] = stat.getOrder() - 1; } } private final int threadId; private String name; private State state = State.INVALID; private long minorFaults; private long majorFaults; private long startMemoryAddress; private long contextSwitches; private long kernelTime; private long userTime; private long startTime; private long upTime; private int priority; public LinuxOSThread(int processId, int tid) { super(processId); this.threadId = tid; updateAttributes(); } @Override public int getThreadId() { return this.threadId; } @Override public String getName() { return this.name; } @Override public State getState() { return this.state; } @Override public long getStartTime() { return this.startTime; } @Override public long getStartMemoryAddress() { return this.startMemoryAddress; } @Override public long getContextSwitches() { return this.contextSwitches; } @Override public long getMinorFaults() { return this.minorFaults; } @Override public long getMajorFaults() { return this.majorFaults; } @Override public long getKernelTime() { return this.kernelTime; } @Override public long getUserTime() { return this.userTime; } @Override public long getUpTime() { return this.upTime; } @Override public int getPriority() { return this.priority; } @Override public boolean updateAttributes() {<FILL_FUNCTION_BODY>} /** * Enum used to update attributes. The order field represents the 1-indexed numeric order of the stat in * /proc/pid/task/tid/stat per the man file. */ private enum ThreadPidStat { // The parsing implementation in ParseUtil requires these to be declared // in increasing order PPID(4), MINOR_FAULTS(10), MAJOR_FAULT(12), USER_TIME(14), KERNEL_TIME(15), PRIORITY(18), THREAD_COUNT(20), START_TIME(22), VSZ(23), RSS(24), START_CODE(26); private final int order; ThreadPidStat(int order) { this.order = order; } public int getOrder() { return this.order; } } }
this.name = FileUtil.getStringFromFile( String.format(Locale.ROOT, ProcPath.TASK_COMM, this.getOwningProcessId(), this.threadId)); Map<String, String> status = FileUtil.getKeyValueMapFromFile( String.format(Locale.ROOT, ProcPath.TASK_STATUS, this.getOwningProcessId(), this.threadId), ":"); String stat = FileUtil.getStringFromFile( String.format(Locale.ROOT, ProcPath.TASK_STAT, this.getOwningProcessId(), this.threadId)); if (stat.isEmpty()) { this.state = State.INVALID; return false; } long now = System.currentTimeMillis(); long[] statArray = ParseUtil.parseStringToLongArray(stat, PROC_TASK_STAT_ORDERS, ProcessStat.PROC_PID_STAT_LENGTH, ' '); // BOOTTIME is in seconds and start time from proc/pid/stat is in jiffies. // Combine units to jiffies and convert to millijiffies before hz division to // avoid precision loss without having to cast this.startTime = (LinuxOperatingSystem.BOOTTIME * LinuxOperatingSystem.getHz() + statArray[LinuxOSThread.ThreadPidStat.START_TIME.ordinal()]) * 1000L / LinuxOperatingSystem.getHz(); // BOOT_TIME could be up to 500ms off and start time up to 5ms off. A process // that has started within last 505ms could produce a future start time/negative // up time, so insert a sanity check. if (this.startTime >= now) { this.startTime = now - 1; } this.minorFaults = statArray[ThreadPidStat.MINOR_FAULTS.ordinal()]; this.majorFaults = statArray[ThreadPidStat.MAJOR_FAULT.ordinal()]; this.startMemoryAddress = statArray[ThreadPidStat.START_CODE.ordinal()]; long voluntaryContextSwitches = ParseUtil.parseLongOrDefault(status.get("voluntary_ctxt_switches"), 0L); long nonVoluntaryContextSwitches = ParseUtil.parseLongOrDefault(status.get("nonvoluntary_ctxt_switches"), 0L); this.contextSwitches = voluntaryContextSwitches + nonVoluntaryContextSwitches; this.state = ProcessStat.getState(status.getOrDefault("State", "U").charAt(0)); this.kernelTime = statArray[ThreadPidStat.KERNEL_TIME.ordinal()] * 1000L / LinuxOperatingSystem.getHz(); this.userTime = statArray[ThreadPidStat.USER_TIME.ordinal()] * 1000L / LinuxOperatingSystem.getHz(); this.upTime = now - startTime; this.priority = (int) statArray[ThreadPidStat.PRIORITY.ordinal()]; return true;
843
786
1,629
<methods>public int getOwningProcessId() ,public double getThreadCpuLoadBetweenTicks(oshi.software.os.OSThread) ,public double getThreadCpuLoadCumulative() ,public java.lang.String toString() <variables>private final Supplier<java.lang.Double> cumulativeCpuLoad,private final non-sealed int owningProcessId
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/mac/MacNetworkParams.java
MacNetworkParams
getDomainName
class MacNetworkParams extends AbstractNetworkParams { private static final Logger LOG = LoggerFactory.getLogger(MacNetworkParams.class); private static final SystemB SYS = SystemB.INSTANCE; private static final String IPV6_ROUTE_HEADER = "Internet6:"; private static final String DEFAULT_GATEWAY = "default"; @Override public String getDomainName() {<FILL_FUNCTION_BODY>} @Override public String getHostName() { byte[] hostnameBuffer = new byte[HOST_NAME_MAX + 1]; if (0 != SYS.gethostname(hostnameBuffer, hostnameBuffer.length)) { return super.getHostName(); } return Native.toString(hostnameBuffer); } @Override public String getIpv4DefaultGateway() { return searchGateway(ExecutingCommand.runNative("route -n get default")); } @Override public String getIpv6DefaultGateway() { List<String> lines = ExecutingCommand.runNative("netstat -nr"); boolean v6Table = false; for (String line : lines) { if (v6Table && line.startsWith(DEFAULT_GATEWAY)) { String[] fields = ParseUtil.whitespaces.split(line); if (fields.length > 2 && fields[2].contains("G")) { return fields[1].split("%")[0]; } } else if (line.startsWith(IPV6_ROUTE_HEADER)) { v6Table = true; } } return ""; } }
String hostname = ""; try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { LOG.error("Unknown host exception when getting address of local host: {}", e.getMessage()); return ""; } try (Addrinfo hint = new Addrinfo(); CloseablePointerByReference ptr = new CloseablePointerByReference()) { hint.ai_flags = CLibrary.AI_CANONNAME; int res = SYS.getaddrinfo(hostname, null, hint, ptr); if (res > 0) { if (LOG.isErrorEnabled()) { LOG.error("Failed getaddrinfo(): {}", SYS.gai_strerror(res)); } return ""; } Addrinfo info = new Addrinfo(ptr.getValue()); // NOSONAR String canonname = info.ai_canonname.trim(); SYS.freeaddrinfo(ptr.getValue()); return canonname; }
426
256
682
<methods>public non-sealed void <init>() ,public java.lang.String[] getDnsServers() ,public java.lang.String getDomainName() ,public java.lang.String getHostName() ,public java.lang.String toString() <variables>private static final java.lang.String NAMESERVER
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/mac/MacOSFileStore.java
MacOSFileStore
updateAttributes
class MacOSFileStore extends AbstractOSFileStore { private String logicalVolume; private String description; private String fsType; private long freeSpace; private long usableSpace; private long totalSpace; private long freeInodes; private long totalInodes; public MacOSFileStore(String name, String volume, String label, String mount, String options, String uuid, String logicalVolume, String description, String fsType, long freeSpace, long usableSpace, long totalSpace, long freeInodes, long totalInodes) { super(name, volume, label, mount, options, uuid); this.logicalVolume = logicalVolume; this.description = description; this.fsType = fsType; this.freeSpace = freeSpace; this.usableSpace = usableSpace; this.totalSpace = totalSpace; this.freeInodes = freeInodes; this.totalInodes = totalInodes; } @Override public String getLogicalVolume() { return this.logicalVolume; } @Override public String getDescription() { return this.description; } @Override public String getType() { return this.fsType; } @Override public long getFreeSpace() { return this.freeSpace; } @Override public long getUsableSpace() { return this.usableSpace; } @Override public long getTotalSpace() { return this.totalSpace; } @Override public long getFreeInodes() { return this.freeInodes; } @Override public long getTotalInodes() { return this.totalInodes; } @Override public boolean updateAttributes() {<FILL_FUNCTION_BODY>} }
for (OSFileStore fileStore : MacFileSystem.getFileStoreMatching(getName())) { if (getVolume().equals(fileStore.getVolume()) && getMount().equals(fileStore.getMount())) { this.logicalVolume = fileStore.getLogicalVolume(); this.description = fileStore.getDescription(); this.fsType = fileStore.getType(); this.freeSpace = fileStore.getFreeSpace(); this.usableSpace = fileStore.getUsableSpace(); this.totalSpace = fileStore.getTotalSpace(); this.freeInodes = fileStore.getFreeInodes(); this.totalInodes = fileStore.getTotalInodes(); return true; } } return false;
476
187
663
<methods>public java.lang.String getLabel() ,public java.lang.String getMount() ,public java.lang.String getName() ,public java.lang.String getOptions() ,public java.lang.String getUUID() ,public java.lang.String getVolume() ,public java.lang.String toString() <variables>private java.lang.String label,private java.lang.String mount,private java.lang.String name,private java.lang.String options,private java.lang.String uuid,private java.lang.String volume
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/unix/aix/AixInternetProtocolStats.java
AixInternetProtocolStats
getTCPv4Stats
class AixInternetProtocolStats extends AbstractInternetProtocolStats { private Supplier<perfstat_protocol_t[]> ipstats = memoize(PerfstatProtocol::queryProtocols, defaultExpiration()); @Override public TcpStats getTCPv4Stats() {<FILL_FUNCTION_BODY>} @Override public UdpStats getUDPv4Stats() { for (perfstat_protocol_t stat : ipstats.get()) { if ("udp".equals(Native.toString(stat.name))) { return new UdpStats(stat.u.udp.opackets, stat.u.udp.ipackets, stat.u.udp.no_socket, stat.u.udp.ierrors); } } return new UdpStats(0L, 0L, 0L, 0L); } }
for (perfstat_protocol_t stat : ipstats.get()) { if ("tcp".equals(Native.toString(stat.name))) { return new TcpStats(stat.u.tcp.established, stat.u.tcp.initiated, stat.u.tcp.accepted, stat.u.tcp.dropped, stat.u.tcp.dropped, stat.u.tcp.opackets, stat.u.tcp.ipackets, 0L, stat.u.tcp.ierrors, 0L); } } return new TcpStats(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L);
221
184
405
<methods>public non-sealed void <init>() ,public List<oshi.software.os.InternetProtocolStats.IPConnection> getConnections() ,public oshi.software.os.InternetProtocolStats.TcpStats getTCPv6Stats() ,public oshi.software.os.InternetProtocolStats.UdpStats getUDPv6Stats() <variables>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/unix/aix/AixNetworkParams.java
AixNetworkParams
getDefaultGateway
class AixNetworkParams extends AbstractNetworkParams { private static final AixLibc LIBC = AixLibc.INSTANCE; @Override public String getHostName() { byte[] hostnameBuffer = new byte[HOST_NAME_MAX + 1]; if (0 != LIBC.gethostname(hostnameBuffer, hostnameBuffer.length)) { return super.getHostName(); } return Native.toString(hostnameBuffer); } @Override public String getIpv4DefaultGateway() { return getDefaultGateway("netstat -rnf inet"); } @Override public String getIpv6DefaultGateway() { return getDefaultGateway("netstat -rnf inet6"); } private static String getDefaultGateway(String netstat) {<FILL_FUNCTION_BODY>} }
/*- $ netstat -rnf inet Routing tables Destination Gateway Flags Refs Use If Exp Groups * Route Tree for Protocol Family 2 (Internet): default 192.168.10.1 UG 9 873816 en0 - - 127/8 127.0.0.1 U 9 839480 lo0 - - 192.168.10.0 192.168.10.80 UHSb 0 0 en0 - - => 192.168.10/24 192.168.10.80 U 3 394820 en0 - - 192.168.10.80 127.0.0.1 UGHS 0 7 lo0 - - 192.168.10.255 192.168.10.80 UHSb 2 7466 en0 - - */ for (String line : ExecutingCommand.runNative(netstat)) { String[] split = ParseUtil.whitespaces.split(line); if (split.length > 7 && "default".equals(split[0])) { return split[1]; } } return Constants.UNKNOWN;
224
386
610
<methods>public non-sealed void <init>() ,public java.lang.String[] getDnsServers() ,public java.lang.String getDomainName() ,public java.lang.String getHostName() ,public java.lang.String toString() <variables>private static final java.lang.String NAMESERVER
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/unix/aix/AixOSFileStore.java
AixOSFileStore
updateAttributes
class AixOSFileStore extends AbstractOSFileStore { private String logicalVolume; private String description; private String fsType; private long freeSpace; private long usableSpace; private long totalSpace; private long freeInodes; private long totalInodes; public AixOSFileStore(String name, String volume, String label, String mount, String options, String uuid, String logicalVolume, String description, String fsType, long freeSpace, long usableSpace, long totalSpace, long freeInodes, long totalInodes) { super(name, volume, label, mount, options, uuid); this.logicalVolume = logicalVolume; this.description = description; this.fsType = fsType; this.freeSpace = freeSpace; this.usableSpace = usableSpace; this.totalSpace = totalSpace; this.freeInodes = freeInodes; this.totalInodes = totalInodes; } @Override public String getLogicalVolume() { return this.logicalVolume; } @Override public String getDescription() { return this.description; } @Override public String getType() { return this.fsType; } @Override public long getFreeSpace() { return this.freeSpace; } @Override public long getUsableSpace() { return this.usableSpace; } @Override public long getTotalSpace() { return this.totalSpace; } @Override public long getFreeInodes() { return this.freeInodes; } @Override public long getTotalInodes() { return this.totalInodes; } @Override public boolean updateAttributes() {<FILL_FUNCTION_BODY>} }
for (OSFileStore fileStore : AixFileSystem.getFileStoreMatching(getName())) { if (getVolume().equals(fileStore.getVolume()) && getMount().equals(fileStore.getMount())) { this.logicalVolume = fileStore.getLogicalVolume(); this.description = fileStore.getDescription(); this.fsType = fileStore.getType(); this.freeSpace = fileStore.getFreeSpace(); this.usableSpace = fileStore.getUsableSpace(); this.totalSpace = fileStore.getTotalSpace(); this.freeInodes = fileStore.getFreeInodes(); this.totalInodes = fileStore.getTotalInodes(); return true; } } return false;
476
187
663
<methods>public java.lang.String getLabel() ,public java.lang.String getMount() ,public java.lang.String getName() ,public java.lang.String getOptions() ,public java.lang.String getUUID() ,public java.lang.String getVolume() ,public java.lang.String toString() <variables>private java.lang.String label,private java.lang.String mount,private java.lang.String name,private java.lang.String options,private java.lang.String uuid,private java.lang.String volume
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/unix/aix/AixOSThread.java
AixOSThread
updateAttributes
class AixOSThread extends AbstractOSThread { private int threadId; private OSProcess.State state = OSProcess.State.INVALID; private long startMemoryAddress; private long contextSwitches; private long kernelTime; private long userTime; private long startTime; private long upTime; private int priority; public AixOSThread(int pid, int tid) { super(pid); this.threadId = tid; updateAttributes(); } @Override public int getThreadId() { return this.threadId; } @Override public OSProcess.State getState() { return this.state; } @Override public long getStartMemoryAddress() { return this.startMemoryAddress; } @Override public long getContextSwitches() { return this.contextSwitches; } @Override public long getKernelTime() { return this.kernelTime; } @Override public long getUserTime() { return this.userTime; } @Override public long getUpTime() { return this.upTime; } @Override public long getStartTime() { return this.startTime; } @Override public int getPriority() { return this.priority; } @Override public boolean updateAttributes() {<FILL_FUNCTION_BODY>} }
AixLwpsInfo lwpsinfo = PsInfo.queryLwpsInfo(getOwningProcessId(), getThreadId()); if (lwpsinfo == null) { this.state = OSProcess.State.INVALID; return false; } this.threadId = (int) lwpsinfo.pr_lwpid; // 64 bit storage but always 32 bit this.startMemoryAddress = lwpsinfo.pr_addr; this.state = AixOSProcess.getStateFromOutput((char) lwpsinfo.pr_sname); this.priority = lwpsinfo.pr_pri; return true;
381
168
549
<methods>public int getOwningProcessId() ,public double getThreadCpuLoadBetweenTicks(oshi.software.os.OSThread) ,public double getThreadCpuLoadCumulative() ,public java.lang.String toString() <variables>private final Supplier<java.lang.Double> cumulativeCpuLoad,private final non-sealed int owningProcessId
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdFileSystem.java
FreeBsdFileSystem
getFileStores
class FreeBsdFileSystem extends AbstractFileSystem { public static final String OSHI_FREEBSD_FS_PATH_EXCLUDES = "oshi.os.freebsd.filesystem.path.excludes"; public static final String OSHI_FREEBSD_FS_PATH_INCLUDES = "oshi.os.freebsd.filesystem.path.includes"; public static final String OSHI_FREEBSD_FS_VOLUME_EXCLUDES = "oshi.os.freebsd.filesystem.volume.excludes"; public static final String OSHI_FREEBSD_FS_VOLUME_INCLUDES = "oshi.os.freebsd.filesystem.volume.includes"; private static final List<PathMatcher> FS_PATH_EXCLUDES = FileSystemUtil .loadAndParseFileSystemConfig(OSHI_FREEBSD_FS_PATH_EXCLUDES); private static final List<PathMatcher> FS_PATH_INCLUDES = FileSystemUtil .loadAndParseFileSystemConfig(OSHI_FREEBSD_FS_PATH_INCLUDES); private static final List<PathMatcher> FS_VOLUME_EXCLUDES = FileSystemUtil .loadAndParseFileSystemConfig(OSHI_FREEBSD_FS_VOLUME_EXCLUDES); private static final List<PathMatcher> FS_VOLUME_INCLUDES = FileSystemUtil .loadAndParseFileSystemConfig(OSHI_FREEBSD_FS_VOLUME_INCLUDES); @Override public List<OSFileStore> getFileStores(boolean localOnly) {<FILL_FUNCTION_BODY>} @Override public long getOpenFileDescriptors() { return BsdSysctlUtil.sysctl("kern.openfiles", 0); } @Override public long getMaxFileDescriptors() { return BsdSysctlUtil.sysctl("kern.maxfiles", 0); } @Override public long getMaxFileDescriptorsPerProcess() { // On FreeBsd there is no process specific system-wide limit, so the general limit is returned return getMaxFileDescriptors(); } }
// TODO map mount point to UUID? // is /etc/fstab useful for this? Map<String, String> uuidMap = new HashMap<>(); // Now grab dmssg output String device = ""; for (String line : ExecutingCommand.runNative("geom part list")) { if (line.contains("Name: ")) { device = line.substring(line.lastIndexOf(' ') + 1); } // If we aren't working with a current partition, continue if (device.isEmpty()) { continue; } line = line.trim(); if (line.startsWith("rawuuid:")) { uuidMap.put(device, line.substring(line.lastIndexOf(' ') + 1)); device = ""; } } List<OSFileStore> fsList = new ArrayList<>(); // Get inode usage data Map<String, Long> inodeFreeMap = new HashMap<>(); Map<String, Long> inodeTotalMap = new HashMap<>(); for (String line : ExecutingCommand.runNative("df -i")) { /*- Sample Output: Filesystem 1K-blocks Used Avail Capacity iused ifree %iused Mounted on /dev/twed0s1a 2026030 584112 1279836 31% 2751 279871 1% / */ if (line.startsWith("/")) { String[] split = ParseUtil.whitespaces.split(line); if (split.length > 7) { inodeFreeMap.put(split[0], ParseUtil.parseLongOrDefault(split[6], 0L)); // total is used + free inodeTotalMap.put(split[0], inodeFreeMap.get(split[0]) + ParseUtil.parseLongOrDefault(split[5], 0L)); } } } // Get mount table for (String fs : ExecutingCommand.runNative("mount -p")) { String[] split = ParseUtil.whitespaces.split(fs); if (split.length < 5) { continue; } // 1st field is volume name // 2nd field is mount point // 3rd field is fs type // 4th field is options // other fields ignored String volume = split[0]; String path = split[1]; String type = split[2]; String options = split[3]; // Skip non-local drives if requested, and exclude pseudo file systems if ((localOnly && NETWORK_FS_TYPES.contains(type)) || !path.equals("/") && (PSEUDO_FS_TYPES.contains(type) || FileSystemUtil.isFileStoreExcluded(path, volume, FS_PATH_INCLUDES, FS_PATH_EXCLUDES, FS_VOLUME_INCLUDES, FS_VOLUME_EXCLUDES))) { continue; } String name = path.substring(path.lastIndexOf('/') + 1); // Special case for /, pull last element of volume instead if (name.isEmpty()) { name = volume.substring(volume.lastIndexOf('/') + 1); } File f = new File(path); long totalSpace = f.getTotalSpace(); long usableSpace = f.getUsableSpace(); long freeSpace = f.getFreeSpace(); String description; if (volume.startsWith("/dev") || path.equals("/")) { description = "Local Disk"; } else if (volume.equals("tmpfs")) { description = "Ram Disk"; } else if (NETWORK_FS_TYPES.contains(type)) { description = "Network Disk"; } else { description = "Mount Point"; } // Match UUID String uuid = uuidMap.getOrDefault(name, ""); fsList.add(new LinuxOSFileStore(name, volume, name, path, options, uuid, "", description, type, freeSpace, usableSpace, totalSpace, inodeFreeMap.containsKey(path) ? inodeFreeMap.get(path) : 0L, inodeTotalMap.containsKey(path) ? inodeTotalMap.get(path) : 0L)); } return fsList;
588
1,137
1,725
<methods>public non-sealed void <init>() ,public List<oshi.software.os.OSFileStore> getFileStores() <variables>protected static final List<java.lang.String> NETWORK_FS_TYPES,protected static final List<java.lang.String> PSEUDO_FS_TYPES
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdInternetProtocolStats.java
FreeBsdInternetProtocolStats
queryTcpstat
class FreeBsdInternetProtocolStats extends AbstractInternetProtocolStats { private Supplier<Pair<Long, Long>> establishedv4v6 = memoize(NetStat::queryTcpnetstat, defaultExpiration()); private Supplier<BsdTcpstat> tcpstat = memoize(FreeBsdInternetProtocolStats::queryTcpstat, defaultExpiration()); private Supplier<BsdUdpstat> udpstat = memoize(FreeBsdInternetProtocolStats::queryUdpstat, defaultExpiration()); @Override public TcpStats getTCPv4Stats() { BsdTcpstat tcp = tcpstat.get(); return new TcpStats(establishedv4v6.get().getA(), ParseUtil.unsignedIntToLong(tcp.tcps_connattempt), ParseUtil.unsignedIntToLong(tcp.tcps_accepts), ParseUtil.unsignedIntToLong(tcp.tcps_conndrops), ParseUtil.unsignedIntToLong(tcp.tcps_drops), ParseUtil.unsignedIntToLong(tcp.tcps_sndpack), ParseUtil.unsignedIntToLong(tcp.tcps_rcvpack), ParseUtil.unsignedIntToLong(tcp.tcps_sndrexmitpack), ParseUtil.unsignedIntToLong( tcp.tcps_rcvbadsum + tcp.tcps_rcvbadoff + tcp.tcps_rcvmemdrop + tcp.tcps_rcvshort), 0L); } @Override public UdpStats getUDPv4Stats() { BsdUdpstat stat = udpstat.get(); return new UdpStats(ParseUtil.unsignedIntToLong(stat.udps_opackets), ParseUtil.unsignedIntToLong(stat.udps_ipackets), ParseUtil.unsignedIntToLong(stat.udps_noportmcast), ParseUtil.unsignedIntToLong(stat.udps_hdrops + stat.udps_badsum + stat.udps_badlen)); } @Override public UdpStats getUDPv6Stats() { BsdUdpstat stat = udpstat.get(); return new UdpStats(ParseUtil.unsignedIntToLong(stat.udps_snd6_swcsum), ParseUtil.unsignedIntToLong(stat.udps_rcv6_swcsum), 0L, 0L); } private static BsdTcpstat queryTcpstat() {<FILL_FUNCTION_BODY>} private static BsdUdpstat queryUdpstat() { BsdUdpstat ut = new BsdUdpstat(); try (Memory m = BsdSysctlUtil.sysctl("net.inet.udp.stats")) { if (m != null && m.size() >= 1644) { ut.udps_ipackets = m.getInt(0); ut.udps_hdrops = m.getInt(4); ut.udps_badsum = m.getInt(8); ut.udps_badlen = m.getInt(12); ut.udps_opackets = m.getInt(36); ut.udps_noportmcast = m.getInt(48); ut.udps_rcv6_swcsum = m.getInt(64); ut.udps_snd6_swcsum = m.getInt(80); } } return ut; } }
BsdTcpstat ft = new BsdTcpstat(); try (Memory m = BsdSysctlUtil.sysctl("net.inet.tcp.stats")) { if (m != null && m.size() >= 128) { ft.tcps_connattempt = m.getInt(0); ft.tcps_accepts = m.getInt(4); ft.tcps_drops = m.getInt(12); ft.tcps_conndrops = m.getInt(16); ft.tcps_sndpack = m.getInt(64); ft.tcps_sndrexmitpack = m.getInt(72); ft.tcps_rcvpack = m.getInt(104); ft.tcps_rcvbadsum = m.getInt(112); ft.tcps_rcvbadoff = m.getInt(116); ft.tcps_rcvmemdrop = m.getInt(120); ft.tcps_rcvshort = m.getInt(124); } } return ft;
886
290
1,176
<methods>public non-sealed void <init>() ,public List<oshi.software.os.InternetProtocolStats.IPConnection> getConnections() ,public oshi.software.os.InternetProtocolStats.TcpStats getTCPv6Stats() ,public oshi.software.os.InternetProtocolStats.UdpStats getUDPv6Stats() <variables>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdNetworkParams.java
FreeBsdNetworkParams
getDomainName
class FreeBsdNetworkParams extends AbstractNetworkParams { private static final Logger LOG = LoggerFactory.getLogger(FreeBsdNetworkParams.class); private static final FreeBsdLibc LIBC = FreeBsdLibc.INSTANCE; @Override public String getDomainName() {<FILL_FUNCTION_BODY>} @Override public String getHostName() { byte[] hostnameBuffer = new byte[HOST_NAME_MAX + 1]; if (0 != LIBC.gethostname(hostnameBuffer, hostnameBuffer.length)) { return super.getHostName(); } return Native.toString(hostnameBuffer); } @Override public String getIpv4DefaultGateway() { return searchGateway(ExecutingCommand.runNative("route -4 get default")); } @Override public String getIpv6DefaultGateway() { return searchGateway(ExecutingCommand.runNative("route -6 get default")); } }
try (Addrinfo hint = new Addrinfo()) { hint.ai_flags = CLibrary.AI_CANONNAME; String hostname = getHostName(); try (CloseablePointerByReference ptr = new CloseablePointerByReference()) { int res = LIBC.getaddrinfo(hostname, null, hint, ptr); if (res > 0) { if (LOG.isErrorEnabled()) { LOG.warn("Failed getaddrinfo(): {}", LIBC.gai_strerror(res)); } return ""; } Addrinfo info = new Addrinfo(ptr.getValue()); // NOSONAR String canonname = info.ai_canonname.trim(); LIBC.freeaddrinfo(ptr.getValue()); return canonname; } }
261
207
468
<methods>public non-sealed void <init>() ,public java.lang.String[] getDnsServers() ,public java.lang.String getDomainName() ,public java.lang.String getHostName() ,public java.lang.String toString() <variables>private static final java.lang.String NAMESERVER
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSFileStore.java
FreeBsdOSFileStore
updateAttributes
class FreeBsdOSFileStore extends AbstractOSFileStore { private String logicalVolume; private String description; private String fsType; private long freeSpace; private long usableSpace; private long totalSpace; private long freeInodes; private long totalInodes; public FreeBsdOSFileStore(String name, String volume, String label, String mount, String options, String uuid, String logicalVolume, String description, String fsType, long freeSpace, long usableSpace, long totalSpace, long freeInodes, long totalInodes) { super(name, volume, label, mount, options, uuid); this.logicalVolume = logicalVolume; this.description = description; this.fsType = fsType; this.freeSpace = freeSpace; this.usableSpace = usableSpace; this.totalSpace = totalSpace; this.freeInodes = freeInodes; this.totalInodes = totalInodes; } @Override public String getLogicalVolume() { return this.logicalVolume; } @Override public String getDescription() { return this.description; } @Override public String getType() { return this.fsType; } @Override public long getFreeSpace() { return this.freeSpace; } @Override public long getUsableSpace() { return this.usableSpace; } @Override public long getTotalSpace() { return this.totalSpace; } @Override public long getFreeInodes() { return this.freeInodes; } @Override public long getTotalInodes() { return this.totalInodes; } @Override public boolean updateAttributes() {<FILL_FUNCTION_BODY>} }
for (OSFileStore fileStore : new FreeBsdFileSystem().getFileStores()) { if (getName().equals(fileStore.getName()) && getVolume().equals(fileStore.getVolume()) && getMount().equals(fileStore.getMount())) { this.logicalVolume = fileStore.getLogicalVolume(); this.description = fileStore.getDescription(); this.fsType = fileStore.getType(); this.freeSpace = fileStore.getFreeSpace(); this.usableSpace = fileStore.getUsableSpace(); this.totalSpace = fileStore.getTotalSpace(); this.freeInodes = fileStore.getFreeInodes(); this.totalInodes = fileStore.getTotalInodes(); return true; } } return false;
480
200
680
<methods>public java.lang.String getLabel() ,public java.lang.String getMount() ,public java.lang.String getName() ,public java.lang.String getOptions() ,public java.lang.String getUUID() ,public java.lang.String getVolume() ,public java.lang.String toString() <variables>private java.lang.String label,private java.lang.String mount,private java.lang.String name,private java.lang.String options,private java.lang.String uuid,private java.lang.String volume
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSThread.java
FreeBsdOSThread
updateAttributes
class FreeBsdOSThread extends AbstractOSThread { private int threadId; private String name = ""; private OSProcess.State state = INVALID; private long minorFaults; private long majorFaults; private long startMemoryAddress; private long contextSwitches; private long kernelTime; private long userTime; private long startTime; private long upTime; private int priority; public FreeBsdOSThread(int processId, Map<PsThreadColumns, String> threadMap) { super(processId); updateAttributes(threadMap); } public FreeBsdOSThread(int processId, int threadId) { super(processId); this.threadId = threadId; updateAttributes(); } @Override public int getThreadId() { return this.threadId; } @Override public String getName() { return this.name; } @Override public OSProcess.State getState() { return this.state; } @Override public long getStartMemoryAddress() { return this.startMemoryAddress; } @Override public long getContextSwitches() { return this.contextSwitches; } @Override public long getMinorFaults() { return this.minorFaults; } @Override public long getMajorFaults() { return this.majorFaults; } @Override public long getKernelTime() { return this.kernelTime; } @Override public long getUserTime() { return this.userTime; } @Override public long getUpTime() { return this.upTime; } @Override public long getStartTime() { return this.startTime; } @Override public int getPriority() { return this.priority; } @Override public boolean updateAttributes() { List<String> threadList = ExecutingCommand .runNative("ps -awwxo " + FreeBsdOSProcess.PS_THREAD_COLUMNS + " -H -p " + getOwningProcessId()); // there is no switch for thread in ps command, hence filtering. String lwpStr = Integer.toString(this.threadId); for (String psOutput : threadList) { Map<PsThreadColumns, String> threadMap = ParseUtil.stringToEnumMap(PsThreadColumns.class, psOutput.trim(), ' '); if (threadMap.containsKey(PsThreadColumns.PRI) && lwpStr.equals(threadMap.get(PsThreadColumns.LWP))) { return updateAttributes(threadMap); } } this.state = INVALID; return false; } private boolean updateAttributes(Map<PsThreadColumns, String> threadMap) {<FILL_FUNCTION_BODY>} }
this.name = threadMap.get(PsThreadColumns.TDNAME); this.threadId = ParseUtil.parseIntOrDefault(threadMap.get(PsThreadColumns.LWP), 0); switch (threadMap.get(PsThreadColumns.STATE).charAt(0)) { case 'R': this.state = RUNNING; break; case 'I': case 'S': this.state = SLEEPING; break; case 'D': case 'L': case 'U': this.state = WAITING; break; case 'Z': this.state = ZOMBIE; break; case 'T': this.state = STOPPED; break; default: this.state = OTHER; break; } long elapsedTime = ParseUtil.parseDHMSOrDefault(threadMap.get(PsThreadColumns.ETIMES), 0L); // Avoid divide by zero for processes up less than a second this.upTime = elapsedTime < 1L ? 1L : elapsedTime; long now = System.currentTimeMillis(); this.startTime = now - this.upTime; this.kernelTime = ParseUtil.parseDHMSOrDefault(threadMap.get(PsThreadColumns.SYSTIME), 0L); this.userTime = ParseUtil.parseDHMSOrDefault(threadMap.get(PsThreadColumns.TIME), 0L) - this.kernelTime; this.startMemoryAddress = ParseUtil.hexStringToLong(threadMap.get(PsThreadColumns.TDADDR), 0L); long nonVoluntaryContextSwitches = ParseUtil.parseLongOrDefault(threadMap.get(PsThreadColumns.NIVCSW), 0L); long voluntaryContextSwitches = ParseUtil.parseLongOrDefault(threadMap.get(PsThreadColumns.NVCSW), 0L); this.contextSwitches = voluntaryContextSwitches + nonVoluntaryContextSwitches; this.majorFaults = ParseUtil.parseLongOrDefault(threadMap.get(PsThreadColumns.MAJFLT), 0L); this.minorFaults = ParseUtil.parseLongOrDefault(threadMap.get(PsThreadColumns.MINFLT), 0L); this.priority = ParseUtil.parseIntOrDefault(threadMap.get(PsThreadColumns.PRI), 0); return true;
762
625
1,387
<methods>public int getOwningProcessId() ,public double getThreadCpuLoadBetweenTicks(oshi.software.os.OSThread) ,public double getThreadCpuLoadCumulative() ,public java.lang.String toString() <variables>private final Supplier<java.lang.Double> cumulativeCpuLoad,private final non-sealed int owningProcessId
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdFileSystem.java
OpenBsdFileSystem
getFileStoreMatching
class OpenBsdFileSystem extends AbstractFileSystem { public static final String OSHI_OPENBSD_FS_PATH_EXCLUDES = "oshi.os.openbsd.filesystem.path.excludes"; public static final String OSHI_OPENBSD_FS_PATH_INCLUDES = "oshi.os.openbsd.filesystem.path.includes"; public static final String OSHI_OPENBSD_FS_VOLUME_EXCLUDES = "oshi.os.openbsd.filesystem.volume.excludes"; public static final String OSHI_OPENBSD_FS_VOLUME_INCLUDES = "oshi.os.openbsd.filesystem.volume.includes"; private static final List<PathMatcher> FS_PATH_EXCLUDES = FileSystemUtil .loadAndParseFileSystemConfig(OSHI_OPENBSD_FS_PATH_EXCLUDES); private static final List<PathMatcher> FS_PATH_INCLUDES = FileSystemUtil .loadAndParseFileSystemConfig(OSHI_OPENBSD_FS_PATH_INCLUDES); private static final List<PathMatcher> FS_VOLUME_EXCLUDES = FileSystemUtil .loadAndParseFileSystemConfig(OSHI_OPENBSD_FS_VOLUME_EXCLUDES); private static final List<PathMatcher> FS_VOLUME_INCLUDES = FileSystemUtil .loadAndParseFileSystemConfig(OSHI_OPENBSD_FS_VOLUME_INCLUDES); @Override public List<OSFileStore> getFileStores(boolean localOnly) { return getFileStoreMatching(null, localOnly); } // Called by OpenBsdOSFileStore static List<OSFileStore> getFileStoreMatching(String nameToMatch) { return getFileStoreMatching(nameToMatch, false); } private static List<OSFileStore> getFileStoreMatching(String nameToMatch, boolean localOnly) {<FILL_FUNCTION_BODY>} @Override public long getOpenFileDescriptors() { return OpenBsdSysctlUtil.sysctl("kern.nfiles", 0); } @Override public long getMaxFileDescriptors() { return OpenBsdSysctlUtil.sysctl("kern.maxfiles", 0); } @Override public long getMaxFileDescriptorsPerProcess() { return OpenBsdSysctlUtil.sysctl("kern.maxfilesperproc", 0); } }
List<OSFileStore> fsList = new ArrayList<>(); // Get inode usage data Map<String, Long> inodeFreeMap = new HashMap<>(); Map<String, Long> inodeUsedlMap = new HashMap<>(); String command = "df -i" + (localOnly ? " -l" : ""); for (String line : ExecutingCommand.runNative(command)) { /*- Sample Output: $ df -i Filesystem 512-blocks Used Avail Capacity iused ifree %iused Mounted on /dev/wd0a 2149212 908676 1133076 45% 8355 147163 5% / /dev/wd0e 4050876 36 3848300 0% 10 285108 0% /home /dev/wd0d 6082908 3343172 2435592 58% 27813 386905 7% /usr */ if (line.startsWith("/")) { String[] split = ParseUtil.whitespaces.split(line); if (split.length > 6) { inodeUsedlMap.put(split[0], ParseUtil.parseLongOrDefault(split[5], 0L)); inodeFreeMap.put(split[0], ParseUtil.parseLongOrDefault(split[6], 0L)); } } } // Get mount table for (String fs : ExecutingCommand.runNative("mount -v")) { // NOSONAR squid:S135 /*- Sample Output: /dev/wd0a (d1c342b6965d372c.a) on / type ffs (rw, local, ctime=Sun Jan 3 18:03:00 2021) /dev/wd0e (d1c342b6965d372c.e) on /home type ffs (rw, local, nodevl, nosuid, ctime=Sun Jan 3 18:02:56 2021) /dev/wd0d (d1c342b6965d372c.d) on /usr type ffs (rw, local, nodev, wxallowed, ctime=Sun Jan 3 18:02:56 2021) */ String[] split = ParseUtil.whitespaces.split(fs, 7); if (split.length == 7) { // 1st field is volume name [0-index] + partition letter // 2nd field is disklabel UUID (DUID) + partition letter after the dot // 4th field is mount point // 6rd field is fs type // 7th field is options String volume = split[0]; String uuid = split[1]; String path = split[3]; String type = split[5]; String options = split[6]; // Skip non-local drives if requested, and exclude pseudo file systems if ((localOnly && NETWORK_FS_TYPES.contains(type)) || !path.equals("/") && (PSEUDO_FS_TYPES.contains(type) || FileSystemUtil.isFileStoreExcluded(path, volume, FS_PATH_INCLUDES, FS_PATH_EXCLUDES, FS_VOLUME_INCLUDES, FS_VOLUME_EXCLUDES))) { continue; } String name = path.substring(path.lastIndexOf('/') + 1); // Special case for /, pull last element of volume instead if (name.isEmpty()) { name = volume.substring(volume.lastIndexOf('/') + 1); } if (nameToMatch != null && !nameToMatch.equals(name)) { continue; } File f = new File(path); long totalSpace = f.getTotalSpace(); long usableSpace = f.getUsableSpace(); long freeSpace = f.getFreeSpace(); String description; if (volume.startsWith("/dev") || path.equals("/")) { description = "Local Disk"; } else if (volume.equals("tmpfs")) { // dynamic size in memory FS description = "Ram Disk (dynamic)"; } else if (volume.equals("mfs")) { // fixed size in memory FS description = "Ram Disk (fixed)"; } else if (NETWORK_FS_TYPES.contains(type)) { description = "Network Disk"; } else { description = "Mount Point"; } fsList.add(new OpenBsdOSFileStore(name, volume, name, path, options, uuid, "", description, type, freeSpace, usableSpace, totalSpace, inodeFreeMap.getOrDefault(volume, 0L), inodeUsedlMap.getOrDefault(volume, 0L) + inodeFreeMap.getOrDefault(volume, 0L))); } } return fsList;
678
1,343
2,021
<methods>public non-sealed void <init>() ,public List<oshi.software.os.OSFileStore> getFileStores() <variables>protected static final List<java.lang.String> NETWORK_FS_TYPES,protected static final List<java.lang.String> PSEUDO_FS_TYPES
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSFileStore.java
OpenBsdOSFileStore
updateAttributes
class OpenBsdOSFileStore extends AbstractOSFileStore { private String logicalVolume; private String description; private String fsType; private long freeSpace; private long usableSpace; private long totalSpace; private long freeInodes; private long totalInodes; public OpenBsdOSFileStore(String name, String volume, String label, String mount, String options, String uuid, String logicalVolume, String description, String fsType, long freeSpace, long usableSpace, long totalSpace, long freeInodes, long totalInodes) { super(name, volume, label, mount, options, uuid); this.logicalVolume = logicalVolume; this.description = description; this.fsType = fsType; this.freeSpace = freeSpace; this.usableSpace = usableSpace; this.totalSpace = totalSpace; this.freeInodes = freeInodes; this.totalInodes = totalInodes; } @Override public String getLogicalVolume() { return this.logicalVolume; } @Override public String getDescription() { return this.description; } @Override public String getType() { return this.fsType; } @Override public long getFreeSpace() { return this.freeSpace; } @Override public long getUsableSpace() { return this.usableSpace; } @Override public long getTotalSpace() { return this.totalSpace; } @Override public long getFreeInodes() { return this.freeInodes; } @Override public long getTotalInodes() { return this.totalInodes; } @Override public boolean updateAttributes() {<FILL_FUNCTION_BODY>} }
for (OSFileStore fileStore : OpenBsdFileSystem.getFileStoreMatching(getName())) { if (getName().equals(fileStore.getName()) && getVolume().equals(fileStore.getVolume()) && getMount().equals(fileStore.getMount())) { this.logicalVolume = fileStore.getLogicalVolume(); this.description = fileStore.getDescription(); this.fsType = fileStore.getType(); this.freeSpace = fileStore.getFreeSpace(); this.usableSpace = fileStore.getUsableSpace(); this.totalSpace = fileStore.getTotalSpace(); this.freeInodes = fileStore.getFreeInodes(); this.totalInodes = fileStore.getTotalInodes(); return true; } } return false;
480
201
681
<methods>public java.lang.String getLabel() ,public java.lang.String getMount() ,public java.lang.String getName() ,public java.lang.String getOptions() ,public java.lang.String getUUID() ,public java.lang.String getVolume() ,public java.lang.String toString() <variables>private java.lang.String label,private java.lang.String mount,private java.lang.String name,private java.lang.String options,private java.lang.String uuid,private java.lang.String volume
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSThread.java
OpenBsdOSThread
updateAttributes
class OpenBsdOSThread extends AbstractOSThread { private int threadId; private String name = ""; private OSProcess.State state = INVALID; private long minorFaults; private long majorFaults; private long startMemoryAddress; private long contextSwitches; private long kernelTime; private long userTime; private long startTime; private long upTime; private int priority; public OpenBsdOSThread(int processId, Map<PsThreadColumns, String> threadMap) { super(processId); updateAttributes(threadMap); } public OpenBsdOSThread(int processId, int threadId) { super(processId); this.threadId = threadId; updateAttributes(); } @Override public int getThreadId() { return this.threadId; } @Override public String getName() { return this.name; } @Override public OSProcess.State getState() { return this.state; } @Override public long getStartMemoryAddress() { return this.startMemoryAddress; } @Override public long getContextSwitches() { return this.contextSwitches; } @Override public long getMinorFaults() { return this.minorFaults; } @Override public long getMajorFaults() { return this.majorFaults; } @Override public long getKernelTime() { return this.kernelTime; } @Override public long getUserTime() { return this.userTime; } @Override public long getUpTime() { return this.upTime; } @Override public long getStartTime() { return this.startTime; } @Override public int getPriority() { return this.priority; } @Override public boolean updateAttributes() { String psCommand = "ps -aHwwxo " + OpenBsdOSProcess.PS_THREAD_COLUMNS + " -p " + getOwningProcessId(); // there is no switch for thread in ps command, hence filtering. List<String> threadList = ExecutingCommand.runNative(psCommand); String tidStr = Integer.toString(this.threadId); for (String psOutput : threadList) { Map<PsThreadColumns, String> threadMap = ParseUtil.stringToEnumMap(PsThreadColumns.class, psOutput.trim(), ' '); if (threadMap.containsKey(PsThreadColumns.ARGS) && tidStr.equals(threadMap.get(PsThreadColumns.TID))) { return updateAttributes(threadMap); } } this.state = INVALID; return false; } private boolean updateAttributes(Map<PsThreadColumns, String> threadMap) {<FILL_FUNCTION_BODY>} }
this.threadId = ParseUtil.parseIntOrDefault(threadMap.get(PsThreadColumns.TID), 0); switch (threadMap.get(PsThreadColumns.STATE).charAt(0)) { case 'R': this.state = RUNNING; break; case 'I': case 'S': this.state = SLEEPING; break; case 'D': case 'L': case 'U': this.state = WAITING; break; case 'Z': this.state = ZOMBIE; break; case 'T': this.state = STOPPED; break; default: this.state = OTHER; break; } // Avoid divide by zero for processes up less than a second long elapsedTime = ParseUtil.parseDHMSOrDefault(threadMap.get(PsThreadColumns.ETIME), 0L); this.upTime = elapsedTime < 1L ? 1L : elapsedTime; long now = System.currentTimeMillis(); this.startTime = now - this.upTime; // ps does not provide kerneltime on OpenBSD this.kernelTime = 0L; this.userTime = ParseUtil.parseDHMSOrDefault(threadMap.get(PsThreadColumns.CPUTIME), 0L); this.startMemoryAddress = 0L; long nonVoluntaryContextSwitches = ParseUtil.parseLongOrDefault(threadMap.get(PsThreadColumns.NIVCSW), 0L); long voluntaryContextSwitches = ParseUtil.parseLongOrDefault(threadMap.get(PsThreadColumns.NVCSW), 0L); this.contextSwitches = voluntaryContextSwitches + nonVoluntaryContextSwitches; this.majorFaults = ParseUtil.parseLongOrDefault(threadMap.get(PsThreadColumns.MAJFLT), 0L); this.minorFaults = ParseUtil.parseLongOrDefault(threadMap.get(PsThreadColumns.MINFLT), 0L); this.priority = ParseUtil.parseIntOrDefault(threadMap.get(PsThreadColumns.PRI), 0); this.name = threadMap.get(PsThreadColumns.ARGS); return true;
768
584
1,352
<methods>public int getOwningProcessId() ,public double getThreadCpuLoadBetweenTicks(oshi.software.os.OSThread) ,public double getThreadCpuLoadCumulative() ,public java.lang.String toString() <variables>private final Supplier<java.lang.Double> cumulativeCpuLoad,private final non-sealed int owningProcessId
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisInternetProtocolStats.java
SolarisInternetProtocolStats
getTcpStats
class SolarisInternetProtocolStats extends AbstractInternetProtocolStats { @Override public TcpStats getTCPv4Stats() { return getTcpStats(); } @Override public UdpStats getUDPv4Stats() { return getUdpStats(); } private static TcpStats getTcpStats() {<FILL_FUNCTION_BODY>} private static UdpStats getUdpStats() { long datagramsSent = 0; long datagramsReceived = 0; long datagramsNoPort = 0; long datagramsReceivedErrors = 0; List<String> netstat = ExecutingCommand.runNative("netstat -s -P udp"); // append IP netstat.addAll(ExecutingCommand.runNative("netstat -s -P ip")); for (String s : netstat) { // Two stats per line. Split the strings by index of "udp" String[] stats = splitOnPrefix(s, "udp"); // Now of form udpXX = 123 for (String stat : stats) { if (stat != null) { String[] split = stat.split("="); if (split.length == 2) { switch (split[0].trim()) { case "udpOutDatagrams": datagramsSent = ParseUtil.parseLongOrDefault(split[1].trim(), 0L); break; case "udpInDatagrams": datagramsReceived = ParseUtil.parseLongOrDefault(split[1].trim(), 0L); break; case "udpNoPorts": datagramsNoPort = ParseUtil.parseLongOrDefault(split[1].trim(), 0L); break; case "udpInErrors": datagramsReceivedErrors = ParseUtil.parseLongOrDefault(split[1].trim(), 0L); break; default: break; } } } } } return new UdpStats(datagramsSent, datagramsReceived, datagramsNoPort, datagramsReceivedErrors); } private static String[] splitOnPrefix(String s, String prefix) { String[] stats = new String[2]; int first = s.indexOf(prefix); if (first >= 0) { int second = s.indexOf(prefix, first + 1); if (second >= 0) { stats[0] = s.substring(first, second).trim(); stats[1] = s.substring(second).trim(); } else { stats[0] = s.substring(first).trim(); } } return stats; } }
long connectionsEstablished = 0; long connectionsActive = 0; long connectionsPassive = 0; long connectionFailures = 0; long connectionsReset = 0; long segmentsSent = 0; long segmentsReceived = 0; long segmentsRetransmitted = 0; long inErrors = 0; long outResets = 0; List<String> netstat = ExecutingCommand.runNative("netstat -s -P tcp"); // append IP netstat.addAll(ExecutingCommand.runNative("netstat -s -P ip")); for (String s : netstat) { // Two stats per line. Split the strings by index of "tcp" String[] stats = splitOnPrefix(s, "tcp"); // Now of form tcpXX = 123 for (String stat : stats) { if (stat != null) { String[] split = stat.split("="); if (split.length == 2) { switch (split[0].trim()) { case "tcpCurrEstab": connectionsEstablished = ParseUtil.parseLongOrDefault(split[1].trim(), 0L); break; case "tcpActiveOpens": connectionsActive = ParseUtil.parseLongOrDefault(split[1].trim(), 0L); break; case "tcpPassiveOpens": connectionsPassive = ParseUtil.parseLongOrDefault(split[1].trim(), 0L); break; case "tcpAttemptFails": connectionFailures = ParseUtil.parseLongOrDefault(split[1].trim(), 0L); break; case "tcpEstabResets": connectionsReset = ParseUtil.parseLongOrDefault(split[1].trim(), 0L); break; case "tcpOutSegs": segmentsSent = ParseUtil.parseLongOrDefault(split[1].trim(), 0L); break; case "tcpInSegs": segmentsReceived = ParseUtil.parseLongOrDefault(split[1].trim(), 0L); break; case "tcpRetransSegs": segmentsRetransmitted = ParseUtil.parseLongOrDefault(split[1].trim(), 0L); break; case "tcpInErr": // doesn't have tcp in second column inErrors = ParseUtil.getFirstIntValue(split[1].trim()); break; case "tcpOutRsts": outResets = ParseUtil.parseLongOrDefault(split[1].trim(), 0L); break; default: break; } } } } } return new TcpStats(connectionsEstablished, connectionsActive, connectionsPassive, connectionFailures, connectionsReset, segmentsSent, segmentsReceived, segmentsRetransmitted, inErrors, outResets);
694
718
1,412
<methods>public non-sealed void <init>() ,public List<oshi.software.os.InternetProtocolStats.IPConnection> getConnections() ,public oshi.software.os.InternetProtocolStats.TcpStats getTCPv6Stats() ,public oshi.software.os.InternetProtocolStats.UdpStats getUDPv6Stats() <variables>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisNetworkParams.java
SolarisNetworkParams
getHostName
class SolarisNetworkParams extends AbstractNetworkParams { private static final SolarisLibc LIBC = SolarisLibc.INSTANCE; @Override public String getHostName() {<FILL_FUNCTION_BODY>} @Override public String getIpv4DefaultGateway() { return searchGateway(ExecutingCommand.runNative("route get -inet default")); } @Override public String getIpv6DefaultGateway() { return searchGateway(ExecutingCommand.runNative("route get -inet6 default")); } }
byte[] hostnameBuffer = new byte[HOST_NAME_MAX + 1]; if (0 != LIBC.gethostname(hostnameBuffer, hostnameBuffer.length)) { return super.getHostName(); } return Native.toString(hostnameBuffer);
149
71
220
<methods>public non-sealed void <init>() ,public java.lang.String[] getDnsServers() ,public java.lang.String getDomainName() ,public java.lang.String getHostName() ,public java.lang.String toString() <variables>private static final java.lang.String NAMESERVER
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSFileStore.java
SolarisOSFileStore
updateAttributes
class SolarisOSFileStore extends AbstractOSFileStore { private String logicalVolume; private String description; private String fsType; private long freeSpace; private long usableSpace; private long totalSpace; private long freeInodes; private long totalInodes; public SolarisOSFileStore(String name, String volume, String label, String mount, String options, String uuid, String logicalVolume, String description, String fsType, long freeSpace, long usableSpace, long totalSpace, long freeInodes, long totalInodes) { super(name, volume, label, mount, options, uuid); this.logicalVolume = logicalVolume; this.description = description; this.fsType = fsType; this.freeSpace = freeSpace; this.usableSpace = usableSpace; this.totalSpace = totalSpace; this.freeInodes = freeInodes; this.totalInodes = totalInodes; } @Override public String getLogicalVolume() { return this.logicalVolume; } @Override public String getDescription() { return this.description; } @Override public String getType() { return this.fsType; } @Override public long getFreeSpace() { return this.freeSpace; } @Override public long getUsableSpace() { return this.usableSpace; } @Override public long getTotalSpace() { return this.totalSpace; } @Override public long getFreeInodes() { return this.freeInodes; } @Override public long getTotalInodes() { return this.totalInodes; } @Override public boolean updateAttributes() {<FILL_FUNCTION_BODY>} }
for (OSFileStore fileStore : SolarisFileSystem.getFileStoreMatching(getName())) { if (getVolume().equals(fileStore.getVolume()) && getMount().equals(fileStore.getMount())) { this.logicalVolume = fileStore.getLogicalVolume(); this.description = fileStore.getDescription(); this.fsType = fileStore.getType(); this.freeSpace = fileStore.getFreeSpace(); this.usableSpace = fileStore.getUsableSpace(); this.totalSpace = fileStore.getTotalSpace(); this.freeInodes = fileStore.getFreeInodes(); this.totalInodes = fileStore.getTotalInodes(); return true; } } return false;
478
188
666
<methods>public java.lang.String getLabel() ,public java.lang.String getMount() ,public java.lang.String getName() ,public java.lang.String getOptions() ,public java.lang.String getUUID() ,public java.lang.String getVolume() ,public java.lang.String toString() <variables>private java.lang.String label,private java.lang.String mount,private java.lang.String name,private java.lang.String options,private java.lang.String uuid,private java.lang.String volume
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSThread.java
SolarisOSThread
updateAttributes
class SolarisOSThread extends AbstractOSThread { private Supplier<SolarisLwpsInfo> lwpsinfo = memoize(this::queryLwpsInfo, defaultExpiration()); private Supplier<SolarisPrUsage> prusage = memoize(this::queryPrUsage, defaultExpiration()); private String name; private int threadId; private OSProcess.State state = OSProcess.State.INVALID; private long startMemoryAddress; private long contextSwitches; private long kernelTime; private long userTime; private long startTime; private long upTime; private int priority; public SolarisOSThread(int pid, int lwpid) { super(pid); this.threadId = lwpid; updateAttributes(); } private SolarisLwpsInfo queryLwpsInfo() { return PsInfo.queryLwpsInfo(this.getOwningProcessId(), this.getThreadId()); } private SolarisPrUsage queryPrUsage() { return PsInfo.queryPrUsage(this.getOwningProcessId(), this.getThreadId()); } @Override public String getName() { return this.name != null ? name : ""; } @Override public int getThreadId() { return this.threadId; } @Override public OSProcess.State getState() { return this.state; } @Override public long getStartMemoryAddress() { return this.startMemoryAddress; } @Override public long getContextSwitches() { return this.contextSwitches; } @Override public long getKernelTime() { return this.kernelTime; } @Override public long getUserTime() { return this.userTime; } @Override public long getUpTime() { return this.upTime; } @Override public long getStartTime() { return this.startTime; } @Override public int getPriority() { return this.priority; } @Override public boolean updateAttributes() {<FILL_FUNCTION_BODY>} }
SolarisLwpsInfo info = lwpsinfo.get(); if (info == null) { this.state = INVALID; return false; } SolarisPrUsage usage = prusage.get(); long now = System.currentTimeMillis(); this.state = SolarisOSProcess.getStateFromOutput((char) info.pr_sname); this.startTime = info.pr_start.tv_sec.longValue() * 1000L + info.pr_start.tv_nsec.longValue() / 1_000_000L; // Avoid divide by zero for processes up less than a millisecond long elapsedTime = now - this.startTime; this.upTime = elapsedTime < 1L ? 1L : elapsedTime; this.kernelTime = 0L; this.userTime = info.pr_time.tv_sec.longValue() * 1000L + info.pr_time.tv_nsec.longValue() / 1_000_000L; this.startMemoryAddress = Pointer.nativeValue(info.pr_addr); this.priority = info.pr_pri; if (usage != null) { this.userTime = usage.pr_utime.tv_sec.longValue() * 1000L + usage.pr_utime.tv_nsec.longValue() / 1_000_000L; this.kernelTime = usage.pr_stime.tv_sec.longValue() * 1000L + usage.pr_stime.tv_nsec.longValue() / 1_000_000L; this.contextSwitches = usage.pr_ictx.longValue() + usage.pr_vctx.longValue(); } this.name = com.sun.jna.Native.toString(info.pr_name); if (Util.isBlank(name)) { this.name = com.sun.jna.Native.toString(info.pr_oldname); } return true;
573
527
1,100
<methods>public int getOwningProcessId() ,public double getThreadCpuLoadBetweenTicks(oshi.software.os.OSThread) ,public double getThreadCpuLoadCumulative() ,public java.lang.String toString() <variables>private final Supplier<java.lang.Double> cumulativeCpuLoad,private final non-sealed int owningProcessId
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/windows/WindowsNetworkParams.java
WindowsNetworkParams
parseIpv4Route
class WindowsNetworkParams extends AbstractNetworkParams { private static final Logger LOG = LoggerFactory.getLogger(WindowsNetworkParams.class); private static final int COMPUTER_NAME_DNS_DOMAIN_FULLY_QUALIFIED = 3; @Override public String getDomainName() { char[] buffer = new char[256]; try (CloseableIntByReference bufferSize = new CloseableIntByReference(buffer.length)) { if (!Kernel32.INSTANCE.GetComputerNameEx(COMPUTER_NAME_DNS_DOMAIN_FULLY_QUALIFIED, buffer, bufferSize)) { LOG.error("Failed to get dns domain name. Error code: {}", Kernel32.INSTANCE.GetLastError()); return ""; } } return Native.toString(buffer); } @Override public String[] getDnsServers() { try (CloseableIntByReference bufferSize = new CloseableIntByReference()) { int ret = IPHlpAPI.INSTANCE.GetNetworkParams(null, bufferSize); if (ret != WinError.ERROR_BUFFER_OVERFLOW) { LOG.error("Failed to get network parameters buffer size. Error code: {}", ret); return new String[0]; } try (Memory buffer = new Memory(bufferSize.getValue())) { ret = IPHlpAPI.INSTANCE.GetNetworkParams(buffer, bufferSize); if (ret != 0) { LOG.error("Failed to get network parameters. Error code: {}", ret); return new String[0]; } FIXED_INFO fixedInfo = new FIXED_INFO(buffer); List<String> list = new ArrayList<>(); IP_ADDR_STRING dns = fixedInfo.DnsServerList; while (dns != null) { // a char array of size 16. // This array holds an IPv4 address in dotted decimal notation. String addr = Native.toString(dns.IpAddress.String, StandardCharsets.US_ASCII); int nullPos = addr.indexOf(0); if (nullPos != -1) { addr = addr.substring(0, nullPos); } list.add(addr); dns = dns.Next; } return list.toArray(new String[0]); } } } @Override public String getHostName() { try { return Kernel32Util.getComputerName(); } catch (Win32Exception e) { return super.getHostName(); } } @Override public String getIpv4DefaultGateway() { return parseIpv4Route(); } @Override public String getIpv6DefaultGateway() { return parseIpv6Route(); } private static String parseIpv4Route() {<FILL_FUNCTION_BODY>} private static String parseIpv6Route() { List<String> lines = ExecutingCommand.runNative("route print -6 ::/0"); for (String line : lines) { String[] fields = ParseUtil.whitespaces.split(line.trim()); if (fields.length > 3 && "::/0".equals(fields[2])) { return fields[3]; } } return ""; } }
List<String> lines = ExecutingCommand.runNative("route print -4 0.0.0.0"); for (String line : lines) { String[] fields = ParseUtil.whitespaces.split(line.trim()); if (fields.length > 2 && "0.0.0.0".equals(fields[0])) { return fields[2]; } } return "";
862
104
966
<methods>public non-sealed void <init>() ,public java.lang.String[] getDnsServers() ,public java.lang.String getDomainName() ,public java.lang.String getHostName() ,public java.lang.String toString() <variables>private static final java.lang.String NAMESERVER
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/windows/WindowsOSFileStore.java
WindowsOSFileStore
updateAttributes
class WindowsOSFileStore extends AbstractOSFileStore { private String logicalVolume; private String description; private String fsType; private long freeSpace; private long usableSpace; private long totalSpace; private long freeInodes; private long totalInodes; public WindowsOSFileStore(String name, String volume, String label, String mount, String options, String uuid, String logicalVolume, String description, String fsType, long freeSpace, long usableSpace, long totalSpace, long freeInodes, long totalInodes) { super(name, volume, label, mount, options, uuid); this.logicalVolume = logicalVolume; this.description = description; this.fsType = fsType; this.freeSpace = freeSpace; this.usableSpace = usableSpace; this.totalSpace = totalSpace; this.freeInodes = freeInodes; this.totalInodes = totalInodes; } @Override public String getLogicalVolume() { return this.logicalVolume; } @Override public String getDescription() { return this.description; } @Override public String getType() { return this.fsType; } @Override public long getFreeSpace() { return this.freeSpace; } @Override public long getUsableSpace() { return this.usableSpace; } @Override public long getTotalSpace() { return this.totalSpace; } @Override public long getFreeInodes() { return this.freeInodes; } @Override public long getTotalInodes() { return this.totalInodes; } @Override public boolean updateAttributes() {<FILL_FUNCTION_BODY>} }
// Check if we have the volume locally List<OSFileStore> volumes = WindowsFileSystem.getLocalVolumes(getVolume()); if (volumes.isEmpty()) { // Not locally, search WMI String nameToMatch = getMount().length() < 2 ? null : getMount().substring(0, 2); volumes = WindowsFileSystem.getWmiVolumes(nameToMatch, false); } for (OSFileStore fileStore : volumes) { if (getVolume().equals(fileStore.getVolume()) && getMount().equals(fileStore.getMount())) { this.logicalVolume = fileStore.getLogicalVolume(); this.description = fileStore.getDescription(); this.fsType = fileStore.getType(); this.freeSpace = fileStore.getFreeSpace(); this.usableSpace = fileStore.getUsableSpace(); this.totalSpace = fileStore.getTotalSpace(); this.freeInodes = fileStore.getFreeInodes(); this.totalInodes = fileStore.getTotalInodes(); return true; } } return false;
476
279
755
<methods>public java.lang.String getLabel() ,public java.lang.String getMount() ,public java.lang.String getName() ,public java.lang.String getOptions() ,public java.lang.String getUUID() ,public java.lang.String getVolume() ,public java.lang.String toString() <variables>private java.lang.String label,private java.lang.String mount,private java.lang.String name,private java.lang.String options,private java.lang.String uuid,private java.lang.String volume
oshi_oshi
oshi/oshi-core/src/main/java/oshi/software/os/windows/WindowsOSThread.java
WindowsOSThread
updateAttributes
class WindowsOSThread extends AbstractOSThread { private final int threadId; private String name; private State state; private long startMemoryAddress; private long contextSwitches; private long kernelTime; private long userTime; private long startTime; private long upTime; private int priority; public WindowsOSThread(int pid, int tid, String procName, PerfCounterBlock pcb) { super(pid); this.threadId = tid; updateAttributes(procName, pcb); } @Override public int getThreadId() { return threadId; } @Override public String getName() { return name; } @Override public State getState() { return state; } @Override public long getStartMemoryAddress() { return startMemoryAddress; } @Override public long getContextSwitches() { return contextSwitches; } @Override public long getKernelTime() { return kernelTime; } @Override public long getUserTime() { return userTime; } @Override public long getStartTime() { return startTime; } @Override public long getUpTime() { return upTime; } @Override public int getPriority() { return this.priority; } @Override public boolean updateAttributes() { Set<Integer> pids = Collections.singleton(getOwningProcessId()); String procName = this.name.split("/")[0]; Map<Integer, ThreadPerformanceData.PerfCounterBlock> threads = ThreadPerformanceData .buildThreadMapFromPerfCounters(pids, procName, getThreadId()); return updateAttributes(procName, threads.get(getThreadId())); } private boolean updateAttributes(String procName, PerfCounterBlock pcb) {<FILL_FUNCTION_BODY>} }
if (pcb == null) { this.state = INVALID; return false; } else if (pcb.getName().contains("/") || procName.isEmpty()) { name = pcb.getName(); } else { this.name = procName + "/" + pcb.getName(); } if (pcb.getThreadWaitReason() == 5) { state = SUSPENDED; } else { switch (pcb.getThreadState()) { case 0: state = NEW; break; case 2: case 3: state = RUNNING; break; case 4: state = STOPPED; break; case 5: state = SLEEPING; break; case 1: case 6: state = WAITING; break; case 7: default: state = OTHER; } } startMemoryAddress = pcb.getStartAddress(); contextSwitches = pcb.getContextSwitches(); kernelTime = pcb.getKernelTime(); userTime = pcb.getUserTime(); startTime = pcb.getStartTime(); upTime = System.currentTimeMillis() - pcb.getStartTime(); priority = pcb.getPriority(); return true;
518
349
867
<methods>public int getOwningProcessId() ,public double getThreadCpuLoadBetweenTicks(oshi.software.os.OSThread) ,public double getThreadCpuLoadCumulative() ,public java.lang.String toString() <variables>private final Supplier<java.lang.Double> cumulativeCpuLoad,private final non-sealed int owningProcessId
oshi_oshi
oshi/oshi-core/src/main/java/oshi/util/ExecutingCommand.java
ExecutingCommand
getAnswerAt
class ExecutingCommand { private static final Logger LOG = LoggerFactory.getLogger(ExecutingCommand.class); private static final String[] DEFAULT_ENV = getDefaultEnv(); private ExecutingCommand() { } private static String[] getDefaultEnv() { if (Platform.isWindows()) { return new String[] { "LANGUAGE=C" }; } else { return new String[] { "LC_ALL=C" }; } } /** * Executes a command on the native command line and returns the result. This is a convenience method to call * {@link java.lang.Runtime#exec(String)} and capture the resulting output in a list of Strings. On Windows, * built-in commands not associated with an executable program may require {@code cmd.exe /c} to be prepended to the * command. * * @param cmdToRun Command to run * @return A list of Strings representing the result of the command, or empty string if the command failed */ public static List<String> runNative(String cmdToRun) { String[] cmd = cmdToRun.split(" "); return runNative(cmd); } /** * Executes a command on the native command line and returns the result line by line. This is a convenience method * to call {@link java.lang.Runtime#exec(String[])} and capture the resulting output in a list of Strings. On * Windows, built-in commands not associated with an executable program may require the strings {@code cmd.exe} and * {@code /c} to be prepended to the array. * * @param cmdToRunWithArgs Command to run and args, in an array * @return A list of Strings representing the result of the command, or empty string if the command failed */ public static List<String> runNative(String[] cmdToRunWithArgs) { return runNative(cmdToRunWithArgs, DEFAULT_ENV); } /** * Executes a command on the native command line and returns the result line by line. This is a convenience method * to call {@link java.lang.Runtime#exec(String[])} and capture the resulting output in a list of Strings. On * Windows, built-in commands not associated with an executable program may require the strings {@code cmd.exe} and * {@code /c} to be prepended to the array. * * @param cmdToRunWithArgs Command to run and args, in an array * @param envp array of strings, each element of which has environment variable settings in the format * name=value, or null if the subprocess should inherit the environment of the current * process. * @return A list of Strings representing the result of the command, or empty string if the command failed */ public static List<String> runNative(String[] cmdToRunWithArgs, String[] envp) { Process p = null; try { p = Runtime.getRuntime().exec(cmdToRunWithArgs, envp); return getProcessOutput(p, cmdToRunWithArgs); } catch (SecurityException | IOException e) { LOG.trace("Couldn't run command {}: {}", Arrays.toString(cmdToRunWithArgs), e.getMessage()); } finally { // Ensure all resources are released if (p != null) { // Windows and Solaris don't close descriptors on destroy, // so we must handle separately if (Platform.isWindows() || Platform.isSolaris()) { try { p.getOutputStream().close(); } catch (IOException e) { // do nothing on failure } try { p.getInputStream().close(); } catch (IOException e) { // do nothing on failure } try { p.getErrorStream().close(); } catch (IOException e) { // do nothing on failure } } p.destroy(); } } return Collections.emptyList(); } private static List<String> getProcessOutput(Process p, String[] cmd) { ArrayList<String> sa = new ArrayList<>(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(p.getInputStream(), Charset.defaultCharset()))) { String line; while ((line = reader.readLine()) != null) { sa.add(line); } p.waitFor(); } catch (IOException e) { LOG.trace("Problem reading output from {}: {}", Arrays.toString(cmd), e.getMessage()); } catch (InterruptedException ie) { LOG.trace("Interrupted while reading output from {}: {}", Arrays.toString(cmd), ie.getMessage()); Thread.currentThread().interrupt(); } return sa; } /** * Return first line of response for selected command. * * @param cmd2launch String command to be launched * @return String or empty string if command failed */ public static String getFirstAnswer(String cmd2launch) { return getAnswerAt(cmd2launch, 0); } /** * Return response on selected line index (0-based) after running selected command. * * @param cmd2launch String command to be launched * @param answerIdx int index of line in response of the command * @return String whole line in response or empty string if invalid index or running of command fails */ public static String getAnswerAt(String cmd2launch, int answerIdx) {<FILL_FUNCTION_BODY>} }
List<String> sa = ExecutingCommand.runNative(cmd2launch); if (answerIdx >= 0 && answerIdx < sa.size()) { return sa.get(answerIdx); } return "";
1,393
60
1,453
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/util/FileSystemUtil.java
FileSystemUtil
parseFileSystemConfig
class FileSystemUtil { private static final String GLOB_PREFIX = "glob:"; private static final String REGEX_PREFIX = "regex:"; private FileSystemUtil() { } /** * Evaluates if file store (identified by {@code path} and {@code volume}) should be excluded or not based on * configuration {@code pathIncludes, pathExcludes, volumeIncludes, volumeExcludes}. * * Inclusion has priority over exclusion. If no exclusion/inclusion pattern is specified, then filestore is not * excluded. * * @param path Mountpoint of filestore. * @param volume Filestore volume. * @param pathIncludes List of patterns for path inclusions. * @param pathExcludes List of patterns for path exclusions. * @param volumeIncludes List of patterns for volume inclusions. * @param volumeExcludes List of patterns for volume exclusions. * @return {@code true} if file store should be excluded or {@code false} otherwise. */ public static boolean isFileStoreExcluded(String path, String volume, List<PathMatcher> pathIncludes, List<PathMatcher> pathExcludes, List<PathMatcher> volumeIncludes, List<PathMatcher> volumeExcludes) { Path p = Paths.get(path); Path v = Paths.get(volume); if (matches(p, pathIncludes) || matches(v, volumeIncludes)) { return false; } return matches(p, pathExcludes) || matches(v, volumeExcludes); } /** * Load from config and parse file system include/exclude line. * * @param configPropertyName The config property containing the line to be parsed. * @return List of PathMatchers to be used to match filestore volume and path. */ public static List<PathMatcher> loadAndParseFileSystemConfig(String configPropertyName) { String config = GlobalConfig.get(configPropertyName, ""); return parseFileSystemConfig(config); } /** * Parse file system include/exclude line. * * @param config The config line to be parsed. * @return List of PathMatchers to be used to match filestore volume and path. */ public static List<PathMatcher> parseFileSystemConfig(String config) {<FILL_FUNCTION_BODY>} /** * Checks if {@code text} matches any of @param patterns}. * * @param text The text to be matched. * @param patterns List of patterns. * @return {@code true} if given text matches at least one glob pattern or {@code false} otherwise. * @see <a href="https://en.wikipedia.org/wiki/Glob_(programming)">Wikipedia - glob (programming)</a> */ public static boolean matches(Path text, List<PathMatcher> patterns) { for (PathMatcher pattern : patterns) { if (pattern.matches(text)) { return true; } } return false; } }
FileSystem fs = FileSystems.getDefault(); // can't be closed List<PathMatcher> patterns = new ArrayList<>(); for (String item : config.split(",")) { if (item.length() > 0) { // Using glob: prefix as the defult unless user has specified glob or regex. See // https://docs.oracle.com/javase/8/docs/api/java/nio/file/FileSystem.html#getPathMatcher-java.lang.String- if (!(item.startsWith(GLOB_PREFIX) || item.startsWith(REGEX_PREFIX))) { item = GLOB_PREFIX + item; } patterns.add(fs.getPathMatcher(item)); } } return patterns;
788
197
985
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/util/Memoizer.java
Memoizer
get
class Memoizer { private static final Supplier<Long> DEFAULT_EXPIRATION_NANOS = memoize(Memoizer::queryExpirationConfig, TimeUnit.MINUTES.toNanos(1)); private Memoizer() { } private static long queryExpirationConfig() { return TimeUnit.MILLISECONDS.toNanos(GlobalConfig.get(GlobalConfig.OSHI_UTIL_MEMOIZER_EXPIRATION, 300)); } /** * Default exipiration of memoized values in nanoseconds, which will refresh after this time elapses. Update by * setting {@link GlobalConfig} property <code>oshi.util.memoizer.expiration</code> to a value in milliseconds. * * @return The number of nanoseconds to keep memoized values before refreshing */ public static long defaultExpiration() { return DEFAULT_EXPIRATION_NANOS.get(); } /** * Store a supplier in a delegate function to be computed once, and only again after time to live (ttl) has expired. * * @param <T> The type of object supplied * @param original The {@link java.util.function.Supplier} to memoize * @param ttlNanos Time in nanoseconds to retain calculation. If negative, retain indefinitely. * @return A memoized version of the supplier */ public static <T> Supplier<T> memoize(Supplier<T> original, long ttlNanos) { // Adapted from Guava's ExpiringMemoizingSupplier return new Supplier<T>() { private final Supplier<T> delegate = original; private volatile T value; // NOSONAR squid:S3077 private volatile long expirationNanos; @Override public T get() {<FILL_FUNCTION_BODY>} }; } /** * Store a supplier in a delegate function to be computed only once. * * @param <T> The type of object supplied * @param original The {@link java.util.function.Supplier} to memoize * @return A memoized version of the supplier */ public static <T> Supplier<T> memoize(Supplier<T> original) { return memoize(original, -1L); } }
long nanos = expirationNanos; long now = System.nanoTime(); if (nanos == 0 || (ttlNanos >= 0 && now - nanos >= 0)) { synchronized (this) { if (nanos == expirationNanos) { // recheck for lost race T t = delegate.get(); value = t; nanos = now + ttlNanos; expirationNanos = (nanos == 0) ? 1 : nanos; return t; } } } return value;
623
149
772
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/util/UserGroupInfo.java
UserGroupInfo
parseGroup
class UserGroupInfo { // Temporarily cache users and groups in concurrent maps, completely refresh // every 5 minutes private static final Supplier<Map<String, String>> USERS_ID_MAP = memoize(UserGroupInfo::getUserMap, TimeUnit.MINUTES.toNanos(5)); private static final Supplier<Map<String, String>> GROUPS_ID_MAP = memoize(UserGroupInfo::getGroupMap, TimeUnit.MINUTES.toNanos(5)); private static final boolean ELEVATED = 0 == ParseUtil.parseIntOrDefault(ExecutingCommand.getFirstAnswer("id -u"), -1); private UserGroupInfo() { } /** * Determine whether the current process has elevated permissions such as sudo / * Administrator * * @return True if this process has elevated permissions */ public static boolean isElevated() { return ELEVATED; } /** * Gets a user from their ID * * @param userId * a user ID * @return a pair containing that user id as the first element and the user name * as the second */ public static String getUser(String userId) { // If value is in cached /etc/passwd return, else do getent passwd uid return USERS_ID_MAP.get().getOrDefault(userId, getentPasswd(userId)); } /** * Gets the group name for a given ID * * @param groupId * a {@link java.lang.String} object. * @return a {@link java.lang.String} object. */ public static String getGroupName(String groupId) { // If value is in cached /etc/passwd return, else do getent group gid return GROUPS_ID_MAP.get().getOrDefault(groupId, getentGroup(groupId)); } private static Map<String, String> getUserMap() { return parsePasswd(FileUtil.readFile("/etc/passwd")); } private static String getentPasswd(String userId) { if (Platform.isAIX()) { return Constants.UNKNOWN; } Map<String, String> newUsers = parsePasswd(ExecutingCommand.runNative("getent passwd " + userId)); // add to user map for future queries USERS_ID_MAP.get().putAll(newUsers); return newUsers.getOrDefault(userId, Constants.UNKNOWN); } private static Map<String, String> parsePasswd(List<String> passwd) { Map<String, String> userMap = new ConcurrentHashMap<>(); // see man 5 passwd for the fields for (String entry : passwd) { String[] split = entry.split(":"); if (split.length > 2) { String userName = split[0]; String uid = split[2]; // it is allowed to have multiple entries for the same userId, // we use the first one userMap.putIfAbsent(uid, userName); } } return userMap; } private static Map<String, String> getGroupMap() { return parseGroup(FileUtil.readFile("/etc/group")); } private static String getentGroup(String groupId) { if (Platform.isAIX()) { return Constants.UNKNOWN; } Map<String, String> newGroups = parseGroup(ExecutingCommand.runNative("getent group " + groupId)); // add to group map for future queries GROUPS_ID_MAP.get().putAll(newGroups); return newGroups.getOrDefault(groupId, Constants.UNKNOWN); } private static Map<String, String> parseGroup(List<String> group) {<FILL_FUNCTION_BODY>} }
Map<String, String> groupMap = new ConcurrentHashMap<>(); // see man 5 group for the fields for (String entry : group) { String[] split = entry.split(":"); if (split.length > 2) { String groupName = split[0]; String gid = split[2]; groupMap.putIfAbsent(gid, groupName); } } return groupMap;
1,009
113
1,122
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/util/Util.java
Util
wildcardMatch
class Util { private static final Logger LOG = LoggerFactory.getLogger(Util.class); private Util() { } /** * Sleeps for the specified number of milliseconds. * * @param ms How long to sleep */ public static void sleep(long ms) { try { LOG.trace("Sleeping for {} ms", ms); Thread.sleep(ms); } catch (InterruptedException e) { // NOSONAR squid:S2142 LOG.warn("Interrupted while sleeping for {} ms: {}", ms, e.getMessage()); Thread.currentThread().interrupt(); } } /** * Tests if a String matches another String with a wildcard pattern. * * @param text The String to test * @param pattern The String containing a wildcard pattern where ? represents a single character and * represents * any number of characters. If the first character of the pattern is a carat (^) the test is * performed against the remaining characters and the result of the test is the opposite. * @return True if the String matches or if the first character is ^ and the remainder of the String does not match. */ public static boolean wildcardMatch(String text, String pattern) {<FILL_FUNCTION_BODY>} /** * Tests if a String is either null or empty. * * @param s The string to test * @return True if the String is either null or empty. */ public static boolean isBlank(String s) { return s == null || s.isEmpty(); } /** * Tests if a String is either null or empty or the unknown constant. * * @param s The string to test * @return True if the String is either null or empty or the unknown constant. */ public static boolean isBlankOrUnknown(String s) { return isBlank(s) || Constants.UNKNOWN.equals(s); } /** * If the given Pointer is of class Memory, executes the close method on it to free its native allocation * * @param p A pointer */ public static void freeMemory(Pointer p) { if (p instanceof Memory) { ((Memory) p).close(); } } /** * Tests if session of a user logged in a device is valid or not. * * @param user The user logged in * @param device The device used by user * @param loginTime The login time of the user * @return True if Session is valid or False if the user of device is empty or the login time is lesser than zero or * greater than current time. */ public static boolean isSessionValid(String user, String device, Long loginTime) { return !(user.isEmpty() || device.isEmpty() || loginTime < 0 || loginTime > System.currentTimeMillis()); } }
if (pattern.length() > 0 && pattern.charAt(0) == '^') { return !wildcardMatch(text, pattern.substring(1)); } return text.matches(pattern.replace("?", ".?").replace("*", ".*?"));
738
71
809
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/util/platform/linux/DevPath.java
DevPath
queryDevConfig
class DevPath { /** * The /dev filesystem location. */ public static final String DEV = queryDevConfig() + "/"; public static final String DISK_BY_UUID = DEV + "disk/by-uuid"; public static final String DM = DEV + "dm"; public static final String LOOP = DEV + "loop"; public static final String MAPPER = DEV + "mapper/"; public static final String RAM = DEV + "ram"; private DevPath() { } private static String queryDevConfig() {<FILL_FUNCTION_BODY>} }
String devPath = GlobalConfig.get(GlobalConfig.OSHI_UTIL_DEV_PATH, "/dev"); // Ensure prefix begins with path separator, but doesn't end with one devPath = '/' + devPath.replaceAll("/$|^/", ""); if (!new File(devPath).exists()) { throw new GlobalConfig.PropertyException(GlobalConfig.OSHI_UTIL_DEV_PATH, "The path does not exist"); } return devPath;
158
123
281
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/util/platform/linux/ProcPath.java
ProcPath
queryProcConfig
class ProcPath { /** * The /proc filesystem location. */ public static final String PROC = queryProcConfig(); public static final String ASOUND = PROC + "/asound/"; public static final String AUXV = PROC + "/self/auxv"; public static final String CPUINFO = PROC + "/cpuinfo"; public static final String DISKSTATS = PROC + "/diskstats"; public static final String MEMINFO = PROC + "/meminfo"; public static final String MODEL = PROC + "/device-tree/model"; public static final String MOUNTS = PROC + "/mounts"; public static final String NET = PROC + "/net"; public static final String PID_CMDLINE = PROC + "/%d/cmdline"; public static final String PID_CWD = PROC + "/%d/cwd"; public static final String PID_EXE = PROC + "/%d/exe"; public static final String PID_ENVIRON = PROC + "/%d/environ"; public static final String PID_FD = PROC + "/%d/fd"; public static final String PID_IO = PROC + "/%d/io"; public static final String PID_STAT = PROC + "/%d/stat"; public static final String PID_STATM = PROC + "/%d/statm"; public static final String PID_STATUS = PROC + "/%d/status"; public static final String SELF_STAT = PROC + "/self/stat"; public static final String STAT = PROC + "/stat"; public static final String SYS_FS_FILE_NR = PROC + "/sys/fs/file-nr"; public static final String SYS_FS_FILE_MAX = PROC + "/sys/fs/file-max"; public static final String TASK_PATH = PROC + "/%d/task"; public static final String TASK_COMM = TASK_PATH + "/%d/comm"; public static final String TASK_STATUS = TASK_PATH + "/%d/status"; public static final String TASK_STAT = TASK_PATH + "/%d/stat"; public static final String THREAD_SELF = PROC + "/thread-self"; public static final String UPTIME = PROC + "/uptime"; public static final String VERSION = PROC + "/version"; public static final String VMSTAT = PROC + "/vmstat"; private ProcPath() { } private static String queryProcConfig() {<FILL_FUNCTION_BODY>} }
String procPath = GlobalConfig.get(GlobalConfig.OSHI_UTIL_PROC_PATH, "/proc"); // Ensure prefix begins with path separator, but doesn't end with one procPath = '/' + procPath.replaceAll("/$|^/", ""); if (!new File(procPath).exists()) { throw new GlobalConfig.PropertyException(GlobalConfig.OSHI_UTIL_PROC_PATH, "The path does not exist"); } return procPath;
651
123
774
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/util/platform/linux/SysPath.java
SysPath
querySysConfig
class SysPath { /** * The /sys filesystem location. */ public static final String SYS = querySysConfig() + "/"; public static final String CPU = SYS + "devices/system/cpu/"; public static final String DMI_ID = SYS + "devices/virtual/dmi/id/"; public static final String NET = SYS + "class/net/"; public static final String MODEL = SYS + "firmware/devicetree/base/model"; public static final String POWER_SUPPLY = SYS + "class/power_supply"; public static final String HWMON = SYS + "class/hwmon/"; public static final String THERMAL = SYS + "class/thermal/thermal_zone"; private SysPath() { } private static String querySysConfig() {<FILL_FUNCTION_BODY>} }
String sysPath = GlobalConfig.get(GlobalConfig.OSHI_UTIL_SYS_PATH, "/sys"); // Ensure prefix begins with path separator, but doesn't end with one sysPath = '/' + sysPath.replaceAll("/$|^/", ""); if (!new File(sysPath).exists()) { throw new GlobalConfig.PropertyException(GlobalConfig.OSHI_UTIL_SYS_PATH, "The path does not exist"); } return sysPath;
237
123
360
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/util/platform/mac/CFUtil.java
CFUtil
cfPointerToString
class CFUtil { private CFUtil() { } /** * /** Convert a pointer to a CFString into a String. * * @param result Pointer to the CFString * @return a CFString or "unknown" if it has no value */ public static String cfPointerToString(Pointer result) { return cfPointerToString(result, true); } /** * Convert a pointer to a CFString into a String. * * @param result Pointer to the CFString * @param returnUnknown Whether to return the "unknown" string * @return a CFString including a possible empty one if {@code returnUnknown} is false, or "unknown" if it is true */ public static String cfPointerToString(Pointer result, boolean returnUnknown) {<FILL_FUNCTION_BODY>} }
String s = ""; if (result != null) { CFStringRef cfs = new CFStringRef(result); s = cfs.stringValue(); } if (returnUnknown && s.isEmpty()) { return Constants.UNKNOWN; } return s;
211
78
289
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/util/platform/mac/SysctlUtil.java
SysctlUtil
sysctl
class SysctlUtil { private static final Logger LOG = LoggerFactory.getLogger(SysctlUtil.class); private static final String SYSCTL_FAIL = "Failed sysctl call: {}, Error code: {}"; private SysctlUtil() { } /** * Executes a sysctl call with an int result * * @param name name of the sysctl * @param def default int value * @return The int result of the call if successful; the default otherwise */ public static int sysctl(String name, int def) { return sysctl(name, def, true); } /** * Executes a sysctl call with an int result * * @param name name of the sysctl * @param def default int value * @param logWarning whether to log the warning if not available * @return The int result of the call if successful; the default otherwise */ public static int sysctl(String name, int def, boolean logWarning) { int intSize = com.sun.jna.platform.mac.SystemB.INT_SIZE; try (Memory p = new Memory(intSize); CloseableSizeTByReference size = new CloseableSizeTByReference(intSize)) { if (0 != SystemB.INSTANCE.sysctlbyname(name, p, size, null, size_t.ZERO)) { if (logWarning) { LOG.warn(SYSCTL_FAIL, name, Native.getLastError()); } return def; } return p.getInt(0); } } /** * Executes a sysctl call with a long result * * @param name name of the sysctl * @param def default long value * @return The long result of the call if successful; the default otherwise */ public static long sysctl(String name, long def) { int uint64Size = com.sun.jna.platform.mac.SystemB.UINT64_SIZE; try (Memory p = new Memory(uint64Size); CloseableSizeTByReference size = new CloseableSizeTByReference(uint64Size)) { if (0 != SystemB.INSTANCE.sysctlbyname(name, p, size, null, size_t.ZERO)) { LOG.warn(SYSCTL_FAIL, name, Native.getLastError()); return def; } return p.getLong(0); } } /** * Executes a sysctl call with a String result * * @param name name of the sysctl * @param def default String value * @return The String result of the call if successful; the default otherwise */ public static String sysctl(String name, String def) { return sysctl(name, def, true); } /** * Executes a sysctl call with a String result * * @param name name of the sysctl * @param def default String value * @param logWarning whether to log the warning if not available * @return The String result of the call if successful; the default otherwise */ public static String sysctl(String name, String def, boolean logWarning) {<FILL_FUNCTION_BODY>} /** * Executes a sysctl call with a Structure result * * @param name name of the sysctl * @param struct structure for the result * @return True if structure is successfuly populated, false otherwise */ public static boolean sysctl(String name, Structure struct) { try (CloseableSizeTByReference size = new CloseableSizeTByReference(struct.size())) { if (0 != SystemB.INSTANCE.sysctlbyname(name, struct.getPointer(), size, null, size_t.ZERO)) { LOG.warn(SYSCTL_FAIL, name, Native.getLastError()); return false; } } struct.read(); return true; } /** * Executes a sysctl call with a Pointer result * * @param name name of the sysctl * @return An allocated memory buffer containing the result on success, null otherwise. Its value on failure is * undefined. */ public static Memory sysctl(String name) { try (CloseableSizeTByReference size = new CloseableSizeTByReference()) { if (0 != SystemB.INSTANCE.sysctlbyname(name, null, size, null, size_t.ZERO)) { LOG.warn(SYSCTL_FAIL, name, Native.getLastError()); return null; } Memory m = new Memory(size.longValue()); if (0 != SystemB.INSTANCE.sysctlbyname(name, m, size, null, size_t.ZERO)) { LOG.warn(SYSCTL_FAIL, name, Native.getLastError()); m.close(); return null; } return m; } } }
// Call first time with null pointer to get value of size try (CloseableSizeTByReference size = new CloseableSizeTByReference()) { if (0 != SystemB.INSTANCE.sysctlbyname(name, null, size, null, size_t.ZERO)) { if (logWarning) { LOG.warn(SYSCTL_FAIL, name, Native.getLastError()); } return def; } // Add 1 to size for null terminated string try (Memory p = new Memory(size.longValue() + 1L)) { if (0 != SystemB.INSTANCE.sysctlbyname(name, p, size, null, size_t.ZERO)) { if (logWarning) { LOG.warn(SYSCTL_FAIL, name, Native.getLastError()); } return def; } return p.getString(0); } }
1,279
238
1,517
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/util/platform/unix/freebsd/BsdSysctlUtil.java
BsdSysctlUtil
sysctl
class BsdSysctlUtil { private static final Logger LOG = LoggerFactory.getLogger(BsdSysctlUtil.class); private static final String SYSCTL_FAIL = "Failed sysctl call: {}, Error code: {}"; private BsdSysctlUtil() { } /** * Executes a sysctl call with an int result * * @param name name of the sysctl * @param def default int value * @return The int result of the call if successful; the default otherwise */ public static int sysctl(String name, int def) { int intSize = FreeBsdLibc.INT_SIZE; try (Memory p = new Memory(intSize); CloseableSizeTByReference size = new CloseableSizeTByReference(intSize)) { if (0 != FreeBsdLibc.INSTANCE.sysctlbyname(name, p, size, null, size_t.ZERO)) { LOG.warn(SYSCTL_FAIL, name, Native.getLastError()); return def; } return p.getInt(0); } } /** * Executes a sysctl call with a long result * * @param name name of the sysctl * @param def default long value * @return The long result of the call if successful; the default otherwise */ public static long sysctl(String name, long def) { int uint64Size = FreeBsdLibc.UINT64_SIZE; try (Memory p = new Memory(uint64Size); CloseableSizeTByReference size = new CloseableSizeTByReference(uint64Size)) { if (0 != FreeBsdLibc.INSTANCE.sysctlbyname(name, p, size, null, size_t.ZERO)) { LOG.warn(SYSCTL_FAIL, name, Native.getLastError()); return def; } return p.getLong(0); } } /** * Executes a sysctl call with a String result * * @param name name of the sysctl * @param def default String value * @return The String result of the call if successful; the default otherwise */ public static String sysctl(String name, String def) { // Call first time with null pointer to get value of size try (CloseableSizeTByReference size = new CloseableSizeTByReference()) { if (0 != FreeBsdLibc.INSTANCE.sysctlbyname(name, null, size, null, size_t.ZERO)) { LOG.warn(SYSCTL_FAIL, name, Native.getLastError()); return def; } // Add 1 to size for null terminated string try (Memory p = new Memory(size.longValue() + 1L)) { if (0 != FreeBsdLibc.INSTANCE.sysctlbyname(name, p, size, null, size_t.ZERO)) { LOG.warn(SYSCTL_FAIL, name, Native.getLastError()); return def; } return p.getString(0); } } } /** * Executes a sysctl call with a Structure result * * @param name name of the sysctl * @param struct structure for the result * @return True if structure is successfuly populated, false otherwise */ public static boolean sysctl(String name, Structure struct) {<FILL_FUNCTION_BODY>} /** * Executes a sysctl call with a Pointer result * * @param name name of the sysctl * @return An allocated memory buffer containing the result on success, null otherwise. Its value on failure is * undefined. */ public static Memory sysctl(String name) { try (CloseableSizeTByReference size = new CloseableSizeTByReference()) { if (0 != FreeBsdLibc.INSTANCE.sysctlbyname(name, null, size, null, size_t.ZERO)) { LOG.error(SYSCTL_FAIL, name, Native.getLastError()); return null; } Memory m = new Memory(size.longValue()); if (0 != FreeBsdLibc.INSTANCE.sysctlbyname(name, m, size, null, size_t.ZERO)) { LOG.error(SYSCTL_FAIL, name, Native.getLastError()); m.close(); return null; } return m; } } }
try (CloseableSizeTByReference size = new CloseableSizeTByReference(struct.size())) { if (0 != FreeBsdLibc.INSTANCE.sysctlbyname(name, struct.getPointer(), size, null, size_t.ZERO)) { LOG.error(SYSCTL_FAIL, name, Native.getLastError()); return false; } } struct.read(); return true;
1,160
113
1,273
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/util/platform/unix/freebsd/ProcstatUtil.java
ProcstatUtil
getOpenFiles
class ProcstatUtil { private ProcstatUtil() { } /** * Gets a map containing current working directory info * * @param pid a process ID, optional * @return a map of process IDs to their current working directory. If {@code pid} is a negative number, all * processes are returned; otherwise the map may contain only a single element for {@code pid} */ public static Map<Integer, String> getCwdMap(int pid) { List<String> procstat = ExecutingCommand.runNative("procstat -f " + (pid < 0 ? "-a" : pid)); Map<Integer, String> cwdMap = new HashMap<>(); for (String line : procstat) { String[] split = ParseUtil.whitespaces.split(line.trim(), 10); if (split.length == 10 && split[2].equals("cwd")) { cwdMap.put(ParseUtil.parseIntOrDefault(split[0], -1), split[9]); } } return cwdMap; } /** * Gets current working directory info * * @param pid a process ID * @return the current working directory for that process. */ public static String getCwd(int pid) { List<String> procstat = ExecutingCommand.runNative("procstat -f " + pid); for (String line : procstat) { String[] split = ParseUtil.whitespaces.split(line.trim(), 10); if (split.length == 10 && split[2].equals("cwd")) { return split[9]; } } return ""; } /** * Gets open files * * @param pid The process ID * @return the number of open files. */ public static long getOpenFiles(int pid) {<FILL_FUNCTION_BODY>} }
long fd = 0L; List<String> procstat = ExecutingCommand.runNative("procstat -f " + pid); for (String line : procstat) { String[] split = ParseUtil.whitespaces.split(line.trim(), 10); if (split.length == 10 && !"Vd-".contains(split[4])) { fd++; } } return fd;
486
113
599
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/util/platform/unix/openbsd/FstatUtil.java
FstatUtil
getOpenFiles
class FstatUtil { private FstatUtil() { } /** * Gets current working directory info (using {@code ps} actually). * * @param pid a process ID * @return the current working directory for that process. */ public static String getCwd(int pid) { List<String> ps = ExecutingCommand.runNative("ps -axwwo cwd -p " + pid); if (ps.size() > 1) { return ps.get(1); } return ""; } /** * Gets open number of files. * * @param pid The process ID * @return the number of open files. */ public static long getOpenFiles(int pid) {<FILL_FUNCTION_BODY>} }
long fd = 0L; List<String> fstat = ExecutingCommand.runNative("fstat -sp " + pid); for (String line : fstat) { String[] split = ParseUtil.whitespaces.split(line.trim(), 11); if (split.length == 11 && !"pipe".contains(split[4]) && !"unix".contains(split[4])) { fd++; } } // subtract 1 for header row return fd - 1;
203
136
339
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/util/platform/unix/openbsd/OpenBsdSysctlUtil.java
OpenBsdSysctlUtil
sysctl
class OpenBsdSysctlUtil { private static final String SYSCTL_N = "sysctl -n "; private static final Logger LOG = LoggerFactory.getLogger(OpenBsdSysctlUtil.class); private static final String SYSCTL_FAIL = "Failed sysctl call: {}, Error code: {}"; private OpenBsdSysctlUtil() { } /** * Executes a sysctl call with an int result * * @param name name of the sysctl * @param def default int value * @return The int result of the call if successful; the default otherwise */ public static int sysctl(int[] name, int def) { int intSize = OpenBsdLibc.INT_SIZE; try (Memory p = new Memory(intSize); CloseableSizeTByReference size = new CloseableSizeTByReference(intSize)) { if (0 != OpenBsdLibc.INSTANCE.sysctl(name, name.length, p, size, null, size_t.ZERO)) { LOG.warn(SYSCTL_FAIL, name, Native.getLastError()); return def; } return p.getInt(0); } } /** * Executes a sysctl call with a long result * * @param name name of the sysctl * @param def default long value * @return The long result of the call if successful; the default otherwise */ public static long sysctl(int[] name, long def) { int uint64Size = OpenBsdLibc.UINT64_SIZE; try (Memory p = new Memory(uint64Size); CloseableSizeTByReference size = new CloseableSizeTByReference(uint64Size)) { if (0 != OpenBsdLibc.INSTANCE.sysctl(name, name.length, p, size, null, size_t.ZERO)) { LOG.warn(SYSCTL_FAIL, name, Native.getLastError()); return def; } return p.getLong(0); } } /** * Executes a sysctl call with a String result * * @param name name of the sysctl * @param def default String value * @return The String result of the call if successful; the default otherwise */ public static String sysctl(int[] name, String def) {<FILL_FUNCTION_BODY>} /** * Executes a sysctl call with a Structure result * * @param name name of the sysctl * @param struct structure for the result * @return True if structure is successfuly populated, false otherwise */ public static boolean sysctl(int[] name, Structure struct) { try (CloseableSizeTByReference size = new CloseableSizeTByReference(struct.size())) { if (0 != OpenBsdLibc.INSTANCE.sysctl(name, name.length, struct.getPointer(), size, null, size_t.ZERO)) { LOG.error(SYSCTL_FAIL, name, Native.getLastError()); return false; } } struct.read(); return true; } /** * Executes a sysctl call with a Pointer result * * @param name name of the sysctl * @return An allocated memory buffer containing the result on success, null otherwise. Its value on failure is * undefined. */ public static Memory sysctl(int[] name) { try (CloseableSizeTByReference size = new CloseableSizeTByReference()) { if (0 != OpenBsdLibc.INSTANCE.sysctl(name, name.length, null, size, null, size_t.ZERO)) { LOG.error(SYSCTL_FAIL, name, Native.getLastError()); return null; } Memory m = new Memory(size.longValue()); if (0 != OpenBsdLibc.INSTANCE.sysctl(name, name.length, m, size, null, size_t.ZERO)) { LOG.error(SYSCTL_FAIL, name, Native.getLastError()); m.close(); return null; } return m; } } /* * Backup versions with command parsing */ /** * Executes a sysctl call with an int result * * @param name name of the sysctl * @param def default int value * @return The int result of the call if successful; the default otherwise */ public static int sysctl(String name, int def) { return ParseUtil.parseIntOrDefault(ExecutingCommand.getFirstAnswer(SYSCTL_N + name), def); } /** * Executes a sysctl call with a long result * * @param name name of the sysctl * @param def default long value * @return The long result of the call if successful; the default otherwise */ public static long sysctl(String name, long def) { return ParseUtil.parseLongOrDefault(ExecutingCommand.getFirstAnswer(SYSCTL_N + name), def); } /** * Executes a sysctl call with a String result * * @param name name of the sysctl * @param def default String value * @return The String result of the call if successful; the default otherwise */ public static String sysctl(String name, String def) { String v = ExecutingCommand.getFirstAnswer(SYSCTL_N + name); if (null == v || v.isEmpty()) { return def; } return v; } }
// Call first time with null pointer to get value of size try (CloseableSizeTByReference size = new CloseableSizeTByReference()) { if (0 != OpenBsdLibc.INSTANCE.sysctl(name, name.length, null, size, null, size_t.ZERO)) { LOG.warn(SYSCTL_FAIL, name, Native.getLastError()); return def; } // Add 1 to size for null terminated string try (Memory p = new Memory(size.longValue() + 1L)) { if (0 != OpenBsdLibc.INSTANCE.sysctl(name, name.length, p, size, null, size_t.ZERO)) { LOG.warn(SYSCTL_FAIL, name, Native.getLastError()); return def; } return p.getString(0); } }
1,456
226
1,682
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/util/platform/unix/solaris/KstatUtil.java
KstatChain
dataLookupString
class KstatChain implements AutoCloseable { private final KstatCtl localCtlRef; private KstatChain(KstatCtl ctl) { this.localCtlRef = ctl; update(); } /** * Convenience method for {@link LibKstat#kstat_read} which gets data from the kernel for the kstat pointed to * by {@code ksp}. {@code ksp.ks_data} is automatically allocated (or reallocated) to be large enough to hold * all of the data. {@code ksp.ks_ndata} is set to the number of data fields, {@code ksp.ks_data_size} is set to * the total size of the data, and ksp.ks_snaptime is set to the high-resolution time at which the data snapshot * was taken. * * @param ksp The kstat from which to retrieve data * @return {@code true} if successful; {@code false} otherwise */ @GuardedBy("CHAIN") public boolean read(Kstat ksp) { int retry = 0; while (0 > LibKstat.INSTANCE.kstat_read(localCtlRef, ksp, null)) { if (LibKstat.EAGAIN != Native.getLastError() || 5 <= ++retry) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to read kstat {}:{}:{}", Native.toString(ksp.ks_module, StandardCharsets.US_ASCII), ksp.ks_instance, Native.toString(ksp.ks_name, StandardCharsets.US_ASCII)); } return false; } Util.sleep(8 << retry); } return true; } /** * Convenience method for {@link LibKstat#kstat_lookup}. Traverses the kstat chain, searching for a kstat with * the same {@code module}, {@code instance}, and {@code name} fields; this triplet uniquely identifies a kstat. * If {@code module} is {@code null}, {@code instance} is -1, or {@code name} is {@code null}, then those fields * will be ignored in the search. * * @param module The module, or null to ignore * @param instance The instance, or -1 to ignore * @param name The name, or null to ignore * @return The first match of the requested Kstat structure if found, or {@code null} */ @GuardedBy("CHAIN") public Kstat lookup(String module, int instance, String name) { return LibKstat.INSTANCE.kstat_lookup(localCtlRef, module, instance, name); } /** * Convenience method for {@link LibKstat#kstat_lookup}. Traverses the kstat chain, searching for all kstats * with the same {@code module}, {@code instance}, and {@code name} fields; this triplet uniquely identifies a * kstat. If {@code module} is {@code null}, {@code instance} is -1, or {@code name} is {@code null}, then those * fields will be ignored in the search. * * @param module The module, or null to ignore * @param instance The instance, or -1 to ignore * @param name The name, or null to ignore * @return All matches of the requested Kstat structure if found, or an empty list otherwise */ @GuardedBy("CHAIN") public List<Kstat> lookupAll(String module, int instance, String name) { List<Kstat> kstats = new ArrayList<>(); for (Kstat ksp = LibKstat.INSTANCE.kstat_lookup(localCtlRef, module, instance, name); ksp != null; ksp = ksp .next()) { if ((module == null || module.equals(Native.toString(ksp.ks_module, StandardCharsets.US_ASCII))) && (instance < 0 || instance == ksp.ks_instance) && (name == null || name.equals(Native.toString(ksp.ks_name, StandardCharsets.US_ASCII)))) { kstats.add(ksp); } } return kstats; } /** * Convenience method for {@link LibKstat#kstat_chain_update}. Brings this kstat header chain in sync with that * of the kernel. * <p> * This function compares the kernel's current kstat chain ID(KCID), which is incremented every time the kstat * chain changes, to this object's KCID. * * @return the new KCID if the kstat chain has changed, 0 if it hasn't, or -1 on failure. */ @GuardedBy("CHAIN") public int update() { return LibKstat.INSTANCE.kstat_chain_update(localCtlRef); } /** * Release the lock on the chain. */ @Override public void close() { CHAIN.unlock(); } } /** * Lock the Kstat chain for use by this object until it's closed. * * @return A locked copy of the chain. It should be unlocked/released when you are done with it with * {@link KstatChain#close()}. */ public static synchronized KstatChain openChain() { CHAIN.lock(); if (kstatCtl == null) { kstatCtl = LibKstat.INSTANCE.kstat_open(); } return new KstatChain(kstatCtl); } /** * Convenience method for {@link LibKstat#kstat_data_lookup} with String return values. Searches the kstat's data * section for the record with the specified name. This operation is valid only for kstat types which have named * data records. Currently, only the KSTAT_TYPE_NAMED and KSTAT_TYPE_TIMER kstats have named data records. * * @param ksp The kstat to search * @param name The key for the name-value pair, or name of the timer as applicable * @return The value as a String. */ public static String dataLookupString(Kstat ksp, String name) {<FILL_FUNCTION_BODY>
if (ksp.ks_type != LibKstat.KSTAT_TYPE_NAMED && ksp.ks_type != LibKstat.KSTAT_TYPE_TIMER) { throw new IllegalArgumentException("Not a kstat_named or kstat_timer kstat."); } Pointer p = LibKstat.INSTANCE.kstat_data_lookup(ksp, name); if (p == null) { LOG.debug("Failed to lookup kstat value for key {}", name); return ""; } KstatNamed data = new KstatNamed(p); switch (data.data_type) { case LibKstat.KSTAT_DATA_CHAR: return Native.toString(data.value.charc, StandardCharsets.UTF_8); case LibKstat.KSTAT_DATA_INT32: return Integer.toString(data.value.i32); case LibKstat.KSTAT_DATA_UINT32: return FormatUtil.toUnsignedString(data.value.ui32); case LibKstat.KSTAT_DATA_INT64: return Long.toString(data.value.i64); case LibKstat.KSTAT_DATA_UINT64: return FormatUtil.toUnsignedString(data.value.ui64); case LibKstat.KSTAT_DATA_STRING: return data.value.str.addr.getString(0); default: LOG.error("Unimplemented kstat data type {}", data.data_type); return ""; }
1,603
393
1,996
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/util/platform/windows/PerfCounterQueryHandler.java
PerfCounterQueryHandler
queryCounter
class PerfCounterQueryHandler implements AutoCloseable { private static final Logger LOG = LoggerFactory.getLogger(PerfCounterQueryHandler.class); // Map of counter handles private Map<PerfCounter, CloseableHANDLEByReference> counterHandleMap = new HashMap<>(); // The query handle private CloseableHANDLEByReference queryHandle = null; /** * Begin monitoring a Performance Data counter. * * @param counter A PerfCounter object. * @return True if the counter was successfully added to the query. */ public boolean addCounterToQuery(PerfCounter counter) { // Open a new query or get the handle to an existing one if (this.queryHandle == null) { this.queryHandle = new CloseableHANDLEByReference(); if (!PerfDataUtil.openQuery(this.queryHandle)) { LOG.warn("Failed to open a query for PDH counter: {}", counter.getCounterPath()); this.queryHandle.close(); this.queryHandle = null; return false; } } // Get a new handle for the counter CloseableHANDLEByReference p = new CloseableHANDLEByReference(); if (!PerfDataUtil.addCounter(this.queryHandle, counter.getCounterPath(), p)) { LOG.warn("Failed to add counter for PDH counter: {}", counter.getCounterPath()); p.close(); return false; } counterHandleMap.put(counter, p); return true; } /** * Stop monitoring a Performance Data counter. * * @param counter A PerfCounter object * @return True if the counter was successfully removed. */ public boolean removeCounterFromQuery(PerfCounter counter) { boolean success = false; try (CloseableHANDLEByReference href = counterHandleMap.remove(counter)) { // null if handle wasn't present if (href != null) { success = PerfDataUtil.removeCounter(href); } } if (counterHandleMap.isEmpty()) { PerfDataUtil.closeQuery(this.queryHandle); this.queryHandle.close(); this.queryHandle = null; } return success; } /** * Stop monitoring all Performance Data counters and release their resources */ public void removeAllCounters() { // Remove all counters from counterHandle map for (CloseableHANDLEByReference href : counterHandleMap.values()) { PerfDataUtil.removeCounter(href); href.close(); } counterHandleMap.clear(); // Remove query if (this.queryHandle != null) { PerfDataUtil.closeQuery(this.queryHandle); this.queryHandle.close(); this.queryHandle = null; } } /** * Update all counters on this query. * * @return The timestamp for the update of all the counters, in milliseconds since the epoch, or 0 if the update * failed */ public long updateQuery() { if (this.queryHandle == null) { LOG.warn("Query does not exist to update."); return 0L; } return PerfDataUtil.updateQueryTimestamp(queryHandle); } /** * Query the raw counter value of a Performance Data counter. Further mathematical manipulation/conversion is left * to the caller. * * @param counter The counter to query * @return The raw value of the counter */ public long queryCounter(PerfCounter counter) {<FILL_FUNCTION_BODY>} @Override public void close() { removeAllCounters(); } }
if (!counterHandleMap.containsKey(counter)) { if (LOG.isWarnEnabled()) { LOG.warn("Counter {} does not exist to query.", counter.getCounterPath()); } return 0; } long value = counter.isBaseCounter() ? PerfDataUtil.querySecondCounter(counterHandleMap.get(counter)) : PerfDataUtil.queryCounter(counterHandleMap.get(counter)); if (value < 0) { if (LOG.isWarnEnabled()) { LOG.warn("Error querying counter {}: {}", counter.getCounterPath(), String.format(Locale.ROOT, FormatUtil.formatError((int) value))); } return 0L; } return value;
943
190
1,133
<no_super_class>
oshi_oshi
oshi/oshi-core/src/main/java/oshi/util/platform/windows/PerfDataUtil.java
PerfCounter
addCounter
class PerfCounter { private final String object; private final String instance; private final String counter; private final boolean baseCounter; public PerfCounter(String objectName, String instanceName, String counterName) { this.object = objectName; this.instance = instanceName; int baseIdx = counterName.indexOf("_Base"); if (baseIdx > 0) { this.counter = counterName.substring(0, baseIdx); this.baseCounter = true; } else { this.counter = counterName; this.baseCounter = false; } } /** * @return Returns the object. */ public String getObject() { return object; } /** * @return Returns the instance. */ public String getInstance() { return instance; } /** * @return Returns the counter. */ public String getCounter() { return counter; } /** * @return Returns whether the counter is a base counter */ public boolean isBaseCounter() { return baseCounter; } /** * Returns the path for this counter * * @return A string representing the counter path */ public String getCounterPath() { StringBuilder sb = new StringBuilder(); sb.append('\\').append(object); if (instance != null) { sb.append('(').append(instance).append(')'); } sb.append('\\').append(counter); return sb.toString(); } } private PerfDataUtil() { } /** * Create a Performance Counter * * @param object The object/path for the counter * @param instance The instance of the counter, or null if no instance * @param counter The counter name * @return A PerfCounter object encapsulating the object, instance, and counter */ public static PerfCounter createCounter(String object, String instance, String counter) { return new PerfCounter(object, instance, counter); } /** * Update a query and get the timestamp * * @param query The query to update all counters in * @return The update timestamp of the first counter in the query */ public static long updateQueryTimestamp(HANDLEByReference query) { try (CloseableLONGLONGByReference pllTimeStamp = new CloseableLONGLONGByReference()) { int ret = IS_VISTA_OR_GREATER ? PDH.PdhCollectQueryDataWithTime(query.getValue(), pllTimeStamp) : PDH.PdhCollectQueryData(query.getValue()); // Due to race condition, initial update may fail with PDH_NO_DATA. int retries = 0; while (ret == PdhMsg.PDH_NO_DATA && retries++ < 3) { // Exponential fallback. Util.sleep(1 << retries); ret = IS_VISTA_OR_GREATER ? PDH.PdhCollectQueryDataWithTime(query.getValue(), pllTimeStamp) : PDH.PdhCollectQueryData(query.getValue()); } if (ret != WinError.ERROR_SUCCESS) { if (LOG.isWarnEnabled()) { LOG.warn("Failed to update counter. Error code: {}", String.format(Locale.ROOT, FormatUtil.formatError(ret))); } return 0L; } // Perf Counter timestamp is in local time return IS_VISTA_OR_GREATER ? ParseUtil.filetimeToUtcMs(pllTimeStamp.getValue().longValue(), true) : System.currentTimeMillis(); } } /** * Open a pdh query * * @param q pointer to the query * @return true if successful */ public static boolean openQuery(HANDLEByReference q) { int ret = PDH.PdhOpenQuery(null, PZERO, q); if (ret != WinError.ERROR_SUCCESS) { if (LOG.isErrorEnabled()) { LOG.error("Failed to open PDH Query. Error code: {}", String.format(Locale.ROOT, FormatUtil.formatError(ret))); } return false; } return true; } /** * Close a pdh query * * @param q pointer to the query * @return true if successful */ public static boolean closeQuery(HANDLEByReference q) { return WinError.ERROR_SUCCESS == PDH.PdhCloseQuery(q.getValue()); } /** * Get value of pdh counter * * @param counter The counter to get the value of * @return long value of the counter, or negative value representing an error code */ public static long queryCounter(HANDLEByReference counter) { try (CloseablePdhRawCounter counterValue = new CloseablePdhRawCounter()) { int ret = PDH.PdhGetRawCounterValue(counter.getValue(), PDH_FMT_RAW, counterValue); if (ret != WinError.ERROR_SUCCESS) { if (LOG.isWarnEnabled()) { LOG.warn("Failed to get counter. Error code: {}", String.format(Locale.ROOT, FormatUtil.formatError(ret))); } return ret; } return counterValue.FirstValue; } } /** * Get value of pdh counter's second value (base counters) * * @param counter The counter to get the value of * @return long value of the counter's second value, or negative value representing an error code */ public static long querySecondCounter(HANDLEByReference counter) { try (CloseablePdhRawCounter counterValue = new CloseablePdhRawCounter()) { int ret = PDH.PdhGetRawCounterValue(counter.getValue(), PDH_FMT_RAW, counterValue); if (ret != WinError.ERROR_SUCCESS) { if (LOG.isWarnEnabled()) { LOG.warn("Failed to get counter. Error code: {}", String.format(Locale.ROOT, FormatUtil.formatError(ret))); } return ret; } return counterValue.SecondValue; } } /** * Adds a pdh counter to a query * * @param query Pointer to the query to add the counter * @param path String name of the PerfMon counter. For Vista+, must be in English. Must localize this path for * pre-Vista. * @param p Pointer to the counter * @return true if successful */ public static boolean addCounter(HANDLEByReference query, String path, HANDLEByReference p) {<FILL_FUNCTION_BODY>
int ret = IS_VISTA_OR_GREATER ? PDH.PdhAddEnglishCounter(query.getValue(), path, PZERO, p) : PDH.PdhAddCounter(query.getValue(), path, PZERO, p); if (ret != WinError.ERROR_SUCCESS) { if (LOG.isWarnEnabled()) { LOG.warn("Failed to add PDH Counter: {}, Error code: {}", path, String.format(Locale.ROOT, FormatUtil.formatError(ret))); } return false; } return true;
1,777
157
1,934
<no_super_class>