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
|
|---|---|---|---|---|---|---|---|---|---|
oracle_opengrok
|
opengrok/suggester/src/main/java/org/opengrok/suggest/query/customized/PhrasePositions.java
|
PhrasePositions
|
nextPosition
|
class PhrasePositions {
int position; // position in doc
int count; // remaining pos in this doc
int offset; // position in phrase
final int ord; // unique across all PhrasePositions instances
final PostingsEnum postings; // stream of docs & positions
int rptGroup = -1; // >=0 indicates that this is a repeating PP
int rptInd; // index in the rptGroup
final Term[] terms; // for repetitions initialization
PhrasePositions(PostingsEnum postings, int o, int ord, Term[] terms) {
this.postings = postings;
offset = o;
this.ord = ord;
this.terms = terms;
}
void firstPosition() throws IOException {
count = postings.freq(); // read first pos
nextPosition();
}
/**
* Go to next location of this term current document, and set
* <code>position</code> as <code>location - offset</code>, so that a
* matching exact phrase is easily identified when all PhrasePositions
* have exactly the same <code>position</code>.
*/
boolean nextPosition() throws IOException {<FILL_FUNCTION_BODY>}
/** for debug purposes */
@Override
public String toString() {
String s = "o:"+offset+" p:"+position+" c:"+count;
if (rptGroup >=0 ) {
s += " rpt:"+rptGroup+",i"+rptInd;
}
return s;
}
}
|
if (count-- > 0) { // read subsequent pos's
position = postings.nextPosition() - offset;
return true;
} else {
return false;
}
| 399
| 51
| 450
|
<no_super_class>
|
oracle_opengrok
|
opengrok/suggester/src/main/java/org/opengrok/suggest/query/customized/PhraseQueue.java
|
PhraseQueue
|
lessThan
|
class PhraseQueue extends PriorityQueue<PhrasePositions> {
PhraseQueue(int size) {
super(size);
}
@Override
protected boolean lessThan(PhrasePositions pp1, PhrasePositions pp2) {<FILL_FUNCTION_BODY>}
}
|
if (pp1.position == pp2.position) {
// same doc and pp.position, so decide by actual term positions.
// rely on: pp.position == tp.position - offset.
if (pp1.offset == pp2.offset) {
return pp1.ord < pp2.ord;
} else {
return pp1.offset < pp2.offset;
}
} else {
return pp1.position < pp2.position;
}
| 78
| 122
| 200
|
<no_super_class>
|
oracle_opengrok
|
opengrok/suggester/src/main/java/org/opengrok/suggest/util/Progress.java
|
Progress
|
getLevel
|
class Progress implements AutoCloseable {
private final Logger logger;
private final Long totalCount;
private final String suffix;
private final AtomicLong currentCount = new AtomicLong();
private final Map<Level, Integer> levelCountMap = new TreeMap<>(Comparator.comparingInt(Level::intValue).reversed());
private Thread loggerThread = null;
private volatile boolean run;
private final Level baseLogLevel;
private final Object sync = new Object();
/**
* @param logger logger instance
* @param suffix string suffix to identify the operation
* @param totalCount total count
* @param logLevel base log level
* @param isPrintProgress whether to print the progress
*/
public Progress(Logger logger, String suffix, long totalCount, Level logLevel, boolean isPrintProgress) {
this.logger = logger;
this.suffix = suffix;
this.baseLogLevel = logLevel;
if (totalCount < 0) {
this.totalCount = null;
} else {
this.totalCount = totalCount;
}
// Note: Level.CONFIG is missing as it does not make too much sense for progress reporting semantically.
final List<Level> standardLevels = Arrays.asList(Level.OFF, Level.SEVERE, Level.WARNING, Level.INFO,
Level.FINE, Level.FINER, Level.FINEST, Level.ALL);
int[] num = new int[]{100, 50, 10, 1};
for (int i = standardLevels.indexOf(baseLogLevel), j = 0;
i < standardLevels.size() && j < num.length; i++, j++) {
Level level = standardLevels.get(i);
levelCountMap.put(level, num[j]);
}
// Assuming the printProgress configuration setting cannot be changed on the fly.
if (!baseLogLevel.equals(Level.OFF) && isPrintProgress) {
spawnLogThread();
}
}
private void spawnLogThread() {
// spawn a logger thread.
run = true;
loggerThread = new Thread(this::logLoop,
"progress-thread-" + suffix.replace(" ", "_"));
loggerThread.start();
}
/**
* Increment counter. The actual logging will be done eventually.
*/
public void increment() {
this.currentCount.incrementAndGet();
if (loggerThread != null) {
// nag the thread.
synchronized (sync) {
sync.notifyAll();
}
}
}
private void logLoop() {
long cachedCount = 0;
Map<Level, Long> lastLoggedChunk = new HashMap<>();
while (true) {
long longCurrentCount = this.currentCount.get();
Level currentLevel = Level.FINEST;
// Do not log if there was no progress.
if (cachedCount < longCurrentCount) {
currentLevel = getLevel(lastLoggedChunk, longCurrentCount, currentLevel);
logIt(lastLoggedChunk, longCurrentCount, currentLevel);
}
if (!run) {
return;
}
cachedCount = longCurrentCount;
// wait for event
try {
synchronized (sync) {
if (!run) {
// Loop once more to do the final logging.
continue;
}
sync.wait();
}
} catch (InterruptedException e) {
logger.log(Level.WARNING, "logger thread interrupted");
}
}
}
@VisibleForTesting
Level getLevel(Map<Level, Long> lastLoggedChunk, long currentCount, Level currentLevel) {<FILL_FUNCTION_BODY>}
private void logIt(Map<Level, Long> lastLoggedChunk, long currentCount, Level currentLevel) {
if (logger.isLoggable(currentLevel)) {
lastLoggedChunk.put(currentLevel, currentCount / levelCountMap.get(currentLevel));
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Progress: ");
stringBuilder.append(currentCount);
stringBuilder.append(" ");
if (totalCount != null) {
stringBuilder.append("(");
stringBuilder.append(String.format("%.2f", currentCount * 100.0f / totalCount));
stringBuilder.append("%) ");
}
stringBuilder.append(suffix);
logger.log(currentLevel, stringBuilder.toString());
}
}
@Override
public void close() {
if (loggerThread == null) {
return;
}
try {
run = false;
synchronized (sync) {
sync.notifyAll();
}
loggerThread.join();
} catch (InterruptedException e) {
logger.log(Level.WARNING, "logger thread interrupted");
}
}
}
|
// The intention is to log the initial and final count at the base log level.
if (currentCount <= 1 || (totalCount != null && currentCount == totalCount)) {
currentLevel = baseLogLevel;
} else {
// Set the log level based on the "buckets".
for (var levelCountItem : levelCountMap.entrySet()) {
if (lastLoggedChunk.getOrDefault(levelCountItem.getKey(), -1L) <
currentCount / levelCountItem.getValue()) {
currentLevel = levelCountItem.getKey();
break;
}
}
}
return currentLevel;
| 1,249
| 160
| 1,409
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/SystemInfo.java
|
SystemInfo
|
createOperatingSystem
|
class SystemInfo {
// The platform isn't going to change, and making this static enables easy
// access from outside this class
private static final PlatformEnum CURRENT_PLATFORM = PlatformEnum.getValue(Platform.getOSType());
private static final String NOT_SUPPORTED = "Operating system not supported: ";
private final Supplier<OperatingSystem> os = memoize(SystemInfo::createOperatingSystem);
private final Supplier<HardwareAbstractionLayer> hardware = memoize(SystemInfo::createHardware);
/**
* Create a new instance of {@link SystemInfo}. This is the main entry point to OSHI and provides access to
* cross-platform code.
* <p>
* Platform-specific Hardware and Software objects are retrieved via memoized suppliers. To conserve memory at the
* cost of additional processing time, create a new version of SystemInfo() for subsequent calls. To conserve
* processing time at the cost of additional memory usage, re-use the same {@link SystemInfo} object for future
* queries.
*/
public SystemInfo() {
// Intentionally empty, here to enable the constructor javadoc.
}
/**
* Gets the {@link PlatformEnum} value representing this system.
*
* @return Returns the current platform
*/
public static PlatformEnum getCurrentPlatform() {
return CURRENT_PLATFORM;
}
/**
* Creates a new instance of the appropriate platform-specific {@link oshi.software.os.OperatingSystem}.
*
* @return A new instance of {@link oshi.software.os.OperatingSystem}.
*/
public OperatingSystem getOperatingSystem() {
return os.get();
}
private static OperatingSystem createOperatingSystem() {<FILL_FUNCTION_BODY>}
/**
* Creates a new instance of the appropriate platform-specific {@link oshi.hardware.HardwareAbstractionLayer}.
*
* @return A new instance of {@link oshi.hardware.HardwareAbstractionLayer}.
*/
public HardwareAbstractionLayer getHardware() {
return hardware.get();
}
private static HardwareAbstractionLayer createHardware() {
switch (CURRENT_PLATFORM) {
case WINDOWS:
return new WindowsHardwareAbstractionLayer();
case LINUX:
case ANDROID:
return new LinuxHardwareAbstractionLayer();
case MACOS:
return new MacHardwareAbstractionLayer();
case SOLARIS:
return new SolarisHardwareAbstractionLayer();
case FREEBSD:
return new FreeBsdHardwareAbstractionLayer();
case AIX:
return new AixHardwareAbstractionLayer();
case OPENBSD:
return new OpenBsdHardwareAbstractionLayer();
default:
throw new UnsupportedOperationException(NOT_SUPPORTED + CURRENT_PLATFORM.getName());
}
}
}
|
switch (CURRENT_PLATFORM) {
case WINDOWS:
return new WindowsOperatingSystem();
case LINUX:
case ANDROID:
return new LinuxOperatingSystem();
case MACOS:
return new MacOperatingSystem();
case SOLARIS:
return new SolarisOperatingSystem();
case FREEBSD:
return new FreeBsdOperatingSystem();
case AIX:
return new AixOperatingSystem();
case OPENBSD:
return new OpenBsdOperatingSystem();
default:
throw new UnsupportedOperationException(NOT_SUPPORTED + CURRENT_PLATFORM.getName());
}
| 755
| 172
| 927
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/linux/Devicetree.java
|
Devicetree
|
queryModel
|
class Devicetree {
private Devicetree() {
}
/**
* Query the model from the devicetree
*
* @return The model if available, null otherwise
*/
public static String queryModel() {<FILL_FUNCTION_BODY>}
}
|
String modelStr = FileUtil.getStringFromFile(SysPath.MODEL);
if (!modelStr.isEmpty()) {
return modelStr.replace("Machine: ", "");
}
return null;
| 77
| 54
| 131
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/linux/Dmidecode.java
|
Dmidecode
|
queryUUID
|
class Dmidecode {
private Dmidecode() {
}
// $ sudo dmidecode -t bios
// # dmidecode 2.11
// SMBIOS 2.4 present.
//
// Handle 0x0000, DMI type 0, 24 bytes
// BIOS Information
// Vendor: Phoenix Technologies LTD
// Version: 6.00
// Release Date: 07/02/2015
// Address: 0xEA5E0
// Runtime Size: 88608 bytes
// ROM Size: 64 kB
// Characteristics:
// ISA is supported
// PCI is supported
// PC Card (PCMCIA) is supported
// PNP is supported
// APM is supported
// BIOS is upgradeable
// BIOS shadowing is allowed
// ESCD support is available
// Boot from CD is supported
// Selectable boot is supported
// EDD is supported
// Print screen service is supported (int 5h)
// 8042 keyboard services are supported (int 9h)
// Serial services are supported (int 14h)
// Printer services are supported (int 17h)
// CGA/mono video services are supported (int 10h)
// ACPI is supported
// Smart battery is supported
// BIOS boot specification is supported
// Function key-initiated network boot is supported
// Targeted content distribution is supported
// BIOS Revision: 4.6
// Firmware Revision: 0.0
/**
* Query the serial number from dmidecode
*
* @return The serial number if available, null otherwise
*/
public static String querySerialNumber() {
// If root privileges this will work
if (UserGroupInfo.isElevated()) {
String marker = "Serial Number:";
for (String checkLine : ExecutingCommand.runNative("dmidecode -t system")) {
if (checkLine.contains(marker)) {
return checkLine.split(marker)[1].trim();
}
}
}
return null;
}
/**
* Query the UUID from dmidecode
*
* @return The UUID if available, null otherwise
*/
public static String queryUUID() {<FILL_FUNCTION_BODY>}
/**
* Query the name and revision from dmidecode
*
* @return The a pair containing the name and revision if available, null values in the pair otherwise
*/
public static Pair<String, String> queryBiosNameRev() {
String biosName = null;
String revision = null;
// Requires root, may not return anything
if (UserGroupInfo.isElevated()) {
final String biosMarker = "SMBIOS";
final String revMarker = "Bios Revision:";
for (final String checkLine : ExecutingCommand.runNative("dmidecode -t bios")) {
if (checkLine.contains(biosMarker)) {
String[] biosArr = ParseUtil.whitespaces.split(checkLine);
if (biosArr.length >= 2) {
biosName = biosArr[0] + " " + biosArr[1];
}
}
if (checkLine.contains(revMarker)) {
revision = checkLine.split(revMarker)[1].trim();
// SMBIOS should be first line so if we're here we are done iterating
break;
}
}
}
return new Pair<>(biosName, revision);
}
}
|
// If root privileges this will work
if (UserGroupInfo.isElevated()) {
String marker = "UUID:";
for (String checkLine : ExecutingCommand.runNative("dmidecode -t system")) {
if (checkLine.contains(marker)) {
return checkLine.split(marker)[1].trim();
}
}
}
return null;
| 921
| 100
| 1,021
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/linux/Lshal.java
|
Lshal
|
queryUUID
|
class Lshal {
private Lshal() {
}
/**
* Query the serial number from lshal
*
* @return The serial number if available, null otherwise
*/
public static String querySerialNumber() {
// if lshal command available (HAL deprecated in newer linuxes)
String marker = "system.hardware.serial =";
for (String checkLine : ExecutingCommand.runNative("lshal")) {
if (checkLine.contains(marker)) {
return ParseUtil.getSingleQuoteStringValue(checkLine);
}
}
return null;
}
/**
* Query the UUID from lshal
*
* @return The UUID if available, null otherwise
*/
public static String queryUUID() {<FILL_FUNCTION_BODY>}
}
|
// if lshal command available (HAL deprecated in newer linuxes)
String marker = "system.hardware.uuid =";
for (String checkLine : ExecutingCommand.runNative("lshal")) {
if (checkLine.contains(marker)) {
return ParseUtil.getSingleQuoteStringValue(checkLine);
}
}
return null;
| 208
| 95
| 303
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/linux/Lshw.java
|
Lshw
|
queryCpuCapacity
|
class Lshw {
private Lshw() {
}
private static final String MODEL;
private static final String SERIAL;
private static final String UUID;
static {
String model = null;
String serial = null;
String uuid = null;
if (UserGroupInfo.isElevated()) {
String modelMarker = "product:";
String serialMarker = "serial:";
String uuidMarker = "uuid:";
for (String checkLine : ExecutingCommand.runNative("lshw -C system")) {
if (checkLine.contains(modelMarker)) {
model = checkLine.split(modelMarker)[1].trim();
} else if (checkLine.contains(serialMarker)) {
serial = checkLine.split(serialMarker)[1].trim();
} else if (checkLine.contains(uuidMarker)) {
uuid = checkLine.split(uuidMarker)[1].trim();
}
}
}
MODEL = model;
SERIAL = serial;
UUID = uuid;
}
/**
* Query the model from lshw
*
* @return The model if available, null otherwise
*/
public static String queryModel() {
return MODEL;
}
/**
* Query the serial number from lshw
*
* @return The serial number if available, null otherwise
*/
public static String querySerialNumber() {
return SERIAL;
}
/**
* Query the UUID from lshw
*
* @return The UUID if available, null otherwise
*/
public static String queryUUID() {
return UUID;
}
/**
* Query the CPU capacity (max frequency) from lshw
*
* @return The CPU capacity (max frequency) if available, -1 otherwise
*/
public static long queryCpuCapacity() {<FILL_FUNCTION_BODY>}
}
|
String capacityMarker = "capacity:";
for (String checkLine : ExecutingCommand.runNative("lshw -class processor")) {
if (checkLine.contains(capacityMarker)) {
return ParseUtil.parseHertz(checkLine.split(capacityMarker)[1].trim());
}
}
return -1L;
| 490
| 89
| 579
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/linux/Sysfs.java
|
Sysfs
|
queryProductModel
|
class Sysfs {
private Sysfs() {
}
/**
* Query the vendor from sysfs
*
* @return The vendor if available, null otherwise
*/
public static String querySystemVendor() {
final String sysVendor = FileUtil.getStringFromFile(SysPath.DMI_ID + "sys_vendor").trim();
if (!sysVendor.isEmpty()) {
return sysVendor;
}
return null;
}
/**
* Query the model from sysfs
*
* @return The model if available, null otherwise
*/
public static String queryProductModel() {<FILL_FUNCTION_BODY>}
/**
* Query the product serial number from sysfs
*
* @return The serial number if available, null otherwise
*/
public static String queryProductSerial() {
// These sysfs files accessible by root, or can be chmod'd at boot time
// to enable access without root
String serial = FileUtil.getStringFromFile(SysPath.DMI_ID + "product_serial");
if (!serial.isEmpty() && !"None".equals(serial)) {
return serial;
}
return queryBoardSerial();
}
/**
* Query the UUID from sysfs
*
* @return The UUID if available, null otherwise
*/
public static String queryUUID() {
// These sysfs files accessible by root, or can be chmod'd at boot time
// to enable access without root
String uuid = FileUtil.getStringFromFile(SysPath.DMI_ID + "product_uuid");
if (!uuid.isEmpty() && !"None".equals(uuid)) {
return uuid;
}
return null;
}
/**
* Query the board vendor from sysfs
*
* @return The board vendor if available, null otherwise
*/
public static String queryBoardVendor() {
final String boardVendor = FileUtil.getStringFromFile(SysPath.DMI_ID + "board_vendor").trim();
if (!boardVendor.isEmpty()) {
return boardVendor;
}
return null;
}
/**
* Query the board model from sysfs
*
* @return The board model if available, null otherwise
*/
public static String queryBoardModel() {
final String boardName = FileUtil.getStringFromFile(SysPath.DMI_ID + "board_name").trim();
if (!boardName.isEmpty()) {
return boardName;
}
return null;
}
/**
* Query the board version from sysfs
*
* @return The board version if available, null otherwise
*/
public static String queryBoardVersion() {
final String boardVersion = FileUtil.getStringFromFile(SysPath.DMI_ID + "board_version").trim();
if (!boardVersion.isEmpty()) {
return boardVersion;
}
return null;
}
/**
* Query the board serial number from sysfs
*
* @return The board serial number if available, null otherwise
*/
public static String queryBoardSerial() {
final String boardSerial = FileUtil.getStringFromFile(SysPath.DMI_ID + "board_serial").trim();
if (!boardSerial.isEmpty()) {
return boardSerial;
}
return null;
}
/**
* Query the bios vendor from sysfs
*
* @return The bios vendor if available, null otherwise
*/
public static String queryBiosVendor() {
final String biosVendor = FileUtil.getStringFromFile(SysPath.DMI_ID + "bios_vendor").trim();
if (biosVendor.isEmpty()) {
return biosVendor;
}
return null;
}
/**
* Query the bios description from sysfs
*
* @return The bios description if available, null otherwise
*/
public static String queryBiosDescription() {
final String modalias = FileUtil.getStringFromFile(SysPath.DMI_ID + "modalias").trim();
if (!modalias.isEmpty()) {
return modalias;
}
return null;
}
/**
* Query the bios version from sysfs
*
* @param biosRevision A revision string to append
* @return The bios version if available, null otherwise
*/
public static String queryBiosVersion(String biosRevision) {
final String biosVersion = FileUtil.getStringFromFile(SysPath.DMI_ID + "bios_version").trim();
if (!biosVersion.isEmpty()) {
return biosVersion + (Util.isBlank(biosRevision) ? "" : " (revision " + biosRevision + ")");
}
return null;
}
/**
* Query the bios release date from sysfs
*
* @return The bios release date if available, null otherwise
*/
public static String queryBiosReleaseDate() {
final String biosDate = FileUtil.getStringFromFile(SysPath.DMI_ID + "bios_date").trim();
if (!biosDate.isEmpty()) {
return ParseUtil.parseMmDdYyyyToYyyyMmDD(biosDate);
}
return null;
}
}
|
final String productName = FileUtil.getStringFromFile(SysPath.DMI_ID + "product_name").trim();
final String productVersion = FileUtil.getStringFromFile(SysPath.DMI_ID + "product_version").trim();
if (productName.isEmpty()) {
if (!productVersion.isEmpty()) {
return productVersion;
}
} else {
if (!productVersion.isEmpty() && !"None".equals(productVersion)) {
return productName + " (version: " + productVersion + ")";
}
return productName;
}
return null;
| 1,348
| 151
| 1,499
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/linux/Who.java
|
Who
|
queryUtxent
|
class Who {
private static final LinuxLibc LIBC = LinuxLibc.INSTANCE;
private Who() {
}
/**
* Query {@code getutxent} to get logged in users.
*
* @return A list of logged in user sessions
*/
public static synchronized List<OSSession> queryUtxent() {<FILL_FUNCTION_BODY>}
}
|
List<OSSession> whoList = new ArrayList<>();
LinuxUtmpx ut;
// Rewind
LIBC.setutxent();
try {
// Iterate
while ((ut = LIBC.getutxent()) != null) {
if (ut.ut_type == USER_PROCESS || ut.ut_type == LOGIN_PROCESS) {
String user = Native.toString(ut.ut_user, Charset.defaultCharset());
String device = Native.toString(ut.ut_line, Charset.defaultCharset());
String host = ParseUtil.parseUtAddrV6toIP(ut.ut_addr_v6);
long loginTime = ut.ut_tv.tv_sec * 1000L + ut.ut_tv.tv_usec / 1000L;
// Sanity check. If errors, default to who command line
if (!isSessionValid(user, device, loginTime)) {
return oshi.driver.unix.Who.queryWho();
}
whoList.add(new OSSession(user, device, loginTime, host));
}
}
} finally {
// Close
LIBC.endutxent();
}
return whoList;
| 104
| 317
| 421
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/linux/proc/Auxv.java
|
Auxv
|
queryAuxv
|
class Auxv {
private Auxv() {
}
public static final int AT_PAGESZ = 6; // system page size
public static final int AT_HWCAP = 16; // arch dependent hints at CPU capabilities
public static final int AT_CLKTCK = 17; // frequency at which times() increments
/**
* Retrieve the auxiliary vector for the current process
*
* @return A map of auxiliary vector keys to their respective values
* @see <a href= "https://github.com/torvalds/linux/blob/v3.19/include/uapi/linux/auxvec.h">auxvec.h</a>
*/
public static Map<Integer, Long> queryAuxv() {<FILL_FUNCTION_BODY>}
}
|
ByteBuffer buff = FileUtil.readAllBytesAsBuffer(ProcPath.AUXV);
Map<Integer, Long> auxvMap = new HashMap<>();
int key;
do {
key = FileUtil.readNativeLongFromBuffer(buff).intValue();
if (key > 0) {
auxvMap.put(key, FileUtil.readNativeLongFromBuffer(buff).longValue());
}
} while (key > 0);
return auxvMap;
| 202
| 123
| 325
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/linux/proc/CpuInfo.java
|
CpuInfo
|
queryBoardInfo
|
class CpuInfo {
private CpuInfo() {
}
/**
* Gets the CPU manufacturer from {@code /proc/cpuinfo}
*
* @return The manufacturer if known, null otherwise
*/
public static String queryCpuManufacturer() {
List<String> cpuInfo = FileUtil.readFile(CPUINFO);
for (String line : cpuInfo) {
if (line.startsWith("CPU implementer")) {
int part = ParseUtil.parseLastInt(line, 0);
switch (part) {
case 0x41:
return "ARM";
case 0x42:
return "Broadcom";
case 0x43:
return "Cavium";
case 0x44:
return "DEC";
case 0x4e:
return "Nvidia";
case 0x50:
return "APM";
case 0x51:
return "Qualcomm";
case 0x53:
return "Samsung";
case 0x56:
return "Marvell";
case 0x66:
return "Faraday";
case 0x69:
return "Intel";
default:
return null;
}
}
}
return null;
}
/**
* Gets the board manufacturer, model, version, and serial number from {@code /proc/cpuinfo}
*
* @return A quartet of strings for manufacturer, model, version, and serial number. Each one may be null if
* unknown.
*/
public static Quartet<String, String, String, String> queryBoardInfo() {<FILL_FUNCTION_BODY>}
private static String queryBoardManufacturer(char digit) {
switch (digit) {
case '0':
return "Sony UK";
case '1':
return "Egoman";
case '2':
return "Embest";
case '3':
return "Sony Japan";
case '4':
return "Embest";
case '5':
return "Stadium";
default:
return Constants.UNKNOWN;
}
}
public static List<String> queryFeatureFlags() {
return FileUtil.readFile(CPUINFO).stream().filter(f -> {
String s = f.toLowerCase(Locale.ROOT);
return s.startsWith("flags") || s.startsWith("features");
}).distinct().collect(Collectors.toList());
}
}
|
String pcManufacturer = null;
String pcModel = null;
String pcVersion = null;
String pcSerialNumber = null;
List<String> cpuInfo = FileUtil.readFile(CPUINFO);
for (String line : cpuInfo) {
String[] splitLine = ParseUtil.whitespacesColonWhitespace.split(line);
if (splitLine.length < 2) {
continue;
}
switch (splitLine[0]) {
case "Hardware":
pcModel = splitLine[1];
break;
case "Revision":
pcVersion = splitLine[1];
if (pcVersion.length() > 1) {
pcManufacturer = queryBoardManufacturer(pcVersion.charAt(1));
}
break;
case "Serial":
pcSerialNumber = splitLine[1];
break;
default:
// Do nothing
}
}
return new Quartet<>(pcManufacturer, pcModel, pcVersion, pcSerialNumber);
| 667
| 262
| 929
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/linux/proc/CpuStat.java
|
CpuStat
|
getSystemCpuLoadTicks
|
class CpuStat {
private CpuStat() {
}
/**
* Gets the System CPU ticks array from {@code /proc/stat}
*
* @return Array of CPU ticks
*/
public static long[] getSystemCpuLoadTicks() {<FILL_FUNCTION_BODY>}
/**
* Gets an arrya of Processor CPU ticks array from /proc/stat
*
* @param logicalProcessorCount The number of logical processors, which corresponds to the number of lines to read
* from the file.
* @return Array of CPU ticks for each processor
*/
public static long[][] getProcessorCpuLoadTicks(int logicalProcessorCount) {
long[][] ticks = new long[logicalProcessorCount][TickType.values().length];
// /proc/stat expected format
// first line is overall user,nice,system,idle, etc.
// cpu 3357 0 4313 1362393 ...
// per-processor subsequent lines for cpu0, cpu1, etc.
int cpu = 0;
List<String> procStat = FileUtil.readFile(ProcPath.STAT);
for (String stat : procStat) {
if (stat.startsWith("cpu") && !stat.startsWith("cpu ")) {
// Split the line. Note the first (0) element is "cpu" so
// remaining
// elements are offset by 1 from the enum index
String[] tickArr = ParseUtil.whitespaces.split(stat);
if (tickArr.length <= TickType.IDLE.getIndex()) {
// If ticks don't at least go user/nice/system/idle, abort
return ticks;
}
// Note tickArr is offset by 1
for (int i = 0; i < TickType.values().length; i++) {
ticks[cpu][i] = ParseUtil.parseLongOrDefault(tickArr[i + 1], 0L);
}
// Ignore guest or guest_nice, they are included in
if (++cpu >= logicalProcessorCount) {
break;
}
}
}
return ticks;
}
/**
* Gets the number of context switches from /proc/stat
*
* @return The number of context switches if available, -1 otherwise
*/
public static long getContextSwitches() {
List<String> procStat = FileUtil.readFile(ProcPath.STAT);
for (String stat : procStat) {
if (stat.startsWith("ctxt ")) {
String[] ctxtArr = ParseUtil.whitespaces.split(stat);
if (ctxtArr.length == 2) {
return ParseUtil.parseLongOrDefault(ctxtArr[1], 0);
}
}
}
return 0L;
}
/**
* Gets the number of interrupts from /proc/stat
*
* @return The number of interrupts if available, -1 otherwise
*/
public static long getInterrupts() {
List<String> procStat = FileUtil.readFile(ProcPath.STAT);
for (String stat : procStat) {
if (stat.startsWith("intr ")) {
String[] intrArr = ParseUtil.whitespaces.split(stat);
if (intrArr.length > 2) {
return ParseUtil.parseLongOrDefault(intrArr[1], 0);
}
}
}
return 0L;
}
/**
* Gets the boot time from /proc/stat
*
* @return The boot time if available, 0 otherwise
*/
public static long getBootTime() {
// Boot time given by btime variable in /proc/stat.
List<String> procStat = FileUtil.readFile(ProcPath.STAT);
for (String stat : procStat) {
if (stat.startsWith("btime")) {
String[] bTime = ParseUtil.whitespaces.split(stat);
return ParseUtil.parseLongOrDefault(bTime[1], 0L);
}
}
return 0;
}
}
|
long[] ticks = new long[TickType.values().length];
// /proc/stat expected format
// first line is overall user,nice,system,idle,iowait,irq, etc.
// cpu 3357 0 4313 1362393 ...
String tickStr;
List<String> procStat = FileUtil.readLines(ProcPath.STAT, 1);
if (procStat.isEmpty()) {
return ticks;
}
tickStr = procStat.get(0);
// Split the line. Note the first (0) element is "cpu" so remaining
// elements are offset by 1 from the enum index
String[] tickArr = ParseUtil.whitespaces.split(tickStr);
if (tickArr.length <= TickType.IDLE.getIndex()) {
// If ticks don't at least go user/nice/system/idle, abort
return ticks;
}
// Note tickArr is offset by 1 because first element is "cpu"
for (int i = 0; i < TickType.values().length; i++) {
ticks[i] = ParseUtil.parseLongOrDefault(tickArr[i + 1], 0L);
}
// Ignore guest or guest_nice, they are included in user/nice
return ticks;
| 1,086
| 357
| 1,443
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/linux/proc/DiskStats.java
|
DiskStats
|
getDiskStats
|
class DiskStats {
/**
* Enum corresponding to the fields in the output of {@code /proc/diskstats}
*/
public enum IoStat {
/**
* The device major number.
*/
MAJOR,
/**
* The device minor number.
*/
MINOR,
/**
* The device name.
*/
NAME,
/**
* The total number of reads completed successfully.
*/
READS,
/**
* Reads which are adjacent to each other merged for efficiency.
*/
READS_MERGED,
/**
* The total number of sectors read successfully.
*/
READS_SECTOR,
/**
* The total number of milliseconds spent by all reads.
*/
READS_MS,
/**
* The total number of writes completed successfully.
*/
WRITES,
/**
* Writes which are adjacent to each other merged for efficiency.
*/
WRITES_MERGED,
/**
* The total number of sectors written successfully.
*/
WRITES_SECTOR,
/**
* The total number of milliseconds spent by all writes.
*/
WRITES_MS,
/**
* Incremented as requests are given to appropriate struct request_queue and decremented as they finish.
*/
IO_QUEUE_LENGTH,
/**
* The total number of milliseconds spent doing I/Os.
*/
IO_MS,
/**
* Incremented at each I/O start, I/O completion, I/O merge, or read of these stats by the number of I/Os in
* progress {@link #IO_QUEUE_LENGTH} times the number of milliseconds spent doing I/O since the last update of
* this field.
*/
IO_MS_WEIGHTED,
/**
* The total number of discards completed successfully.
*/
DISCARDS,
/**
* Discards which are adjacent to each other merged for efficiency.
*/
DISCARDS_MERGED,
/**
* The total number of sectors discarded successfully.
*/
DISCARDS_SECTOR,
/**
* The total number of milliseconds spent by all discards.
*/
DISCARDS_MS,
/**
* The total number of flush requests completed successfully.
*/
FLUSHES,
/**
* The total number of milliseconds spent by all flush requests.
*/
FLUSHES_MS;
}
private DiskStats() {
}
/**
* Reads the statistics in {@code /proc/diskstats} and returns the results.
*
* @return A map with each disk's name as the key, and an EnumMap as the value, where the numeric values in
* {@link IoStat} are mapped to a {@link Long} value.
*/
public static Map<String, Map<IoStat, Long>> getDiskStats() {<FILL_FUNCTION_BODY>}
}
|
Map<String, Map<IoStat, Long>> diskStatMap = new HashMap<>();
IoStat[] enumArray = IoStat.class.getEnumConstants();
List<String> diskStats = FileUtil.readFile(ProcPath.DISKSTATS);
for (String stat : diskStats) {
String[] split = ParseUtil.whitespaces.split(stat.trim());
Map<IoStat, Long> statMap = new EnumMap<>(IoStat.class);
String name = null;
for (int i = 0; i < enumArray.length && i < split.length; i++) {
if (enumArray[i] == IoStat.NAME) {
name = split[i];
} else {
statMap.put(enumArray[i], ParseUtil.parseLongOrDefault(split[i], 0L));
}
}
if (name != null) {
diskStatMap.put(name, statMap);
}
}
return diskStatMap;
| 777
| 256
| 1,033
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/linux/proc/UpTime.java
|
UpTime
|
getSystemUptimeSeconds
|
class UpTime {
private UpTime() {
}
/**
* Parses the first value in {@code /proc/uptime} for seconds since boot
*
* @return Seconds since boot
*/
public static double getSystemUptimeSeconds() {<FILL_FUNCTION_BODY>}
}
|
String uptime = FileUtil.getStringFromFile(ProcPath.UPTIME);
int spaceIndex = uptime.indexOf(' ');
if (spaceIndex < 0) {
// No space, error
return 0d;
}
return ParseUtil.parseDoubleOrDefault(uptime.substring(0, spaceIndex), 0d);
| 85
| 90
| 175
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/mac/ThreadInfo.java
|
ThreadInfo
|
queryTaskThreads
|
class ThreadInfo {
private static final Pattern PS_M = Pattern.compile(
"\\D+(\\d+).+(\\d+\\.\\d)\\s+(\\w)\\s+(\\d+)\\D+(\\d+:\\d{2}\\.\\d{2})\\s+(\\d+:\\d{2}\\.\\d{2}).+");
private ThreadInfo() {
}
public static List<ThreadStats> queryTaskThreads(int pid) {<FILL_FUNCTION_BODY>}
/**
* Class to encapsulate mach thread info
*/
@Immutable
public static class ThreadStats {
private final int threadId;
private final long userTime;
private final long systemTime;
private final long upTime;
private final State state;
private final int priority;
public ThreadStats(int tid, double cpu, char state, long sTime, long uTime, int pri) {
this.threadId = tid;
this.userTime = uTime;
this.systemTime = sTime;
// user + system / uptime = cpu/100
// so: uptime = user+system / cpu/100
this.upTime = (long) ((uTime + sTime) / (cpu / 100d + 0.0005));
switch (state) {
case 'I':
case 'S':
this.state = SLEEPING;
break;
case 'U':
this.state = WAITING;
break;
case 'R':
this.state = RUNNING;
break;
case 'Z':
this.state = ZOMBIE;
break;
case 'T':
this.state = STOPPED;
break;
default:
this.state = OTHER;
break;
}
this.priority = pri;
}
/**
* @return the threadId
*/
public int getThreadId() {
return threadId;
}
/**
* @return the userTime
*/
public long getUserTime() {
return userTime;
}
/**
* @return the systemTime
*/
public long getSystemTime() {
return systemTime;
}
/**
* @return the upTime
*/
public long getUpTime() {
return upTime;
}
/**
* @return the state
*/
public State getState() {
return state;
}
/**
* @return the priority
*/
public int getPriority() {
return priority;
}
}
}
|
String pidStr = " " + pid + " ";
List<ThreadStats> taskThreads = new ArrayList<>();
// Only way to get thread info without root permissions
// Using the M switch gives all threads with no possibility to filter
List<String> psThread = ExecutingCommand.runNative("ps -awwxM").stream().filter(s -> s.contains(pidStr))
.collect(Collectors.toList());
int tid = 0;
for (String thread : psThread) {
Matcher m = PS_M.matcher(thread);
if (m.matches() && pid == ParseUtil.parseIntOrDefault(m.group(1), -1)) {
double cpu = ParseUtil.parseDoubleOrDefault(m.group(2), 0d);
char state = m.group(3).charAt(0);
int pri = ParseUtil.parseIntOrDefault(m.group(4), 0);
long sTime = ParseUtil.parseDHMSOrDefault(m.group(5), 0L);
long uTime = ParseUtil.parseDHMSOrDefault(m.group(6), 0L);
taskThreads.add(new ThreadStats(tid++, cpu, state, sTime, uTime, pri));
}
}
return taskThreads;
| 685
| 331
| 1,016
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/mac/Who.java
|
Who
|
queryUtxent
|
class Who {
private static final SystemB SYS = SystemB.INSTANCE;
private Who() {
}
/**
* Query {@code getutxent} to get logged in users.
*
* @return A list of logged in user sessions
*/
public static synchronized List<OSSession> queryUtxent() {<FILL_FUNCTION_BODY>}
}
|
List<OSSession> whoList = new ArrayList<>();
MacUtmpx ut;
// Rewind
SYS.setutxent();
try { // Iterate
while ((ut = SYS.getutxent()) != null) {
if (ut.ut_type == USER_PROCESS || ut.ut_type == LOGIN_PROCESS) {
String user = Native.toString(ut.ut_user, StandardCharsets.US_ASCII);
String device = Native.toString(ut.ut_line, StandardCharsets.US_ASCII);
String host = Native.toString(ut.ut_host, StandardCharsets.US_ASCII);
long loginTime = ut.ut_tv.tv_sec.longValue() * 1000L + ut.ut_tv.tv_usec / 1000L;
// Sanity check. If errors, default to who command line
if (!isSessionValid(user, device, loginTime)) {
return oshi.driver.unix.Who.queryWho();
}
whoList.add(new OSSession(user, device, loginTime, host));
}
}
} finally {
// Close
SYS.endutxent();
}
return whoList;
| 102
| 323
| 425
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/mac/WindowInfo.java
|
WindowInfo
|
queryDesktopWindows
|
class WindowInfo {
private WindowInfo() {
}
/**
* Gets windows on the operating system's GUI desktop.
*
* @param visibleOnly Whether to restrict the list to only windows visible to the user.
* @return A list of {@link oshi.software.os.OSDesktopWindow} objects representing the desktop windows.
*/
public static List<OSDesktopWindow> queryDesktopWindows(boolean visibleOnly) {<FILL_FUNCTION_BODY>}
}
|
CFArrayRef windowInfo = CoreGraphics.INSTANCE.CGWindowListCopyWindowInfo(
visibleOnly ? kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements
: kCGWindowListOptionAll,
kCGNullWindowID);
int numWindows = windowInfo.getCount();
// Prepare a list to return
List<OSDesktopWindow> windowList = new ArrayList<>();
// Set up keys for dictionary lookup
CFStringRef kCGWindowIsOnscreen = CFStringRef.createCFString("kCGWindowIsOnscreen");
CFStringRef kCGWindowNumber = CFStringRef.createCFString("kCGWindowNumber");
CFStringRef kCGWindowOwnerPID = CFStringRef.createCFString("kCGWindowOwnerPID");
CFStringRef kCGWindowLayer = CFStringRef.createCFString("kCGWindowLayer");
CFStringRef kCGWindowBounds = CFStringRef.createCFString("kCGWindowBounds");
CFStringRef kCGWindowName = CFStringRef.createCFString("kCGWindowName");
CFStringRef kCGWindowOwnerName = CFStringRef.createCFString("kCGWindowOwnerName");
try {
// Populate the list
for (int i = 0; i < numWindows; i++) {
// For each array element, get the dictionary
Pointer result = windowInfo.getValueAtIndex(i);
CFDictionaryRef windowRef = new CFDictionaryRef(result);
// Now get information from the dictionary.
result = windowRef.getValue(kCGWindowIsOnscreen); // Optional key, check for null
boolean visible = result == null || new CFBooleanRef(result).booleanValue();
if (!visibleOnly || visible) {
result = windowRef.getValue(kCGWindowNumber); // kCFNumberSInt64Type
long windowNumber = new CFNumberRef(result).longValue();
result = windowRef.getValue(kCGWindowOwnerPID); // kCFNumberSInt64Type
long windowOwnerPID = new CFNumberRef(result).longValue();
result = windowRef.getValue(kCGWindowLayer); // kCFNumberIntType
int windowLayer = new CFNumberRef(result).intValue();
result = windowRef.getValue(kCGWindowBounds);
try (CGRect rect = new CGRect()) {
CoreGraphics.INSTANCE.CGRectMakeWithDictionaryRepresentation(new CFDictionaryRef(result), rect);
Rectangle windowBounds = new Rectangle(FormatUtil.roundToInt(rect.origin.x),
FormatUtil.roundToInt(rect.origin.y), FormatUtil.roundToInt(rect.size.width),
FormatUtil.roundToInt(rect.size.height));
// Note: the Quartz name returned by this field is rarely used
result = windowRef.getValue(kCGWindowName); // Optional key, check for null
String windowName = CFUtil.cfPointerToString(result, false);
// This is the program running the window, use as name if name blank or add in
// parenthesis
result = windowRef.getValue(kCGWindowOwnerName); // Optional key, check for null
String windowOwnerName = CFUtil.cfPointerToString(result, false);
if (windowName.isEmpty()) {
windowName = windowOwnerName;
} else {
windowName = windowName + "(" + windowOwnerName + ")";
}
windowList.add(new OSDesktopWindow(windowNumber, windowName, windowOwnerName, windowBounds,
windowOwnerPID, windowLayer, visible));
}
}
}
} finally {
// CF references from "Copy" or "Create" must be released
kCGWindowIsOnscreen.release();
kCGWindowNumber.release();
kCGWindowOwnerPID.release();
kCGWindowLayer.release();
kCGWindowBounds.release();
kCGWindowName.release();
kCGWindowOwnerName.release();
windowInfo.release();
}
return windowList;
| 121
| 974
| 1,095
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/mac/disk/Fsstat.java
|
Fsstat
|
queryPartitionToMountMap
|
class Fsstat {
private Fsstat() {
}
/**
* Query fsstat to map partitions to mount points
*
* @return A map with partitions as the key and mount points as the value
*/
public static Map<String, String> queryPartitionToMountMap() {<FILL_FUNCTION_BODY>}
private static int queryFsstat(Statfs[] buf, int bufsize, int flags) {
return SystemB.INSTANCE.getfsstat64(buf, bufsize, flags);
}
}
|
Map<String, String> mountPointMap = new HashMap<>();
// Use statfs to get size of mounted file systems
int numfs = queryFsstat(null, 0, 0);
// Get data on file system
Statfs s = new Statfs();
// Create array to hold results
Statfs[] fs = (Statfs[]) s.toArray(numfs);
// Write file system data to array
queryFsstat(fs, numfs * fs[0].size(), SystemB.MNT_NOWAIT);
// Iterate all mounted file systems
for (Statfs f : fs) {
String mntFrom = Native.toString(f.f_mntfromname, StandardCharsets.UTF_8);
mountPointMap.put(mntFrom.replace("/dev/", ""), Native.toString(f.f_mntonname, StandardCharsets.UTF_8));
}
return mountPointMap;
| 139
| 233
| 372
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/mac/net/NetStat.java
|
NetStat
|
queryIFdata
|
class NetStat {
private static final Logger LOG = LoggerFactory.getLogger(NetStat.class);
private static final int CTL_NET = 4;
private static final int PF_ROUTE = 17;
private static final int NET_RT_IFLIST2 = 6;
private static final int RTM_IFINFO2 = 0x12;
private NetStat() {
}
/**
* Map data for network interfaces.
*
* @param index If positive, limit the map to only return data for this interface index. If negative, returns data
* for all indices.
*
* @return a map of {@link IFdata} object indexed by the interface index, encapsulating the stats
*/
public static Map<Integer, IFdata> queryIFdata(int index) {<FILL_FUNCTION_BODY>}
/**
* Class to encapsulate IF data for method return
*/
@Immutable
public static class IFdata {
private final int ifType;
private final long oPackets;
private final long iPackets;
private final long oBytes;
private final long iBytes;
private final long oErrors;
private final long iErrors;
private final long collisions;
private final long iDrops;
private final long speed;
private final long timeStamp;
IFdata(int ifType, // NOSONAR squid:S00107
long oPackets, long iPackets, long oBytes, long iBytes, long oErrors, long iErrors, long collisions,
long iDrops, long speed, long timeStamp) {
this.ifType = ifType;
this.oPackets = oPackets & 0xffffffffL;
this.iPackets = iPackets & 0xffffffffL;
this.oBytes = oBytes & 0xffffffffL;
this.iBytes = iBytes & 0xffffffffL;
this.oErrors = oErrors & 0xffffffffL;
this.iErrors = iErrors & 0xffffffffL;
this.collisions = collisions & 0xffffffffL;
this.iDrops = iDrops & 0xffffffffL;
this.speed = speed & 0xffffffffL;
this.timeStamp = timeStamp;
}
/**
* @return the ifType
*/
public int getIfType() {
return ifType;
}
/**
* @return the oPackets
*/
public long getOPackets() {
return oPackets;
}
/**
* @return the iPackets
*/
public long getIPackets() {
return iPackets;
}
/**
* @return the oBytes
*/
public long getOBytes() {
return oBytes;
}
/**
* @return the iBytes
*/
public long getIBytes() {
return iBytes;
}
/**
* @return the oErrors
*/
public long getOErrors() {
return oErrors;
}
/**
* @return the iErrors
*/
public long getIErrors() {
return iErrors;
}
/**
* @return the collisions
*/
public long getCollisions() {
return collisions;
}
/**
* @return the iDrops
*/
public long getIDrops() {
return iDrops;
}
/**
* @return the speed
*/
public long getSpeed() {
return speed;
}
/**
* @return the timeStamp
*/
public long getTimeStamp() {
return timeStamp;
}
}
}
|
// Ported from source code of "netstat -ir". See
// https://opensource.apple.com/source/network_cmds/network_cmds-457/netstat.tproj/if.c
Map<Integer, IFdata> data = new HashMap<>();
// Get buffer of all interface information
int[] mib = { CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST2, 0 };
try (CloseableSizeTByReference len = new CloseableSizeTByReference()) {
if (0 != SystemB.INSTANCE.sysctl(mib, 6, null, len, null, size_t.ZERO)) {
LOG.error("Didn't get buffer length for IFLIST2");
return data;
}
try (Memory buf = new Memory(len.longValue())) {
if (0 != SystemB.INSTANCE.sysctl(mib, 6, buf, len, null, size_t.ZERO)) {
LOG.error("Didn't get buffer for IFLIST2");
return data;
}
final long now = System.currentTimeMillis();
// Iterate offset from buf's pointer up to limit of buf
int lim = (int) (buf.size() - new IFmsgHdr().size());
int offset = 0;
while (offset < lim) {
// Get pointer to current native part of buf
Pointer p = buf.share(offset);
// Cast pointer to if_msghdr
IFmsgHdr ifm = new IFmsgHdr(p);
ifm.read();
// Advance next
offset += ifm.ifm_msglen;
// Skip messages which are not the right format
if (ifm.ifm_type == RTM_IFINFO2) {
// Cast pointer to if_msghdr2
IFmsgHdr2 if2m = new IFmsgHdr2(p);
if2m.read();
if (index < 0 || index == if2m.ifm_index) {
data.put((int) if2m.ifm_index,
new IFdata(0xff & if2m.ifm_data.ifi_type, if2m.ifm_data.ifi_opackets,
if2m.ifm_data.ifi_ipackets, if2m.ifm_data.ifi_obytes,
if2m.ifm_data.ifi_ibytes, if2m.ifm_data.ifi_oerrors,
if2m.ifm_data.ifi_ierrors, if2m.ifm_data.ifi_collisions,
if2m.ifm_data.ifi_iqdrops, if2m.ifm_data.ifi_baudrate, now));
if (index >= 0) {
return data;
}
}
}
}
}
}
return data;
| 963
| 737
| 1,700
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/Who.java
|
Who
|
matchUnix
|
class Who {
// sample format:
// oshi pts/0 2020-05-14 21:23 (192.168.1.23)
private static final Pattern WHO_FORMAT_LINUX = Pattern
.compile("(\\S+)\\s+(\\S+)\\s+(\\d{4}-\\d{2}-\\d{2})\\s+(\\d{2}:\\d{2})\\s*(?:\\((.+)\\))?");
private static final DateTimeFormatter WHO_DATE_FORMAT_LINUX = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm",
Locale.ROOT);
// oshi ttys000 May 4 23:50 (192.168.1.23)
// middle 12 characters from Thu Nov 24 18:22:48 1986
private static final Pattern WHO_FORMAT_UNIX = Pattern
.compile("(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\d+)\\s+(\\d{2}:\\d{2})\\s*(?:\\((.+)\\))?");
private static final DateTimeFormatter WHO_DATE_FORMAT_UNIX = new DateTimeFormatterBuilder()
.appendPattern("MMM d HH:mm").parseDefaulting(ChronoField.YEAR, Year.now(ZoneId.systemDefault()).getValue())
.toFormatter(Locale.US);
private Who() {
}
/**
* Query {@code who} to get logged in users
*
* @return A list of logged in user sessions
*/
public static synchronized List<OSSession> queryWho() {
List<OSSession> whoList = new ArrayList<>();
List<String> who = ExecutingCommand.runNative("who");
for (String s : who) {
boolean matched = false;
if (Platform.isLinux()) {
matched = matchLinux(whoList, s);
}
if (!matched) {
matchUnix(whoList, s);
}
}
return whoList;
}
/**
* Attempt to match Linux WHO format and add to the list
*
* @param whoList the list to add to
* @param s the string to match
* @return true if successful, false otherwise
*/
private static boolean matchLinux(List<OSSession> whoList, String s) {
Matcher m = WHO_FORMAT_LINUX.matcher(s);
if (m.matches()) {
try {
whoList.add(new OSSession(m.group(1), m.group(2),
LocalDateTime.parse(m.group(3) + " " + m.group(4), WHO_DATE_FORMAT_LINUX)
.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(),
m.group(5) == null ? Constants.UNKNOWN : m.group(5)));
return true;
} catch (DateTimeParseException | NullPointerException e) {
// shouldn't happen if regex matches and OS is producing sensible dates
}
}
return false;
}
/**
* Attempt to match Unix WHO format and add to the list
*
* @param whoList the list to add to
* @param s the string to match
* @return true if successful, false otherwise
*/
private static boolean matchUnix(List<OSSession> whoList, String s) {<FILL_FUNCTION_BODY>}
}
|
Matcher m = WHO_FORMAT_UNIX.matcher(s);
if (m.matches()) {
try {
// Missing year, parse date time with current year
LocalDateTime login = LocalDateTime.parse(m.group(3) + " " + m.group(4) + " " + m.group(5),
WHO_DATE_FORMAT_UNIX);
// If this date is in the future, subtract a year
if (login.isAfter(LocalDateTime.now(ZoneId.systemDefault()))) {
login = login.minus(1, ChronoUnit.YEARS);
}
long millis = login.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
whoList.add(new OSSession(m.group(1), m.group(2), millis, m.group(6) == null ? "" : m.group(6)));
return true;
} catch (DateTimeParseException | NullPointerException e) {
// shouldn't happen if regex matches and OS is producing sensible dates
}
}
return false;
| 920
| 275
| 1,195
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/Xrandr.java
|
Xrandr
|
getEdidArrays
|
class Xrandr {
private static final String[] XRANDR_VERBOSE = { "xrandr", "--verbose" };
private Xrandr() {
}
public static List<byte[]> getEdidArrays() {<FILL_FUNCTION_BODY>}
}
|
// Special handling for X commands, don't use LC_ALL
List<String> xrandr = ExecutingCommand.runNative(XRANDR_VERBOSE, null);
// xrandr reports edid in multiple lines. After seeing a line containing
// EDID, read subsequent lines of hex until 256 characters are reached
if (xrandr.isEmpty()) {
return Collections.emptyList();
}
List<byte[]> displays = new ArrayList<>();
StringBuilder sb = null;
for (String s : xrandr) {
if (s.contains("EDID")) {
sb = new StringBuilder();
} else if (sb != null) {
sb.append(s.trim());
if (sb.length() < 256) {
continue;
}
String edidStr = sb.toString();
byte[] edid = ParseUtil.hexStringToByteArray(edidStr);
if (edid.length >= 128) {
displays.add(edid);
}
sb = null;
}
}
return displays;
| 78
| 278
| 356
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/Xwininfo.java
|
Xwininfo
|
queryXWindows
|
class Xwininfo {
private static final String[] NET_CLIENT_LIST_STACKING = ParseUtil.whitespaces
.split("xprop -root _NET_CLIENT_LIST_STACKING");
private static final String[] XWININFO_ROOT_TREE = ParseUtil.whitespaces.split("xwininfo -root -tree");
private static final String[] XPROP_NET_WM_PID_ID = ParseUtil.whitespaces.split("xprop _NET_WM_PID -id");
private Xwininfo() {
}
/**
* Gets windows on the operating system's GUI desktop.
*
* @param visibleOnly Whether to restrict the list to only windows visible to the user.
* @return A list of {@link oshi.software.os.OSDesktopWindow} objects representing the desktop windows.
*/
public static List<OSDesktopWindow> queryXWindows(boolean visibleOnly) {<FILL_FUNCTION_BODY>}
private static long queryPidFromId(String id) {
// X commands don't work with LC_ALL
String[] cmd = new String[XPROP_NET_WM_PID_ID.length + 1];
System.arraycopy(XPROP_NET_WM_PID_ID, 0, cmd, 0, XPROP_NET_WM_PID_ID.length);
cmd[XPROP_NET_WM_PID_ID.length] = id;
List<String> pidStr = ExecutingCommand.runNative(cmd, null);
if (pidStr.isEmpty()) {
return 0;
}
return ParseUtil.getFirstIntValue(pidStr.get(0));
}
}
|
// Attempted to implement using native X11 code. However, this produced native X
// errors (e.g., BadValue) which cannot be caught on the Java side and
// terminated the thread. Using x command lines which execute in a separate
// process. Errors are caught by the terminal process and safely ignored.
// Get visible windows in their Z order. Assign 1 to bottom and increment.
// All other non visible windows will be assigned 0.
Map<String, Integer> zOrderMap = new HashMap<>();
int z = 0;
// X commands don't work with LC_ALL
List<String> stacking = ExecutingCommand.runNative(NET_CLIENT_LIST_STACKING, null);
if (!stacking.isEmpty()) {
String stack = stacking.get(0);
int bottom = stack.indexOf("0x");
if (bottom >= 0) {
for (String id : stack.substring(bottom).split(", ")) {
zOrderMap.put(id, ++z);
}
}
}
// Get all windows along with title and path info
Pattern windowPattern = Pattern.compile(
"(0x\\S+) (?:\"(.+)\")?.*: \\((?:\"(.+)\" \".+\")?\\) (\\d+)x(\\d+)\\+.+ \\+(-?\\d+)\\+(-?\\d+)");
Map<String, String> windowNameMap = new HashMap<>();
Map<String, String> windowPathMap = new HashMap<>();
// This map will include all the windows, preserve the insertion order
Map<String, Rectangle> windowMap = new LinkedHashMap<>();
// X commands don't work with LC_ALL
for (String line : ExecutingCommand.runNative(XWININFO_ROOT_TREE, null)) {
Matcher m = windowPattern.matcher(line.trim());
if (m.matches()) {
String id = m.group(1);
if (!visibleOnly || zOrderMap.containsKey(id)) {
String windowName = m.group(2);
if (!Util.isBlank(windowName)) {
windowNameMap.put(id, windowName);
}
String windowPath = m.group(3);
if (!Util.isBlank(windowPath)) {
windowPathMap.put(id, windowPath);
}
windowMap.put(id, new Rectangle(ParseUtil.parseIntOrDefault(m.group(6), 0),
ParseUtil.parseIntOrDefault(m.group(7), 0), ParseUtil.parseIntOrDefault(m.group(4), 0),
ParseUtil.parseIntOrDefault(m.group(5), 0)));
}
}
}
// Get info for each window
// Prepare a list to return
List<OSDesktopWindow> windowList = new ArrayList<>();
for (Entry<String, Rectangle> e : windowMap.entrySet()) {
String id = e.getKey();
long pid = queryPidFromId(id);
boolean visible = zOrderMap.containsKey(id);
windowList.add(new OSDesktopWindow(ParseUtil.hexStringToLong(id, 0L), windowNameMap.getOrDefault(id, ""),
windowPathMap.getOrDefault(id, ""), e.getValue(), pid, zOrderMap.getOrDefault(id, 0), visible));
}
return windowList;
| 425
| 875
| 1,300
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/aix/Ls.java
|
Ls
|
queryDeviceMajorMinor
|
class Ls {
private Ls() {
}
/**
* Query {@code ls} to get parition info
*
* @return A map of device name to a major-minor pair
*/
public static Map<String, Pair<Integer, Integer>> queryDeviceMajorMinor() {<FILL_FUNCTION_BODY>}
}
|
// Map major and minor from ls
/*-
$ ls -l /dev
brw-rw---- 1 root system 10, 5 Sep 12 2017 hd2
brw------- 1 root system 20, 0 Jun 28 1970 hdisk0
*/
Map<String, Pair<Integer, Integer>> majMinMap = new HashMap<>();
for (String s : ExecutingCommand.runNative("ls -l /dev")) {
// Filter to block devices
if (!s.isEmpty() && s.charAt(0) == 'b') {
// Device name is last space-delim string
int idx = s.lastIndexOf(' ');
if (idx > 0 && idx < s.length()) {
String device = s.substring(idx + 1);
int major = ParseUtil.getNthIntValue(s, 2);
int minor = ParseUtil.getNthIntValue(s, 3);
majMinMap.put(device, new Pair<>(major, minor));
}
}
}
return majMinMap;
| 93
| 283
| 376
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/aix/Lscfg.java
|
Lscfg
|
queryBackplaneModelSerialVersion
|
class Lscfg {
private Lscfg() {
}
/**
* Query {@code lscfg -vp} to get all hardware devices
*
* @return A list of the output
*/
public static List<String> queryAllDevices() {
return ExecutingCommand.runNative("lscfg -vp");
}
/**
* Parse the output of {@code lscfg -vp} to get backplane info
*
* @param lscfg The output of a previous call to {@code lscfg -vp}
* @return A triplet with backplane model, serial number, and version
*/
public static Triplet<String, String, String> queryBackplaneModelSerialVersion(List<String> lscfg) {<FILL_FUNCTION_BODY>}
/**
* Query {@code lscfg -vl device} to get hardware info
*
* @param device The disk to get the model and serial from
* @return A pair containing the model and serial number for the device, or null if not found
*/
public static Pair<String, String> queryModelSerial(String device) {
String modelMarker = "Machine Type and Model";
String serialMarker = "Serial Number";
String model = null;
String serial = null;
for (String s : ExecutingCommand.runNative("lscfg -vl " + device)) {
// Default model to description at end of first line
if (model == null && s.contains(device)) {
String locDesc = s.split(device)[1].trim();
int idx = locDesc.indexOf(' ');
if (idx > 0) {
model = locDesc.substring(idx).trim();
}
}
if (s.contains(modelMarker)) {
model = ParseUtil.removeLeadingDots(s.split(modelMarker)[1].trim());
} else if (s.contains(serialMarker)) {
serial = ParseUtil.removeLeadingDots(s.split(serialMarker)[1].trim());
}
}
return new Pair<>(model, serial);
}
}
|
final String planeMarker = "WAY BACKPLANE";
final String modelMarker = "Part Number";
final String serialMarker = "Serial Number";
final String versionMarker = "Version";
final String locationMarker = "Physical Location";
// 1 WAY BACKPLANE :
// Serial Number...............YL10243490FB
// Part Number.................80P4315
// Customer Card ID Number.....26F4
// CCIN Extender...............1
// FRU Number.................. 80P4315
// Version.....................RS6K
// Hardware Location Code......U0.1-P1
// Physical Location: U0.1-P1
String model = null;
String serialNumber = null;
String version = null;
boolean planeFlag = false;
for (final String checkLine : lscfg) {
if (!planeFlag && checkLine.contains(planeMarker)) {
planeFlag = true;
} else if (planeFlag) {
if (checkLine.contains(modelMarker)) {
model = ParseUtil.removeLeadingDots(checkLine.split(modelMarker)[1].trim());
} else if (checkLine.contains(serialMarker)) {
serialNumber = ParseUtil.removeLeadingDots(checkLine.split(serialMarker)[1].trim());
} else if (checkLine.contains(versionMarker)) {
version = ParseUtil.removeLeadingDots(checkLine.split(versionMarker)[1].trim());
} else if (checkLine.contains(locationMarker)) {
break;
}
}
}
return new Triplet<>(model, serialNumber, version);
| 534
| 433
| 967
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/aix/Lspv.java
|
Lspv
|
computeLogicalVolumes
|
class Lspv {
/**
* The lspv command incurs a lot of disk reads. Since partitions shouldn't change during operation, cache the result
* here.
*/
private static final Map<String, List<HWPartition>> PARTITION_CACHE = new ConcurrentHashMap<>();
private Lspv() {
}
/**
* Query {@code lspv} to get partition info, or return a cached value.
*
* @param device The disk to get the volumes from.
* @param majMinMap A map of device name to a pair with major and minor numbers.
*
* @return A list of logical volumes (partitions) on this device.
*/
public static List<HWPartition> queryLogicalVolumes(String device, Map<String, Pair<Integer, Integer>> majMinMap) {
return PARTITION_CACHE.computeIfAbsent(device,
d -> Collections.unmodifiableList(computeLogicalVolumes(d, majMinMap).stream()
.sorted(Comparator.comparing(HWPartition::getMinor).thenComparing(HWPartition::getName))
.collect(Collectors.toList())));
}
private static List<HWPartition> computeLogicalVolumes(String device,
Map<String, Pair<Integer, Integer>> majMinMap) {<FILL_FUNCTION_BODY>}
}
|
List<HWPartition> partitions = new ArrayList<>();
/*-
$ lspv -L hdisk0
PHYSICAL VOLUME: hdisk0 VOLUME GROUP: rootvg
PV IDENTIFIER: 000acfde95524f85 VG IDENTIFIER 000acfde00004c000000000395525276
PV STATE: active
STALE PARTITIONS: 0 ALLOCATABLE: yes
PP SIZE: 128 megabyte(s) LOGICAL VOLUMES: 12
TOTAL PPs: 271 (34688 megabytes) VG DESCRIPTORS: 2
FREE PPs: 227 (29056 megabytes) HOT SPARE: no
USED PPs: 44 (5632 megabytes) MAX REQUEST: 256 kilobytes
FREE DISTRIBUTION: 54..46..19..54..54
USED DISTRIBUTION: 01..08..35..00..00
*/
String stateMarker = "PV STATE:";
String sizeMarker = "PP SIZE:";
long ppSize = 0L; // All physical partitions are the same size
for (String s : ExecutingCommand.runNative("lspv -L " + device)) {
if (s.startsWith(stateMarker)) {
if (!s.contains("active")) {
return partitions;
}
} else if (s.contains(sizeMarker)) {
ppSize = ParseUtil.getFirstIntValue(s);
}
}
if (ppSize == 0L) {
return partitions;
}
// Convert to megabytes
ppSize <<= 20;
/*-
$ lspv -p hdisk0
hdisk0:
PP RANGE STATE REGION LV NAME TYPE MOUNT POINT
1-1 used outer edge hd5 boot N/A
2-55 free outer edge
56-59 used outer middle hd6 paging N/A
60-61 used outer middle livedump jfs2 /var/adm/ras/livedump
62-62 used outer middle loglv01 jfslog N/A
63-63 used outer middle lv01 jfs N/A
64-109 free outer middle
110-110 used center hd8 jfs2log N/A
111-112 used center hd4 jfs2 /
113-128 used center hd2 jfs2 /usr
129-131 used center hd9var jfs2 /var
132-132 used center hd3 jfs2 /tmp
133-133 used center hd9var jfs2 /var
134-136 used center hd10opt jfs2 /opt
137-137 used center hd11admin jfs2 /admin
138-140 used center hd2 jfs2 /usr
141-141 used center hd3 jfs2 /tmp
142-142 used center hd4 jfs2 /
143-143 used center hd9var jfs2 /var
144-144 used center hd2 jfs2 /usr
145-163 free center
164-217 free inner middle
218-271 free inner edge
*/
Map<String, String> mountMap = new HashMap<>();
Map<String, String> typeMap = new HashMap<>();
Map<String, Integer> ppMap = new HashMap<>();
for (String s : ExecutingCommand.runNative("lspv -p " + device)) {
String[] split = ParseUtil.whitespaces.split(s.trim());
if (split.length >= 6 && "used".equals(split[1])) {
// Region may have two words, so count from end
String name = split[split.length - 3];
mountMap.put(name, split[split.length - 1]);
typeMap.put(name, split[split.length - 2]);
int ppCount = 1 + ParseUtil.getNthIntValue(split[0], 2) - ParseUtil.getNthIntValue(split[0], 1);
ppMap.put(name, ppCount + ppMap.getOrDefault(name, 0));
}
}
for (Entry<String, String> entry : mountMap.entrySet()) {
String mount = "N/A".equals(entry.getValue()) ? "" : entry.getValue();
// All maps should have same keys
String name = entry.getKey();
String type = typeMap.get(name);
long size = ppSize * ppMap.get(name);
Pair<Integer, Integer> majMin = majMinMap.get(name);
int major = majMin == null ? ParseUtil.getFirstIntValue(name) : majMin.getA();
int minor = majMin == null ? ParseUtil.getFirstIntValue(name) : majMin.getB();
partitions.add(new HWPartition(name, name, type, "", size, major, minor, mount));
}
return partitions;
| 353
| 1,493
| 1,846
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/aix/Lssrad.java
|
Lssrad
|
queryNodesPackages
|
class Lssrad {
private Lssrad() {
}
/**
* Query {@code lssrad} to get numa node and physical package info
*
* @return A map of processor number to a pair containing the ref (NUMA equivalent) and srad (package)
*/
public static Map<Integer, Pair<Integer, Integer>> queryNodesPackages() {<FILL_FUNCTION_BODY>}
}
|
/*-
# lssrad -av
REF1 SRAD MEM CPU
0
0 32749.12 0-63
1 9462.00 64-67 72-75
80-83 88-91
1
2 2471.19 92-95
2
3 1992.00
4 249.00
*/
int node = 0;
int slot = 0;
Map<Integer, Pair<Integer, Integer>> nodeMap = new HashMap<>();
List<String> lssrad = ExecutingCommand.runNative("lssrad -av");
// remove header
if (!lssrad.isEmpty()) {
lssrad.remove(0);
}
for (String s : lssrad) {
String t = s.trim();
if (!t.isEmpty()) {
if (Character.isDigit(s.charAt(0))) {
node = ParseUtil.parseIntOrDefault(t, 0);
} else {
if (t.contains(".")) {
String[] split = ParseUtil.whitespaces.split(t, 3);
slot = ParseUtil.parseIntOrDefault(split[0], 0);
t = split.length > 2 ? split[2] : "";
}
for (Integer proc : ParseUtil.parseHyphenatedIntList(t)) {
nodeMap.put(proc, new Pair<>(node, slot));
}
}
}
}
return nodeMap;
| 110
| 418
| 528
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/aix/Uptime.java
|
Uptime
|
queryUpTime
|
class Uptime {
private static final long MINUTE_MS = 60L * 1000L;
private static final long HOUR_MS = 60L * MINUTE_MS;
private static final long DAY_MS = 24L * HOUR_MS;
// sample format:
// 18:36pm up 10 days 8:11, 2 users, load average: 3.14, 2.74, 2.41
private static final Pattern UPTIME_FORMAT_AIX = Pattern
.compile(".*\\sup\\s+((\\d+)\\s+days?,?\\s+)?\\b((\\d+):)?(\\d+)(\\s+min(utes?)?)?,\\s+\\d+\\s+user.+"); // NOSONAR:squid:S5843
private Uptime() {
}
/**
* Query {@code uptime} to get up time
*
* @return Up time in milliseconds
*/
public static long queryUpTime() {<FILL_FUNCTION_BODY>}
}
|
long uptime = 0L;
String s = ExecutingCommand.getFirstAnswer("uptime");
if (s.isEmpty()) {
s = ExecutingCommand.getFirstAnswer("w");
}
if (s.isEmpty()) {
s = ExecutingCommand.getFirstAnswer("/usr/bin/uptime");
}
Matcher m = UPTIME_FORMAT_AIX.matcher(s);
if (m.matches()) {
if (m.group(2) != null) {
uptime += ParseUtil.parseLongOrDefault(m.group(2), 0L) * DAY_MS;
}
if (m.group(4) != null) {
uptime += ParseUtil.parseLongOrDefault(m.group(4), 0L) * HOUR_MS;
}
uptime += ParseUtil.parseLongOrDefault(m.group(5), 0L) * MINUTE_MS;
}
return uptime;
| 286
| 253
| 539
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/aix/Who.java
|
Who
|
queryBootTime
|
class Who {
// sample format:
// system boot 2020-06-16 09:12
private static final Pattern BOOT_FORMAT_AIX = Pattern.compile("\\D+(\\d{4}-\\d{2}-\\d{2})\\s+(\\d{2}:\\d{2}).*");
private static final DateTimeFormatter BOOT_DATE_FORMAT_AIX = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm",
Locale.ROOT);
private Who() {
}
/**
* Query {@code who -b} to get boot time
*
* @return Boot time in milliseconds since the epoch
*/
public static long queryBootTime() {<FILL_FUNCTION_BODY>}
}
|
String s = ExecutingCommand.getFirstAnswer("who -b");
if (s.isEmpty()) {
s = ExecutingCommand.getFirstAnswer("/usr/bin/who -b");
}
Matcher m = BOOT_FORMAT_AIX.matcher(s);
if (m.matches()) {
try {
return LocalDateTime.parse(m.group(1) + " " + m.group(2), BOOT_DATE_FORMAT_AIX)
.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
} catch (DateTimeParseException | NullPointerException e) {
// Shouldn't happen with regex matching
}
}
return 0L;
| 204
| 182
| 386
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatConfig.java
|
PerfstatConfig
|
queryConfig
|
class PerfstatConfig {
private static final Perfstat PERF = Perfstat.INSTANCE;
private PerfstatConfig() {
}
/**
* Queries perfstat_partition_config for config
*
* @return usage statistics
*/
public static perfstat_partition_config_t queryConfig() {<FILL_FUNCTION_BODY>}
}
|
perfstat_partition_config_t config = new perfstat_partition_config_t();
int ret = PERF.perfstat_partition_config(null, config, config.size(), 1);
if (ret > 0) {
return config;
}
return new perfstat_partition_config_t();
| 99
| 82
| 181
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatCpu.java
|
PerfstatCpu
|
queryCpu
|
class PerfstatCpu {
private static final Perfstat PERF = Perfstat.INSTANCE;
private PerfstatCpu() {
}
/**
* Queries perfstat_cpu_total for total CPU usage statistics
*
* @return usage statistics
*/
public static perfstat_cpu_total_t queryCpuTotal() {
perfstat_cpu_total_t cpu = new perfstat_cpu_total_t();
int ret = PERF.perfstat_cpu_total(null, cpu, cpu.size(), 1);
if (ret > 0) {
return cpu;
}
return new perfstat_cpu_total_t();
}
/**
* Queries perfstat_cpu for per-CPU usage statistics
*
* @return an array of usage statistics
*/
public static perfstat_cpu_t[] queryCpu() {<FILL_FUNCTION_BODY>}
/**
* Returns affinity mask from the number of CPU in the OS.
*
* @return affinity mask
*/
public static long queryCpuAffinityMask() {
int cpus = queryCpuTotal().ncpus;
if (cpus < 63) {
return (1L << cpus) - 1;
}
return cpus == 63 ? Long.MAX_VALUE : -1L;
}
}
|
perfstat_cpu_t cpu = new perfstat_cpu_t();
// With null, null, ..., 0, returns total # of elements
int cputotal = PERF.perfstat_cpu(null, null, cpu.size(), 0);
if (cputotal > 0) {
perfstat_cpu_t[] statp = (perfstat_cpu_t[]) cpu.toArray(cputotal);
perfstat_id_t firstcpu = new perfstat_id_t(); // name is ""
int ret = PERF.perfstat_cpu(firstcpu, statp, cpu.size(), cputotal);
if (ret > 0) {
return statp;
}
}
return new perfstat_cpu_t[0];
| 356
| 197
| 553
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatDisk.java
|
PerfstatDisk
|
queryDiskStats
|
class PerfstatDisk {
private static final Perfstat PERF = Perfstat.INSTANCE;
private PerfstatDisk() {
}
/**
* Queries perfstat_disk for per-disk usage statistics
*
* @return an array of usage statistics
*/
public static perfstat_disk_t[] queryDiskStats() {<FILL_FUNCTION_BODY>}
}
|
perfstat_disk_t diskStats = new perfstat_disk_t();
// With null, null, ..., 0, returns total # of elements
int total = PERF.perfstat_disk(null, null, diskStats.size(), 0);
if (total > 0) {
perfstat_disk_t[] statp = (perfstat_disk_t[]) diskStats.toArray(total);
perfstat_id_t firstdiskStats = new perfstat_id_t(); // name is ""
int ret = PERF.perfstat_disk(firstdiskStats, statp, diskStats.size(), total);
if (ret > 0) {
return statp;
}
}
return new perfstat_disk_t[0];
| 104
| 191
| 295
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatMemory.java
|
PerfstatMemory
|
queryMemoryTotal
|
class PerfstatMemory {
private static final Perfstat PERF = Perfstat.INSTANCE;
private PerfstatMemory() {
}
/**
* Queries perfstat_memory_total for total memory usage statistics
*
* @return usage statistics
*/
public static perfstat_memory_total_t queryMemoryTotal() {<FILL_FUNCTION_BODY>}
}
|
perfstat_memory_total_t memory = new perfstat_memory_total_t();
int ret = PERF.perfstat_memory_total(null, memory, memory.size(), 1);
if (ret > 0) {
return memory;
}
return new perfstat_memory_total_t();
| 103
| 82
| 185
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatNetInterface.java
|
PerfstatNetInterface
|
queryNetInterfaces
|
class PerfstatNetInterface {
private static final Perfstat PERF = Perfstat.INSTANCE;
private PerfstatNetInterface() {
}
/**
* Queries perfstat_netinterface for per-netinterface usage statistics
*
* @return an array of usage statistics
*/
public static perfstat_netinterface_t[] queryNetInterfaces() {<FILL_FUNCTION_BODY>}
}
|
perfstat_netinterface_t netinterface = new perfstat_netinterface_t();
// With null, null, ..., 0, returns total # of elements
int total = PERF.perfstat_netinterface(null, null, netinterface.size(), 0);
if (total > 0) {
perfstat_netinterface_t[] statp = (perfstat_netinterface_t[]) netinterface.toArray(total);
perfstat_id_t firstnetinterface = new perfstat_id_t(); // name is ""
int ret = PERF.perfstat_netinterface(firstnetinterface, statp, netinterface.size(), total);
if (ret > 0) {
return statp;
}
}
return new perfstat_netinterface_t[0];
| 110
| 198
| 308
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcess.java
|
PerfstatProcess
|
queryProcesses
|
class PerfstatProcess {
private static final Perfstat PERF = Perfstat.INSTANCE;
private PerfstatProcess() {
}
/**
* Queries perfstat_process for per-process usage statistics
*
* @return an array of usage statistics
*/
public static perfstat_process_t[] queryProcesses() {<FILL_FUNCTION_BODY>}
}
|
perfstat_process_t process = new perfstat_process_t();
// With null, null, ..., 0, returns total # of elements
int procCount = PERF.perfstat_process(null, null, process.size(), 0);
if (procCount > 0) {
perfstat_process_t[] proct = (perfstat_process_t[]) process.toArray(procCount);
perfstat_id_t firstprocess = new perfstat_id_t(); // name is ""
int ret = PERF.perfstat_process(firstprocess, proct, process.size(), procCount);
if (ret > 0) {
return Arrays.copyOf(proct, ret);
}
}
return new perfstat_process_t[0];
| 104
| 197
| 301
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProtocol.java
|
PerfstatProtocol
|
queryProtocols
|
class PerfstatProtocol {
private static final Perfstat PERF = Perfstat.INSTANCE;
private PerfstatProtocol() {
}
/**
* Queries perfstat_protocol for per-protocol usage statistics
*
* @return an array of usage statistics
*/
public static perfstat_protocol_t[] queryProtocols() {<FILL_FUNCTION_BODY>}
}
|
perfstat_protocol_t protocol = new perfstat_protocol_t();
// With null, null, ..., 0, returns total # of elements
int total = PERF.perfstat_protocol(null, null, protocol.size(), 0);
if (total > 0) {
perfstat_protocol_t[] statp = (perfstat_protocol_t[]) protocol.toArray(total);
perfstat_id_t firstprotocol = new perfstat_id_t(); // name is ""
int ret = PERF.perfstat_protocol(firstprotocol, statp, protocol.size(), total);
if (ret > 0) {
return statp;
}
}
return new perfstat_protocol_t[0];
| 105
| 185
| 290
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/freebsd/Who.java
|
Who
|
queryUtxent
|
class Who {
private static final FreeBsdLibc LIBC = FreeBsdLibc.INSTANCE;
private Who() {
}
/**
* Query {@code getutxent} to get logged in users.
*
* @return A list of logged in user sessions
*/
public static synchronized List<OSSession> queryUtxent() {<FILL_FUNCTION_BODY>}
}
|
List<OSSession> whoList = new ArrayList<>();
FreeBsdUtmpx ut;
// Rewind
LIBC.setutxent();
try {
// Iterate
while ((ut = LIBC.getutxent()) != null) {
if (ut.ut_type == USER_PROCESS || ut.ut_type == LOGIN_PROCESS) {
String user = Native.toString(ut.ut_user, StandardCharsets.US_ASCII);
String device = Native.toString(ut.ut_line, StandardCharsets.US_ASCII);
String host = Native.toString(ut.ut_host, StandardCharsets.US_ASCII);
long loginTime = ut.ut_tv.tv_sec * 1000L + ut.ut_tv.tv_usec / 1000L;
// Sanity check. If errors, default to who command line
if (!isSessionValid(user, device, loginTime)) {
return oshi.driver.unix.Who.queryWho();
}
whoList.add(new OSSession(user, device, loginTime, host));
}
}
} finally {
// Close
LIBC.endutxent();
}
return whoList;
| 108
| 323
| 431
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/freebsd/disk/GeomDiskList.java
|
GeomDiskList
|
queryDisks
|
class GeomDiskList {
private static final String GEOM_DISK_LIST = "geom disk list";
private GeomDiskList() {
}
/**
* Queries disk data using geom
*
* @return A map with disk name as the key and a Triplet of model, serial, and size as the value
*/
public static Map<String, Triplet<String, String, Long>> queryDisks() {<FILL_FUNCTION_BODY>}
}
|
// Map of device name to disk, to be returned
Map<String, Triplet<String, String, Long>> diskMap = new HashMap<>();
// Parameters needed.
String diskName = null; // Non-null identifies a valid partition
String descr = Constants.UNKNOWN;
String ident = Constants.UNKNOWN;
long mediaSize = 0L;
List<String> geom = ExecutingCommand.runNative(GEOM_DISK_LIST);
for (String line : geom) {
line = line.trim();
// Marks the DiskStore device
if (line.startsWith("Geom name:")) {
// Save any previous disk in the map
if (diskName != null) {
diskMap.put(diskName, new Triplet<>(descr, ident, mediaSize));
descr = Constants.UNKNOWN;
ident = Constants.UNKNOWN;
mediaSize = 0L;
}
// Now use new diskName
diskName = line.substring(line.lastIndexOf(' ') + 1);
}
// If we don't have a valid store, don't bother parsing anything
if (diskName != null) {
line = line.trim();
if (line.startsWith("Mediasize:")) {
String[] split = ParseUtil.whitespaces.split(line);
if (split.length > 1) {
mediaSize = ParseUtil.parseLongOrDefault(split[1], 0L);
}
}
if (line.startsWith("descr:")) {
descr = line.replace("descr:", "").trim();
}
if (line.startsWith("ident:")) {
ident = line.replace("ident:", "").replace("(null)", "").trim();
}
}
}
if (diskName != null) {
diskMap.put(diskName, new Triplet<>(descr, ident, mediaSize));
}
return diskMap;
| 125
| 518
| 643
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/freebsd/disk/GeomPartList.java
|
GeomPartList
|
queryPartitions
|
class GeomPartList {
private static final String GEOM_PART_LIST = "geom part list";
private static final String STAT_FILESIZE = "stat -f %i /dev/";
private GeomPartList() {
}
/**
* Queries partition data using geom, mount, and stat commands
*
* @return A map with disk name as the key and a List of partitions as the value
*/
public static Map<String, List<HWPartition>> queryPartitions() {<FILL_FUNCTION_BODY>}
}
|
Map<String, String> mountMap = Mount.queryPartitionToMountMap();
// Map of device name to partitions, to be returned
Map<String, List<HWPartition>> partitionMap = new HashMap<>();
// The Disk Store associated with a partition, key to the map
String diskName = null;
// List to hold partitions, will be added as value to the map
List<HWPartition> partList = new ArrayList<>();
// Parameters needed for constructor.
String partName = null; // Non-null identifies a valid partition
String identification = Constants.UNKNOWN;
String type = Constants.UNKNOWN;
String uuid = Constants.UNKNOWN;
long size = 0;
String mountPoint = "";
List<String> geom = ExecutingCommand.runNative(GEOM_PART_LIST);
for (String line : geom) {
line = line.trim();
// Marks the DiskStore device for a partition.
if (line.startsWith("Geom name:")) {
// Save any previous partition list in the map
if (diskName != null && !partList.isEmpty()) {
// Store map (old diskName)
partitionMap.put(diskName, partList);
// Reset the list
partList = new ArrayList<>();
}
// Now use new diskName
diskName = line.substring(line.lastIndexOf(' ') + 1);
}
// If we don't have a valid store, don't bother parsing anything
if (diskName != null) {
// Marks the beginning of partition data
if (line.contains("Name:")) {
// Add the current partition to the list, if any
if (partName != null) {
// FreeBSD Major # is 0.
// Minor # is filesize of /dev entry.
int minor = ParseUtil
.parseIntOrDefault(ExecutingCommand.getFirstAnswer(STAT_FILESIZE + partName), 0);
partList.add(new HWPartition(identification, partName, type, uuid, size, 0, minor, mountPoint));
partName = null;
identification = Constants.UNKNOWN;
type = Constants.UNKNOWN;
uuid = Constants.UNKNOWN;
size = 0;
}
// Verify new entry is a partition
// (will happen in 'providers' section)
String part = line.substring(line.lastIndexOf(' ') + 1);
if (part.startsWith(diskName)) {
partName = part;
identification = part;
mountPoint = mountMap.getOrDefault(part, "");
}
}
// If we don't have a valid partition, don't parse anything until we do.
if (partName != null) {
String[] split = ParseUtil.whitespaces.split(line);
if (split.length >= 2) {
if (line.startsWith("Mediasize:")) {
size = ParseUtil.parseLongOrDefault(split[1], 0L);
} else if (line.startsWith("rawuuid:")) {
uuid = split[1];
} else if (line.startsWith("type:")) {
type = split[1];
}
}
}
}
}
if (diskName != null) {
// Process last partition
if (partName != null) {
int minor = ParseUtil.parseIntOrDefault(ExecutingCommand.getFirstAnswer(STAT_FILESIZE + partName), 0);
partList.add(new HWPartition(identification, partName, type, uuid, size, 0, minor, mountPoint));
}
// Process last diskstore
if (!partList.isEmpty()) {
partList = partList.stream().sorted(Comparator.comparing(HWPartition::getName))
.collect(Collectors.toList());
partitionMap.put(diskName, partList);
}
}
return partitionMap;
| 140
| 1,022
| 1,162
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/freebsd/disk/Mount.java
|
Mount
|
queryPartitionToMountMap
|
class Mount {
private static final String MOUNT_CMD = "mount";
private static final Pattern MOUNT_PATTERN = Pattern.compile("/dev/(\\S+p\\d+) on (\\S+) .*");
private Mount() {
}
/**
* Query mount to map partitions to mount points
*
* @return A map with partitions as the key and mount points as the value
*/
public static Map<String, String> queryPartitionToMountMap() {<FILL_FUNCTION_BODY>}
}
|
// Parse 'mount' to map partitions to mount point
Map<String, String> mountMap = new HashMap<>();
for (String mnt : ExecutingCommand.runNative(MOUNT_CMD)) {
Matcher m = MOUNT_PATTERN.matcher(mnt);
if (m.matches()) {
mountMap.put(m.group(1), m.group(2));
}
}
return mountMap;
| 139
| 114
| 253
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/openbsd/disk/Disklabel.java
|
Disklabel
|
getDiskParams
|
class Disklabel {
private Disklabel() {
}
/**
* Gets disk and partition information
*
* @param diskName The disk to fetch partition information from
* @return A quartet containing the disk's name/label, DUID, size, and a list of partitions
*/
public static Quartet<String, String, Long, List<HWPartition>> getDiskParams(String diskName) {<FILL_FUNCTION_BODY>}
private static Quartet<String, String, Long, List<HWPartition>> getDiskParamsNoRoot(String diskName) {
List<HWPartition> partitions = new ArrayList<>();
for (String line : ExecutingCommand.runNative("df")) {
if (line.startsWith("/dev/" + diskName)) {
String[] split = ParseUtil.whitespaces.split(line);
String name = split[0].substring(5 + diskName.length());
Pair<Integer, Integer> majorMinor = getMajorMinor(diskName, name);
if (split.length > 5) {
long partSize = ParseUtil.parseLongOrDefault(split[1], 1L) * 512L;
partitions.add(new HWPartition(split[0], split[0].substring(5), Constants.UNKNOWN,
Constants.UNKNOWN, partSize, majorMinor.getA(), majorMinor.getB(), split[5]));
}
}
}
return new Quartet<>(Constants.UNKNOWN, Constants.UNKNOWN, 0L, partitions);
}
private static Pair<Integer, Integer> getMajorMinor(String diskName, String name) {
int major = 0;
int minor = 0;
String majorMinor = ExecutingCommand.getFirstAnswer("stat -f %Hr,%Lr /dev/" + diskName + name);
int comma = majorMinor.indexOf(',');
if (comma > 0 && comma < majorMinor.length()) {
major = ParseUtil.parseIntOrDefault(majorMinor.substring(0, comma), 0);
minor = ParseUtil.parseIntOrDefault(majorMinor.substring(comma + 1), 0);
}
return new Pair<>(major, minor);
}
}
|
// disklabel (requires root) supports 15 configurable partitions, `a' through
// `p', excluding `c'.
// The `c' partition describes the entire physical disk.
// By convention, the `a' partition of the boot disk is the root
// partition, and the `b' partition of the boot disk is the swap partition,
// and the 'i' partition is usually the boot record
// Create a list for all the other partitions
List<HWPartition> partitions = new ArrayList<>();
// Save some values to return to the caller to populate HWDiskStore values
String totalMarker = "total sectors:";
long totalSectors = 1L;
String bpsMarker = "bytes/sector:";
int bytesPerSector = 1;
String labelMarker = "label:";
String label = "";
String duidMarker = "duid:";
String duid = "";
for (String line : ExecutingCommand.runNative("disklabel -n " + diskName)) {
// Check for values in the header we need for the HWDiskstore
// # /dev/rsd1c:
// type: SCSI
// disk: SCSI disk
// label: Storage Device
// duid: 0000000000000000
// flags:
// bytes/sector: 512
// sectors/track: 63
// tracks/cylinder: 255
// sectors/cylinder: 16065
// cylinders: 976
// total sectors: 15693824
// boundstart: 0
// boundend: 15693824
// drivedata: 0
if (line.contains(totalMarker)) {
totalSectors = ParseUtil.getFirstIntValue(line);
} else if (line.contains(bpsMarker)) {
bytesPerSector = ParseUtil.getFirstIntValue(line);
} else if (line.contains(labelMarker)) {
label = line.split(labelMarker)[1].trim();
} else if (line.contains(duidMarker)) {
duid = line.split(duidMarker)[1].trim();
}
/*-
16 partitions:
# size offset fstype [fsize bsize cpg]
a: 2097152 1024 4.2BSD 2048 16384 12958 # /
b: 17023368 2098176 swap # none
c: 500118192 0 unused
d: 8388576 19121568 4.2BSD 2048 16384 12958 # /tmp
e: 41386752 27510144 4.2BSD 2048 16384 12958 # /var
f: 4194304 68896896 4.2BSD 2048 16384 12958 # /usr
g: 2097152 73091200 4.2BSD 2048 16384 12958 # /usr/X11R6
h: 20971520 75188352 4.2BSD 2048 16384 12958 # /usr/local
i: 960 64 MSDOS
j: 4194304 96159872 4.2BSD 2048 16384 12958 # /usr/src
k: 12582912 100354176 4.2BSD 2048 16384 12958 # /usr/obj
l: 387166336 112937088 4.2BSD 4096 32768 26062 # /home
Note size is in sectors
*/
if (line.trim().indexOf(':') == 1) {
// partition table values have a single letter followed by a colon
String[] split = ParseUtil.whitespaces.split(line.trim(), 9);
String name = split[0].substring(0, 1);
// get major and minor from stat
Pair<Integer, Integer> majorMinor = getMajorMinor(diskName, name);
// add partitions
if (split.length > 4) {
partitions.add(new HWPartition(diskName + name, name, split[3], duid + "." + name,
ParseUtil.parseLongOrDefault(split[1], 0L) * bytesPerSector, majorMinor.getA(),
majorMinor.getB(), split.length > 5 ? split[split.length - 1] : ""));
}
}
}
if (partitions.isEmpty()) {
return getDiskParamsNoRoot(diskName);
}
return new Quartet<>(label, duid, totalSectors * bytesPerSector, partitions);
| 582
| 1,365
| 1,947
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/solaris/Who.java
|
Who
|
queryUtxent
|
class Who {
private static final SolarisLibc LIBC = SolarisLibc.INSTANCE;
private Who() {
}
/**
* Query {@code getutxent} to get logged in users.
*
* @return A list of logged in user sessions
*/
public static synchronized List<OSSession> queryUtxent() {<FILL_FUNCTION_BODY>}
}
|
List<OSSession> whoList = new ArrayList<>();
SolarisUtmpx ut;
// Rewind
LIBC.setutxent();
try {
// Iterate
while ((ut = LIBC.getutxent()) != null) {
if (ut.ut_type == USER_PROCESS || ut.ut_type == LOGIN_PROCESS) {
String user = Native.toString(ut.ut_user, StandardCharsets.US_ASCII);
String device = Native.toString(ut.ut_line, StandardCharsets.US_ASCII);
String host = Native.toString(ut.ut_host, StandardCharsets.US_ASCII);
long loginTime = ut.ut_tv.tv_sec.longValue() * 1000L + ut.ut_tv.tv_usec.longValue() / 1000L;
// Sanity check. If errors, default to who command line
if (!isSessionValid(user, device, loginTime)) {
return oshi.driver.unix.Who.queryWho();
}
whoList.add(new OSSession(user, device, loginTime, host));
}
}
} finally {
// Close
LIBC.endutxent();
}
return whoList;
| 106
| 330
| 436
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/solaris/disk/Iostat.java
|
Iostat
|
queryDeviceStrings
|
class Iostat {
// Note uppercase E
private static final String IOSTAT_ER_DETAIL = "iostat -Er";
// Note lowercase e
private static final String IOSTAT_ER = "iostat -er";
// Sample output:
// errors
// device,s/w,h/w,trn,tot
// cmdk0,0,0,0,0
// sd0,0,0,0
// Note lowercase e
private static final String IOSTAT_ERN = "iostat -ern";
// Sample output:
// errors
// s/w,h/w,trn,tot,device
// 0,0,0,0,c1d0
// 0,0,0,0,c1t1d0
private static final String DEVICE_HEADER = "device";
private Iostat() {
}
/**
* Query iostat to map partitions to mount points
*
* @return A map with partitions as the key and mount points as the value
*/
public static Map<String, String> queryPartitionToMountMap() {
// Create map to correlate disk name with block device mount point for
// later use in partition info
Map<String, String> deviceMap = new HashMap<>();
// First, run iostat -er to enumerate disks by name.
List<String> mountNames = ExecutingCommand.runNative(IOSTAT_ER);
// Also run iostat -ern to get the same list by mount point.
List<String> mountPoints = ExecutingCommand.runNative(IOSTAT_ERN);
String disk;
for (int i = 0; i < mountNames.size() && i < mountPoints.size(); i++) {
// Map disk
disk = mountNames.get(i);
String[] diskSplit = disk.split(",");
if (diskSplit.length >= 5 && !DEVICE_HEADER.equals(diskSplit[0])) {
String mount = mountPoints.get(i);
String[] mountSplit = mount.split(",");
if (mountSplit.length >= 5 && !DEVICE_HEADER.equals(mountSplit[4])) {
deviceMap.put(diskSplit[0], mountSplit[4]);
}
}
}
return deviceMap;
}
/**
* Query iostat to map detailed drive information
*
* @param diskSet A set of valid disk names; others will be ignored
* @return A map with disk name as the key and a quintet of model, vendor, product, serial, size as the value
*/
public static Map<String, Quintet<String, String, String, String, Long>> queryDeviceStrings(Set<String> diskSet) {<FILL_FUNCTION_BODY>}
}
|
Map<String, Quintet<String, String, String, String, Long>> deviceParamMap = new HashMap<>();
// Run iostat -Er to get model, etc.
List<String> iostat = ExecutingCommand.runNative(IOSTAT_ER_DETAIL);
// We'll use Model if available, otherwise Vendor+Product
String diskName = null;
String model = "";
String vendor = "";
String product = "";
String serial = "";
long size = 0;
for (String line : iostat) {
// The -r switch enables comma delimited for easy parsing!
// No guarantees on which line the results appear so we'll nest
// a loop iterating on the comma splits
String[] split = line.split(",");
for (String keyValue : split) {
keyValue = keyValue.trim();
// If entry is tne name of a disk, this is beginning of new
// output for that disk.
if (diskSet.contains(keyValue)) {
// First, if we have existing output from previous,
// update
if (diskName != null) {
deviceParamMap.put(diskName, new Quintet<>(model, vendor, product, serial, size));
}
// Reset values for next iteration
diskName = keyValue;
model = "";
vendor = "";
product = "";
serial = "";
size = 0L;
continue;
}
// Otherwise update variables
if (keyValue.startsWith("Model:")) {
model = keyValue.replace("Model:", "").trim();
} else if (keyValue.startsWith("Serial No:")) {
serial = keyValue.replace("Serial No:", "").trim();
} else if (keyValue.startsWith("Vendor:")) {
vendor = keyValue.replace("Vendor:", "").trim();
} else if (keyValue.startsWith("Product:")) {
product = keyValue.replace("Product:", "").trim();
} else if (keyValue.startsWith("Size:")) {
// Size: 1.23GB <1227563008 bytes>
String[] bytes = keyValue.split("<");
if (bytes.length > 1) {
bytes = ParseUtil.whitespaces.split(bytes[1]);
size = ParseUtil.parseLongOrDefault(bytes[0], 0L);
}
}
}
// At end of output update last entry
if (diskName != null) {
deviceParamMap.put(diskName, new Quintet<>(model, vendor, product, serial, size));
}
}
return deviceParamMap;
| 705
| 680
| 1,385
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/solaris/disk/Lshal.java
|
Lshal
|
queryDiskToMajorMap
|
class Lshal {
private static final String LSHAL_CMD = "lshal";
private Lshal() {
}
/**
* Query lshal to get device major
*
* @return A map with disk names as the key and block device major as the value if lshal is installed; empty map
* otherwise
*/
public static Map<String, Integer> queryDiskToMajorMap() {<FILL_FUNCTION_BODY>}
}
|
Map<String, Integer> majorMap = new HashMap<>();
List<String> lshal = ExecutingCommand.runNative(LSHAL_CMD);
String diskName = null;
for (String line : lshal) {
if (line.startsWith("udi ")) {
String udi = ParseUtil.getSingleQuoteStringValue(line);
diskName = udi.substring(udi.lastIndexOf('/') + 1);
} else {
line = line.trim();
if (line.startsWith("block.major") && diskName != null) {
majorMap.put(diskName, ParseUtil.getFirstIntValue(line));
}
}
}
return majorMap;
| 119
| 186
| 305
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/solaris/disk/Prtvtoc.java
|
Prtvtoc
|
queryPartitions
|
class Prtvtoc {
private static final String PRTVTOC_DEV_DSK = "prtvtoc /dev/dsk/";
private Prtvtoc() {
}
public static List<HWPartition> queryPartitions(String mount, int major) {<FILL_FUNCTION_BODY>}
}
|
List<HWPartition> partList = new ArrayList<>();
// This requires sudo permissions; will result in "permission denied"
// otherwise in which case we return empty partition list
List<String> prtvotc = ExecutingCommand.runNative(PRTVTOC_DEV_DSK + mount);
// Sample output - see man prtvtoc
if (prtvotc.size() > 1) {
int bytesPerSector = 0;
String[] split;
// We have a result, parse partition table
for (String line : prtvotc) {
// If line starts with asterisk we ignore except for the one
// specifying bytes per sector
if (line.startsWith("*")) {
if (line.endsWith("bytes/sector")) {
split = ParseUtil.whitespaces.split(line);
if (split.length > 0) {
bytesPerSector = ParseUtil.parseIntOrDefault(split[1], 0);
}
}
} else if (bytesPerSector > 0) {
// If bytes/sector is still 0, these are not real partitions so
// ignore.
// Lines without asterisk have 6 or 7 whitespaces-split values
// representing (last field optional):
// Partition Tag Flags Sector Count Sector Mount
split = ParseUtil.whitespaces.split(line.trim());
// Partition 2 is always the whole disk so we ignore it
if (split.length >= 6 && !"2".equals(split[0])) {
// First field is partition number
String identification = mount + "s" + split[0];
// major already defined as method param
int minor = ParseUtil.parseIntOrDefault(split[0], 0);
// Second field is tag. Parse:
String name;
switch (ParseUtil.parseIntOrDefault(split[1], 0)) {
case 0x01:
case 0x18:
name = "boot";
break;
case 0x02:
name = "root";
break;
case 0x03:
name = "swap";
break;
case 0x04:
name = "usr";
break;
case 0x05:
name = "backup";
break;
case 0x06:
name = "stand";
break;
case 0x07:
name = "var";
break;
case 0x08:
name = "home";
break;
case 0x09:
name = "altsctr";
break;
case 0x0a:
name = "cache";
break;
case 0x0b:
name = "reserved";
break;
case 0x0c:
name = "system";
break;
case 0x0e:
name = "public region";
break;
case 0x0f:
name = "private region";
break;
default:
name = Constants.UNKNOWN;
break;
}
// Third field is flags.
String type;
// First character writable, second is mountable
switch (split[2]) {
case "00":
type = "wm";
break;
case "10":
type = "rm";
break;
case "01":
type = "wu";
break;
default:
type = "ru";
break;
}
// Fifth field is sector count
long partSize = bytesPerSector * ParseUtil.parseLongOrDefault(split[4], 0L);
// Seventh field (if present) is mount point
String mountPoint = "";
if (split.length > 6) {
mountPoint = split[6];
}
partList.add(
new HWPartition(identification, name, type, "", partSize, major, minor, mountPoint));
}
}
}
}
return partList;
| 83
| 1,027
| 1,110
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/unix/solaris/kstat/SystemPages.java
|
SystemPages
|
queryAvailableTotal
|
class SystemPages {
private SystemPages() {
}
/**
* Queries the {@code system_pages} kstat and returns available and physical memory
*
* @return A pair with the available and total memory, in pages. Mutiply by page size for bytes.
*/
public static Pair<Long, Long> queryAvailableTotal() {<FILL_FUNCTION_BODY>}
private static Pair<Long, Long> queryAvailableTotal2() {
Object[] results = KstatUtil.queryKstat2("kstat:/pages/unix/system_pages", "availrmem", "physmem");
long avail = results[0] == null ? 0L : (long) results[0];
long total = results[1] == null ? 0L : (long) results[1];
return new Pair<>(avail, total);
}
}
|
if (HAS_KSTAT2) {
// Use Kstat2 implementation
return queryAvailableTotal2();
}
long memAvailable = 0;
long memTotal = 0;
// Get first result
try (KstatChain kc = KstatUtil.openChain()) {
Kstat ksp = kc.lookup(null, -1, "system_pages");
// Set values
if (ksp != null && kc.read(ksp)) {
memAvailable = KstatUtil.dataLookupLong(ksp, "availrmem"); // not a typo
memTotal = KstatUtil.dataLookupLong(ksp, "physmem");
}
}
return new Pair<>(memAvailable, memTotal);
| 219
| 190
| 409
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/DeviceTree.java
|
DeviceTree
|
queryDeviceTree
|
class DeviceTree {
private static final int MAX_PATH = 260;
private static final SetupApi SA = SetupApi.INSTANCE;
private static final Cfgmgr32 C32 = Cfgmgr32.INSTANCE;
private DeviceTree() {
}
/**
* Queries devices matching the specified device interface and returns maps representing device tree relationships,
* name, device ID, and manufacturer
*
* @param guidDevInterface The GUID of a device interface class for which the tree should be collected.
*
* @return A {@link Quintet} of maps indexed by node ID, where the key set represents node IDs for all devices
* matching the specified device interface GUID. The first element is a set containing devices with no
* parents, match the device interface requested.. The second element maps each node ID to its parents, if
* any. This map's key set excludes the no-parent devices returned in the first element. The third element
* maps a node ID to a name or description. The fourth element maps a node id to a device ID. The fifth
* element maps a node ID to a manufacturer.
*/
public static Quintet<Set<Integer>, Map<Integer, Integer>, Map<Integer, String>, Map<Integer, String>, Map<Integer, String>> queryDeviceTree(
GUID guidDevInterface) {<FILL_FUNCTION_BODY>}
private static String getDevNodeProperty(int node, int cmDrp, Memory buf, IntByReference size) {
buf.clear();
size.setValue((int) buf.size());
C32.CM_Get_DevNode_Registry_Property(node, cmDrp, null, buf, size, 0);
return buf.getWideString(0);
}
}
|
Map<Integer, Integer> parentMap = new HashMap<>();
Map<Integer, String> nameMap = new HashMap<>();
Map<Integer, String> deviceIdMap = new HashMap<>();
Map<Integer, String> mfgMap = new HashMap<>();
// Get device IDs for the top level devices
HANDLE hDevInfo = SA.SetupDiGetClassDevs(guidDevInterface, null, null, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
if (!INVALID_HANDLE_VALUE.equals(hDevInfo)) {
try (Memory buf = new Memory(MAX_PATH);
CloseableIntByReference size = new CloseableIntByReference(MAX_PATH);
CloseableIntByReference child = new CloseableIntByReference();
CloseableIntByReference sibling = new CloseableIntByReference();
CloseableSpDevinfoData devInfoData = new CloseableSpDevinfoData()) {
devInfoData.cbSize = devInfoData.size();
// Enumerate Device Info using BFS queue
Queue<Integer> deviceTree = new ArrayDeque<>();
for (int i = 0; SA.SetupDiEnumDeviceInfo(hDevInfo, i, devInfoData); i++) {
deviceTree.add(devInfoData.DevInst);
// Initialize parent and child objects
int node = 0;
while (!deviceTree.isEmpty()) {
// Process the next device in the queue
node = deviceTree.poll();
// Save the strings in their maps
String deviceId = Cfgmgr32Util.CM_Get_Device_ID(node);
deviceIdMap.put(node, deviceId);
// Prefer friendly name over desc if it is present.
// If neither, use class (service)
String name = getDevNodeProperty(node, CM_DRP_FRIENDLYNAME, buf, size);
if (name.isEmpty()) {
name = getDevNodeProperty(node, CM_DRP_DEVICEDESC, buf, size);
}
if (name.isEmpty()) {
name = getDevNodeProperty(node, CM_DRP_CLASS, buf, size);
String svc = getDevNodeProperty(node, CM_DRP_SERVICE, buf, size);
if (!svc.isEmpty()) {
name = name + " (" + svc + ")";
}
}
nameMap.put(node, name);
mfgMap.put(node, getDevNodeProperty(node, CM_DRP_MFG, buf, size));
// Add any children to the queue, tracking the parent node
if (ERROR_SUCCESS == C32.CM_Get_Child(child, node, 0)) {
parentMap.put(child.getValue(), node);
deviceTree.add(child.getValue());
while (ERROR_SUCCESS == C32.CM_Get_Sibling(sibling, child.getValue(), 0)) {
parentMap.put(sibling.getValue(), node);
deviceTree.add(sibling.getValue());
child.setValue(sibling.getValue());
}
}
}
}
} finally {
SA.SetupDiDestroyDeviceInfoList(hDevInfo);
}
}
// Look for output without parents, these are top of tree
Set<Integer> controllerDevices = deviceIdMap.keySet().stream().filter(k -> !parentMap.containsKey(k))
.collect(Collectors.toSet());
return new Quintet<>(controllerDevices, parentMap, nameMap, deviceIdMap, mfgMap);
| 446
| 898
| 1,344
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/EnumWindows.java
|
EnumWindows
|
queryDesktopWindows
|
class EnumWindows {
private static final DWORD GW_HWNDNEXT = new DWORD(2);
private EnumWindows() {
}
/**
* Gets windows on the operating system's GUI desktop.
*
* @param visibleOnly Whether to restrict the list to only windows visible to the user.
* @return A list of {@link oshi.software.os.OSDesktopWindow} objects representing the desktop windows.
*/
public static List<OSDesktopWindow> queryDesktopWindows(boolean visibleOnly) {<FILL_FUNCTION_BODY>}
private static void updateWindowZOrderMap(HWND hWnd, Map<HWND, Integer> zOrderMap) {
if (hWnd != null) {
int zOrder = 1;
HWND h = new HWND(hWnd.getPointer());
// First is highest, so decrement
do {
zOrderMap.put(h, --zOrder);
} while ((h = User32.INSTANCE.GetWindow(h, GW_HWNDNEXT)) != null);
// now add lowest value to all
final int offset = zOrder * -1;
zOrderMap.replaceAll((k, v) -> v + offset);
}
}
}
|
// Get the windows using JNA's implementation
List<DesktopWindow> windows = WindowUtils.getAllWindows(true);
// Prepare a list to return
List<OSDesktopWindow> windowList = new ArrayList<>();
// Populate the list
Map<HWND, Integer> zOrderMap = new HashMap<>();
for (DesktopWindow window : windows) {
HWND hWnd = window.getHWND();
if (hWnd != null) {
boolean visible = User32.INSTANCE.IsWindowVisible(hWnd);
if (!visibleOnly || visible) {
if (!zOrderMap.containsKey(hWnd)) {
updateWindowZOrderMap(hWnd, zOrderMap);
}
try (CloseableIntByReference pProcessId = new CloseableIntByReference()) {
User32.INSTANCE.GetWindowThreadProcessId(hWnd, pProcessId);
windowList.add(new OSDesktopWindow(Pointer.nativeValue(hWnd.getPointer()), window.getTitle(),
window.getFilePath(), window.getLocAndSize(), pProcessId.getValue(),
zOrderMap.get(hWnd), visible));
}
}
}
}
return windowList;
| 323
| 313
| 636
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/perfmon/LoadAverage.java
|
LoadAverage
|
startDaemon
|
class LoadAverage {
// Daemon thread for Load Average
private static Thread loadAvgThread = null;
private static double[] loadAverages = new double[] { -1d, -1d, -1d };
private static final double[] EXP_WEIGHT = new double[] {
// 1-, 5-, and 15-minute exponential smoothing weight
Math.exp(-5d / 60d), Math.exp(-5d / 300d), Math.exp(-5d / 900d) };
private LoadAverage() {
}
public static double[] queryLoadAverage(int nelem) {
synchronized (loadAverages) {
return Arrays.copyOf(loadAverages, nelem);
}
}
public static synchronized void stopDaemon() {
if (loadAvgThread != null) {
loadAvgThread.interrupt();
loadAvgThread = null;
}
}
public static synchronized void startDaemon() {<FILL_FUNCTION_BODY>}
private static Pair<Long, Long> queryNonIdleTicks() {
Pair<List<String>, Map<IdleProcessorTimeProperty, List<Long>>> idleValues = ProcessInformation
.queryIdleProcessCounters();
List<String> instances = idleValues.getA();
Map<IdleProcessorTimeProperty, List<Long>> valueMap = idleValues.getB();
List<Long> proctimeTicks = valueMap.get(IdleProcessorTimeProperty.PERCENTPROCESSORTIME);
List<Long> proctimeBase = valueMap.get(IdleProcessorTimeProperty.ELAPSEDTIME);
long nonIdleTicks = 0L;
long nonIdleBase = 0L;
for (int i = 0; i < instances.size(); i++) {
if ("_Total".equals(instances.get(i))) {
nonIdleTicks += proctimeTicks.get(i);
nonIdleBase += proctimeBase.get(i);
} else if ("Idle".equals(instances.get(i))) {
nonIdleTicks -= proctimeTicks.get(i);
}
}
return new Pair<>(nonIdleTicks, nonIdleBase);
}
}
|
if (loadAvgThread != null) {
return;
}
loadAvgThread = new Thread("OSHI Load Average daemon") {
@Override
public void run() {
// Initialize tick counters
Pair<Long, Long> nonIdlePair = LoadAverage.queryNonIdleTicks();
long nonIdleTicks0 = nonIdlePair.getA();
long nonIdleBase0 = nonIdlePair.getB();
long nonIdleTicks;
long nonIdleBase;
// Use nanoTime to synchronize queries at 5 seconds
long initNanos = System.nanoTime();
long delay;
// The two components of load average
double runningProcesses;
long queueLength;
try {
Thread.sleep(2500L);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
while (!Thread.currentThread().isInterrupted()) {
// get non-idle ticks, proxy for average processes running
nonIdlePair = LoadAverage.queryNonIdleTicks();
nonIdleTicks = nonIdlePair.getA() - nonIdleTicks0;
nonIdleBase = nonIdlePair.getB() - nonIdleBase0;
if (nonIdleBase > 0 && nonIdleTicks > 0) {
runningProcesses = (double) nonIdleTicks / nonIdleBase;
} else {
runningProcesses = 0d;
}
nonIdleTicks0 = nonIdlePair.getA();
nonIdleBase0 = nonIdlePair.getB();
// get processes waiting
queueLength = SystemInformation.queryProcessorQueueLength()
.getOrDefault(ProcessorQueueLengthProperty.PROCESSORQUEUELENGTH, 0L);
synchronized (loadAverages) {
// Init to running procs the first time
if (loadAverages[0] < 0d) {
Arrays.fill(loadAverages, runningProcesses);
}
// Use exponential smoothing to update values
for (int i = 0; i < loadAverages.length; i++) {
loadAverages[i] *= EXP_WEIGHT[i];
loadAverages[i] += (runningProcesses + queueLength) * (1d - EXP_WEIGHT[i]);
}
}
delay = 5000L - (System.nanoTime() - initNanos) % 5_000_000_000L / 1_000_000;
if (delay < 500L) {
delay += 5000L;
}
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
};
loadAvgThread.setDaemon(true);
loadAvgThread.start();
| 587
| 754
| 1,341
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/perfmon/MemoryInformation.java
|
MemoryInformation
|
queryPageSwaps
|
class MemoryInformation {
/**
* For pages in/out
*/
public enum PageSwapProperty implements PdhCounterProperty {
PAGESINPUTPERSEC(null, "Pages Input/sec"), //
PAGESOUTPUTPERSEC(null, "Pages Output/sec");
private final String instance;
private final String counter;
PageSwapProperty(String instance, String counter) {
this.instance = instance;
this.counter = counter;
}
@Override
public String getInstance() {
return instance;
}
@Override
public String getCounter() {
return counter;
}
}
private MemoryInformation() {
}
/**
* Returns page swap counters
*
* @return Page swap counters for memory.
*/
public static Map<PageSwapProperty, Long> queryPageSwaps() {<FILL_FUNCTION_BODY>}
}
|
if (PerfmonDisabled.PERF_OS_DISABLED) {
return Collections.emptyMap();
}
return PerfCounterQuery.queryValues(PageSwapProperty.class, MEMORY, WIN32_PERF_RAW_DATA_PERF_OS_MEMORY);
| 241
| 78
| 319
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/perfmon/PagingFile.java
|
PagingFile
|
querySwapUsed
|
class PagingFile {
/**
* For swap file usage
*/
public enum PagingPercentProperty implements PdhCounterProperty {
PERCENTUSAGE(PerfCounterQuery.TOTAL_INSTANCE, "% Usage");
private final String instance;
private final String counter;
PagingPercentProperty(String instance, String counter) {
this.instance = instance;
this.counter = counter;
}
@Override
public String getInstance() {
return instance;
}
@Override
public String getCounter() {
return counter;
}
}
private PagingFile() {
}
/**
* Returns paging file counters
*
* @return Paging file counters for memory.
*/
public static Map<PagingPercentProperty, Long> querySwapUsed() {<FILL_FUNCTION_BODY>}
}
|
if (PerfmonDisabled.PERF_OS_DISABLED) {
return Collections.emptyMap();
}
return PerfCounterQuery.queryValues(PagingPercentProperty.class, PAGING_FILE,
WIN32_PERF_RAW_DATA_PERF_OS_PAGING_FILE);
| 232
| 86
| 318
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/perfmon/PerfmonDisabled.java
|
PerfmonDisabled
|
isDisabled
|
class PerfmonDisabled {
private static final Logger LOG = LoggerFactory.getLogger(PerfmonDisabled.class);
public static final boolean PERF_OS_DISABLED = isDisabled(GlobalConfig.OSHI_OS_WINDOWS_PERFOS_DIABLED, "PerfOS");
public static final boolean PERF_PROC_DISABLED = isDisabled(GlobalConfig.OSHI_OS_WINDOWS_PERFPROC_DIABLED,
"PerfProc");
public static final boolean PERF_DISK_DISABLED = isDisabled(GlobalConfig.OSHI_OS_WINDOWS_PERFDISK_DIABLED,
"PerfDisk");
/**
* Everything in this class is static, never instantiate it
*/
private PerfmonDisabled() {
throw new AssertionError();
}
private static boolean isDisabled(String config, String service) {<FILL_FUNCTION_BODY>}
}
|
String perfDisabled = GlobalConfig.get(config);
// If null or empty, check registry
if (Util.isBlank(perfDisabled)) {
String key = String.format(Locale.ROOT, "SYSTEM\\CurrentControlSet\\Services\\%s\\Performance", service);
String value = "Disable Performance Counters";
// If disabled in registry, log warning and return
if (Advapi32Util.registryValueExists(WinReg.HKEY_LOCAL_MACHINE, key, value)) {
Object disabled = Advapi32Util.registryGetValue(WinReg.HKEY_LOCAL_MACHINE, key, value);
if (disabled instanceof Integer) {
if ((Integer) disabled > 0) {
LOG.warn("{} counters are disabled and won't return data: {}\\\\{}\\\\{} > 0.", service,
"HKEY_LOCAL_MACHINE", key, value);
return true;
}
} else {
LOG.warn(
"Invalid registry value type detected for {} counters. Should be REG_DWORD. Ignoring: {}\\\\{}\\\\{}.",
service, "HKEY_LOCAL_MACHINE", key, value);
}
}
return false;
}
// If not null or empty, parse as boolean
return Boolean.parseBoolean(perfDisabled);
| 251
| 344
| 595
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/perfmon/PhysicalDisk.java
|
PhysicalDisk
|
queryDiskCounters
|
class PhysicalDisk {
/**
* Physical Disk performance counters.
*/
public enum PhysicalDiskProperty implements PdhCounterWildcardProperty {
// First element defines WMI instance name field and PDH instance filter
NAME(PerfCounterQuery.NOT_TOTAL_INSTANCE),
// Remaining elements define counters
DISKREADSPERSEC("Disk Reads/sec"), //
DISKREADBYTESPERSEC("Disk Read Bytes/sec"), //
DISKWRITESPERSEC("Disk Writes/sec"), //
DISKWRITEBYTESPERSEC("Disk Write Bytes/sec"), //
CURRENTDISKQUEUELENGTH("Current Disk Queue Length"), //
PERCENTDISKTIME("% Disk Time");
private final String counter;
PhysicalDiskProperty(String counter) {
this.counter = counter;
}
@Override
public String getCounter() {
return counter;
}
}
private PhysicalDisk() {
}
/**
* Returns physical disk performance counters.
*
* @return Performance Counters for physical disks.
*/
public static Pair<List<String>, Map<PhysicalDiskProperty, List<Long>>> queryDiskCounters() {<FILL_FUNCTION_BODY>}
}
|
if (PerfmonDisabled.PERF_DISK_DISABLED) {
return new Pair<>(Collections.emptyList(), Collections.emptyMap());
}
return PerfCounterWildcardQuery.queryInstancesAndValues(PhysicalDiskProperty.class, PHYSICAL_DISK,
WIN32_PERF_RAW_DATA_PERF_DISK_PHYSICAL_DISK_WHERE_NAME_NOT_TOTAL);
| 331
| 115
| 446
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/perfmon/ProcessInformation.java
|
ProcessInformation
|
queryHandles
|
class ProcessInformation {
/**
* Process performance counters
*/
public enum ProcessPerformanceProperty implements PdhCounterWildcardProperty {
// First element defines WMI instance name field and PDH instance filter
NAME(PerfCounterQuery.NOT_TOTAL_INSTANCES),
// Remaining elements define counters
PRIORITYBASE("Priority Base"), //
ELAPSEDTIME("Elapsed Time"), //
IDPROCESS("ID Process"), //
CREATINGPROCESSID("Creating Process ID"), //
IOREADBYTESPERSEC("IO Read Bytes/sec"), //
IOWRITEBYTESPERSEC("IO Write Bytes/sec"), //
PRIVATEBYTES("Working Set - Private"), //
PAGEFAULTSPERSEC("Page Faults/sec");
private final String counter;
ProcessPerformanceProperty(String counter) {
this.counter = counter;
}
@Override
public String getCounter() {
return counter;
}
}
/**
* Handle performance counters
*/
public enum HandleCountProperty implements PdhCounterWildcardProperty {
// First element defines WMI instance name field and PDH instance filter
NAME(PerfCounterQuery.TOTAL_INSTANCE),
// Remaining elements define counters
HANDLECOUNT("Handle Count");
private final String counter;
HandleCountProperty(String counter) {
this.counter = counter;
}
@Override
public String getCounter() {
return counter;
}
}
/**
* Processor performance counters
*/
public enum IdleProcessorTimeProperty implements PdhCounterWildcardProperty {
// First element defines WMI instance name field and PDH instance filter
NAME(PerfCounterQuery.TOTAL_OR_IDLE_INSTANCES),
// Remaining elements define counters
PERCENTPROCESSORTIME("% Processor Time"), //
ELAPSEDTIME("Elapsed Time");
private final String counter;
IdleProcessorTimeProperty(String counter) {
this.counter = counter;
}
@Override
public String getCounter() {
return counter;
}
}
private ProcessInformation() {
}
/**
* Returns process counters.
*
* @return Process counters for each process.
*/
public static Pair<List<String>, Map<ProcessPerformanceProperty, List<Long>>> queryProcessCounters() {
if (PerfmonDisabled.PERF_PROC_DISABLED) {
return new Pair<>(Collections.emptyList(), Collections.emptyMap());
}
return PerfCounterWildcardQuery.queryInstancesAndValues(ProcessPerformanceProperty.class, PROCESS,
WIN32_PERFPROC_PROCESS_WHERE_NOT_NAME_LIKE_TOTAL);
}
/**
* Returns handle counters
*
* @return Process handle counters for each process.
*/
public static Pair<List<String>, Map<HandleCountProperty, List<Long>>> queryHandles() {<FILL_FUNCTION_BODY>}
/**
* Returns cooked idle process performance counters.
*
* @return Cooked performance counters for idle process.
*/
public static Pair<List<String>, Map<IdleProcessorTimeProperty, List<Long>>> queryIdleProcessCounters() {
if (PerfmonDisabled.PERF_OS_DISABLED) {
return new Pair<>(Collections.emptyList(), Collections.emptyMap());
}
return PerfCounterWildcardQuery.queryInstancesAndValues(IdleProcessorTimeProperty.class, PROCESS,
WIN32_PERFPROC_PROCESS_WHERE_IDPROCESS_0);
}
}
|
if (PerfmonDisabled.PERF_PROC_DISABLED) {
return new Pair<>(Collections.emptyList(), Collections.emptyMap());
}
return PerfCounterWildcardQuery.queryInstancesAndValues(HandleCountProperty.class, PROCESS,
WIN32_PERFPROC_PROCESS);
| 967
| 87
| 1,054
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/perfmon/ProcessorInformation.java
|
ProcessorInformation
|
queryInterruptCounters
|
class ProcessorInformation {
private static final boolean IS_WIN7_OR_GREATER = VersionHelpers.IsWindows7OrGreater();
/**
* Processor performance counters
*/
public enum ProcessorTickCountProperty implements PdhCounterWildcardProperty {
// First element defines WMI instance name field and PDH instance filter
NAME(PerfCounterQuery.NOT_TOTAL_INSTANCES),
// Remaining elements define counters
PERCENTDPCTIME("% DPC Time"), //
PERCENTINTERRUPTTIME("% Interrupt Time"), //
PERCENTPRIVILEGEDTIME("% Privileged Time"), //
PERCENTPROCESSORTIME("% Processor Time"), //
PERCENTUSERTIME("% User Time");
private final String counter;
ProcessorTickCountProperty(String counter) {
this.counter = counter;
}
@Override
public String getCounter() {
return counter;
}
}
/**
* Processor performance counters including utility counters
*/
public enum ProcessorUtilityTickCountProperty implements PdhCounterWildcardProperty {
// First element defines WMI instance name field and PDH instance filter
NAME(PerfCounterQuery.NOT_TOTAL_INSTANCES),
// Remaining elements define counters
PERCENTDPCTIME("% DPC Time"), //
PERCENTINTERRUPTTIME("% Interrupt Time"), //
PERCENTPRIVILEGEDTIME("% Privileged Time"), //
PERCENTPROCESSORTIME("% Processor Time"), //
// The above 3 counters are 100ns base type
// For PDH accessible as secondary counter in any of them
TIMESTAMP_SYS100NS("% Processor Time_Base"), //
PERCENTPRIVILEGEDUTILITY("% Privileged Utility"), //
PERCENTPROCESSORUTILITY("% Processor Utility"), //
PERCENTPROCESSORUTILITY_BASE("% Processor Utility_Base"), //
PERCENTUSERTIME("% User Time");
private final String counter;
ProcessorUtilityTickCountProperty(String counter) {
this.counter = counter;
}
@Override
public String getCounter() {
return counter;
}
}
/**
* System interrupts counters
*/
public enum InterruptsProperty implements PdhCounterProperty {
INTERRUPTSPERSEC(PerfCounterQuery.TOTAL_INSTANCE, "Interrupts/sec");
private final String instance;
private final String counter;
InterruptsProperty(String instance, String counter) {
this.instance = instance;
this.counter = counter;
}
@Override
public String getInstance() {
return instance;
}
@Override
public String getCounter() {
return counter;
}
}
/**
* Processor Frequency counters. Requires Win7 or greater
*/
public enum ProcessorFrequencyProperty implements PdhCounterWildcardProperty {
// First element defines WMI instance name field and PDH instance filter
NAME(PerfCounterQuery.NOT_TOTAL_INSTANCES),
// Remaining elements define counters
PERCENTOFMAXIMUMFREQUENCY("% of Maximum Frequency");
private final String counter;
ProcessorFrequencyProperty(String counter) {
this.counter = counter;
}
@Override
public String getCounter() {
return counter;
}
}
private ProcessorInformation() {
}
/**
* Returns processor performance counters.
*
* @return Performance Counters for processors.
*/
public static Pair<List<String>, Map<ProcessorTickCountProperty, List<Long>>> queryProcessorCounters() {
if (PerfmonDisabled.PERF_OS_DISABLED) {
return new Pair<>(Collections.emptyList(), Collections.emptyMap());
}
return IS_WIN7_OR_GREATER ? PerfCounterWildcardQuery.queryInstancesAndValues(ProcessorTickCountProperty.class,
PROCESSOR_INFORMATION, WIN32_PERF_RAW_DATA_COUNTERS_PROCESSOR_INFORMATION_WHERE_NOT_NAME_LIKE_TOTAL)
: PerfCounterWildcardQuery.queryInstancesAndValues(ProcessorTickCountProperty.class, PROCESSOR,
WIN32_PERF_RAW_DATA_PERF_OS_PROCESSOR_WHERE_NAME_NOT_TOTAL);
}
/**
* Returns processor capacity performance counters.
*
* @return Performance Counters for processor capacity.
*/
public static Pair<List<String>, Map<ProcessorUtilityTickCountProperty, List<Long>>> queryProcessorCapacityCounters() {
if (PerfmonDisabled.PERF_OS_DISABLED) {
return new Pair<>(Collections.emptyList(), Collections.emptyMap());
}
return PerfCounterWildcardQuery.queryInstancesAndValues(ProcessorUtilityTickCountProperty.class,
PROCESSOR_INFORMATION, WIN32_PERF_RAW_DATA_COUNTERS_PROCESSOR_INFORMATION_WHERE_NOT_NAME_LIKE_TOTAL);
}
/**
* Returns system interrupts counters.
*
* @return Interrupts counter for the total of all processors.
*/
public static Map<InterruptsProperty, Long> queryInterruptCounters() {<FILL_FUNCTION_BODY>}
/**
* Returns processor frequency counters.
*
* @return Processor frequency counter for each processor.
*/
public static Pair<List<String>, Map<ProcessorFrequencyProperty, List<Long>>> queryFrequencyCounters() {
if (PerfmonDisabled.PERF_OS_DISABLED) {
return new Pair<>(Collections.emptyList(), Collections.emptyMap());
}
return PerfCounterWildcardQuery.queryInstancesAndValues(ProcessorFrequencyProperty.class, PROCESSOR_INFORMATION,
WIN32_PERF_RAW_DATA_COUNTERS_PROCESSOR_INFORMATION_WHERE_NOT_NAME_LIKE_TOTAL);
}
}
|
if (PerfmonDisabled.PERF_OS_DISABLED) {
return Collections.emptyMap();
}
return PerfCounterQuery.queryValues(InterruptsProperty.class, PROCESSOR,
WIN32_PERF_RAW_DATA_PERF_OS_PROCESSOR_WHERE_NAME_TOTAL);
| 1,607
| 89
| 1,696
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/perfmon/SystemInformation.java
|
SystemInformation
|
queryProcessorQueueLength
|
class SystemInformation {
/**
* Context switch property
*/
public enum ContextSwitchProperty implements PdhCounterProperty {
CONTEXTSWITCHESPERSEC(null, "Context Switches/sec");
private final String instance;
private final String counter;
ContextSwitchProperty(String instance, String counter) {
this.instance = instance;
this.counter = counter;
}
@Override
public String getInstance() {
return instance;
}
@Override
public String getCounter() {
return counter;
}
}
/**
* Processor Queue Length property
*/
public enum ProcessorQueueLengthProperty implements PdhCounterProperty {
PROCESSORQUEUELENGTH(null, "Processor Queue Length");
private final String instance;
private final String counter;
ProcessorQueueLengthProperty(String instance, String counter) {
this.instance = instance;
this.counter = counter;
}
@Override
public String getInstance() {
return instance;
}
@Override
public String getCounter() {
return counter;
}
}
private SystemInformation() {
}
/**
* Returns system context switch counters.
*
* @return Context switches counter for the total of all processors.
*/
public static Map<ContextSwitchProperty, Long> queryContextSwitchCounters() {
if (PerfmonDisabled.PERF_OS_DISABLED) {
return Collections.emptyMap();
}
return PerfCounterQuery.queryValues(ContextSwitchProperty.class, SYSTEM, WIN32_PERF_RAW_DATA_PERF_OS_SYSTEM);
}
/**
* Returns processor queue length.
*
* @return Processor Queue Length.
*/
public static Map<ProcessorQueueLengthProperty, Long> queryProcessorQueueLength() {<FILL_FUNCTION_BODY>}
}
|
if (PerfmonDisabled.PERF_OS_DISABLED) {
return Collections.emptyMap();
}
return PerfCounterQuery.queryValues(ProcessorQueueLengthProperty.class, SYSTEM,
WIN32_PERF_RAW_DATA_PERF_OS_SYSTEM);
| 498
| 79
| 577
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/perfmon/ThreadInformation.java
|
ThreadInformation
|
queryThreadCounters
|
class ThreadInformation {
/**
* Thread performance counters
*/
public enum ThreadPerformanceProperty implements PdhCounterWildcardProperty {
// First element defines WMI instance name field and PDH instance filter
NAME(PerfCounterQuery.NOT_TOTAL_INSTANCES),
// Remaining elements define counters
PERCENTUSERTIME("% User Time"), //
PERCENTPRIVILEGEDTIME("% Privileged Time"), //
ELAPSEDTIME("Elapsed Time"), //
PRIORITYCURRENT("Priority Current"), //
STARTADDRESS("Start Address"), //
THREADSTATE("Thread State"), //
THREADWAITREASON("Thread Wait Reason"), // 5 is SUSPENDED
IDPROCESS("ID Process"), //
IDTHREAD("ID Thread"), //
CONTEXTSWITCHESPERSEC("Context Switches/sec");
private final String counter;
ThreadPerformanceProperty(String counter) {
this.counter = counter;
}
@Override
public String getCounter() {
return counter;
}
}
private ThreadInformation() {
}
/**
* Returns thread counters.
*
* @return Thread counters for each thread.
*/
public static Pair<List<String>, Map<ThreadPerformanceProperty, List<Long>>> queryThreadCounters() {
return PerfCounterWildcardQuery.queryInstancesAndValues(ThreadPerformanceProperty.class, THREAD,
WIN32_PERF_RAW_DATA_PERF_PROC_THREAD_WHERE_NOT_NAME_LIKE_TOTAL);
}
/**
* Returns thread counters filtered to the specified process name and thread.
*
* @param name The process name to filter
* @param threadNum The thread number to match. -1 matches all threads.
*
* @return Thread counters for each thread.
*/
public static Pair<List<String>, Map<ThreadPerformanceProperty, List<Long>>> queryThreadCounters(String name,
int threadNum) {<FILL_FUNCTION_BODY>}
}
|
String procName = name.toLowerCase(Locale.ROOT);
if (threadNum >= 0) {
return PerfCounterWildcardQuery.queryInstancesAndValues(
ThreadPerformanceProperty.class, THREAD, WIN32_PERF_RAW_DATA_PERF_PROC_THREAD
+ " WHERE Name LIKE \\\"" + procName + "\\\" AND IDThread=" + threadNum,
procName + "/" + threadNum);
}
return PerfCounterWildcardQuery.queryInstancesAndValues(ThreadPerformanceProperty.class, THREAD,
WIN32_PERF_RAW_DATA_PERF_PROC_THREAD + " WHERE Name LIKE \\\"" + procName + "\\\"", procName + "/*");
| 540
| 195
| 735
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/registry/HkeyUserData.java
|
HkeyUserData
|
queryUserSessions
|
class HkeyUserData {
private static final String PATH_DELIMITER = "\\";
private static final String DEFAULT_DEVICE = "Console";
private static final String VOLATILE_ENV_SUBKEY = "Volatile Environment";
private static final String CLIENTNAME = "CLIENTNAME";
private static final String SESSIONNAME = "SESSIONNAME";
private static final Logger LOG = LoggerFactory.getLogger(HkeyUserData.class);
private HkeyUserData() {
}
public static List<OSSession> queryUserSessions() {<FILL_FUNCTION_BODY>}
}
|
List<OSSession> sessions = new ArrayList<>();
for (String sidKey : Advapi32Util.registryGetKeys(WinReg.HKEY_USERS)) {
if (!sidKey.startsWith(".") && !sidKey.endsWith("_Classes")) {
try {
Account a = Advapi32Util.getAccountBySid(sidKey);
String name = a.name;
String device = DEFAULT_DEVICE;
String host = a.domain; // temporary default
long loginTime = 0;
String keyPath = sidKey + PATH_DELIMITER + VOLATILE_ENV_SUBKEY;
if (Advapi32Util.registryKeyExists(WinReg.HKEY_USERS, keyPath)) {
HKEY hKey = Advapi32Util.registryGetKey(WinReg.HKEY_USERS, keyPath, WinNT.KEY_READ).getValue();
// InfoKey write time is user login time
InfoKey info = Advapi32Util.registryQueryInfoKey(hKey, 0);
loginTime = info.lpftLastWriteTime.toTime();
for (String subKey : Advapi32Util.registryGetKeys(hKey)) {
String subKeyPath = keyPath + PATH_DELIMITER + subKey;
// Check for session and client name
if (Advapi32Util.registryValueExists(WinReg.HKEY_USERS, subKeyPath, SESSIONNAME)) {
String session = Advapi32Util.registryGetStringValue(WinReg.HKEY_USERS, subKeyPath,
SESSIONNAME);
if (!session.isEmpty()) {
device = session;
}
}
if (Advapi32Util.registryValueExists(WinReg.HKEY_USERS, subKeyPath, CLIENTNAME)) {
String client = Advapi32Util.registryGetStringValue(WinReg.HKEY_USERS, subKeyPath,
CLIENTNAME);
if (!client.isEmpty() && !DEFAULT_DEVICE.equals(client)) {
host = client;
}
}
}
Advapi32Util.registryCloseKey(hKey);
}
sessions.add(new OSSession(name, device, loginTime, host));
} catch (Win32Exception ex) {
LOG.warn("Error querying SID {} from registry: {}", sidKey, ex.getMessage());
}
}
}
return sessions;
| 156
| 618
| 774
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/registry/NetSessionData.java
|
NetSessionData
|
queryUserSessions
|
class NetSessionData {
private static final Netapi32 NET = Netapi32.INSTANCE;
private NetSessionData() {
}
public static List<OSSession> queryUserSessions() {<FILL_FUNCTION_BODY>}
}
|
List<OSSession> sessions = new ArrayList<>();
try (CloseablePointerByReference bufptr = new CloseablePointerByReference();
CloseableIntByReference entriesread = new CloseableIntByReference();
CloseableIntByReference totalentries = new CloseableIntByReference()) {
if (0 == NET.NetSessionEnum(null, null, null, 10, bufptr, Netapi32.MAX_PREFERRED_LENGTH, entriesread,
totalentries, null)) {
Pointer buf = bufptr.getValue();
SESSION_INFO_10 si10 = new SESSION_INFO_10(buf);
if (entriesread.getValue() > 0) {
SESSION_INFO_10[] sessionInfo = (SESSION_INFO_10[]) si10.toArray(entriesread.getValue());
for (SESSION_INFO_10 si : sessionInfo) {
// time field is connected seconds
long logonTime = System.currentTimeMillis() - (1000L * si.sesi10_time);
sessions.add(new OSSession(si.sesi10_username, "Network session", logonTime, si.sesi10_cname));
}
}
NET.NetApiBufferFree(buf);
}
}
return sessions;
| 70
| 331
| 401
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/registry/ProcessWtsData.java
|
ProcessWtsData
|
queryProcessWtsMapFromWTS
|
class ProcessWtsData {
private static final Logger LOG = LoggerFactory.getLogger(ProcessWtsData.class);
private static final boolean IS_WINDOWS7_OR_GREATER = VersionHelpers.IsWindows7OrGreater();
private ProcessWtsData() {
}
/**
* Query the registry for process performance counters
*
* @param pids An optional collection of process IDs to filter the list to. May be null for no filtering.
* @return A map with Process ID as the key and a {@link WtsInfo} object populated with data.
*/
public static Map<Integer, WtsInfo> queryProcessWtsMap(Collection<Integer> pids) {
if (IS_WINDOWS7_OR_GREATER) {
// Get processes from WTS
return queryProcessWtsMapFromWTS(pids);
}
// Pre-Win7 we can't use WTSEnumerateProcessesEx so we'll grab the
// same info from WMI and fake the array
return queryProcessWtsMapFromPerfMon(pids);
}
private static Map<Integer, WtsInfo> queryProcessWtsMapFromWTS(Collection<Integer> pids) {<FILL_FUNCTION_BODY>}
private static Map<Integer, WtsInfo> queryProcessWtsMapFromPerfMon(Collection<Integer> pids) {
Map<Integer, WtsInfo> wtsMap = new HashMap<>();
WmiResult<ProcessXPProperty> processWmiResult = Win32Process.queryProcesses(pids);
for (int i = 0; i < processWmiResult.getResultCount(); i++) {
wtsMap.put(WmiUtil.getUint32(processWmiResult, ProcessXPProperty.PROCESSID, i), new WtsInfo(
WmiUtil.getString(processWmiResult, ProcessXPProperty.NAME, i),
WmiUtil.getString(processWmiResult, ProcessXPProperty.EXECUTABLEPATH, i),
WmiUtil.getUint32(processWmiResult, ProcessXPProperty.THREADCOUNT, i),
// WMI Pagefile usage is in KB
1024 * (WmiUtil.getUint32(processWmiResult, ProcessXPProperty.PAGEFILEUSAGE, i) & 0xffff_ffffL),
WmiUtil.getUint64(processWmiResult, ProcessXPProperty.KERNELMODETIME, i) / 10_000L,
WmiUtil.getUint64(processWmiResult, ProcessXPProperty.USERMODETIME, i) / 10_000L,
WmiUtil.getUint32(processWmiResult, ProcessXPProperty.HANDLECOUNT, i)));
}
return wtsMap;
}
/**
* Class to encapsulate data from WTS Process Info
*/
@Immutable
public static class WtsInfo {
private final String name;
private final String path;
private final int threadCount;
private final long virtualSize;
private final long kernelTime;
private final long userTime;
private final long openFiles;
public WtsInfo(String name, String path, int threadCount, long virtualSize, long kernelTime, long userTime,
long openFiles) {
this.name = name;
this.path = path;
this.threadCount = threadCount;
this.virtualSize = virtualSize;
this.kernelTime = kernelTime;
this.userTime = userTime;
this.openFiles = openFiles;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @return the path
*/
public String getPath() {
return path;
}
/**
* @return the threadCount
*/
public int getThreadCount() {
return threadCount;
}
/**
* @return the virtualSize
*/
public long getVirtualSize() {
return virtualSize;
}
/**
* @return the kernelTime
*/
public long getKernelTime() {
return kernelTime;
}
/**
* @return the userTime
*/
public long getUserTime() {
return userTime;
}
/**
* @return the openFiles
*/
public long getOpenFiles() {
return openFiles;
}
}
}
|
Map<Integer, WtsInfo> wtsMap = new HashMap<>();
try (CloseableIntByReference pCount = new CloseableIntByReference(0);
CloseablePointerByReference ppProcessInfo = new CloseablePointerByReference();
CloseableIntByReference infoLevel1 = new CloseableIntByReference(Wtsapi32.WTS_PROCESS_INFO_LEVEL_1)) {
if (!Wtsapi32.INSTANCE.WTSEnumerateProcessesEx(Wtsapi32.WTS_CURRENT_SERVER_HANDLE, infoLevel1,
Wtsapi32.WTS_ANY_SESSION, ppProcessInfo, pCount)) {
LOG.error("Failed to enumerate Processes. Error code: {}", Kernel32.INSTANCE.GetLastError());
return wtsMap;
}
// extract the pointed-to pointer and create array
Pointer pProcessInfo = ppProcessInfo.getValue();
final WTS_PROCESS_INFO_EX processInfoRef = new WTS_PROCESS_INFO_EX(pProcessInfo);
WTS_PROCESS_INFO_EX[] processInfo = (WTS_PROCESS_INFO_EX[]) processInfoRef.toArray(pCount.getValue());
for (WTS_PROCESS_INFO_EX info : processInfo) {
if (pids == null || pids.contains(info.ProcessId)) {
wtsMap.put(info.ProcessId,
new WtsInfo(info.pProcessName, "", info.NumberOfThreads, info.PagefileUsage & 0xffff_ffffL,
info.KernelTime.getValue() / 10_000L, info.UserTime.getValue() / 10_000,
info.HandleCount));
}
}
// Clean up memory
if (!Wtsapi32.INSTANCE.WTSFreeMemoryEx(Wtsapi32.WTS_PROCESS_INFO_LEVEL_1, pProcessInfo,
pCount.getValue())) {
LOG.warn("Failed to Free Memory for Processes. Error code: {}", Kernel32.INSTANCE.GetLastError());
}
}
return wtsMap;
| 1,144
| 536
| 1,680
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/registry/SessionWtsData.java
|
SessionWtsData
|
queryUserSessions
|
class SessionWtsData {
private static final int WTS_ACTIVE = 0;
private static final int WTS_CLIENTADDRESS = 14;
private static final int WTS_SESSIONINFO = 24;
private static final int WTS_CLIENTPROTOCOLTYPE = 16;
private static final boolean IS_VISTA_OR_GREATER = VersionHelpers.IsWindowsVistaOrGreater();
private static final Wtsapi32 WTS = Wtsapi32.INSTANCE;
private SessionWtsData() {
}
public static List<OSSession> queryUserSessions() {<FILL_FUNCTION_BODY>}
/**
* Per WTS_INFO_CLASS docs, the IP address is offset by two bytes from the start of the Address member of the
* WTS_CLIENT_ADDRESS structure. Also contrary to docs, IPv4 is not a null terminated string.
* <p>
* This method converts the byte[20] to an int[4] parseable by existing code
*
* @param address The 20-byte array from the WTS_CLIENT_ADDRESS structure
* @return A 4-int array for {@link ParseUtil#parseUtAddrV6toIP}
*/
private static int[] convertBytesToInts(byte[] address) {
IntBuffer intBuf = ByteBuffer.wrap(Arrays.copyOfRange(address, 2, 18)).order(ByteOrder.BIG_ENDIAN)
.asIntBuffer();
int[] array = new int[intBuf.remaining()];
intBuf.get(array);
return array;
}
}
|
List<OSSession> sessions = new ArrayList<>();
if (IS_VISTA_OR_GREATER) {
try (CloseablePointerByReference ppSessionInfo = new CloseablePointerByReference();
CloseableIntByReference pCount = new CloseableIntByReference();
CloseablePointerByReference ppBuffer = new CloseablePointerByReference();
CloseableIntByReference pBytes = new CloseableIntByReference()) {
if (WTS.WTSEnumerateSessions(Wtsapi32.WTS_CURRENT_SERVER_HANDLE, 0, 1, ppSessionInfo, pCount)) {
Pointer pSessionInfo = ppSessionInfo.getValue();
if (pCount.getValue() > 0) {
WTS_SESSION_INFO sessionInfoRef = new WTS_SESSION_INFO(pSessionInfo);
WTS_SESSION_INFO[] sessionInfo = (WTS_SESSION_INFO[]) sessionInfoRef.toArray(pCount.getValue());
for (WTS_SESSION_INFO session : sessionInfo) {
if (session.State == WTS_ACTIVE) {
// Use session id to fetch additional session information
WTS.WTSQuerySessionInformation(Wtsapi32.WTS_CURRENT_SERVER_HANDLE, session.SessionId,
WTS_CLIENTPROTOCOLTYPE, ppBuffer, pBytes);
Pointer pBuffer = ppBuffer.getValue(); // pointer to USHORT
short protocolType = pBuffer.getShort(0); // 0 = console, 2 = RDP
WTS.WTSFreeMemory(pBuffer);
// We've already got console from registry, only test RDP
if (protocolType > 0) {
// DEVICE
String device = session.pWinStationName;
// USER and LOGIN TIME
WTS.WTSQuerySessionInformation(Wtsapi32.WTS_CURRENT_SERVER_HANDLE,
session.SessionId, WTS_SESSIONINFO, ppBuffer, pBytes);
pBuffer = ppBuffer.getValue(); // returns WTSINFO
WTSINFO wtsInfo = new WTSINFO(pBuffer);
// Temporary due to broken LARGE_INTEGER, remove in JNA 5.6.0
long logonTime = new WinBase.FILETIME(
new WinNT.LARGE_INTEGER(wtsInfo.LogonTime.getValue())).toTime();
String userName = wtsInfo.getUserName();
WTS.WTSFreeMemory(pBuffer);
// HOST
WTS.WTSQuerySessionInformation(Wtsapi32.WTS_CURRENT_SERVER_HANDLE,
session.SessionId, WTS_CLIENTADDRESS, ppBuffer, pBytes);
pBuffer = ppBuffer.getValue(); // returns WTS_CLIENT_ADDRESS
WTS_CLIENT_ADDRESS addr = new WTS_CLIENT_ADDRESS(pBuffer);
WTS.WTSFreeMemory(pBuffer);
String host = "::";
if (addr.AddressFamily == IPHlpAPI.AF_INET) {
try {
host = InetAddress.getByAddress(Arrays.copyOfRange(addr.Address, 2, 6))
.getHostAddress();
} catch (UnknownHostException e) {
// If array is not length of 4, shouldn't happen
host = "Illegal length IP Array";
}
} else if (addr.AddressFamily == IPHlpAPI.AF_INET6) {
// Get ints for address parsing
int[] ipArray = convertBytesToInts(addr.Address);
host = ParseUtil.parseUtAddrV6toIP(ipArray);
}
sessions.add(new OSSession(userName, device, logonTime, host));
}
}
}
}
WTS.WTSFreeMemory(pSessionInfo);
}
}
}
return sessions;
| 418
| 974
| 1,392
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/wmi/MSAcpiThermalZoneTemperature.java
|
MSAcpiThermalZoneTemperature
|
queryCurrentTemperature
|
class MSAcpiThermalZoneTemperature {
public static final String WMI_NAMESPACE = "ROOT\\WMI";
private static final String MS_ACPI_THERMAL_ZONE_TEMPERATURE = "MSAcpi_ThermalZoneTemperature";
/**
* Current temperature property.
*/
public enum TemperatureProperty {
CURRENTTEMPERATURE;
}
private MSAcpiThermalZoneTemperature() {
}
/**
* Queries the current temperature
*
* @return Temperature at thermal zone in tenths of degrees Kelvin.
*/
public static WmiResult<TemperatureProperty> queryCurrentTemperature() {<FILL_FUNCTION_BODY>}
}
|
WmiQuery<TemperatureProperty> curTempQuery = new WmiQuery<>(WMI_NAMESPACE, MS_ACPI_THERMAL_ZONE_TEMPERATURE,
TemperatureProperty.class);
return Objects.requireNonNull(WmiQueryHandler.createInstance()).queryWMI(curTempQuery);
| 194
| 82
| 276
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/wmi/MSFTStorage.java
|
MSFTStorage
|
queryPhysicalDisks
|
class MSFTStorage {
private static final String STORAGE_NAMESPACE = "ROOT\\Microsoft\\Windows\\Storage";
private static final String MSFT_STORAGE_POOL_WHERE_IS_PRIMORDIAL_FALSE = "MSFT_StoragePool WHERE IsPrimordial=FALSE";
private static final String MSFT_STORAGE_POOL_TO_PHYSICAL_DISK = "MSFT_StoragePoolToPhysicalDisk";
private static final String MSFT_PHYSICAL_DISK = "MSFT_PhysicalDisk";
private static final String MSFT_VIRTUAL_DISK = "MSFT_VirtualDisk";
/**
* Properties to identify the storage pool. The Object ID uniquely defines the pool.
*/
public enum StoragePoolProperty {
FRIENDLYNAME, OBJECTID;
}
/**
* Properties to link a storage pool with a physical disk. OSHI parses these references to strings that can match
* the object IDs.
*/
public enum StoragePoolToPhysicalDiskProperty {
STORAGEPOOL, PHYSICALDISK;
}
/**
* Properties for a physical disk. The Object ID uniquely defines the disk.
*/
public enum PhysicalDiskProperty {
FRIENDLYNAME, PHYSICALLOCATION, OBJECTID;
}
/**
* Properties for a virtual disk. The Object ID uniquely defines the disk.
*/
public enum VirtualDiskProperty {
FRIENDLYNAME, OBJECTID;
}
private MSFTStorage() {
}
/**
* Query the storage pools.
*
* @param h An instantiated {@link WmiQueryHandler}. User should have already initialized COM.
* @return Storage pools that are not primordial (raw disks not added to a storage space).
*/
public static WmiResult<StoragePoolProperty> queryStoragePools(WmiQueryHandler h) {
WmiQuery<StoragePoolProperty> storagePoolQuery = new WmiQuery<>(STORAGE_NAMESPACE,
MSFT_STORAGE_POOL_WHERE_IS_PRIMORDIAL_FALSE, StoragePoolProperty.class);
return h.queryWMI(storagePoolQuery, false);
}
/**
* Query the storage pool to physical disk connection.
*
* @param h An instantiated {@link WmiQueryHandler}. User should have already initialized COM.
* @return Links between physical disks and storage pools. All raw disks will be part of the primordial pool in
* addition to the storage space they are a member of.
*/
public static WmiResult<StoragePoolToPhysicalDiskProperty> queryStoragePoolPhysicalDisks(WmiQueryHandler h) {
WmiQuery<StoragePoolToPhysicalDiskProperty> storagePoolToPhysicalDiskQuery = new WmiQuery<>(STORAGE_NAMESPACE,
MSFT_STORAGE_POOL_TO_PHYSICAL_DISK, StoragePoolToPhysicalDiskProperty.class);
return h.queryWMI(storagePoolToPhysicalDiskQuery, false);
}
/**
* Query the physical disks.
*
* @param h An instantiated {@link WmiQueryHandler}. User should have already initialized COM.
* @return The physical disks.
*/
public static WmiResult<PhysicalDiskProperty> queryPhysicalDisks(WmiQueryHandler h) {<FILL_FUNCTION_BODY>}
/**
* Query the virtual disks.
*
* @param h An instantiated {@link WmiQueryHandler}. User should have already initialized COM.
* @return The virtual disks.
*/
public static WmiResult<VirtualDiskProperty> queryVirtualDisks(WmiQueryHandler h) {
WmiQuery<VirtualDiskProperty> virtualDiskQuery = new WmiQuery<>(STORAGE_NAMESPACE, MSFT_VIRTUAL_DISK,
VirtualDiskProperty.class);
return h.queryWMI(virtualDiskQuery, false);
}
}
|
WmiQuery<PhysicalDiskProperty> physicalDiskQuery = new WmiQuery<>(STORAGE_NAMESPACE, MSFT_PHYSICAL_DISK,
PhysicalDiskProperty.class);
return h.queryWMI(physicalDiskQuery, false);
| 994
| 66
| 1,060
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/wmi/OhmHardware.java
|
OhmHardware
|
queryHwIdentifier
|
class OhmHardware {
private static final String HARDWARE = "Hardware";
/**
* HW Identifier Property
*/
public enum IdentifierProperty {
IDENTIFIER;
}
private OhmHardware() {
}
/**
* Queries the hardware identifiers for a monitored type.
*
* @param h An instantiated {@link WmiQueryHandler}. User should have already initialized COM.
* @param typeToQuery which type to filter based on
* @param typeName the name of the type
* @return The sensor value.
*/
public static WmiResult<IdentifierProperty> queryHwIdentifier(WmiQueryHandler h, String typeToQuery,
String typeName) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sb = new StringBuilder(HARDWARE);
sb.append(" WHERE ").append(typeToQuery).append("Type=\"").append(typeName).append('\"');
WmiQuery<IdentifierProperty> cpuIdentifierQuery = new WmiQuery<>(WmiUtil.OHM_NAMESPACE, sb.toString(),
IdentifierProperty.class);
return h.queryWMI(cpuIdentifierQuery, false);
| 203
| 108
| 311
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/wmi/OhmSensor.java
|
OhmSensor
|
querySensorValue
|
class OhmSensor {
private static final String SENSOR = "Sensor";
/**
* Sensor value property
*/
public enum ValueProperty {
VALUE;
}
private OhmSensor() {
}
/**
* Queries the sensor value of an hardware identifier and sensor type.
*
* @param h An instantiated {@link WmiQueryHandler}. User should have already initialized COM.
* @param identifier The identifier whose value to query.
* @param sensorType The type of sensor to query.
* @return The sensor value.
*/
public static WmiResult<ValueProperty> querySensorValue(WmiQueryHandler h, String identifier, String sensorType) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sb = new StringBuilder(SENSOR);
sb.append(" WHERE Parent = \"").append(identifier);
sb.append("\" AND SensorType=\"").append(sensorType).append('\"');
WmiQuery<ValueProperty> ohmSensorQuery = new WmiQuery<>(WmiUtil.OHM_NAMESPACE, sb.toString(),
ValueProperty.class);
return h.queryWMI(ohmSensorQuery, false);
| 194
| 119
| 313
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/wmi/Win32DiskDrive.java
|
Win32DiskDrive
|
queryDiskDrive
|
class Win32DiskDrive {
private static final String WIN32_DISK_DRIVE = "Win32_DiskDrive";
/**
* Disk drive properties
*/
public enum DiskDriveProperty {
INDEX, MANUFACTURER, MODEL, NAME, SERIALNUMBER, SIZE;
}
private Win32DiskDrive() {
}
/**
* Queries the disk drive name info
*
* @param h An instantiated {@link WmiQueryHandler}. User should have already initialized COM.
* @return Information regarding each disk drive.
*/
public static WmiResult<DiskDriveProperty> queryDiskDrive(WmiQueryHandler h) {<FILL_FUNCTION_BODY>}
}
|
WmiQuery<DiskDriveProperty> diskDriveQuery = new WmiQuery<>(WIN32_DISK_DRIVE, DiskDriveProperty.class);
return h.queryWMI(diskDriveQuery, false);
| 193
| 58
| 251
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/wmi/Win32DiskDriveToDiskPartition.java
|
Win32DiskDriveToDiskPartition
|
queryDriveToPartition
|
class Win32DiskDriveToDiskPartition {
private static final String WIN32_DISK_DRIVE_TO_DISK_PARTITION = "Win32_DiskDriveToDiskPartition";
/**
* Links disk drives to partitions
*/
public enum DriveToPartitionProperty {
ANTECEDENT, DEPENDENT;
}
private Win32DiskDriveToDiskPartition() {
}
/**
* Queries the association between disk drive and partition.
*
* @param h An instantiated {@link WmiQueryHandler}. User should have already initialized COM.
* @return Antecedent-dependent pairs of disk and partition.
*/
public static WmiResult<DriveToPartitionProperty> queryDriveToPartition(WmiQueryHandler h) {<FILL_FUNCTION_BODY>}
}
|
WmiQuery<DriveToPartitionProperty> driveToPartitionQuery = new WmiQuery<>(WIN32_DISK_DRIVE_TO_DISK_PARTITION,
DriveToPartitionProperty.class);
return h.queryWMI(driveToPartitionQuery, false);
| 213
| 69
| 282
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/wmi/Win32DiskPartition.java
|
Win32DiskPartition
|
queryPartition
|
class Win32DiskPartition {
private static final String WIN32_DISK_PARTITION = "Win32_DiskPartition";
/**
* Disk partition properties
*/
public enum DiskPartitionProperty {
INDEX, DESCRIPTION, DEVICEID, DISKINDEX, NAME, SIZE, TYPE;
}
private Win32DiskPartition() {
}
/**
* Queries the partition.
*
* @param h An instantiated {@link WmiQueryHandler}. User should have already initialized COM.
* @return Information regarding each disk partition.
*/
public static WmiResult<DiskPartitionProperty> queryPartition(WmiQueryHandler h) {<FILL_FUNCTION_BODY>}
}
|
WmiQuery<DiskPartitionProperty> partitionQuery = new WmiQuery<>(WIN32_DISK_PARTITION,
DiskPartitionProperty.class);
return h.queryWMI(partitionQuery, false);
| 183
| 54
| 237
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/wmi/Win32LogicalDisk.java
|
Win32LogicalDisk
|
queryLogicalDisk
|
class Win32LogicalDisk {
private static final String WIN32_LOGICAL_DISK = "Win32_LogicalDisk";
/**
* Logical disk properties.
*/
public enum LogicalDiskProperty {
ACCESS, DESCRIPTION, DRIVETYPE, FILESYSTEM, FREESPACE, NAME, PROVIDERNAME, SIZE, VOLUMENAME;
}
private Win32LogicalDisk() {
}
/**
* Queries logical disk information
*
* @param nameToMatch an optional string to filter match, null otherwise
* @param localOnly Whether to only search local drives
* @return Logical Disk Information
*/
public static WmiResult<LogicalDiskProperty> queryLogicalDisk(String nameToMatch, boolean localOnly) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder wmiClassName = new StringBuilder(WIN32_LOGICAL_DISK);
boolean where = false;
if (localOnly) {
wmiClassName.append(" WHERE DriveType != 4");
where = true;
}
if (nameToMatch != null) {
wmiClassName.append(where ? " AND" : " WHERE").append(" Name=\"").append(nameToMatch).append('\"');
}
WmiQuery<LogicalDiskProperty> logicalDiskQuery = new WmiQuery<>(wmiClassName.toString(),
LogicalDiskProperty.class);
return Objects.requireNonNull(WmiQueryHandler.createInstance()).queryWMI(logicalDiskQuery);
| 218
| 180
| 398
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/wmi/Win32LogicalDiskToPartition.java
|
Win32LogicalDiskToPartition
|
queryDiskToPartition
|
class Win32LogicalDiskToPartition {
private static final String WIN32_LOGICAL_DISK_TO_PARTITION = "Win32_LogicalDiskToPartition";
/**
* Links disk drives to partitions
*/
public enum DiskToPartitionProperty {
ANTECEDENT, DEPENDENT, ENDINGADDRESS, STARTINGADDRESS;
}
private Win32LogicalDiskToPartition() {
}
/**
* Queries the association between logical disk and partition.
*
* @param h An instantiated {@link WmiQueryHandler}. User should have already initialized COM.
* @return Antecedent-dependent pairs of disk and partition.
*/
public static WmiResult<DiskToPartitionProperty> queryDiskToPartition(WmiQueryHandler h) {<FILL_FUNCTION_BODY>}
}
|
WmiQuery<DiskToPartitionProperty> diskToPartitionQuery = new WmiQuery<>(WIN32_LOGICAL_DISK_TO_PARTITION,
DiskToPartitionProperty.class);
return h.queryWMI(diskToPartitionQuery, false);
| 215
| 65
| 280
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/wmi/Win32Process.java
|
Win32Process
|
queryProcesses
|
class Win32Process {
private static final String WIN32_PROCESS = "Win32_Process";
/**
* Process command lines.
*/
public enum CommandLineProperty {
PROCESSID, COMMANDLINE;
}
/**
* Process properties accessible from WTSEnumerateProcesses in Vista+
*/
public enum ProcessXPProperty {
PROCESSID, NAME, KERNELMODETIME, USERMODETIME, THREADCOUNT, PAGEFILEUSAGE, HANDLECOUNT, EXECUTABLEPATH;
}
private Win32Process() {
}
/**
* Returns process command lines
*
* @param pidsToQuery Process IDs to query for command lines. Pass {@code null} to query all processes.
* @return A {@link WmiResult} containing process IDs and command lines used to start the provided processes.
*/
public static WmiResult<CommandLineProperty> queryCommandLines(Set<Integer> pidsToQuery) {
String sb = WIN32_PROCESS;
if (pidsToQuery != null) {
sb += " WHERE ProcessID="
+ pidsToQuery.stream().map(String::valueOf).collect(Collectors.joining(" OR PROCESSID="));
}
WmiQuery<CommandLineProperty> commandLineQuery = new WmiQuery<>(sb, CommandLineProperty.class);
return Objects.requireNonNull(WmiQueryHandler.createInstance()).queryWMI(commandLineQuery);
}
/**
* Returns process info
*
* @param pids Process IDs to query.
* @return Information on the provided processes.
*/
public static WmiResult<ProcessXPProperty> queryProcesses(Collection<Integer> pids) {<FILL_FUNCTION_BODY>}
}
|
String sb = WIN32_PROCESS;
if (pids != null) {
sb += " WHERE ProcessID="
+ pids.stream().map(String::valueOf).collect(Collectors.joining(" OR PROCESSID="));
}
WmiQuery<ProcessXPProperty> processQueryXP = new WmiQuery<>(sb, ProcessXPProperty.class);
return Objects.requireNonNull(WmiQueryHandler.createInstance()).queryWMI(processQueryXP);
| 462
| 127
| 589
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/driver/windows/wmi/Win32ProcessCached.java
|
Win32ProcessCached
|
getCommandLine
|
class Win32ProcessCached {
private static final Supplier<Win32ProcessCached> INSTANCE = memoize(Win32ProcessCached::createInstance);
// Use a map to cache command line queries
@GuardedBy("commandLineCacheLock")
private final Map<Integer, Pair<Long, String>> commandLineCache = new HashMap<>();
private final ReentrantLock commandLineCacheLock = new ReentrantLock();
private Win32ProcessCached() {
}
/**
* Get the singleton instance of this class, instantiating the map which caches command lines.
*
* @return the singleton instance
*/
public static Win32ProcessCached getInstance() {
return INSTANCE.get();
}
private static Win32ProcessCached createInstance() {
return new Win32ProcessCached();
}
/**
* Gets the process command line, while also querying and caching command lines for all running processes if the
* specified process is not in the cache.
* <p>
* When iterating over a process list, the WMI overhead of querying each single command line can quickly exceed the
* time it takes to query all command lines. This method permits access to cached queries from a previous call,
* significantly improving aggregate performance.
*
* @param processId The process ID for which to return the command line.
* @param startTime The start time of the process, in milliseconds since the 1970 epoch. If this start time is after
* the time this process was previously queried, the prior entry will be deemed invalid and the
* cache refreshed.
* @return The command line of the specified process. If the command line is cached from a previous call and the
* start time is prior to the time it was cached, this method will quickly return the cached value.
* Otherwise, will refresh the cache with all running processes prior to returning, which may incur some
* latency.
* <p>
* May return a command line from the cache even after a process has terminated. Otherwise will return the
* empty string.
*/
public String getCommandLine(int processId, long startTime) {<FILL_FUNCTION_BODY>}
}
|
// We could use synchronized method but this is more clear
commandLineCacheLock.lock();
try {
// See if this process is in the cache already
Pair<Long, String> pair = commandLineCache.get(processId);
// Valid process must have been started before map insertion
if (pair != null && startTime < pair.getA()) {
// Entry is valid, return it!
return pair.getB();
} else {
// Invalid entry, rebuild cache
// Processes started after this time will be invalid
long now = System.currentTimeMillis();
// Gets all processes. Takes ~200ms
WmiResult<CommandLineProperty> commandLineAllProcs = Win32Process.queryCommandLines(null);
// Stale processes use resources. Periodically clear before building
// Use a threshold of map size > 2x # of processes
if (commandLineCache.size() > commandLineAllProcs.getResultCount() * 2) {
commandLineCache.clear();
}
// Iterate results and put in map. Save value for current PID along the way
String result = "";
for (int i = 0; i < commandLineAllProcs.getResultCount(); i++) {
int pid = WmiUtil.getUint32(commandLineAllProcs, CommandLineProperty.PROCESSID, i);
String cl = WmiUtil.getString(commandLineAllProcs, CommandLineProperty.COMMANDLINE, i);
commandLineCache.put(pid, new Pair<>(now, cl));
if (pid == processId) {
result = cl;
}
}
return result;
}
} finally {
commandLineCacheLock.unlock();
}
| 557
| 431
| 988
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/hardware/HWPartition.java
|
HWPartition
|
toString
|
class HWPartition {
private final String identification;
private final String name;
private final String type;
private final String uuid;
private final long size;
private final int major;
private final int minor;
private final String mountPoint;
/**
* Creates a new HWPartition
*
* @param identification The unique partition id
* @param name Friendly name of the partition
* @param type Type or description of the partition
* @param uuid UUID
* @param size Size in bytes
* @param major Device ID (Major)
* @param minor Device ID (Minor)
* @param mountPoint Where the partition is mounted
*/
public HWPartition(String identification, String name, String type, String uuid, long size, int major, int minor,
String mountPoint) {
this.identification = identification;
this.name = name;
this.type = type;
this.uuid = uuid;
this.size = size;
this.major = major;
this.minor = minor;
this.mountPoint = mountPoint;
}
/**
* <p>
* Getter for the field <code>identification</code>.
* </p>
*
* @return Returns the identification.
*/
public String getIdentification() {
return this.identification;
}
/**
* <p>
* Getter for the field <code>name</code>.
* </p>
*
* @return Returns the name.
*/
public String getName() {
return this.name;
}
/**
* <p>
* Getter for the field <code>type</code>.
* </p>
*
* @return Returns the type.
*/
public String getType() {
return this.type;
}
/**
* <p>
* Getter for the field <code>uuid</code>.
* </p>
*
* @return Returns the uuid.
*/
public String getUuid() {
return this.uuid;
}
/**
* <p>
* Getter for the field <code>size</code>.
* </p>
*
* @return Returns the size in bytes.
*/
public long getSize() {
return this.size;
}
/**
* <p>
* Getter for the field <code>major</code>.
* </p>
*
* @return Returns the major device ID.
*/
public int getMajor() {
return this.major;
}
/**
* <p>
* Getter for the field <code>minor</code>.
* </p>
*
* @return Returns the minor device ID.
*/
public int getMinor() {
return this.minor;
}
/**
* <p>
* Getter for the field <code>mountPoint</code>.
* </p>
*
* @return Returns the mount point.
*/
public String getMountPoint() {
return this.mountPoint;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sb = new StringBuilder();
sb.append(getIdentification()).append(": ");
sb.append(getName()).append(" ");
sb.append("(").append(getType()).append(") ");
sb.append("Maj:Min=").append(getMajor()).append(":").append(getMinor()).append(", ");
sb.append("size: ").append(FormatUtil.formatBytesDecimal(getSize()));
sb.append(getMountPoint().isEmpty() ? "" : " @ " + getMountPoint());
return sb.toString();
| 869
| 140
| 1,009
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/hardware/PhysicalMemory.java
|
PhysicalMemory
|
toString
|
class PhysicalMemory {
private final String bankLabel;
private final long capacity;
private final long clockSpeed;
private final String manufacturer;
private final String memoryType;
private final String partNumber;
public PhysicalMemory(String bankLabel, long capacity, long clockSpeed, String manufacturer, String memoryType,
String partNumber) {
this.bankLabel = bankLabel;
this.capacity = capacity;
this.clockSpeed = clockSpeed;
this.manufacturer = manufacturer;
this.memoryType = memoryType;
this.partNumber = partNumber;
}
/**
* The bank and/or slot label.
*
* @return the bank label
*/
public String getBankLabel() {
return bankLabel;
}
/**
* The capacity of memory bank in bytes.
*
* @return the capacity
*/
public long getCapacity() {
return capacity;
}
/**
* The configured memory clock speed in hertz.
* <p>
* For DDR memory, this is the data transfer rate, which is a multiple of the actual bus clock speed.
*
* @return the clock speed, if avaialable. If unknown, returns -1.
*/
public long getClockSpeed() {
return clockSpeed;
}
/**
* The manufacturer of the physical memory.
*
* @return the manufacturer
*/
public String getManufacturer() {
return manufacturer;
}
/**
* The type of physical memory
*
* @return the memory type
*/
public String getMemoryType() {
return memoryType;
}
/**
* The part number of the physical memory
*
* @return the part number
*/
public String getPartNumber() {
return partNumber;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sb = new StringBuilder();
sb.append("Bank label: " + getBankLabel());
sb.append(", Capacity: " + FormatUtil.formatBytes(getCapacity()));
sb.append(", Clock speed: " + FormatUtil.formatHertz(getClockSpeed()));
sb.append(", Manufacturer: " + getManufacturer());
sb.append(", Memory type: " + getMemoryType());
sb.append(", Part number: " + getPartNumber());
return sb.toString();
| 496
| 134
| 630
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/hardware/common/AbstractBaseboard.java
|
AbstractBaseboard
|
toString
|
class AbstractBaseboard implements Baseboard {
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sb = new StringBuilder();
sb.append("manufacturer=").append(getManufacturer()).append(", ");
sb.append("model=").append(getModel()).append(", ");
sb.append("version=").append(getVersion()).append(", ");
sb.append("serial number=").append(getSerialNumber());
return sb.toString();
| 37
| 94
| 131
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/hardware/common/AbstractComputerSystem.java
|
AbstractComputerSystem
|
toString
|
class AbstractComputerSystem implements ComputerSystem {
private final Supplier<Firmware> firmware = memoize(this::createFirmware);
private final Supplier<Baseboard> baseboard = memoize(this::createBaseboard);
@Override
public Firmware getFirmware() {
return firmware.get();
}
/**
* Instantiates the platform-specific {@link Firmware} object
*
* @return platform-specific {@link Firmware} object
*/
protected abstract Firmware createFirmware();
@Override
public Baseboard getBaseboard() {
return baseboard.get();
}
/**
* Instantiates the platform-specific {@link Baseboard} object
*
* @return platform-specific {@link Baseboard} object
*/
protected abstract Baseboard createBaseboard();
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sb = new StringBuilder();
sb.append("manufacturer=").append(getManufacturer()).append(", ");
sb.append("model=").append(getModel()).append(", ");
sb.append("serial number=").append(getSerialNumber()).append(", ");
sb.append("uuid=").append(getHardwareUUID());
return sb.toString();
| 243
| 96
| 339
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/hardware/common/AbstractFirmware.java
|
AbstractFirmware
|
toString
|
class AbstractFirmware implements Firmware {
/*
* Multiple classes don't have these, set defaults here
*/
@Override
public String getName() {
return Constants.UNKNOWN;
}
@Override
public String getDescription() {
return Constants.UNKNOWN;
}
@Override
public String getReleaseDate() {
return Constants.UNKNOWN;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sb = new StringBuilder();
sb.append("manufacturer=").append(getManufacturer()).append(", ");
sb.append("name=").append(getName()).append(", ");
sb.append("description=").append(getDescription()).append(", ");
sb.append("version=").append(getVersion()).append(", ");
sb.append("release date=").append(getReleaseDate() == null ? "unknown" : getReleaseDate());
return sb.toString();
| 143
| 122
| 265
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/hardware/common/AbstractGlobalMemory.java
|
AbstractGlobalMemory
|
getPhysicalMemory
|
class AbstractGlobalMemory implements GlobalMemory {
@Override
public List<PhysicalMemory> getPhysicalMemory() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Available: ");
sb.append(FormatUtil.formatBytes(getAvailable()));
sb.append("/");
sb.append(FormatUtil.formatBytes(getTotal()));
return sb.toString();
}
}
|
// dmidecode requires sudo permission but is the only option on Linux
// and Unix
List<PhysicalMemory> pmList = new ArrayList<>();
List<String> dmi = ExecutingCommand.runNative("dmidecode --type 17");
int bank = 0;
String bankLabel = Constants.UNKNOWN;
String locator = "";
long capacity = 0L;
long speed = 0L;
String manufacturer = Constants.UNKNOWN;
String memoryType = Constants.UNKNOWN;
String partNumber = Constants.UNKNOWN;
for (String line : dmi) {
if (line.trim().contains("DMI type 17")) {
// Save previous bank
if (bank++ > 0) {
if (capacity > 0) {
pmList.add(new PhysicalMemory(bankLabel + locator, capacity, speed, manufacturer, memoryType,
partNumber));
}
bankLabel = Constants.UNKNOWN;
locator = "";
capacity = 0L;
speed = 0L;
}
} else if (bank > 0) {
String[] split = line.trim().split(":");
if (split.length == 2) {
switch (split[0]) {
case "Bank Locator":
bankLabel = split[1].trim();
break;
case "Locator":
locator = "/" + split[1].trim();
break;
case "Size":
capacity = ParseUtil.parseDecimalMemorySizeToBinary(split[1].trim());
break;
case "Type":
memoryType = split[1].trim();
break;
case "Speed":
speed = ParseUtil.parseHertz(split[1]);
break;
case "Manufacturer":
manufacturer = split[1].trim();
break;
case "PartNumber":
case "Part Number":
partNumber = split[1].trim();
break;
default:
break;
}
}
}
}
if (capacity > 0) {
pmList.add(new PhysicalMemory(bankLabel + locator, capacity, speed, manufacturer, memoryType, partNumber));
}
return pmList;
| 122
| 569
| 691
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.java
|
AbstractGraphicsCard
|
toString
|
class AbstractGraphicsCard implements GraphicsCard {
private final String name;
private final String deviceId;
private final String vendor;
private final String versionInfo;
private long vram;
/**
* Constructor for AbstractGraphicsCard
*
* @param name The name
* @param deviceId The device ID
* @param vendor The vendor
* @param versionInfo The version info
* @param vram The VRAM
*/
protected AbstractGraphicsCard(String name, String deviceId, String vendor, String versionInfo, long vram) {
this.name = name;
this.deviceId = deviceId;
this.vendor = vendor;
this.versionInfo = versionInfo;
this.vram = vram;
}
@Override
public String getName() {
return name;
}
@Override
public String getDeviceId() {
return deviceId;
}
@Override
public String getVendor() {
return vendor;
}
@Override
public String getVersionInfo() {
return versionInfo;
}
@Override
public long getVRam() {
return vram;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder builder = new StringBuilder();
builder.append("GraphicsCard@");
builder.append(Integer.toHexString(hashCode()));
builder.append(" [name=");
builder.append(this.name);
builder.append(", deviceId=");
builder.append(this.deviceId);
builder.append(", vendor=");
builder.append(this.vendor);
builder.append(", vRam=");
builder.append(this.vram);
builder.append(", versionInfo=[");
builder.append(this.versionInfo);
builder.append("]]");
return builder.toString();
| 331
| 162
| 493
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/hardware/common/AbstractHWDiskStore.java
|
AbstractHWDiskStore
|
toString
|
class AbstractHWDiskStore implements HWDiskStore {
private final String name;
private final String model;
private final String serial;
private final long size;
protected AbstractHWDiskStore(String name, String model, String serial, long size) {
this.name = name;
this.model = model;
this.serial = serial;
this.size = size;
}
@Override
public String getName() {
return this.name;
}
@Override
public String getModel() {
return this.model;
}
@Override
public String getSerial() {
return this.serial;
}
@Override
public long getSize() {
return this.size;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
boolean readwrite = getReads() > 0 || getWrites() > 0;
StringBuilder sb = new StringBuilder();
sb.append(getName()).append(": ");
sb.append("(model: ").append(getModel());
sb.append(" - S/N: ").append(getSerial()).append(") ");
sb.append("size: ").append(getSize() > 0 ? FormatUtil.formatBytesDecimal(getSize()) : "?").append(", ");
sb.append("reads: ").append(readwrite ? getReads() : "?");
sb.append(" (").append(readwrite ? FormatUtil.formatBytes(getReadBytes()) : "?").append("), ");
sb.append("writes: ").append(readwrite ? getWrites() : "?");
sb.append(" (").append(readwrite ? FormatUtil.formatBytes(getWriteBytes()) : "?").append("), ");
sb.append("xfer: ").append(readwrite ? getTransferTime() : "?");
return sb.toString();
| 219
| 262
| 481
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/hardware/common/AbstractLogicalVolumeGroup.java
|
AbstractLogicalVolumeGroup
|
toString
|
class AbstractLogicalVolumeGroup implements LogicalVolumeGroup {
private final String name;
private final Map<String, Set<String>> lvMap;
private final Set<String> pvSet;
/**
* @param name Name of the volume group
* @param lvMap Logical volumes derived from this volume group and the physical volumes its mapped to.
* @param pvSet Set of physical volumes this volume group consists of.
*/
protected AbstractLogicalVolumeGroup(String name, Map<String, Set<String>> lvMap, Set<String> pvSet) {
this.name = name;
for (Entry<String, Set<String>> entry : lvMap.entrySet()) {
lvMap.put(entry.getKey(), Collections.unmodifiableSet(entry.getValue()));
}
this.lvMap = Collections.unmodifiableMap(lvMap);
this.pvSet = Collections.unmodifiableSet(pvSet);
}
@Override
public String getName() {
return name;
}
@Override
public Map<String, Set<String>> getLogicalVolumes() {
return lvMap;
}
@Override
public Set<String> getPhysicalVolumes() {
return pvSet;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sb = new StringBuilder("Logical Volume Group: ");
sb.append(name).append("\n |-- PVs: ");
sb.append(pvSet.toString());
for (Entry<String, Set<String>> entry : lvMap.entrySet()) {
sb.append("\n |-- LV: ").append(entry.getKey());
Set<String> mappedPVs = entry.getValue();
if (!mappedPVs.isEmpty()) {
sb.append(" --> ").append(mappedPVs);
}
}
return sb.toString();
| 352
| 147
| 499
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/hardware/common/AbstractSensors.java
|
AbstractSensors
|
toString
|
class AbstractSensors implements Sensors {
private final Supplier<Double> cpuTemperature = memoize(this::queryCpuTemperature, defaultExpiration());
private final Supplier<int[]> fanSpeeds = memoize(this::queryFanSpeeds, defaultExpiration());
private final Supplier<Double> cpuVoltage = memoize(this::queryCpuVoltage, defaultExpiration());
@Override
public double getCpuTemperature() {
return cpuTemperature.get();
}
protected abstract double queryCpuTemperature();
@Override
public int[] getFanSpeeds() {
return fanSpeeds.get();
}
protected abstract int[] queryFanSpeeds();
@Override
public double getCpuVoltage() {
return cpuVoltage.get();
}
protected abstract double queryCpuVoltage();
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sb = new StringBuilder();
sb.append("CPU Temperature=").append(getCpuTemperature()).append("C, ");
sb.append("Fan Speeds=").append(Arrays.toString(getFanSpeeds())).append(", ");
sb.append("CPU Voltage=").append(getCpuVoltage());
return sb.toString();
| 255
| 93
| 348
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/hardware/common/AbstractSoundCard.java
|
AbstractSoundCard
|
toString
|
class AbstractSoundCard implements SoundCard {
private String kernelVersion;
private String name;
private String codec;
/**
* Abstract Sound Card Constructor
*
* @param kernelVersion The version
* @param name The name
* @param codec The codec
*/
protected AbstractSoundCard(String kernelVersion, String name, String codec) {
this.kernelVersion = kernelVersion;
this.name = name;
this.codec = codec;
}
@Override
public String getDriverVersion() {
return this.kernelVersion;
}
@Override
public String getName() {
return this.name;
}
@Override
public String getCodec() {
return this.codec;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder builder = new StringBuilder();
builder.append("SoundCard@");
builder.append(Integer.toHexString(hashCode()));
builder.append(" [name=");
builder.append(this.name);
builder.append(", kernelVersion=");
builder.append(this.kernelVersion);
builder.append(", codec=");
builder.append(this.codec);
builder.append(']');
return builder.toString();
| 226
| 117
| 343
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/hardware/common/AbstractUsbDevice.java
|
AbstractUsbDevice
|
indentUsb
|
class AbstractUsbDevice implements UsbDevice {
private final String name;
private final String vendor;
private final String vendorId;
private final String productId;
private final String serialNumber;
private final String uniqueDeviceId;
private final List<UsbDevice> connectedDevices;
protected AbstractUsbDevice(String name, String vendor, String vendorId, String productId, String serialNumber,
String uniqueDeviceId, List<UsbDevice> connectedDevices) {
this.name = name;
this.vendor = vendor;
this.vendorId = vendorId;
this.productId = productId;
this.serialNumber = serialNumber;
this.uniqueDeviceId = uniqueDeviceId;
this.connectedDevices = Collections.unmodifiableList(connectedDevices);
}
@Override
public String getName() {
return this.name;
}
@Override
public String getVendor() {
return this.vendor;
}
@Override
public String getVendorId() {
return this.vendorId;
}
@Override
public String getProductId() {
return this.productId;
}
@Override
public String getSerialNumber() {
return this.serialNumber;
}
@Override
public String getUniqueDeviceId() {
return this.uniqueDeviceId;
}
@Override
public List<UsbDevice> getConnectedDevices() {
return this.connectedDevices;
}
@Override
public int compareTo(UsbDevice usb) {
// Naturally sort by device name
return getName().compareTo(usb.getName());
}
@Override
public String toString() {
return indentUsb(this, 1);
}
/**
* Helper method for indenting chained USB devices
*
* @param usbDevice A USB device to print
* @param indent number of spaces to indent
* @return The device toString, indented
*/
private static String indentUsb(UsbDevice usbDevice, int indent) {<FILL_FUNCTION_BODY>}
}
|
String indentFmt = indent > 4 ? String.format(Locale.ROOT, "%%%ds|-- ", indent - 4)
: String.format(Locale.ROOT, "%%%ds", indent);
StringBuilder sb = new StringBuilder(String.format(Locale.ROOT, indentFmt, ""));
sb.append(usbDevice.getName());
if (!usbDevice.getVendor().isEmpty()) {
sb.append(" (").append(usbDevice.getVendor()).append(')');
}
if (!usbDevice.getSerialNumber().isEmpty()) {
sb.append(" [s/n: ").append(usbDevice.getSerialNumber()).append(']');
}
for (UsbDevice connected : usbDevice.getConnectedDevices()) {
sb.append('\n').append(indentUsb(connected, indent + 4));
}
return sb.toString();
| 552
| 230
| 782
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/hardware/common/AbstractVirtualMemory.java
|
AbstractVirtualMemory
|
toString
|
class AbstractVirtualMemory implements VirtualMemory {
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sb = new StringBuilder();
sb.append("Swap Used/Avail: ");
sb.append(FormatUtil.formatBytes(getSwapUsed()));
sb.append("/");
sb.append(FormatUtil.formatBytes(getSwapTotal()));
sb.append(", Virtual Memory In Use/Max=");
sb.append(FormatUtil.formatBytes(getVirtualInUse()));
sb.append("/");
sb.append(FormatUtil.formatBytes(getVirtualMax()));
return sb.toString();
| 36
| 130
| 166
|
<no_super_class>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxBaseboard.java
|
LinuxBaseboard
|
queryManufacturer
|
class LinuxBaseboard extends AbstractBaseboard {
private final Supplier<String> manufacturer = memoize(this::queryManufacturer);
private final Supplier<String> model = memoize(this::queryModel);
private final Supplier<String> version = memoize(this::queryVersion);
private final Supplier<String> serialNumber = memoize(this::querySerialNumber);
private final Supplier<Quartet<String, String, String, String>> manufacturerModelVersionSerial = memoize(
CpuInfo::queryBoardInfo);
@Override
public String getManufacturer() {
return manufacturer.get();
}
@Override
public String getModel() {
return model.get();
}
@Override
public String getVersion() {
return version.get();
}
@Override
public String getSerialNumber() {
return serialNumber.get();
}
private String queryManufacturer() {<FILL_FUNCTION_BODY>}
private String queryModel() {
String result = null;
if ((result = Sysfs.queryBoardModel()) == null
&& (result = manufacturerModelVersionSerial.get().getB()) == null) {
return Constants.UNKNOWN;
}
return result;
}
private String queryVersion() {
String result = null;
if ((result = Sysfs.queryBoardVersion()) == null
&& (result = manufacturerModelVersionSerial.get().getC()) == null) {
return Constants.UNKNOWN;
}
return result;
}
private String querySerialNumber() {
String result = null;
if ((result = Sysfs.queryBoardSerial()) == null
&& (result = manufacturerModelVersionSerial.get().getD()) == null) {
return Constants.UNKNOWN;
}
return result;
}
}
|
String result = null;
if ((result = Sysfs.queryBoardVendor()) == null
&& (result = manufacturerModelVersionSerial.get().getA()) == null) {
return Constants.UNKNOWN;
}
return result;
| 481
| 67
| 548
|
<methods>public non-sealed void <init>() ,public java.lang.String toString() <variables>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxComputerSystem.java
|
LinuxComputerSystem
|
queryManufacturer
|
class LinuxComputerSystem extends AbstractComputerSystem {
private final Supplier<String> manufacturer = memoize(LinuxComputerSystem::queryManufacturer);
private final Supplier<String> model = memoize(LinuxComputerSystem::queryModel);
private final Supplier<String> serialNumber = memoize(LinuxComputerSystem::querySerialNumber);
private final Supplier<String> uuid = memoize(LinuxComputerSystem::queryUUID);
@Override
public String getManufacturer() {
return manufacturer.get();
}
@Override
public String getModel() {
return model.get();
}
@Override
public String getSerialNumber() {
return serialNumber.get();
}
@Override
public String getHardwareUUID() {
return uuid.get();
}
@Override
public Firmware createFirmware() {
return new LinuxFirmware();
}
@Override
public Baseboard createBaseboard() {
return new LinuxBaseboard();
}
private static String queryManufacturer() {<FILL_FUNCTION_BODY>}
private static String queryModel() {
String result = null;
if ((result = Sysfs.queryProductModel()) == null && (result = Devicetree.queryModel()) == null
&& (result = Lshw.queryModel()) == null) {
return Constants.UNKNOWN;
}
return result;
}
private static String querySerialNumber() {
String result = null;
if ((result = Sysfs.queryProductSerial()) == null && (result = Dmidecode.querySerialNumber()) == null
&& (result = Lshal.querySerialNumber()) == null && (result = Lshw.querySerialNumber()) == null) {
return Constants.UNKNOWN;
}
return result;
}
private static String queryUUID() {
String result = null;
if ((result = Sysfs.queryUUID()) == null && (result = Dmidecode.queryUUID()) == null
&& (result = Lshal.queryUUID()) == null && (result = Lshw.queryUUID()) == null) {
return Constants.UNKNOWN;
}
return result;
}
}
|
String result = null;
if ((result = Sysfs.querySystemVendor()) == null && (result = CpuInfo.queryCpuManufacturer()) == null) {
return Constants.UNKNOWN;
}
return result;
| 578
| 65
| 643
|
<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/linux/LinuxFirmware.java
|
LinuxFirmware
|
queryVersion
|
class LinuxFirmware extends AbstractFirmware {
// Jan 13 2013 16:24:29
private static final DateTimeFormatter VCGEN_FORMATTER = DateTimeFormatter.ofPattern("MMM d uuuu HH:mm:ss",
Locale.ENGLISH);
private final Supplier<String> manufacturer = memoize(this::queryManufacturer);
private final Supplier<String> description = memoize(this::queryDescription);
private final Supplier<String> version = memoize(this::queryVersion);
private final Supplier<String> releaseDate = memoize(this::queryReleaseDate);
private final Supplier<String> name = memoize(this::queryName);
private final Supplier<VcGenCmdStrings> vcGenCmd = memoize(LinuxFirmware::queryVcGenCmd);
private final Supplier<Pair<String, String>> biosNameRev = memoize(Dmidecode::queryBiosNameRev);
@Override
public String getManufacturer() {
return manufacturer.get();
}
@Override
public String getDescription() {
return description.get();
}
@Override
public String getVersion() {
return version.get();
}
@Override
public String getReleaseDate() {
return releaseDate.get();
}
@Override
public String getName() {
return name.get();
}
private String queryManufacturer() {
String result = null;
if ((result = Sysfs.queryBiosVendor()) == null && (result = vcGenCmd.get().manufacturer) == null) {
return Constants.UNKNOWN;
}
return result;
}
private String queryDescription() {
String result = null;
if ((result = Sysfs.queryBiosDescription()) == null && (result = vcGenCmd.get().description) == null) {
return Constants.UNKNOWN;
}
return result;
}
private String queryVersion() {<FILL_FUNCTION_BODY>}
private String queryReleaseDate() {
String result = null;
if ((result = Sysfs.queryBiosReleaseDate()) == null && (result = vcGenCmd.get().releaseDate) == null) {
return Constants.UNKNOWN;
}
return result;
}
private String queryName() {
String result = null;
if ((result = biosNameRev.get().getA()) == null && (result = vcGenCmd.get().name) == null) {
return Constants.UNKNOWN;
}
return result;
}
private static VcGenCmdStrings queryVcGenCmd() {
String vcReleaseDate = null;
String vcManufacturer = null;
String vcVersion = null;
List<String> vcgencmd = ExecutingCommand.runNative("vcgencmd version");
if (vcgencmd.size() >= 3) {
// First line is date
try {
vcReleaseDate = DateTimeFormatter.ISO_LOCAL_DATE.format(VCGEN_FORMATTER.parse(vcgencmd.get(0)));
} catch (DateTimeParseException e) {
vcReleaseDate = Constants.UNKNOWN;
}
// Second line is copyright
String[] copyright = ParseUtil.whitespaces.split(vcgencmd.get(1));
vcManufacturer = copyright[copyright.length - 1];
// Third line is version
vcVersion = vcgencmd.get(2).replace("version ", "");
return new VcGenCmdStrings(vcReleaseDate, vcManufacturer, vcVersion, "RPi", "Bootloader");
}
return new VcGenCmdStrings(null, null, null, null, null);
}
private static final class VcGenCmdStrings {
private final String releaseDate;
private final String manufacturer;
private final String version;
private final String name;
private final String description;
private VcGenCmdStrings(String releaseDate, String manufacturer, String version, String name,
String description) {
this.releaseDate = releaseDate;
this.manufacturer = manufacturer;
this.version = version;
this.name = name;
this.description = description;
}
}
}
|
String result = null;
if ((result = Sysfs.queryBiosVersion(this.biosNameRev.get().getB())) == null
&& (result = vcGenCmd.get().version) == null) {
return Constants.UNKNOWN;
}
return result;
| 1,129
| 77
| 1,206
|
<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/linux/LinuxGlobalMemory.java
|
LinuxGlobalMemory
|
readMemInfo
|
class LinuxGlobalMemory extends AbstractGlobalMemory {
private static final long PAGE_SIZE = LinuxOperatingSystem.getPageSize();
private final Supplier<Pair<Long, Long>> availTotal = memoize(LinuxGlobalMemory::readMemInfo, defaultExpiration());
private final Supplier<VirtualMemory> vm = memoize(this::createVirtualMemory);
@Override
public long getAvailable() {
return availTotal.get().getA();
}
@Override
public long getTotal() {
return availTotal.get().getB();
}
@Override
public long getPageSize() {
return PAGE_SIZE;
}
@Override
public VirtualMemory getVirtualMemory() {
return vm.get();
}
/**
* Updates instance variables from reading /proc/meminfo. While most of the information is available in the sysinfo
* structure, the most accurate calculation of MemAvailable is only available from reading this pseudo-file. The
* maintainers of the Linux Kernel have indicated this location will be kept up to date if the calculation changes:
* see https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?
* id=34e431b0ae398fc54ea69ff85ec700722c9da773
* <p>
* Internally, reading /proc/meminfo is faster than sysinfo because it only spends time populating the memory
* components of the sysinfo structure.
*
* @return A pair containing available and total memory in bytes
*/
private static Pair<Long, Long> readMemInfo() {<FILL_FUNCTION_BODY>}
private VirtualMemory createVirtualMemory() {
return new LinuxVirtualMemory(this);
}
}
|
long memFree = 0L;
long activeFile = 0L;
long inactiveFile = 0L;
long sReclaimable = 0L;
long memTotal = 0L;
long memAvailable;
List<String> procMemInfo = FileUtil.readFile(ProcPath.MEMINFO);
for (String checkLine : procMemInfo) {
String[] memorySplit = ParseUtil.whitespaces.split(checkLine, 2);
if (memorySplit.length > 1) {
switch (memorySplit[0]) {
case "MemTotal:":
memTotal = ParseUtil.parseDecimalMemorySizeToBinary(memorySplit[1]);
break;
case "MemAvailable:":
memAvailable = ParseUtil.parseDecimalMemorySizeToBinary(memorySplit[1]);
// We're done!
return new Pair<>(memAvailable, memTotal);
case "MemFree:":
memFree = ParseUtil.parseDecimalMemorySizeToBinary(memorySplit[1]);
break;
case "Active(file):":
activeFile = ParseUtil.parseDecimalMemorySizeToBinary(memorySplit[1]);
break;
case "Inactive(file):":
inactiveFile = ParseUtil.parseDecimalMemorySizeToBinary(memorySplit[1]);
break;
case "SReclaimable:":
sReclaimable = ParseUtil.parseDecimalMemorySizeToBinary(memorySplit[1]);
break;
default:
// do nothing with other lines
break;
}
}
}
// We didn't find MemAvailable so we estimate from other fields
return new Pair<>(memFree + activeFile + inactiveFile + sReclaimable, memTotal);
| 456
| 437
| 893
|
<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/linux/LinuxGraphicsCard.java
|
LinuxGraphicsCard
|
getGraphicsCardsFromLshw
|
class LinuxGraphicsCard extends AbstractGraphicsCard {
/**
* Constructor for LinuxGraphicsCard
*
* @param name The name
* @param deviceId The device ID
* @param vendor The vendor
* @param versionInfo The version info
* @param vram The VRAM
*/
LinuxGraphicsCard(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.linux.LinuxGraphicsCard} objects.
*/
public static List<GraphicsCard> getGraphicsCards() {
List<GraphicsCard> cardList = getGraphicsCardsFromLspci();
if (cardList.isEmpty()) {
cardList = getGraphicsCardsFromLshw();
}
return cardList;
}
// Faster, use as primary
private static List<GraphicsCard> getGraphicsCardsFromLspci() {
List<GraphicsCard> cardList = new ArrayList<>();
// Machine readable version
List<String> lspci = ExecutingCommand.runNative("lspci -vnnm");
String name = Constants.UNKNOWN;
String deviceId = Constants.UNKNOWN;
String vendor = Constants.UNKNOWN;
List<String> versionInfoList = new ArrayList<>();
boolean found = false;
String lookupDevice = null;
for (String line : lspci) {
String[] split = line.trim().split(":", 2);
String prefix = split[0];
// Skip until line contains "VGA"
if (prefix.equals("Class") && line.contains("VGA")) {
found = true;
} else if (prefix.equals("Device") && !found && split.length > 1) {
lookupDevice = split[1].trim();
}
if (found) {
if (split.length < 2) {
// Save previous card
cardList.add(new LinuxGraphicsCard(name, deviceId, vendor,
versionInfoList.isEmpty() ? Constants.UNKNOWN : String.join(", ", versionInfoList),
queryLspciMemorySize(lookupDevice)));
versionInfoList.clear();
found = false;
} else {
if (prefix.equals("Device")) {
Pair<String, String> pair = ParseUtil.parseLspciMachineReadable(split[1].trim());
if (pair != null) {
name = pair.getA();
deviceId = "0x" + pair.getB();
}
} else if (prefix.equals("Vendor")) {
Pair<String, String> pair = ParseUtil.parseLspciMachineReadable(split[1].trim());
if (pair != null) {
vendor = pair.getA() + " (0x" + pair.getB() + ")";
} else {
vendor = split[1].trim();
}
} else if (prefix.equals("Rev:")) {
versionInfoList.add(line.trim());
}
}
}
}
// If we haven't yet written the last card do so now
if (found) {
cardList.add(new LinuxGraphicsCard(name, deviceId, vendor,
versionInfoList.isEmpty() ? Constants.UNKNOWN : String.join(", ", versionInfoList),
queryLspciMemorySize(lookupDevice)));
}
return cardList;
}
private static long queryLspciMemorySize(String lookupDevice) {
long vram = 0L;
// Lookup memory
// Human readable version, includes memory
List<String> lspciMem = ExecutingCommand.runNative("lspci -v -s " + lookupDevice);
for (String mem : lspciMem) {
if (mem.contains(" prefetchable")) {
vram += ParseUtil.parseLspciMemorySize(mem);
}
}
return vram;
}
// Slower, use as backup
private static List<GraphicsCard> getGraphicsCardsFromLshw() {<FILL_FUNCTION_BODY>}
}
|
List<GraphicsCard> cardList = new ArrayList<>();
List<String> lshw = ExecutingCommand.runNative("lshw -C display");
String name = Constants.UNKNOWN;
String deviceId = Constants.UNKNOWN;
String vendor = Constants.UNKNOWN;
List<String> versionInfoList = new ArrayList<>();
long vram = 0;
int cardNum = 0;
for (String line : lshw) {
String[] split = line.trim().split(":");
if (split[0].startsWith("*-display")) {
// Save previous card
if (cardNum++ > 0) {
cardList.add(new LinuxGraphicsCard(name, deviceId, vendor,
versionInfoList.isEmpty() ? Constants.UNKNOWN : String.join(", ", versionInfoList), vram));
versionInfoList.clear();
}
} else if (split.length == 2) {
String prefix = split[0];
if (prefix.equals("product")) {
name = split[1].trim();
} else if (prefix.equals("vendor")) {
vendor = split[1].trim();
} else if (prefix.equals("version")) {
versionInfoList.add(line.trim());
} else if (prefix.startsWith("resources")) {
vram = ParseUtil.parseLshwResourceString(split[1].trim());
}
}
}
cardList.add(new LinuxGraphicsCard(name, deviceId, vendor,
versionInfoList.isEmpty() ? Constants.UNKNOWN : String.join(", ", versionInfoList), vram));
return cardList;
| 1,100
| 423
| 1,523
|
<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/linux/LinuxLogicalVolumeGroup.java
|
LinuxLogicalVolumeGroup
|
getLogicalVolumeGroups
|
class LinuxLogicalVolumeGroup extends AbstractLogicalVolumeGroup {
private static final Logger LOG = LoggerFactory.getLogger(LinuxLogicalVolumeGroup.class);
private static final String BLOCK = "block";
private static final String DM_UUID = "DM_UUID";
private static final String DM_VG_NAME = "DM_VG_NAME";
private static final String DM_LV_NAME = "DM_LV_NAME";
LinuxLogicalVolumeGroup(String name, Map<String, Set<String>> lvMap, Set<String> pvSet) {
super(name, lvMap, pvSet);
}
static List<LogicalVolumeGroup> getLogicalVolumeGroups() {<FILL_FUNCTION_BODY>}
}
|
if (!HAS_UDEV) {
LOG.warn("Logical Volume Group information requires libudev, which is not present.");
return Collections.emptyList();
}
Map<String, Map<String, Set<String>>> logicalVolumesMap = new HashMap<>();
Map<String, Set<String>> physicalVolumesMap = new HashMap<>();
// Populate pv map from pvs command
// This requires elevated permissions and may fail
for (String s : ExecutingCommand.runNative("pvs -o vg_name,pv_name")) {
String[] split = ParseUtil.whitespaces.split(s.trim());
if (split.length == 2 && split[1].startsWith(DevPath.DEV)) {
physicalVolumesMap.computeIfAbsent(split[0], k -> new HashSet<>()).add(split[1]);
}
}
// Populate lv map from udev
Udev.UdevContext udev = Udev.INSTANCE.udev_new();
try {
Udev.UdevEnumerate enumerate = udev.enumerateNew();
try {
enumerate.addMatchSubsystem(BLOCK);
enumerate.scanDevices();
for (Udev.UdevListEntry entry = enumerate.getListEntry(); entry != null; entry = entry.getNext()) {
String syspath = entry.getName();
Udev.UdevDevice device = udev.deviceNewFromSyspath(syspath);
if (device != null) {
try {
String devnode = device.getDevnode();
if (devnode != null && devnode.startsWith(DevPath.DM)) {
String uuid = device.getPropertyValue(DM_UUID);
if (uuid != null && uuid.startsWith("LVM-")) {
String vgName = device.getPropertyValue(DM_VG_NAME);
String lvName = device.getPropertyValue(DM_LV_NAME);
if (!Util.isBlank(vgName) && !Util.isBlank(lvName)) {
logicalVolumesMap.computeIfAbsent(vgName, k -> new HashMap<>());
Map<String, Set<String>> lvMapForGroup = logicalVolumesMap.get(vgName);
// Backup to add to pv set if pvs command failed
physicalVolumesMap.computeIfAbsent(vgName, k -> new HashSet<>());
Set<String> pvSetForGroup = physicalVolumesMap.get(vgName);
File slavesDir = new File(syspath + "/slaves");
File[] slaves = slavesDir.listFiles();
if (slaves != null) {
for (File f : slaves) {
String pvName = f.getName();
lvMapForGroup.computeIfAbsent(lvName, k -> new HashSet<>())
.add(DevPath.DEV + pvName);
// Backup to add to pv set if pvs command failed
// Added /dev/ to remove duplicates like /dev/sda1 and sda1
pvSetForGroup.add(DevPath.DEV + pvName);
}
}
}
}
}
} finally {
device.unref();
}
}
}
} finally {
enumerate.unref();
}
} finally {
udev.unref();
}
return logicalVolumesMap.entrySet().stream()
.map(e -> new LinuxLogicalVolumeGroup(e.getKey(), e.getValue(), physicalVolumesMap.get(e.getKey())))
.collect(Collectors.toList());
| 189
| 927
| 1,116
|
<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/linux/LinuxNetworkIF.java
|
LinuxNetworkIF
|
updateAttributes
|
class LinuxNetworkIF extends AbstractNetworkIF {
private static final Logger LOG = LoggerFactory.getLogger(LinuxNetworkIF.class);
private int ifType;
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 = IfOperStatus.UNKNOWN;
public LinuxNetworkIF(NetworkInterface netint) throws InstantiationException {
super(netint, queryIfModel(netint));
updateAttributes();
}
private static String queryIfModel(NetworkInterface netint) {
String name = netint.getName();
if (!HAS_UDEV) {
return queryIfModelFromSysfs(name);
}
UdevContext udev = Udev.INSTANCE.udev_new();
if (udev != null) {
try {
UdevDevice device = udev.deviceNewFromSyspath(SysPath.NET + name);
if (device != null) {
try {
String devVendor = device.getPropertyValue("ID_VENDOR_FROM_DATABASE");
String devModel = device.getPropertyValue("ID_MODEL_FROM_DATABASE");
if (!Util.isBlank(devModel)) {
if (!Util.isBlank(devVendor)) {
return devVendor + " " + devModel;
}
return devModel;
}
} finally {
device.unref();
}
}
} finally {
udev.unref();
}
}
return name;
}
private static String queryIfModelFromSysfs(String name) {
Map<String, String> uevent = FileUtil.getKeyValueMapFromFile(SysPath.NET + name + "/uevent", "=");
String devVendor = uevent.get("ID_VENDOR_FROM_DATABASE");
String devModel = uevent.get("ID_MODEL_FROM_DATABASE");
if (!Util.isBlank(devModel)) {
if (!Util.isBlank(devVendor)) {
return devVendor + " " + devModel;
}
return devModel;
}
return name;
}
/**
* Gets 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 LinuxNetworkIF(ni));
} catch (InstantiationException e) {
LOG.debug("Network Interface Instantiation failed: {}", e.getMessage());
}
}
return ifList;
}
@Override
public int getIfType() {
return this.ifType;
}
@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() {<FILL_FUNCTION_BODY>}
private static IfOperStatus parseIfOperStatus(String operState) {
switch (operState) {
case "up":
return IfOperStatus.UP;
case "down":
return IfOperStatus.DOWN;
case "testing":
return IfOperStatus.TESTING;
case "dormant":
return IfOperStatus.DORMANT;
case "notpresent":
return IfOperStatus.NOT_PRESENT;
case "lowerlayerdown":
return IfOperStatus.LOWER_LAYER_DOWN;
case "unknown":
default:
return IfOperStatus.UNKNOWN;
}
}
}
|
String name = SysPath.NET + getName();
try {
File ifDir = new File(name + "/statistics");
if (!ifDir.isDirectory()) {
return false;
}
} catch (SecurityException e) {
return false;
}
this.timeStamp = System.currentTimeMillis();
this.ifType = FileUtil.getIntFromFile(name + "/type");
this.connectorPresent = FileUtil.getIntFromFile(name + "/carrier") > 0;
this.bytesSent = FileUtil.getUnsignedLongFromFile(name + "/statistics/tx_bytes");
this.bytesRecv = FileUtil.getUnsignedLongFromFile(name + "/statistics/rx_bytes");
this.packetsSent = FileUtil.getUnsignedLongFromFile(name + "/statistics/tx_packets");
this.packetsRecv = FileUtil.getUnsignedLongFromFile(name + "/statistics/rx_packets");
this.outErrors = FileUtil.getUnsignedLongFromFile(name + "/statistics/tx_errors");
this.inErrors = FileUtil.getUnsignedLongFromFile(name + "/statistics/rx_errors");
this.collisions = FileUtil.getUnsignedLongFromFile(name + "/statistics/collisions");
this.inDrops = FileUtil.getUnsignedLongFromFile(name + "/statistics/rx_dropped");
long speedMiB = FileUtil.getUnsignedLongFromFile(name + "/speed");
// speed may be -1 from file.
this.speed = speedMiB < 0 ? 0 : speedMiB << 20;
this.ifAlias = FileUtil.getStringFromFile(name + "/ifalias");
this.ifOperStatus = parseIfOperStatus(FileUtil.getStringFromFile(name + "/operstate"));
return true;
| 1,350
| 474
| 1,824
|
<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/linux/LinuxSoundCard.java
|
LinuxSoundCard
|
getCardFolders
|
class LinuxSoundCard extends AbstractSoundCard {
private static final Logger LOG = LoggerFactory.getLogger(LinuxSoundCard.class);
private static final String CARD_FOLDER = "card";
private static final String CARDS_FILE = "cards";
private static final String ID_FILE = "id";
/**
* Constructor for LinuxSoundCard.
*
* @param kernelVersion The version
* @param name The name
* @param codec The codec
*/
LinuxSoundCard(String kernelVersion, String name, String codec) {
super(kernelVersion, name, codec);
}
/**
* Method to find all the card folders contained in the <b>asound</b> folder denoting the cards currently contained
* in our machine.
*
* @return : A list of files starting with 'card'
*/
private static List<File> getCardFolders() {<FILL_FUNCTION_BODY>}
/**
* Reads the 'version' file in the asound folder that contains the complete name of the ALSA driver. Reads all the
* lines of the file and retrieves the first line.
*
* @return The complete name of the ALSA driver currently residing in our machine
*/
private static String getSoundCardVersion() {
String driverVersion = FileUtil.getStringFromFile(ProcPath.ASOUND + "version");
return driverVersion.isEmpty() ? "not available" : driverVersion;
}
/**
* Retrieves the codec of the sound card contained in the <b>codec</b> file. The name of the codec is always the
* first line of that file. <br>
* <b>Working</b> <br>
* This converts the codec file into key value pairs using the {@link FileUtil} class and then returns the value of
* the <b>Codec</b> key.
*
* @param cardDir The sound card directory
* @return The name of the codec
*/
private static String getCardCodec(File cardDir) {
String cardCodec = "";
File[] cardFiles = cardDir.listFiles();
if (cardFiles != null) {
for (File file : cardFiles) {
if (file.getName().startsWith("codec")) {
if (!file.isDirectory()) {
cardCodec = FileUtil.getKeyValueMapFromFile(file.getPath(), ":").get("Codec");
} else {
// on various centos environments, this is a subdirectory
// each file is usually named something like
// codec#0-0
// example : ac97#0-0
File[] codecs = file.listFiles();
if (codecs != null) {
for (File codec : codecs) {
if (!codec.isDirectory() && codec.getName().contains("#")) {
cardCodec = codec.getName().substring(0, codec.getName().indexOf('#'));
break;
}
}
}
}
}
}
}
return cardCodec;
}
/**
* Retrieves the name of the sound card by :
* <ol>
* <li>Reading the <b>id</b> file and comparing each id with the card id present in the <b>cards</b> file</li>
* <li>If the id and the card name matches , then it assigns that name to {@literal cardName}</li>
* </ol>
*
* @param file The sound card File.
* @return The name of the sound card.
*/
private static String getCardName(File file) {
String cardName = "Not Found..";
Map<String, String> cardNamePairs = FileUtil.getKeyValueMapFromFile(ProcPath.ASOUND + "/" + CARDS_FILE, ":");
String cardId = FileUtil.getStringFromFile(file.getPath() + "/" + ID_FILE);
for (Map.Entry<String, String> entry : cardNamePairs.entrySet()) {
if (entry.getKey().contains(cardId)) {
cardName = entry.getValue();
return cardName;
}
}
return cardName;
}
/**
* public method used by {@link oshi.hardware.common.AbstractHardwareAbstractionLayer} to access the sound cards.
*
* @return List of {@link oshi.hardware.platform.linux.LinuxSoundCard} objects.
*/
public static List<SoundCard> getSoundCards() {
List<SoundCard> soundCards = new ArrayList<>();
for (File cardFile : getCardFolders()) {
soundCards.add(new LinuxSoundCard(getSoundCardVersion(), getCardName(cardFile), getCardCodec(cardFile)));
}
return soundCards;
}
}
|
File cardsDirectory = new File(ProcPath.ASOUND);
List<File> cardFolders = new ArrayList<>();
File[] allContents = cardsDirectory.listFiles();
if (allContents != null) {
for (File card : allContents) {
if (card.getName().startsWith(CARD_FOLDER) && card.isDirectory()) {
cardFolders.add(card);
}
}
} else {
LOG.warn("No Audio Cards Found");
}
return cardFolders;
| 1,244
| 141
| 1,385
|
<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/linux/LinuxVirtualMemory.java
|
LinuxVirtualMemory
|
queryVmStat
|
class LinuxVirtualMemory extends AbstractVirtualMemory {
private final LinuxGlobalMemory global;
private final Supplier<Triplet<Long, Long, Long>> usedTotalCommitLim = memoize(LinuxVirtualMemory::queryMemInfo,
defaultExpiration());
private final Supplier<Pair<Long, Long>> inOut = memoize(LinuxVirtualMemory::queryVmStat, defaultExpiration());
/**
* Constructor for LinuxVirtualMemory.
*
* @param linuxGlobalMemory The parent global memory class instantiating this
*/
LinuxVirtualMemory(LinuxGlobalMemory linuxGlobalMemory) {
this.global = linuxGlobalMemory;
}
@Override
public long getSwapUsed() {
return usedTotalCommitLim.get().getA();
}
@Override
public long getSwapTotal() {
return usedTotalCommitLim.get().getB();
}
@Override
public long getVirtualMax() {
return usedTotalCommitLim.get().getC();
}
@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 Triplet<Long, Long, Long> queryMemInfo() {
long swapFree = 0L;
long swapTotal = 0L;
long commitLimit = 0L;
List<String> procMemInfo = FileUtil.readFile(ProcPath.MEMINFO);
for (String checkLine : procMemInfo) {
String[] memorySplit = ParseUtil.whitespaces.split(checkLine);
if (memorySplit.length > 1) {
switch (memorySplit[0]) {
case "SwapTotal:":
swapTotal = parseMeminfo(memorySplit);
break;
case "SwapFree:":
swapFree = parseMeminfo(memorySplit);
break;
case "CommitLimit:":
commitLimit = parseMeminfo(memorySplit);
break;
default:
// do nothing with other lines
break;
}
}
}
return new Triplet<>(swapTotal - swapFree, swapTotal, commitLimit);
}
private static Pair<Long, Long> queryVmStat() {<FILL_FUNCTION_BODY>}
/**
* Parses lines from the display of /proc/meminfo
*
* @param memorySplit Array of Strings representing the 3 columns of /proc/meminfo
* @return value, multiplied by 1024 if kB is specified
*/
private static long parseMeminfo(String[] memorySplit) {
if (memorySplit.length < 2) {
return 0L;
}
long memory = ParseUtil.parseLongOrDefault(memorySplit[1], 0L);
if (memorySplit.length > 2 && "kB".equals(memorySplit[2])) {
memory *= 1024;
}
return memory;
}
}
|
long swapPagesIn = 0L;
long swapPagesOut = 0L;
List<String> procVmStat = FileUtil.readFile(ProcPath.VMSTAT);
for (String checkLine : procVmStat) {
String[] memorySplit = ParseUtil.whitespaces.split(checkLine);
if (memorySplit.length > 1) {
switch (memorySplit[0]) {
case "pswpin":
swapPagesIn = ParseUtil.parseLongOrDefault(memorySplit[1], 0L);
break;
case "pswpout":
swapPagesOut = ParseUtil.parseLongOrDefault(memorySplit[1], 0L);
break;
default:
// do nothing with other lines
break;
}
}
}
return new Pair<>(swapPagesIn, swapPagesOut);
| 813
| 216
| 1,029
|
<methods>public non-sealed void <init>() ,public java.lang.String toString() <variables>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/hardware/platform/mac/MacBaseboard.java
|
MacBaseboard
|
queryPlatform
|
class MacBaseboard extends AbstractBaseboard {
private final Supplier<Quartet<String, String, String, String>> manufModelVersSerial = memoize(
MacBaseboard::queryPlatform);
@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> queryPlatform() {<FILL_FUNCTION_BODY>}
}
|
String manufacturer = null;
String model = null;
String version = null;
String serialNumber = null;
IORegistryEntry platformExpert = IOKitUtil.getMatchingService("IOPlatformExpertDevice");
if (platformExpert != null) {
byte[] data = platformExpert.getByteArrayProperty("manufacturer");
if (data != null) {
manufacturer = Native.toString(data, StandardCharsets.UTF_8);
}
data = platformExpert.getByteArrayProperty("board-id");
if (data != null) {
model = Native.toString(data, StandardCharsets.UTF_8);
}
if (Util.isBlank(model)) {
data = platformExpert.getByteArrayProperty("model-number");
if (data != null) {
model = Native.toString(data, StandardCharsets.UTF_8);
}
}
data = platformExpert.getByteArrayProperty("version");
if (data != null) {
version = Native.toString(data, StandardCharsets.UTF_8);
}
data = platformExpert.getByteArrayProperty("mlb-serial-number");
if (data != null) {
serialNumber = Native.toString(data, StandardCharsets.UTF_8);
}
if (Util.isBlank(serialNumber)) {
serialNumber = platformExpert.getStringProperty("IOPlatformSerialNumber");
}
platformExpert.release();
}
return new Quartet<>(Util.isBlank(manufacturer) ? "Apple Inc." : manufacturer,
Util.isBlank(model) ? Constants.UNKNOWN : model, Util.isBlank(version) ? Constants.UNKNOWN : version,
Util.isBlank(serialNumber) ? Constants.UNKNOWN : serialNumber);
| 206
| 466
| 672
|
<methods>public non-sealed void <init>() ,public java.lang.String toString() <variables>
|
oshi_oshi
|
oshi/oshi-core/src/main/java/oshi/hardware/platform/mac/MacComputerSystem.java
|
MacComputerSystem
|
platformExpert
|
class MacComputerSystem extends AbstractComputerSystem {
private final Supplier<Quartet<String, String, String, String>> manufacturerModelSerialUUID = memoize(
MacComputerSystem::platformExpert);
@Override
public String getManufacturer() {
return manufacturerModelSerialUUID.get().getA();
}
@Override
public String getModel() {
return manufacturerModelSerialUUID.get().getB();
}
@Override
public String getSerialNumber() {
return manufacturerModelSerialUUID.get().getC();
}
@Override
public String getHardwareUUID() {
return manufacturerModelSerialUUID.get().getD();
}
@Override
public Firmware createFirmware() {
return new MacFirmware();
}
@Override
public Baseboard createBaseboard() {
return new MacBaseboard();
}
private static Quartet<String, String, String, String> platformExpert() {<FILL_FUNCTION_BODY>}
}
|
String manufacturer = null;
String model = null;
String serialNumber = null;
String uuid = null;
IORegistryEntry platformExpert = IOKitUtil.getMatchingService("IOPlatformExpertDevice");
if (platformExpert != null) {
byte[] data = platformExpert.getByteArrayProperty("manufacturer");
if (data != null) {
manufacturer = Native.toString(data, StandardCharsets.UTF_8);
}
data = platformExpert.getByteArrayProperty("model");
if (data != null) {
model = Native.toString(data, StandardCharsets.UTF_8);
}
serialNumber = platformExpert.getStringProperty("IOPlatformSerialNumber");
uuid = platformExpert.getStringProperty("IOPlatformUUID");
platformExpert.release();
}
return new Quartet<>(Util.isBlank(manufacturer) ? "Apple Inc." : manufacturer,
Util.isBlank(model) ? Constants.UNKNOWN : model,
Util.isBlank(serialNumber) ? Constants.UNKNOWN : serialNumber,
Util.isBlank(uuid) ? Constants.UNKNOWN : uuid);
| 263
| 304
| 567
|
<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/mac/MacDisplay.java
|
MacDisplay
|
getDisplays
|
class MacDisplay extends AbstractDisplay {
private static final Logger LOG = LoggerFactory.getLogger(MacDisplay.class);
/**
* Constructor for MacDisplay.
*
* @param edid a byte array representing a display EDID
*/
MacDisplay(byte[] edid) {
super(edid);
LOG.debug("Initialized MacDisplay");
}
/**
* 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<>();
// Iterate IO Registry IODisplayConnect
IOIterator serviceIterator = IOKitUtil.getMatchingServices("IODisplayConnect");
if (serviceIterator != null) {
CFStringRef cfEdid = CFStringRef.createCFString("IODisplayEDID");
IORegistryEntry sdService = serviceIterator.next();
while (sdService != null) {
// Display properties are in a child entry
IORegistryEntry properties = sdService.getChildEntry("IOService");
if (properties != null) {
// look up the edid by key
CFTypeRef edidRaw = properties.createCFProperty(cfEdid);
if (edidRaw != null) {
CFDataRef edid = new CFDataRef(edidRaw.getPointer());
// Edid is a byte array of 128 bytes
int length = edid.getLength();
Pointer p = edid.getBytePtr();
displays.add(new MacDisplay(p.getByteArray(0, length)));
edid.release();
}
properties.release();
}
// iterate
sdService.release();
sdService = serviceIterator.next();
}
serviceIterator.release();
cfEdid.release();
}
return displays;
| 155
| 342
| 497
|
<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/mac/MacFirmware.java
|
MacFirmware
|
queryEfi
|
class MacFirmware extends AbstractFirmware {
private final Supplier<Quintet<String, String, String, String, String>> manufNameDescVersRelease = memoize(
MacFirmware::queryEfi);
@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> queryEfi() {<FILL_FUNCTION_BODY>}
}
|
String manufacturer = null;
String name = null;
String description = null;
String version = null;
String releaseDate = null;
IORegistryEntry platformExpert = IOKitUtil.getMatchingService("IOPlatformExpertDevice");
byte[] data;
if (platformExpert != null) {
IOIterator iter = platformExpert.getChildIterator("IODeviceTree");
if (iter != null) {
IORegistryEntry entry = iter.next();
while (entry != null) {
switch (entry.getName()) {
case "rom":
data = entry.getByteArrayProperty("vendor");
if (data != null) {
manufacturer = Native.toString(data, StandardCharsets.UTF_8);
}
data = entry.getByteArrayProperty("version");
if (data != null) {
version = Native.toString(data, StandardCharsets.UTF_8);
}
data = entry.getByteArrayProperty("release-date");
if (data != null) {
releaseDate = Native.toString(data, StandardCharsets.UTF_8);
}
break;
case "chosen":
data = entry.getByteArrayProperty("booter-name");
if (data != null) {
name = Native.toString(data, StandardCharsets.UTF_8);
}
break;
case "efi":
data = entry.getByteArrayProperty("firmware-abi");
if (data != null) {
description = Native.toString(data, StandardCharsets.UTF_8);
}
break;
default:
if (Util.isBlank(name)) {
name = entry.getStringProperty("IONameMatch");
}
break;
}
entry.release();
entry = iter.next();
}
iter.release();
}
if (Util.isBlank(manufacturer)) {
data = platformExpert.getByteArrayProperty("manufacturer");
if (data != null) {
manufacturer = Native.toString(data, StandardCharsets.UTF_8);
}
}
if (Util.isBlank(version)) {
data = platformExpert.getByteArrayProperty("target-type");
if (data != null) {
version = Native.toString(data, StandardCharsets.UTF_8);
}
}
if (Util.isBlank(name)) {
data = platformExpert.getByteArrayProperty("device_type");
if (data != null) {
name = Native.toString(data, StandardCharsets.UTF_8);
}
}
platformExpert.release();
}
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);
| 252
| 794
| 1,046
|
<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/mac/MacGlobalMemory.java
|
MacGlobalMemory
|
queryPageSize
|
class MacGlobalMemory extends AbstractGlobalMemory {
private static final Logger LOG = LoggerFactory.getLogger(MacGlobalMemory.class);
private final Supplier<Long> available = memoize(this::queryVmStats, defaultExpiration());
private final Supplier<Long> total = memoize(MacGlobalMemory::queryPhysMem);
private final Supplier<Long> pageSize = memoize(MacGlobalMemory::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();
}
@Override
public List<PhysicalMemory> getPhysicalMemory() {
List<PhysicalMemory> pmList = new ArrayList<>();
List<String> sp = ExecutingCommand.runNative("system_profiler SPMemoryDataType");
int bank = 0;
String bankLabel = Constants.UNKNOWN;
long capacity = 0L;
long speed = 0L;
String manufacturer = Constants.UNKNOWN;
String memoryType = Constants.UNKNOWN;
String partNumber = Constants.UNKNOWN;
for (String line : sp) {
if (line.trim().startsWith("BANK")) {
// Save previous bank
if (bank++ > 0) {
pmList.add(new PhysicalMemory(bankLabel, capacity, speed, manufacturer, memoryType,
Constants.UNKNOWN));
}
bankLabel = line.trim();
int colon = bankLabel.lastIndexOf(':');
if (colon > 0) {
bankLabel = bankLabel.substring(0, colon - 1);
}
} else if (bank > 0) {
String[] split = line.trim().split(":");
if (split.length == 2) {
switch (split[0]) {
case "Size":
capacity = ParseUtil.parseDecimalMemorySizeToBinary(split[1].trim());
break;
case "Type":
memoryType = split[1].trim();
break;
case "Speed":
speed = ParseUtil.parseHertz(split[1]);
break;
case "Manufacturer":
manufacturer = split[1].trim();
break;
case "Part Number":
partNumber = split[1].trim();
break;
default:
break;
}
}
}
}
pmList.add(new PhysicalMemory(bankLabel, capacity, speed, manufacturer, memoryType, partNumber));
return pmList;
}
private long queryVmStats() {
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)) {
LOG.error("Failed to get host VM info. Error code: {}", Native.getLastError());
return 0L;
}
return (vmStats.free_count + vmStats.inactive_count) * getPageSize();
}
}
private static long queryPhysMem() {
return SysctlUtil.sysctl("hw.memsize", 0L);
}
private static long queryPageSize() {<FILL_FUNCTION_BODY>}
private VirtualMemory createVirtualMemory() {
return new MacVirtualMemory(this);
}
}
|
try (CloseableLongByReference pPageSize = new CloseableLongByReference()) {
if (0 == SystemB.INSTANCE.host_page_size(SystemB.INSTANCE.mach_host_self(), pPageSize)) {
return pPageSize.getValue();
}
}
LOG.error("Failed to get host page size. Error code: {}", Native.getLastError());
return 4098L;
| 979
| 109
| 1,088
|
<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/mac/MacGraphicsCard.java
|
MacGraphicsCard
|
getGraphicsCards
|
class MacGraphicsCard extends AbstractGraphicsCard {
/**
* Constructor for MacGraphicsCard
*
* @param name The name
* @param deviceId The device ID
* @param vendor The vendor
* @param versionInfo The version info
* @param vram The VRAM
*/
MacGraphicsCard(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.mac.MacGraphicsCard} objects.
*/
public static List<GraphicsCard> getGraphicsCards() {<FILL_FUNCTION_BODY>}
}
|
List<GraphicsCard> cardList = new ArrayList<>();
List<String> sp = ExecutingCommand.runNative("system_profiler SPDisplaysDataType");
String name = Constants.UNKNOWN;
String deviceId = Constants.UNKNOWN;
String vendor = Constants.UNKNOWN;
List<String> versionInfoList = new ArrayList<>();
long vram = 0;
int cardNum = 0;
for (String line : sp) {
String[] split = line.trim().split(":", 2);
if (split.length == 2) {
String prefix = split[0].toLowerCase(Locale.ROOT);
if (prefix.equals("chipset model")) {
// Save previous card
if (cardNum++ > 0) {
cardList.add(new MacGraphicsCard(name, deviceId, vendor,
versionInfoList.isEmpty() ? Constants.UNKNOWN : String.join(", ", versionInfoList),
vram));
versionInfoList.clear();
}
name = split[1].trim();
} else if (prefix.equals("device id")) {
deviceId = split[1].trim();
} else if (prefix.equals("vendor")) {
vendor = split[1].trim();
} else if (prefix.contains("version") || prefix.contains("revision")) {
versionInfoList.add(line.trim());
} else if (prefix.startsWith("vram")) {
vram = ParseUtil.parseDecimalMemorySizeToBinary(split[1].trim());
}
}
}
cardList.add(new MacGraphicsCard(name, deviceId, vendor,
versionInfoList.isEmpty() ? Constants.UNKNOWN : String.join(", ", versionInfoList), vram));
return cardList;
| 222
| 458
| 680
|
<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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.