Thank you all for your help. Some of you have sent (as I expected) answers indicating that my approach was wrong or that low-level code should never know if it works in the container. I would agree. However, I am dealing with a complex legacy application and am not able to do a lot of refactoring for the current problem.
Let me step back and ask a question motivated by my initial question.
I have an outdated application running under JBoss and made some changes to the lower level code. I created a unit test for my modification. To run the test, I need to connect to the database.
Inherited code gets the data source this way:
(jndiName is a specific string)
Context ctx = new InitialContext(); DataSource dataSource = (DataSource) ctx.lookup(jndiName);
My problem is that when I run this code under unit test, the Context does not have specific data sources. My solution was to try to find out if I am running under the application server, and if not, create a test DataSource and return it. If I am running under the application server, I use the code above.
So my real question is: what is the right way to do this? Is there an approved way so that unit test can configure the context to return the appropriate data source so that the code under test does not need to know where it works?
For context: MY ORIGINAL QUESTION:
I have Java code that needs to know if it works under JBoss. Is there a canonical way for code to determine if it is running in a container?
My first approach was developed through experimentation and is to get the initial context and testing so that it can find specific values.
private boolean isRunningUnderJBoss(Context ctx) { boolean runningUnderJBoss = false; try { // The following invokes a naming exception when not running under // JBoss. ctx.getNameInNamespace(); // The URL packages must contain the string "jboss". String urlPackages = (String) ctx.lookup("java.naming.factory.url.pkgs"); if ((urlPackages != null) && (urlPackages.toUpperCase().contains("JBOSS"))) { runningUnderJBoss = true; } } catch (Exception e) { // If we get there, we are not under JBoss runningUnderJBoss = false; } return runningUnderJBoss; } Context ctx = new InitialContext(); if (isRunningUnderJboss(ctx) { .........
Now it seems to work, but it looks like a hack. What is the โrightโ way to do this? Ideally, I would like it to be with a lot of application servers, not just JBoss.
java java-ee containers jboss detect
Mark meuer
source share