Skip to content

Commit cd2ebf6

Browse files
committed
[JDK17] Update working with PIDs to be compatible with JDK9+
Even though this change doesn't makes this project able to compile with JDK9+ it at least adds a possibility to utilize its classes and methods in some other projects with regards the work with PIDs running on JDK9+. We are using a "hack" to call the method for PID retrieval by reflection because it is only present in Java 9 and newer. That allows us to still compile this code on older JDKs. As a consequence the pid number changed from integer to long so we had to change it everywhere. Dependent projects should update their usages appropriately to long too, although since long -> integer is just about the precision loss issue and I am not aware of any platform (from those we use) that uses long instead of integer for their PIDs, it shouldn't be a big issue.
1 parent 50cc63f commit cd2ebf6

File tree

13 files changed

+104
-68
lines changed

13 files changed

+104
-68
lines changed

core/src/main/groovy/noe/common/newcmd/KillCmdBuilder.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,8 @@ public KillCmdBuilder addProcessId(final String... processIds) {
6767
* @param processIds process ids to kill as integer
6868
* @return this
6969
*/
70-
public KillCmdBuilder addProcessId(final int... processIds) {
71-
for(int processId: processIds) {
70+
public KillCmdBuilder addProcessId(final long... processIds) {
71+
for(long processId: processIds) {
7272
String stringProcessId = String.valueOf(processId);
7373
addProcessId(stringProcessId);
7474
}

core/src/main/groovy/noe/common/newcmd/ListProcess.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ public Collection<Integer> listParentPids(final int processId) throws IOExceptio
180180
* @return list of map where information about processes in the tree is saved
181181
* @throws IOException when not possible to run the process list command
182182
*/
183-
public List<Map<PsCmdFormat, String>> listProcessTree(final int processId) throws IOException {
183+
public List<Map<PsCmdFormat, String>> listProcessTree(final long processId) throws IOException {
184184
ListProcessData data = listAll(PsCmdFormat.PROCESS_ID, PsCmdFormat.PARENT_PROCESS_ID, PsCmdFormat.COMMAND);
185185

186186
ImmutableList.Builder<Map<PsCmdFormat, String>> psTreeBuilder = ImmutableList.<Map<PsCmdFormat, String>>builder();
@@ -196,7 +196,7 @@ public List<Map<PsCmdFormat, String>> listProcessTree(final int processId) throw
196196

197197
List<String> listOfIdsToCheck = new ArrayList<String>();
198198
List<String> listOfIdsInProgress = new ArrayList<String>();
199-
listOfIdsToCheck.add(Integer.toString(processId));
199+
listOfIdsToCheck.add(Long.toString(processId));
200200

201201
// passing through ps results to get all the process three (filter returns filtered copy of data)
202202
while (!listOfIdsToCheck.isEmpty()) {
@@ -246,7 +246,7 @@ public ListProcessData listProcessInfo(final int processId) throws IOException {
246246
* @return process info
247247
* @throws IOException when some error on execution happens
248248
*/
249-
public String printProcessInfo(final int processId) throws IOException, InterruptedException {
249+
public String printProcessInfo(final long processId) throws IOException, InterruptedException {
250250
CmdBuilder<SimpleCmdBuilder> builder = new CmdBuilder<SimpleCmdBuilder>("");
251251
if (platform.isWindows()) {
252252
builder.setBaseCommand("wmic");

core/src/main/groovy/noe/common/newcmd/ListProcessData.java

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ public int size() {
116116
* @param processId process id that should be search in data
117117
* @return info on data
118118
*/
119-
public Map<PsCmdFormat,String> get(final int processId) {
119+
public Map<PsCmdFormat,String> get(final long processId) {
120120
String processIdAsString = String.valueOf(processId);
121121
if(listing.get(processIdAsString) == null) {
122122
return null;
@@ -328,15 +328,36 @@ public int compare(final Map<PsCmdFormat, String> left, final Map<PsCmdFormat, S
328328
int2 = Integer.valueOf(str2);
329329
} catch (NumberFormatException nfe) {
330330
// if string from left is not possible to convert to int
331-
// then in case of right is not possible to convert do string comparision
332-
// otherwise left was possible to convert but right is not posible to convert (returns 1)
331+
// then in case of right is not possible to convert do string comparison
332+
// otherwise left was possible to convert but right is not possible to convert (returns 1)
333333
return int1error ? str1.compareTo(str2) : 1;
334334
}
335335
// if string from left is not possible to convert to int
336336
// then we know that right was converted fine and we return -1
337-
// otherwise both were converted without problem and returning integer comparision
337+
// otherwise both were converted without problem and returning integer comparison
338338
return int1error ? -1 : int1.compareTo(int2);
339339
}
340+
if(dataType.isInstance(Long.valueOf(0))) {
341+
boolean long1error = false;
342+
Long long1 = null, long2 = null;
343+
try {
344+
long1 = Long.parseLong(str1);
345+
} catch (NumberFormatException nfe) {
346+
long1error = true;
347+
}
348+
try {
349+
long2 = Long.parseLong(str2);
350+
} catch (NumberFormatException nfe) {
351+
// if string from left is not possible to convert to long
352+
// then in case of right is not possible to convert do string comparison
353+
// otherwise left was possible to convert but right is not possible to convert (returns 1)
354+
return long1error ? str1.compareTo(str2) : 1;
355+
}
356+
// if string from left is not possible to convert to long
357+
// then we know that right was converted fine and we return -1
358+
// otherwise both were converted without problem and returning integer comparison
359+
return long1error ? -1 : long1.compareTo(long2);
360+
}
340361
return str1.compareTo(str2);
341362
}
342363
}

core/src/main/groovy/noe/common/newcmd/PsCmdFormat.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,11 @@ public enum PsCmdFormat {
2727
/**
2828
* Id of process.
2929
*/
30-
PROCESS_ID(false, Integer.class),
30+
PROCESS_ID(false, Long.class),
3131
/**
3232
* Pid of process parent.
3333
*/
34-
PARENT_PROCESS_ID(false, Integer.class),
34+
PARENT_PROCESS_ID(false, Long.class),
3535
/**
3636
* Priority (nice) of the process.
3737
*/

core/src/main/groovy/noe/common/utils/Cmd.groovy

Lines changed: 28 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -442,7 +442,7 @@ public class Cmd {
442442
* @param id ... unique identificator of the java process
443443
* @return pid of the java process or null if such process isn't found
444444
*/
445-
static Integer getJavaPid(String id) {
445+
static Long getJavaPid(String id) {
446446
if (!platform.isWindows()) {
447447
def p
448448
def jps = DefaultProperties.JAVA_HOME + "${platform.sep}bin${platform.sep}jps"
@@ -465,7 +465,7 @@ public class Cmd {
465465
}
466466
String o = t.nextElement()
467467
// expects format pid ....
468-
return Integer.valueOf(o)
468+
return Long.parseLong(o)
469469
}
470470
}
471471

@@ -475,7 +475,7 @@ public class Cmd {
475475
* TODO variant only for PID
476476
*
477477
*/
478-
static int kill(Integer pid, winappname) {
478+
static int kill(Long pid, winappname) {
479479
log.debug("Forcibly killing process with PID=${pid}, Window title=${winappname}")
480480
// TODO: Get rid of black magic :-(
481481
if (platform.isRHEL()) {
@@ -495,7 +495,7 @@ public class Cmd {
495495
* returns kill process exit code. If PID is not defined on non-windows platform, -1 is returned
496496
* TODO: properly implement it for Unix/Linux systems as pkill -P kills only processes with given parent PID, it doesn't go recursively killing from bottom to top
497497
*/
498-
static int killTree(Integer pid, winappname) {
498+
static Long killTree(Long pid, winappname) {
499499
if (platform.isWindows()) {
500500
if (pid != null) {
501501
log.debug("killtree(): MS Windows taskkill command: taskkill /PID ${pid} /f /t")
@@ -564,7 +564,7 @@ public class Cmd {
564564
log.debug("Process {} is already dead", process)
565565
return false
566566
}
567-
int pid = ProcessUtils.getProcessId(process)
567+
long pid = ProcessUtils.getProcessId(process)
568568
if (pid == ProcessUtils.UNDEFINED_PROCESS_ID) {
569569
log.warn("Failed to extract pid from process")
570570
return false
@@ -573,7 +573,7 @@ public class Cmd {
573573
return destroyProcessWithTree(pid)
574574
}
575575

576-
private static synchronized boolean destroyProcessWithTree(final Integer pid) {
576+
private static synchronized boolean destroyProcessWithTree(final Long pid) {
577577
// getting tree of processes running under launched cmd
578578
ListProcess listProcessUtil = new ListProcess();
579579
List<Map<PsCmdFormat, String>> processTree = listProcessUtil.listProcessTree(pid);
@@ -594,10 +594,10 @@ public class Cmd {
594594
killBuilder.addProcessId(pid);
595595
return Cmd.executeCommand(killBuilder.build().getCommandLine(), new File(".")) != null
596596
} else {
597-
int[] processTreePidArray = new int[processTree.size()];
597+
long[] processTreePidArray = new long[processTree.size()];
598598
int i = 0;
599599
for(Map<PsCmdFormat, String> processTreeRecord: processTree) {
600-
processTreePidArray[i++] = Integer.valueOf(processTreeRecord.get(PsCmdFormat.PROCESS_ID));
600+
processTreePidArray[i++] = Long.valueOf(processTreeRecord.get(PsCmdFormat.PROCESS_ID));
601601
}
602602
log.debug("*nix platform: destroying process tree of {} as list of pids {}",
603603
pid, processTreePidArray);
@@ -742,16 +742,16 @@ public class Cmd {
742742
}
743743

744744

745-
static Set<Integer> retrievePidsByRegexpFromProcOutput(Process proc, regexp) {
746-
Set<Integer> pids = new HashSet<>()
745+
static Set<Long> retrievePidsByRegexpFromProcOutput(Process proc, regexp) {
746+
Set<Long> pids = new HashSet<>()
747747

748748
proc.in.eachLine { line ->
749749
log.debug("Found process to matching ${regexp}: ${line}")
750750
def match = line =~ regexp
751751
if (match.groupCount() > 0 && match.size() > 0 && match[0].size() > 0) {
752752
String pid = match[0][1]
753753
try {
754-
pids.add(Integer.parseInt(pid))
754+
pids.add(Long.parseLong(pid))
755755
} catch (NumberFormatException ex) {
756756
log.debug("We don't care that line contained an invalid processCode to parse: ${pid}. Continuing...")
757757
}
@@ -761,9 +761,9 @@ public class Cmd {
761761
}
762762

763763

764-
static Integer extractPid(identifier) {
764+
static Long extractPid(identifier) {
765765
log.debug("Extracting pid using identifier ${identifier}")
766-
List<Integer> pids = extractPids(identifier, false)
766+
List<Long> pids = extractPids(identifier, false)
767767
if (pids.isEmpty()) {
768768
return null
769769
}
@@ -788,8 +788,8 @@ public class Cmd {
788788
}
789789
}
790790

791-
static List<Integer> extractUNIXPids(identifier, getAll = true) {
792-
List<Integer> pids = []
791+
static List<Long> extractUNIXPids(identifier, getAll = true) {
792+
List<Long> pids = []
793793
final String ALL_FAILED = "All pid extraction options have failed, including the last resort 'pargs' one. This means that the application the pid of which we were trying to" +
794794
"extract hadn't been started in a supported way. Hint: domain.sh? any custom launch script?"
795795
/**
@@ -841,7 +841,7 @@ public class Cmd {
841841
/**
842842
* Now, we will collect all java processes.
843843
*/
844-
List<Integer> javaPids = []
844+
List<Long> javaPids = []
845845
proc2.in.eachLine { line ->
846846
def match = line =~ psRegExp
847847
log.trace("Java processes match.groupCount(): ${match.groupCount()}")
@@ -852,7 +852,7 @@ public class Cmd {
852852
}
853853
String pid = match[0][1]
854854
try {
855-
javaPids.add(Integer.parseInt(pid))
855+
javaPids.add(Long.parseLong(pid))
856856
} catch (NumberFormatException ex) {
857857
log.error("Error trying to parse process ID from: \"${pid}\"")
858858
throw ex
@@ -896,7 +896,7 @@ public class Cmd {
896896
log.trace("1) match proc4.text: ${line}")
897897
String pid = match[0][1]
898898
try {
899-
pids.add(Integer.parseInt(pid))
899+
pids.add(Long.parseLong(pid))
900900
} catch (NumberFormatException ex) {
901901
log.error("Error trying to parse process ID from: \"${pid}\"")
902902
throw ex
@@ -906,8 +906,8 @@ public class Cmd {
906906
return pids
907907
}
908908

909-
static List<Integer> extractWindowsPids(identifier, getAll = true) {
910-
List<Integer> pids = []
909+
static List<Long> extractWindowsPids(identifier, getAll = true) {
910+
List<Long> pids = []
911911

912912
/**
913913
* WINDOWS STUFF
@@ -952,7 +952,7 @@ public class Cmd {
952952
if (match.size() > 0 && match[0].size() >= 2 && possibleWindowTitlesIds.any { it == match[0][2]}) {
953953
String pid = match[0][1]
954954
try {
955-
pids.add(Integer.parseInt(pid))
955+
pids.add(Long.parseLong(pid))
956956
} catch (NumberFormatException ex) {
957957
log.error("Error trying to parse process ID from: \"${pid}\"")
958958
throw ex
@@ -968,7 +968,7 @@ public class Cmd {
968968
return pids
969969
}
970970

971-
static boolean killSpecifiedProcesses(Collection<Integer> pidList = []) {
971+
static boolean killSpecifiedProcesses(Collection<Long> pidList = []) {
972972
if (!pidList) {
973973
log.debug("No process IDs given => nothing to kill")
974974
return false
@@ -1012,7 +1012,7 @@ public class Cmd {
10121012
/**
10131013
* Wait until is PID removed from system - at max. timeout
10141014
*/
1015-
static boolean waitForPidRemoved(Integer pid, int timeout = 30) {
1015+
static boolean waitForPidRemoved(Long pid, int timeout = 30) {
10161016
if (!pid) return true
10171017
int now = 0
10181018

@@ -1036,11 +1036,11 @@ public class Cmd {
10361036
/**
10371037
* Check if PID exists in a system - process is present in system
10381038
*/
1039-
static boolean pidExists(Integer pid) {
1039+
static boolean pidExists(Long pid) {
10401040
def res = false
10411041

10421042
try {
1043-
res = getPidList().contains(Integer.valueOf(pid))
1043+
res = getPidList().contains(pid)
10441044
}
10451045
catch (e) {
10461046
}
@@ -1054,7 +1054,7 @@ public class Cmd {
10541054
*
10551055
* @return true if none of the pids provided exist in the system, false otherwise
10561056
*/
1057-
static boolean waitForPidsRemoved(List<Integer> pids, int timeout, TimeUnit timeUnit) {
1057+
static boolean waitForPidsRemoved(List<Long> pids, int timeout, TimeUnit timeUnit) {
10581058
long maxTime = System.currentTimeMillis() + timeUnit.toMillis(timeout)
10591059
boolean anyPidExist = !getPidList().intersect(pids).isEmpty()
10601060
while (anyPidExist && System.currentTimeMillis() <= maxTime) {
@@ -1096,7 +1096,7 @@ public class Cmd {
10961096
/**
10971097
* Extract all PIDS from the underlying system
10981098
*/
1099-
static List<Integer> getPidList() {
1099+
static List<Long> getPidList() {
11001100
def res = []
11011101
def row = []
11021102
def command
@@ -1118,7 +1118,7 @@ public class Cmd {
11181118
else row = line.split() as List
11191119

11201120
// on all tested system is PID in 2nd col
1121-
if (!row[1].contains("PID")) res << Integer.parseInt(row[1].replaceAll('"', ''))
1121+
if (!row[1].contains("PID")) res << Long.parseLong(row[1].replaceAll('"', ''))
11221122
}
11231123

11241124
return res

0 commit comments

Comments
 (0)