Tutorial :Can Java Code tell if it is in an App Server?



Question:

Is there something I can call from a POJO to see if the code is currently in an App Server or outside of an App Server?

Something like this (In rough PseudoCode):

System.getRunningEnvironment().equals(Environment.Glassfish)  

or

System.getRunningEnvironment().equals(Environment.ApplicationServer)  

or

System.getRunningEnvironment().equals(Environment.JavaSE)  


Solution:1

If you can change AppServer initialization scripts (take a look at this link):

Add -DRunningInAppServer=true at your AppServer initialization script.

Add -DRunningInAppServer=false at your application initialization script.

Then use this method:

public boolean isRunningInAppServer() {            if ("true".equals(System.getProperty("RunningAppServer"))) {              return true;          }          return false;  }  


Solution:2

I don't believe you can do this trivially. And would you want to distinguish between an app server, a web container etc.?

What is the reason for determining this ? To allow your POJOs to behave differently in different environments ? If so then I think this points to an object/component structure that is not quite correct, or at least where the object responsibilities are not clearly defined.


Solution:3

The easiest way is, to check the existence of Java EE/App Server specific classes.


Solution:4

I never used an application server, but maybe you'll be able to achieve this with System.getProperties() / System.getProperty(...)


Solution:5

Consider checking for the current SecurityManager, if your application server uses one.


Solution:6

I don't think there's any way to determine this directly. Yes, as SourceRebel says you could set a system property. Personally I'd avoid doing this, though, as you then have some hidden coupling going on: your function is dependent on a system property that must be set correctly for it to work, but there is nothing clearly defined in the interface to reflect this. I think you'd be far better off to just pass in a parameter that says which it is, and let the caller be responsible to pass in the correct parameter. Then the existence of this parameter can be clearly seen in the function signature, and anyone using it will have a strong clue that they need to set it correctly. Having the caller set it correctly should be trivial, as presumably at some point in the call chain you are either calling from a desktop app or from a web page, and that caller knows which it is.


Solution:7

Some applications server set system properties, JBoss for example: http://community.jboss.org/wiki/JBossProperties


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »