package eu.openaire.urls_controller.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.text.SimpleDateFormat; import java.util.Date; public class GenericUtils { private static final Logger logger = LoggerFactory.getLogger(GenericUtils.class); public static final String endOfLine = "\n"; private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z"); public static String getReadableCurrentTimeAndZone() { return (simpleDateFormat.format(new Date(System.currentTimeMillis()))); } public static int getRandomNumber(int min, int max) { return (int)(Math.random() * (max - min +1) + min); } public static String getSelectedStackTraceForCausedException(Throwable thr, String firstMessage, String additionalMessage, int numOfLines) { // The stacktrace of the "ExecutionException" is the one of the current code and not the code which ran inside the background-task. Try to get the cause. Throwable causedThrowable = thr.getCause(); if ( causedThrowable == null ) { logger.warn("No cause was retrieved for the \"ExecutionException\"!"); causedThrowable = thr; } String initialMessage = firstMessage + causedThrowable.getMessage() + ((additionalMessage != null) ? additionalMessage : ""); return getSelectiveStackTrace(causedThrowable, initialMessage, numOfLines); } public static String getSelectiveStackTrace(Throwable thr, String initialMessage, int numOfLines) { StackTraceElement[] stels = thr.getStackTrace(); StringBuilder sb = new StringBuilder(numOfLines *100); if ( initialMessage != null ) sb.append(initialMessage).append(GenericUtils.endOfLine).append("Stacktrace:").append(GenericUtils.endOfLine); // This StringBuilder is thread-safe as a local-variable. for ( int i = 0; (i < stels.length) && (i <= numOfLines); ++i ) { sb.append(stels[i]); if (i < numOfLines) sb.append(GenericUtils.endOfLine); } return sb.toString(); } public static String getRequestorAddress(HttpServletRequest request) { String remoteAddr = request.getHeader("X-FORWARDED-FOR"); // This retrieves the original IP address, if the request passes through a proxy server. if ( remoteAddr == null ) remoteAddr = request.getRemoteAddr(); return remoteAddr; } }