Tomcat vs Weblogic JNDI Lookup - java

The Weblogic servers we are using have been configured to allow JNDI datasource names like "appds".
For development (localhost), we might be running Tomcat and when declared in the <context> section of server.xml, Tomcat will hang JNDI datasources on "java:comp/env/jdbc/*" in the JNDI tree.
Problem: in Weblogic, the JNDI lookup is "appds" whilst in Tomcat, it seems that that I must provide the formal "java:comp/env/jdbc/appds". I'm afraid the Tomcat version is an implicit standard but unfortunately, I can't change Weblogic's config ... so that means we end up with two different spring config files (we're using spring 2.5) to facilitate the different environments.
Is there an elegant way to address this. Can I look JNDI names up directly in Tomcat? Can Spring take a name and look in both places? Google searches or suggestions would be great.

How to use a single JNDI name in your web app
I've struggled with this for a few months myself. The best solution is to make your application portable so you have the same JNDI name in both Tomcat and Weblogic.
In order to do that, you change your web.xml and spring-beans.xml to point to a single jndi name, and provide a mapping to each vendor specific jndi name.
I've placed each file below.
You need:
A <resource-ref /> entry in web.xml for your app to use a single name
A file WEB-INF/weblogic.xml to map your jndi name to the resource managed by WebLogic
A file META-INF/context.xml to map your jndi name to the resource managed by Tomcat
This can be either in the Tomcat installation or in your app.
As a general rule, prefer to have your jndi names in your app like jdbc/MyDataSource and jms/ConnFactory and avoid prefixing them with java:comp/env/.
Also, data sources and connection factories are best managed by the container and used with JNDI. It's a common mistake to instantiate database connection pools in your application.
spring
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
<jee:jndi-lookup jndi-name="jdbc/appds"
id="dataSource" />
</beans>
web.xml
<resource-ref>
<description>My data source</description>
<res-ref-name>jdbc/appds</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
weblogic.xml
<?xml version="1.0" encoding="UTF-8" ?>
<weblogic-web-app
xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://xmlns.oracle.com/weblogic/weblogic-web-app http://http://www.oracle.com/technology/weblogic/weblogic-web-app/1.1/weblogic-web-app.xsd">
<resource-description>
<jndi-name>appds</jndi-name>
<res-ref-name>jdbc/appds</res-ref-name>
</resource-description>
</weblogic-web-app>
META-INF/context.xml (for Tomcat)
<Context>
<ResourceLink global="jdbc/appds" name="jdbc/appds" type="javax.sql.DataSource"/>
</Context>

JndiLocatorSupport has a property resourceRef. When setting this true, "java:comp/env/" prefix will be prepended automatically. So I believe it would be correct to differentiate this parameter when moving from Tomcat to Weblogic.

I've managed the trick with Tomcat and WebLogic using Spring. Here is a description of how it worked for me.

The following config works in Tomcat and Weblogic for me.
In Spring:
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<!-- This will prepend 'java:comp/env/' for Tomcat, but still fall back to the short name for Weblogic -->
<property name="resourceRef" value="true" />
<property name="jndiName" value="jdbc/AgriShare" />
</bean>
In Weblogic Admin Console create a JDBC resource named jdbc/AgriShare. Under 'Targets', MAKE SURE YOU TARGET THE DATASOURCE TO THE SERVER YOU ARE DEPLOYING YOUR APP TO!. This particular point cost me some time just now...

How about an evironment variable? Set developers machines with the tomcat name and production with the Weblogic name. You can even set your code to use a default one (WebLogic) in case the variable don't exist.

How are you referencing the resource in spring?
This is what we have for tomcat:
context:
<Resource name="jms/ConnectionFactory" auth="Container" type="org.apache.activemq.ActiveMQConnectionFactory" description="
JMS Connection Factory"
factory="org.apache.activemq.jndi.JNDIReferenceFactory" brokerURL="tcp://localhost:61615" brokerName="StandaloneAc
tiveMQBroker"/>
spring:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<jee:jndi-lookup jndi-name="jms/ConnectionFactory" id="connectionFactory" resource-ref="true"
expected-type="javax.jms.ConnectionFactory" lookup-on-startup="false"/>
The jee namespace comes from:
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd

Setting up DataSource in the application itself is not that crazy :) I would say that is even mandatory if application is meant to be deployed on a grid. River, GigaSpaces, or similar.
Note: I do not say connection settings have to be hardcoded inside of WAR, they need to be supplied at deployment time/runtime. This simplifies management of cloud instances since there is only on place to configure.
Configuring resources at the container makes sense only if multiple applications are deployed there and they can use shared resource.
Again, in cloud type of deployments there is only one application per servlet container instance.

