View Javadoc
1   /*
2    * Copyright 2020-2022 The OSHI Project Contributors
3    * SPDX-License-Identifier: MIT
4    */
5   package oshi.driver.windows.wmi;
6   
7   import java.util.Collection;
8   import java.util.Objects;
9   import java.util.Set;
10  import java.util.stream.Collectors;
11  
12  import com.sun.jna.platform.win32.COM.WbemcliUtil.WmiQuery;
13  import com.sun.jna.platform.win32.COM.WbemcliUtil.WmiResult;
14  
15  import oshi.annotation.concurrent.ThreadSafe;
16  import oshi.util.platform.windows.WmiQueryHandler;
17  
18  /**
19   * Utility to query WMI class {@code Win32_Process}
20   */
21  @ThreadSafe
22  public final class Win32Process {
23  
24      private static final String WIN32_PROCESS = "Win32_Process";
25  
26      /**
27       * Process command lines.
28       */
29      public enum CommandLineProperty {
30          PROCESSID, COMMANDLINE;
31      }
32  
33      /**
34       * Process properties accessible from WTSEnumerateProcesses in Vista+
35       */
36      public enum ProcessXPProperty {
37          PROCESSID, NAME, KERNELMODETIME, USERMODETIME, THREADCOUNT, PAGEFILEUSAGE, HANDLECOUNT, EXECUTABLEPATH;
38      }
39  
40      private Win32Process() {
41      }
42  
43      /**
44       * Returns process command lines
45       *
46       * @param pidsToQuery Process IDs to query for command lines. Pass {@code null} to query all processes.
47       * @return A {@link WmiResult} containing process IDs and command lines used to start the provided processes.
48       */
49      public static WmiResult<CommandLineProperty> queryCommandLines(Set<Integer> pidsToQuery) {
50          String sb = WIN32_PROCESS;
51          if (pidsToQuery != null) {
52              sb += " WHERE ProcessID="
53                      + pidsToQuery.stream().map(String::valueOf).collect(Collectors.joining(" OR PROCESSID="));
54          }
55          WmiQuery<CommandLineProperty> commandLineQuery = new WmiQuery<>(sb, CommandLineProperty.class);
56          return Objects.requireNonNull(WmiQueryHandler.createInstance()).queryWMI(commandLineQuery);
57      }
58  
59      /**
60       * Returns process info
61       *
62       * @param pids Process IDs to query.
63       * @return Information on the provided processes.
64       */
65      public static WmiResult<ProcessXPProperty> queryProcesses(Collection<Integer> pids) {
66          String sb = WIN32_PROCESS;
67          if (pids != null) {
68              sb += " WHERE ProcessID="
69                      + pids.stream().map(String::valueOf).collect(Collectors.joining(" OR PROCESSID="));
70          }
71          WmiQuery<ProcessXPProperty> processQueryXP = new WmiQuery<>(sb, ProcessXPProperty.class);
72          return Objects.requireNonNull(WmiQueryHandler.createInstance()).queryWMI(processQueryXP);
73      }
74  }