Spring + Hibernate + Maven NullPointerException - spring

I thought it was a good idea to add some testing to my project, but during the process I somehow managed to get the real deal broken.
I am using Spring MVC with JPA (Hibernate). The entityManager cannot be loaded properly anymore:
INFO - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#3aa1e2da: defining beans [dataSource,org.springframework.context.support.PropertySourcesPlaceholderConfigurer#0,signatureBlobService,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,validator,emf,org.springframework.security.filterChains,org.springframework.security.filterChainProxy,org.springframework.security.web.PortMapperImpl#0,org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0,org.springframework.security.authentication.ProviderManager#0,org.springframework.security.web.context.HttpSessionSecurityContextRepository#0,org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy#0,org.springframework.security.web.savedrequest.HttpSessionRequestCache#0,org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler#0,org.springframework.security.access.vote.AffirmativeBased#0,org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0,org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator#0,org.springframework.security.authentication.AnonymousAuthenticationProvider#0,org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint#0,org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0,org.springframework.security.userDetailsServiceFactory,org.springframework.security.web.DefaultSecurityFilterChain#0,org.springframework.security.provisioning.InMemoryUserDetailsManager#0,org.springframework.security.authentication.dao.DaoAuthenticationProvider#0,org.springframework.security.authentication.DefaultAuthenticationEventPublisher#0,org.springframework.security.authenticationManager]; root of factory hierarchy
INFO - Hibernate Validator 4.2.0.Final
INFO - Building JPA container EntityManagerFactory for persistence unit 'default'
INFO - HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
INFO - HHH000412: Hibernate Core {4.1.4.Final}
INFO - HHH000206: hibernate.properties not found
INFO - HHH000021: Bytecode provider name : javassist
INFO - HHH000204: Processing PersistenceUnitInfo [
name: default
...]
INFO - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#3aa1e2da: defining beans [dataSource,org.springframework.context.support.PropertySourcesPlaceholderConfigurer#0,signatureBlobService,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,validator,emf,org.springframework.security.filterChains,org.springframework.security.filterChainProxy,org.springframework.security.web.PortMapperImpl#0,org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0,org.springframework.security.authentication.ProviderManager#0,org.springframework.security.web.context.HttpSessionSecurityContextRepository#0,org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy#0,org.springframework.security.web.savedrequest.HttpSessionRequestCache#0,org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler#0,org.springframework.security.access.vote.AffirmativeBased#0,org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0,org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator#0,org.springframework.security.authentication.AnonymousAuthenticationProvider#0,org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint#0,org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0,org.springframework.security.userDetailsServiceFactory,org.springframework.security.web.DefaultSecurityFilterChain#0,org.springframework.security.provisioning.InMemoryUserDetailsManager#0,org.springframework.security.authentication.dao.DaoAuthenticationProvider#0,org.springframework.security.authentication.DefaultAuthenticationEventPublisher#0,org.springframework.security.authenticationManager]; root of factory hierarchy
ERROR - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'emf' defined in ServletContext resource [/WEB-INF/spring/root-context.xml]: Invocation of init method failed; nested exception is java.lang.RuntimeException: error trying to scan <jar-file>: file:/Users/XXX/Documents/Coding/Webapps/.metadata/.plugins/org.eclipse.wst.server.core/tmp2/wtpwebapps/XXX/WEB-INF/classes/
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:567)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:385)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:284)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4779)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5273)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1566)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1556)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:680)
Caused by: java.lang.RuntimeException: error trying to scan <jar-file>: file:/Users/david/Documents/Coding/Webapps/.metadata/.plugins/org.eclipse.wst.server.core/tmp2/wtpwebapps/payworkssign/WEB-INF/classes/
at org.hibernate.ejb.Ejb3Configuration.scanForClasses(Ejb3Configuration.java:855)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:597)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:73)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:268)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
... 22 more
Caused by: java.lang.RuntimeException: java.lang.NullPointerException
at javassist.bytecode.AnnotationsAttribute.getAnnotations(AnnotationsAttribute.java:230)
at javassist.bytecode.AnnotationsAttribute.getAnnotation(AnnotationsAttribute.java:184)
at org.hibernate.ejb.packaging.AbstractJarVisitor.checkAnnotationMatching(AbstractJarVisitor.java:256)
at org.hibernate.ejb.packaging.AbstractJarVisitor.executeJavaElementFilter(AbstractJarVisitor.java:212)
at org.hibernate.ejb.packaging.AbstractJarVisitor.addElement(AbstractJarVisitor.java:173)
at org.hibernate.ejb.packaging.ExplodedJarVisitor.getClassNamesInTree(ExplodedJarVisitor.java:126)
at org.hibernate.ejb.packaging.ExplodedJarVisitor.getClassNamesInTree(ExplodedJarVisitor.java:134)
at org.hibernate.ejb.packaging.ExplodedJarVisitor.getClassNamesInTree(ExplodedJarVisitor.java:134)
at org.hibernate.ejb.packaging.ExplodedJarVisitor.getClassNamesInTree(ExplodedJarVisitor.java:134)
at org.hibernate.ejb.packaging.ExplodedJarVisitor.getClassNamesInTree(ExplodedJarVisitor.java:134)
at org.hibernate.ejb.packaging.ExplodedJarVisitor.doProcessElements(ExplodedJarVisitor.java:92)
at org.hibernate.ejb.packaging.AbstractJarVisitor.getMatchingEntries(AbstractJarVisitor.java:149)
at org.hibernate.ejb.packaging.NativeScanner.getFilesInJar(NativeScanner.java:192)
at org.hibernate.ejb.Ejb3Configuration.addScannedEntries(Ejb3Configuration.java:504)
at org.hibernate.ejb.Ejb3Configuration.scanForClasses(Ejb3Configuration.java:852)
... 28 more
Caused by: java.lang.NullPointerException
at javassist.bytecode.ConstPool.getUtf8Info(ConstPool.java:616)
at javassist.bytecode.annotation.Annotation.addMemberValue(Annotation.java:205)
at javassist.bytecode.annotation.Annotation.addMemberValue(Annotation.java:185)
at javassist.bytecode.AnnotationsAttribute$Parser.memberValuePair(AnnotationsAttribute.java:625)
at javassist.bytecode.AnnotationsAttribute$Walker.memberValuePair(AnnotationsAttribute.java:355)
at javassist.bytecode.AnnotationsAttribute$Walker.annotation(AnnotationsAttribute.java:348)
at javassist.bytecode.AnnotationsAttribute$Parser.annotation(AnnotationsAttribute.java:620)
at javassist.bytecode.AnnotationsAttribute$Walker.annotation(AnnotationsAttribute.java:343)
at javassist.bytecode.AnnotationsAttribute$Parser.annotationArray(AnnotationsAttribute.java:610)
at javassist.bytecode.AnnotationsAttribute$Walker.annotationArray(AnnotationsAttribute.java:330)
at javassist.bytecode.AnnotationsAttribute$Walker.annotationArray(AnnotationsAttribute.java:325)
at javassist.bytecode.AnnotationsAttribute$Parser.parseAnnotations(AnnotationsAttribute.java:588)
at javassist.bytecode.AnnotationsAttribute.getAnnotations(AnnotationsAttribute.java:227)
... 42 more
When running
mvn test
Everything runs through. There I use an embedded H2 database
Removing the test related things (dependencies etc.) did not solve the problem.
Javassist is responsible for annotations in this case, if I understood correctly.
My problem is I have no idea where to continue looking. Is it really a UTF8 issue? And why is it trying to scan the /classes directory while thinking it is a jar file?
A list of what else could be somehow related to the problem:
I played around a bit with the project configuration in eclipse (added for maven, wst). I did remove this configuration again to try if it makes a difference. I also used mvn package war:war to deploy the application on a local tomcat. The same error occurs here. Again mvn test works fine
I updated hibernate-validator and hibernate-entitymanager to the newest version. However, downgrading again left the issue present.
Some other infos that might be necessary to locate the problem:
The relevant part of my root-context.xml
<!-- Enable JPA Support -->
<!-- Enable Annotation driven declaration -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- Define transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf"/>
</bean>
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="packagesToScan" value="com.payworksmobile.dev.jpa"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>

