HI
Is there a way to distinguish inside particular method if it is running in a web application(eg whole applications is deployed on tomcat/web sphere etc) or as a standalone application?
HI
Is there a way to distinguish inside particular method if it is running in a web application(eg whole applications is deployed on tomcat/web sphere etc) or as a standalone application?
Your question is difficult because there isn't a whole lot that is "different" between the two aside from what it runs in. You could attempt to call
org.apache.catalina.util.ServerInfo.getServerBuilt()
And if it fails, then you aren't running Tomcat. I'm not familiar with web sphere, but I would imagine attempting to call a specific method for that would work as well. It's definitely a dirty way to do things, but it will work.
You could check to see if any instance of HttpServlet shows up in the current stack trace. Although it is not fool-proof, it may meet your specific needs.
Note: I have not tried running this sample code. Exception handling has been left out.
public boolean isWebApplication() {
Class<?> httpServletClass;
try {
httpServletClass = Class.forName("javax.servlet.http.HttpServlet");
} catch (ClassNotFoundException e) {
return false;
}
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace()
for (StackTraceElement element : stackTrace) {
Class<?> elementClass = Class.forName(element.getClassName());
if (httpServletClass.isAssignableFrom(elementClass)) {
return true;
}
}
return false;
}
Presumably you'd want to check this within some "generic" business logic code that is not compiled with any app server or J2EE APIs on the classpath, i.e. you can't access HttpServlet directly. In that case, I think doing a Class.forName() for a J2EE or app-server-sepcific class would be your best bet. If it throws and exception, it's standalone, otherwise, maybe you're in an app server.
I think the simplest way would be to test for the JNDI system properties (assuming those don't get set in standalone mode to a remote server - and even then you should be able to know the difference in values, such as the server not referring to a localhost).
The answer is "NO". There is no guaranteed way to determine whether your code runs in some kind of app server / servlet container or standalone without relaying on external information.
You could, however, specify a system property in one case and not the other and check for its existence:
java -Dstandalone.mode=true MyApplication
In your code:
if (Boolean.getBoolean("standalone.mode")) {
// we're in standalone mode
}