server: improved compatibility to run server under java 9+ (related to #12768, #6197)

This commit is contained in:
Oleg Agafonov 2024-09-13 14:53:05 +04:00
parent 060f421ee7
commit 45ded61d6f
3 changed files with 50 additions and 35 deletions

View file

@ -1,7 +1,5 @@
package mage.util;
import java.lang.reflect.Method;
/**
* Devs only: enable or disable debug features
* <p>
@ -58,46 +56,33 @@ public class DebugUtil {
public static boolean NETWORK_PROFILE_REQUESTS = false; // collect diff time between requests, http status and url into special log file
public static String NETWORK_PROFILE_REQUESTS_DUMP_FILE_NAME = "httpRequests.log";
public static String getMethodNameWithSource(final int depth) {
return TraceHelper.getMethodNameWithSource(depth);
/**
* Return method and source line number like "secondMethod - DebugUtilTest.java:21"
*
* @param skipMethodsAmount use 0 to return current method info, use 1 for prev method, use 2 for prev-prev method
*/
public static String getMethodNameWithSource(final int skipMethodsAmount) {
// 3 is default methods amount to skip:
// - getMethodNameWithSource
// - TraceHelper.getMethodNameWithSource
// - Thread.currentThread().getStackTrace()
return TraceHelper.getMethodNameWithSource(3 + skipMethodsAmount);
}
}
/**
* Debug: allows to find a caller's method name
* <a href="https://stackoverflow.com/a/11726687/1276632">Original code</a>
* Debug: allows to find a caller's method name, compatible with java 8 and 9+
* <a href="https://stackoverflow.com/a/10992439">Original code</a>
*/
class TraceHelper {
private static Method m;
static {
try {
m = Throwable.class.getDeclaredMethod("getStackTraceElement", int.class);
m.setAccessible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getMethodName(final int depth) {
try {
StackTraceElement element = (StackTraceElement) m.invoke(new Throwable(), depth + 1);
return element.getMethodName();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String getMethodNameWithSource(final int depth) {
try {
StackTraceElement element = (StackTraceElement) m.invoke(new Throwable(), depth + 1);
return String.format("%s - %s:%d", element.getMethodName(), element.getFileName(), element.getLineNumber());
} catch (Exception e) {
e.printStackTrace();
return null;
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
if (stackTrace.length == 0) {
return "[no access to stack]";
} else {
return String.format("%s - %s:%d", stackTrace[depth].getMethodName(), stackTrace[depth].getFileName(), stackTrace[depth].getLineNumber());
}
}
}