My application also had a similar problem and this is how I solved it:
1) WEB-INF/classes/application.properties contains the entry:
ds.jndi=java:comp/env/jdbc/tcds
2) On the WLS machine, I have an entry in the /etc/sysenv file:
ds.jndi=wlsds
3) I configured spring to lookup the JNDI vis the property ${ds.jndi}, using a PropertyPlaceholderConfigurer bean with classpath:application.properties and file:/etc/sysenv as locations. I also set the ignoreResourceNotFound to true so that developers need not have /etc/sysenv on their machines.
4) I run an integration test using Cargo+Jetty and I could not properly set up a JNDI environment there. So I have a fallback BasicDataSource configured too using the defaultObject property of JndiObjectFactoryBean.

Related

Glassfish4 + EJB + Spring, deploy fails

I am upgrading an application from Java7 on Glassfish 3.1.2.2, to Java8 on Glassfish 4.1. The application is packaged as an ear file, containing a jar-file with remote EJBs and Spring beans, as well as a war-file with a couple of servlets and some webservices.
There are only some minor changes done to the actual application, compared to how it was with Glassfish 3.x, the total changes made are:
Built with Java8 instead of Java7.
Deployed on Glassfish 4.1 instead of 3.1.2.2
Newer version of Hibernate
Newer version of ActiveMQ (client)
I can't see any difference between the previous ear-file and the new one (except the abovementioned lib-jars), but still when I try to deploy I get errors like this for all my EJBs:
org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type SomethingLogic with qualifiers #Default
at injection point [BackedAnnotatedField] #Inject private com.my.application.server.service.SomethingServiceSession.somethingLogic
Where SomethingService is an EJB, SomethingLogic is a Spring bean.
My EJBs are defined like this:
#Stateless
#RolesAllowed("secure")
#Interceptors(SpringBeanAutowiringInterceptor.class)
public class SomethingServiceSession implements SomethingService {
#Inject
private SomethingLogic somethingLogic; //Spring bean
SomethingLogic is an interface.
I have a beanRefContext.xml containing:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="beanFactory" class="org.springframework.context.support.ClassPathXmlApplicationContext">
<constructor-arg value="classpath*:applicationContext-glassfish.xml"/>
</bean>
</beans>
The EJB services are defined in glassfish-ejb-jar.xml, like this:
<ejb>
<ejb-name>SomethingServiceSession</ejb-name>
<ior-security-config>
<as-context>
<auth-method>USERNAME_PASSWORD</auth-method>
<realm>AD</realm>
<required>true</required>
</as-context>
</ior-security-config>
</ejb>
I have tried adding a beans.xml with the following content to the resources\META-INF folder of my EJB-project:
<?xml version="1.0"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://jboss.org/schema/cdi/beans_1_0.xsd" />
No luck.
I have also tried adding #LocalBean to all my EJBs, also with no luck.
In addition, I have tried to disable CDI all together, using this command:
asadmin set configs.config.server-config.cdi-service.enable-implicit-cdi=false
This actually allows my EJB services to be deployed, but I'm suspecting that it has the not so good side effect of my webservices not being discovered, so I want to be able to deploy with CDI enabled to rule this out.
Update:
I have tried changing #Inject with #Autowired in all my non-Spring-handled classes (EJBs, webservices and servlets). Now I get the same error for actual Spring beans. It seems that Glassfish will try to look for EJB beans when encountering #Inject, no matter where they occur.
Fixed my problem by adding bean-discovery-mode="none" to my various beans.xml files.
<?xml version="1.0"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://jboss.org/schema/cdi/beans_1_2.xsd"
bean-discovery-mode="none" />

Spring Framework Unable to Resolve References in IntelliJ

I set up a application configuration file for spring, added it to the facets, and set it up according to another configuration file that works perfectly.
All of the references to the spring components are visible and seem to work, but all references to items within the xml file fail to be found.
An example is with the tasks:
<task:scheduler id="taskScheduler" />
<task:executor id="taskExecutor" pool-size="1" />
<task:annotation-driven executor="taskExecutor" scheduler="taskScheduler" />
Both taskScheduler and taskExecutor cannot be resolved. As a result, the task bean never gets set up so all of my #Scheduled annotations never work.
Setting up the factory provider for services works just fine (all #Service and #Autowired annotations work), so I am completely certain the issue is with some configuration issue in the project.
What else needs to be configured in IntelliJ for the beans to work? Why does spring not rescan the file to find references to beans?
Here is where all of the springframework beans are referenced:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd"
default-lazy-init="true">
The issue is having multiple contexts for application configuration files. To fix it, go to the configuration file in IntelliJ, then there is a section at the top where you can select which application context you want to put the context file into (Reads something like "Spring Application Context in module [your module]. File is included in [n] contexts"). Try selecting each one until the references resolve; it will remove it from the other contexts. My particular issue was that it was in the MVC context and it needed to be in the Spring Application Context.

What happens behind the scenes when a property placeholder is defined in a Spring context (JNDI-wise)?

I have a Java web application using Spring and JSF, deployed in Tomcat.
For the record, in web.xml, only the Faces servlet is configured; there is no Spring servlet.
The entry point to my Spring context is applicationContext.xml, which looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<context:component-scan base-package="my.pack" annotation-config="true" />
<context:property-placeholder location="file:${admin.config.path}/database.properties"/>
<context:spring-configured />
<context:annotation-config />
<aop:aspectj-autoproxy />
</beans>
In the property-placeholder definition one can see that I'm injecting an external property, which, in this case, is an environment variable. This property is passed via Tomcat context configuration, like this:
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/cntxt">
<Environment name="admin.config.path" value="d:/conf/"
type="java.lang.String" override="false"/>
</Context>
I'm also injecting this environment variable in one of my Spring-managed beans, like this:
#Value("${java:comp/env/admin.config.path}")
private String confDir;
(This is because I'm also using that directory for some other configuration files, which are not .properties files).
With the configuration above, everything works just fine - all the wirings are performed without any flaw.
But, at some moment, I stopped needing injecting properties via the property placeholder configurer from database.properties (but I still need the other files from the admin.config.path), therefore I removed the <context:property-placeholder> line from applicationContext.xml.
At that moment, the injection using #Value stopped working in my Spring-managed bean.
Does anybody know what actually happened? It seems like the JNDI injection fails if the property placeholder configurer is not defined in the Spring context.
Is there any way I can re-enable this kind of injection (without defining a dummy property placeholder pointing to an empty properties file)?
You need a property placeholder configurer instance, the sole purpose of it is to replace placeholders with actual values. If you remove it no placeholders will be replaced.
Either add a <context:property-placeholder /> and leave out the location field or add a bean of the type PropertySourcesPlaceholderConfigurer. Either way will re-enable your placeholder support.
Small suggestion remove the java:comp/env part of the property, by default it will do a JNDI lookup if the property cannot be resolved in other locations (servlet context, properties, system properties etc.).

ActiveMQ configuration and Spring Expression Language (SpEL)

I have to start multiple instances (separate JVMs) of this one service on the same machine which has a persistent embedded broker. All config files are pre-generated and have their variable substitutions done on compilation way before the services start. I'm having problems with several instances trying to get a lock of AMQ data directory and KahaDB, obviously the 1st instance successfully gets the lock and the rest keep on trying unsuccessfully.
I need to set something like this:
. . .
<amq:broker dataDirectory="${activemq.directory}/data" id="broker" persistent="true" useJmx="false" >
. . .
I tried PropertyPlaceholderConfigurer but as I understand it loads the properties from a file specified in Spring configuration and at the time it starts up is too late already. I'm trying to use Spring Expression Language so I end up with something like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jms="http://www.springframework.org/schema/jms"
xmlns:amq="http://activemq.apache.org/schema/core"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jms
http://www.springframework.org/schema/jms/spring-jms-3.0.xsd
http://activemq.apache.org/schema/core
http://activemq.apache.org/schema/core/activemq-core-5.5.0.xsd">
<!-- Embedded ActiveMQ Broker -->
<amq:broker dataDirectory="#{systemProperties['activemq.directory']}/data" id="broker" persistent="true" useJmx="false" >
...
I pass on the command line
-Dactivemq.directory=<my-directory>
On the log I see
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named '{systemProperties['activemq.directory']}/data' is defined
Does it seem like I'm missing something with AMQ and Spring3 SpEL? Is there some other solution to that does the same think I may be missing?
1. A very nasty, (but at least working) solution is to put a white space to the beginning if you want to use PropertyPlaceholderConfigurer.
<amq:broker useJmx="false" persistent="false">
<amq:transportConnectors>
<amq:transportConnector uri=" #{myconf.getConfigurationValue('JMS_URI')}" />
</amq:transportConnectors>
</amq:broker>
myconf.properties: JMS_URI=tcp://localhost:0?daemon=false
2. What is also interesting that if you explicitly set at least the protocol, then it also works:
<amq:broker useJmx="false" persistent="false">
<amq:transportConnectors>
<amq:transportConnector uri="tcp://#{myconf.getConfigurationValue('JMS_URI')}" />
</amq:transportConnectors>
</amq:broker>
myconf.properties: JMS_URI=localhost:0?daemon=false
I ended up using simply the good old PropertyPlaceholderConfigurer and removing the SpEL notation, it works like a charm.

Spring Jndi Configuration, Server.xml

I have a problem setting up my configuration for JNDI with Spring. I checked the other posts but could not get my problem solved. I am using Tomcat 6 as my container. From my understanding I need to set up a resource on the server. So in my server.xml file I have this:
<GlobalNamingResources>
<Resource auth="Container" driverClassName="org.postgresql.Driver"
maxActive="100" maxIdle="5" maxWait="10000"
minEvictableIdleTimeMillis="60000" name="jdbc/myTomcatPool"
password="password" testOnBorrow="true" testWhileIdle="true"
timeBetweenEvictionRunsMillis="10000" type="javax.sql.DataSource"
url="jdbc:postgresql://localhost:5432/postgis" username="postgres"
validationQuery="SELECT 1"/>
</GlobalNamingResources>
I have the following in my spring-context.xml (which is on the classpath):
<jee:jndi-lookup id="geoCodeData" jndi-name="java:comp/env/jdbc/myTomcatPool" />
<bean id="geoCodeService" class="com.sample.SampleImpl">
<property name="dataSource" ref="geoCodeData"/>
</bean>
I then have this in file META-INF/context.xml:
<Context path="/myApp" reloadable="true" cacheMaxSize="51200"
cacheObjectMaxSize="2560">
<ResourceLink global="jdbc/myTomcatPool" name="jdbc/myTomcatPool"
type="javax.sql.DataSource"/>
</Context>
My server starts up free of errors.
When I try to run the following test (that worked before I added the JNDI code):
public class Test {
public static void main(String[] args) {
ApplicationContext ctx =
new ClassPathXmlApplicationContext("spring-context.xml");
}
}
I get the following error:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'geoCodeData': Invocation of init method failed;
nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
Is my configuration wrong or is the way I am trying to run the test incorrect?
When you run your testcases, you will want to use JDBC instead of JNDI lookup. The simple reason is because you usually don't run your testcases from the application server. Thus, JNDI lookup will fail.
What I do on my end is to place data source in a separate file. I have one file for production that uses JNDI:-
project-datasource.xml
<jee:jndi-lookup id="geoCodeData" jndi-name="java:comp/env/jdbc/myTomcatPool"></jee:jndi-lookup>
... another another file for unit test that uses JDBC:-
project-datasource-test.xml
// use the same bean name "geoCodeData"
<bean id="geoCodeData" class="...">
<property name="driverClassName" value="..." />
<property name="url" value="..." />
<property name="username" value="..." />
<property name="password" value="..." />
</bean>
The web app will use project-datasource.xml whereas the unit test will use project-datasource-test.xml.
After several hours of tearing out my (already sparse) hair I have managed to get my tomcat server to pool database connections to Oracle and use the Spring framework.
I though I would reply to this question even though there seems to be an answer, just in case it helped anybody else.
What I wanted:
A connection pool administered by Tomcat (rather than per servlet) and the config for the DB connection in the Tomcat server config (again, rather than the servlet config files).
We have several instances of Tomcat and each one connects to a specific Oracle DB, but developers are producing servlets that could be required to run on any one of them, hence I don't want the DB connection details in the WAR file they produce, but to let them look it up and be provided with that server's data source, via JNDI.
In the Tomcat server conf/context.xml I added the following code:
<Resource name="jdbc/banner"
auth="Container"
factory="org.apache.commons.dbcp.BasicDataSourceFactory"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:#DBan8DB1.example.ac.uk:1522:bde8"
username="dbsro"
password="verysecret"
initialSize="5"
maxActive="20"
maxIdle="10"
removeAbandoned="true"
global="jdbc/banner"
maxWait="-1"/>
Obviously I have the ojdbc, pool and dbcp JAR files present in Tomcat's lib directory on the server.
An important point to note here is that the type is of "javax.sql.DataSource" rather than "org.apache.commons.dbcp.BasicDataSource" which I originally thought it should be.
Now in the Web Application's WEB-INF/web.xml I added the following:
<resource-ref>
<description>Oracle Banner Datasource</description>
<res-ref-name>jdbc/banner</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
and in my Web Application's servlet-context.xml file (where ever you keep yours might vary) I had this. This is not the whole file but the XML name space is important here, for the jee parts:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/banner" resource-ref="true" />
Again note the fully qualified reference jndi-name="java:comp/env/jdbc/banner" which seemed to be required. Why is isn't needed in the resource-ref section of the web.xml file, I have no idea.
If anyone has any thoughts on this I would be pleased to read them.
By the way, this URL helped: Tomcat6 JNDI data source how-to
After all that, the connection worked. So I mopped the blood, sweat and tears from my work station and enjoyed a delicious cup of fresh coffee.

Categories

Resources