I cannot even guess what could be the problem.
In a situation like this, when you don't have a clue what's wrong, here's what you can do (I hope you have your source code in a repository (svn/git, etc)).
You just checkout/clone the project to a new place and build it and see if it is OK or not. There is a chance you did not committed the change that broke it.
If the problem still exists, then you just go back to an older revision, and so forth, until you reach the last working revision. Then you compare the last working revision with the next (what is broken), and tada!, you'll see what had caused the problem in the first place.

After trying many things before posting this question, I actually just stumbled upon the solution:
I found two classes from my test cases in my WEB-INF/classes folder. These to classes where actually the configuration classes for my tests. After deleting them everything runs like a charm. I found those classes in there after extracting my war file and looking for leftovers from my tests.
Why did this happen? (This is me just guessing)
When creating a new test folder in eclipse, it took me some time to modify my pom.xml to treat this folder as a <testSourceDirectory>. Eclipse built the project in between, copying the class files from my test configuration classes to WEB-INF/classes. This somehow messed with Spring and Hibernate. My learning: Check that only the relevant classes get copied into the war file and WEB-INF/classes does not contain any leftovers.

Related

java.lang.ClassCastException: com.ibm.ws.tx.jta.TranManagerSet incompatible with javax.transaction.TransactionManager

I am getting class cast exception while trying to Index the entity through Hibernate5 Search API on Websphere 8.5.5.10. The transactions are being managed by Spring Transaction. The document entities are getting indexed properly on local tomcat but not on WebSphere.
I have created a RESTFUl web service call to index the entities.
Spring 4.2
Hibernate Core 5.0.11.Final
Hibernate Search 5.5.5.Final
Here is my config file
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="datasource" />
<property name="packagesToScan">
<list>
<value>model</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.default_schema">dev</prop>
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.search.default.directory_provider">filesystem</prop>
<prop key="hibernate.search.default.indexBase">/var/lucene/indexes</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
And the stack trace in websphere app logs:-
HSEARCH000058: HSEARCH000116: Unexpected error during MassIndexer operation
org.hibernate.engine.transaction.jta.platform.spi.JtaPlatformException: Could not obtain WebSphere TransactionManager
at org.hibernate.engine.transaction.jta.platform.internal.WebSphereJtaPlatform.locateTransactionManager(WebSphereJtaPlatform.java:66)
at org.hibernate.engine.transaction.jta.platform.internal.AbstractJtaPlatform.retrieveTransactionManager(AbstractJtaPlatform.java:87)
at org.hibernate.search.batchindexing.impl.BatchTransactionalContext.lookupTransactionManager(BatchTransactionalContext.java:53)
at org.hibernate.search.batchindexing.impl.BatchTransactionalContext.(BatchTransactionalContext.java:42)
at org.hibernate.search.batchindexing.impl.BatchIndexingWorkspace.runWithErrorHandler(BatchIndexingWorkspace.java:118)
at org.hibernate.search.batchindexing.impl.ErrorHandledRunnable.run(ErrorHandledRunnable.java:32)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:483)
at java.util.concurrent.FutureTask.run(FutureTask.java:274)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1157)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:627)
at java.lang.Thread.run(Thread.java:798)
Caused by: java.lang.ClassCastException: com.ibm.ws.tx.jta.TranManagerSet incompatible with javax.transaction.TransactionManager
at org.hibernate.engine.transaction.jta.platform.internal.WebSphereJtaPlatform.locateTransactionManager(WebSphereJtaPlatform.java:63)
I am not sure what am I doing wrong here. Apart from Index Webservice call, other REST webservices are running fine and my UI is populating as expected.
Any help will be much appreciated.
We ran into this issue.
Issue:
If we use a hibernate version that uses JPA 2.1 (> hibernate version 4.3), it will conflict with older versions of websphere (versions 7, 8.5 without the JPA 2.1 fix packs). Specifically the exception you would see is this:
nested exception is java.lang.NoSuchMethodError: javax/persistence/Table.indexes()[Ljavax/persistence/Index;
Solution 1:
One way to resolve this issue is setting the classloader to parent_last so that JPA 2.1 that ships with hibernate will be used. However, you will run into other problems like the ones mentioned above.
Conflict with TransactionManager that ships with hibernate, Exception:
java.lang.ClassCastException: com.ibm.ws.tx.jta.TranManagerSet incompatible
with javax.transaction.TransactionManager
This can be solved by excluding the following jar (example maven
configuration for the hibernate dependency) that causes the
conflict:
<exclusion>
<artifactId>jboss-transaction-api_1.2_spec</artifactId>
<groupId>org.jboss.spec.javax.transaction</groupId>
</exclusion>
Conflict with xml-apis.jar that ships with hibernate resulting in the exception:
javax.xml.parsers.FactoryConfigurationError: Provider for javax.xml.parsers.DocumentBuilderFactory cannot be found
This can be resolved by excluding the xml-apis.jar from hibernate
dependency like so:
<exclusion>
<artifactId>xml-apis</artifactId>
<groupId>xml-apis</groupId>
</exclusion>
Solution 2:
Use a custom PersistenceProviderResolver so that the Websphere classes do not interfere with Hibernate:
https://stackoverflow.com/a/37354979/5150013
According to this article, this is a conflict between 2 different versions of java.transaction packages (one is in websphere, one in GemFire.jar, a lib deployed with websphere).
It also suggests a fix :
Drop the package javax.transaction from GemFire.jar: zip -d gemfire.jar javax/transaction/*
Hope this helps.
From SpringBoot version 2.2.0.RELEASE, there is transaction manager api used from jakarta. In case you want to make it work just exclude
<dependency>
<groupId>jakarta.transaction</groupId>
<artifactId>jakarta.transaction-api</artifactId>
</dependency>
from
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
The basic thought is to have only one transaction manager. Here we are removing the one being provided from the sprintboot-jpa

use same datasource from already started server

I have configured jBoss 7.1.1 final for datasource and used it in spring by JNDI. Everything is working fine , datasource is up and JMS queue is setup. Now I have to run a batch which will fetch records from DB and put it in JMS(already started instance) . I have to use same datasource which is configured in server but the record fetching program is a normal java program and I am using same configuration as defined in my spring-servlet.xml
<bean id="TransactionalDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:/comp/env/jdbc/FRMWRKPOC_DEV"></property>
</bean>
<!-- Hibernate Session Factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="TransactionalDataSource"/>
<property name="packagesToScan">
<list>
<value>entities</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.connection.autocommit">false</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
</props>
</property>
</bean>
The java code to get sessionFactory is as follows:
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
SessionFactory factory = (SessionFactory)context.getBean("sessionFactory");
return factory;
But it is giving me following error:
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
If some kind of initial context setup is required then please guide me and also tell me is it possible to get the datasource instance if the application is not running on server though server is already started(because it is normal PSVM java code)
Please find below the complete stacktrace
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'NonTransactionalDataSource' defined in class path resource [beans.xml]: 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
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1482)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:610)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.rights.client.DBConnection.getSessionFactory(DBConnection.java:33)
at com.rights.client.SwonToSubLocMapping.main(SwonToSubLocMapping.java:146)
Caused by: 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
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:325)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at org.springframework.jndi.JndiTemplate$1.doInContext(JndiTemplate.java:154)
at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:87)
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:152)
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:178)
at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:95)
at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:105)
at org.springframework.jndi.JndiObjectFactoryBean.lookupWithFallback(JndiObjectFactoryBean.java:201)
at org.springframework.jndi.JndiObjectFactoryBean.afterPropertiesSet(JndiObjectFactoryBean.java:187)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1541)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1479)
... 13 more
As you are using it as a normal Java program, you have to provide details to Spring on how to access the JNDI by providing required properties. For JBOSS you can declare it like this:
<bean id="TransactionalDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:/comp/env/jdbc/FRMWRKPOC_DEV"></property>
<property name="jndiEnvironment">
<props>
<prop key="java.naming.factory.initial">org.jnp.interfaces.NamingContextFactory</prop>
<prop key="java.naming.provider.url">localhost:1099</prop>
<prop key="java.naming.factory.url.pkgs">org.jboss.naming:org.jnp.interfaces</prop>
<props>
</property>
</bean>
I would suggest to write simple java program or jsp to read from JNDI. It looks like you need to pass authentication (principal & credential) and authorization (I think its optional) inforamtion while conncting to JNDI.

When migrating from JBoss AS 7.1.1 to EAP 6.2 causes spring-defined entityManagerFactory to fail when loading

I'm developing an application using JPA 2.1 with spring 4.0.2. Jboss server provides a JNDI Datasource.
I've defined this entityManager in services.xml in order to avoid the use of a persistence.xml file:
<jee:jndi-lookup id="projectDataSourceTaget" jndi-name="${jndi.datasourceName}"
expected-type="javax.sql.DataSource" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
depends-on="flyway">
<property name="jpaVendorAdapter">
<bean
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="packagesToScan" value="com.xxx" />
<property name="persistenceUnitName" value="projectEntityManager" />
<property name="jtaDataSource" ref="projectDataSourceTaget" />
<property name="jpaProperties">
<props>
<prop key="hibernate.transaction.manager_lookup_class">
org.hibernate.transaction.JBossTransactionManagerLookup
</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<!-- validate | update | create | create-drop -->
<prop key="hibernate.hbm2ddl.auto">validate</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="org.hibernate.envers.use_revision_entity_with_native_id">false</prop>
<prop key="javax.persistence.transactionType">JTA</prop>
</props>
</property>
</bean>
Althought this worked fine in Jboss 7.1.1 when changing to EAP 6.2 it fails to initialize the service:
17:27:17,061 WARN [org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator] (ServerService Thread Pool -- 48) HHH000181: No appropriate connection provider encountered, assuming application will be supplying connections
17:27:17,079 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 48) MSC000001: Failed to start service jboss.persistenceunit."Project.war#Project": org.jboss.msc.service.StartException in service jboss.persistenceunit."Project.war#Project": javax.persistence.PersistenceException: [PersistenceUnit: Project] Unable to build EntityManagerFactory
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:103) [jboss-as-jpa-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_60-ea]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_60-ea]
at java.lang.Thread.run(Thread.java:744) [rt.jar:1.7.0_60-ea]
at org.jboss.threads.JBossThread.run(JBossThread.java:122) [jboss-threads-2.1.1.Final-redhat-1.jar:2.1.1.Final-redhat-1]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: GaIA] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:924)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:899)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:76)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl.createContainerEntityManagerFactory(PersistenceUnitServiceImpl.java:200) [jboss-as-jpa-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14]
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl.access$600(PersistenceUnitServiceImpl.java:57) [jboss-as-jpa-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14]
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:99) [jboss-as-jpa-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14]
... 4 more
Caused by: org.hibernate.HibernateException: Connection cannot be null when 'hibernate.dialect' not set
at org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:98)
at org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:68)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:174)
at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:76)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:160)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:132)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1822)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1780)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:96)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:914)
... 9 more
I'm msising something? i've tried several changes in this configuration but nothing seems to work. Maybe LocalContainerEntityManagerFactoryBean is not right supported on JBoss EAP 6.2?
Finally i got the problem: In a older version of the project there was a persistence.xml defined that was deployed in JBoss for days, even when a clean deploy was made (i guess this was beacause a file system malfunction). This make the JBoss loader to mess up with entityManagers defined in both persistence.xml and services.xml.

javax.naming.NameNotFoundException: Name [comp/env] is not bound in this Context

I'm developing a spring application which uses tomcat server managed connection pool.
I defined datasource in tag in context.xml of tomcat: (i am using spring 2.0.7) in context.xml:
<context>
<Resource name="jdbc/irb_prod"
auth="Container"
type="javax.sql.DataSource"
factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
username="xxx"
password="xxx"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:#xxx:1521:xxx"
maxWait="1000"
removeAbandoned="true"
maxActive="5"
maxIdle="5"
removeAbandonedTimeout="60"
logAbandoned="true"/>
</context>
And in my ApplicationContext.xml(i.e in spring configuration file), the code is:
<bean id="dataSource"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:comp/env/jdbc/irb_prod</value>
</property>
</bean>
<!-- Transaction manager for a single JDBC DataSource -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource"><ref local="dataSource"/></property>
</bean>
When the application starts, I get the following errors:
javax.naming.NameNotFoundException: Name java:/comp/env/mypool is not bound in this Context
org.apache.naming.NamingContext.lookup(NamingContext.java:803)
org.apache.naming.NamingContext.lookup(NamingContext.java:159)
org.apache.naming.SelectorContext.lookup(SelectorContext.java:158)
javax.naming.InitialContext.lookup(Unknown Source)
org.springframework.jndi.JndiTemplate$1.doInContext(JndiTemplate.java:132)
org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:88)
org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:130)
org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:155)
org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:93)
org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:105)
org.springframework.jndi.JndiObjectFactoryBean.lookupWithFallback(JndiObjectFactoryBean.java :197)
org.springframework.jndi.JndiObjectFactoryBean.afterPropertiesSet(JndiObjectFactoryBean.java:184)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:563)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInit ialization(AbstractApplicationContext.java:736)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractAppli cationContext.java:369)
org.springframework.context.support.ClassPathXmlApplicationContext.<init> (ClassPathXmlApplicationContext.java:123)
org.springframework.context.support.ClassPathXmlApplicationContext.<init> (ClassPathXmlApplicationContext.java:66)
MainServlet.init(MainServlet.java:21)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:541)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:383)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java :188)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:288)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
please help me to solve this problem.
I faced similar problem with tomcat and did the following in eclipse to solve it:
In the server's context.xml, included the jdbc connection details.
Stop the server
Clean the project(Project --> Clean) , the tomcat server (Server--> Right Click --> Clean) and Tomcat work directory (Server--> Right Click--> Clean Tomcat Work Directory).
Start the server and run.
Even after maintaining the details in context.xml, sometimes it might not get reflected.
In such cases follow step#3 and hope it helps.
Please update your web.xml with the something similar to the following tag
<resource-env-ref>
<description>DataSource
</description>
<resource-env-ref-name>
dbc/irb_prod
</resource-env-ref-name>
<resource-env-ref-type>
javax.sql.DataSource
</resource-env-ref-type>
</resource-env-ref>
You need to refer this link too for more information
That will in case of Tomcat happen when you have for some reason dropped arbitrary servletcontainer-specific JARs such as jsp-api.jar, servlet-api.jar, catalina.jar, etc in webapp's /WEB-INF/lib. You should remove all servletcontainer-specific JARs from there, they do not belong there.
In my case it seems that I had to first close my file explorer (FreeCommander XE) and then do the eclipse cleans (project and server), make sure to close any other programs that might have handles to deployed files even if the files are not open in those programs anymore
In Eclipse: make sure you have the right context.xml file.
This especially valid when you have installed multiple servers.
In your Servers tab -> Right click on your deployed web module -> Browse Deployment Location -> ../conf/context.xml.
Make sure this is the file you want to be using.
I hope this saves you some time, as I wasted some time on it.

Spring tx:annotation-driven works in eclipse, but not in tomcat

I seem to have a problem with spring annotation-driven transaction managing and tomcat.
These are some of the beans I use in my project:
<bean id="dataSource" class="service.myBatis.RoutingDataSource"> </bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
Everything works fine when i run the project in eclipse. But when i run the project in tomcat it doens't get past the creation of beans. It also does not give me an error or any indication of what is wrong.
The log shows it finishes with instantiating a bean and then it suddenly destroys all beans:
[DEBUG] 12 jul 09:28:55.888 AM localhost-startStop-1 [org.springframework.beans.factory.support.DefaultListableBeanFactory]
Finished creating instance of bean 'org.springframework.transaction.config.internalTransactionAdvisor'
[INFO] 12 jul 09:28:55.895 AM localhost-startStop-1 [org.springframework.beans.factory.support.DefaultListableBeanFactory]
Destroying singletons in........
If i remove the <tx:annotation-driven transaction-manager="transactionManager" /> line the project will just startup normaly in tomcat and eclipse.
Usually if something works in eclipse and it doesn't in tomcat it is caused by tomcat not finding some class/lib or resource. I have no idea what is causing this though
Could anyone tell me what the problem is? Why does it destroy all the beans without giving an error?
I figured it out. It was not spring that was causing the problems it was something else in my project. The error was put in some tomcat log instead of to the console. So it seemed like there was no error.

Resources