Skip to content

Commit

Permalink
fix getting caller's name in policy
Browse files Browse the repository at this point in the history
Signed-off-by: Lukas Jungmann <lukas.jungmann@oracle.com>
  • Loading branch information
lukasj committed Mar 9, 2022
1 parent c14a5d6 commit e761fd4
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 29 deletions.
Expand Up @@ -23,6 +23,7 @@
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.Queue;
import java.util.logging.Level;
import javax.xml.namespace.QName;
Expand All @@ -48,16 +49,11 @@ public static class Commons {
* position in the call stack of the current {@link Thread}.
*/
public static String getStackMethodName(final int methodIndexInStack) {
final String methodName;

final StackTraceElement[] stack = Thread.currentThread().getStackTrace();
if (stack.length > methodIndexInStack + 1) {
methodName = stack[methodIndexInStack].getMethodName();
} else {
methodName = "UNKNOWN METHOD";
}

return methodName;
final Optional<String> method = StackWalker.getInstance().walk(frames ->
frames.map(StackWalker.StackFrame::getMethodName)
.skip(methodIndexInStack)
.findFirst());
return method.orElse("UNKNOWN METHOD");
}

/**
Expand All @@ -67,11 +63,7 @@ public static String getStackMethodName(final int methodIndexInStack) {
* @return caller method name from the call stack of the current {@link Thread}.
*/
public static String getCallerMethodName() {
String result = getStackMethodName(5);
if (result.equals("invoke0")) {
// We are likely running on Mac OS X, which returns a shorter stack trace
result = getStackMethodName(4);
}
String result = getStackMethodName(3);
return result;
}
}
Expand Down
Expand Up @@ -47,20 +47,6 @@ public void testCommonsGetStackMethodName() {
String expResult, result;

index = 0;
result = PolicyUtils.Commons.getStackMethodName(index);
// On Mac OS X, getStackMethodName returns getStackTrace. On other systems,
// this method first returns dumpThreads and then getStackTrace.
if (result.equals("dumpThreads")) {
index++;
expResult = "getStackTrace";
result = PolicyUtils.Commons.getStackMethodName(index);
assertEquals(expResult, result);
}
else if (!result.equals("getStackTrace")) {
fail("Expected \"dumpThreads\" or \"getStackTrace\", but got instead \"" + result + "\"");
}

index++;
expResult = "getStackMethodName";
result = PolicyUtils.Commons.getStackMethodName(index);
assertEquals(expResult, result);
Expand Down

0 comments on commit e761fd4

Please sign in to comment.