Hi iv been struggling with this error for some time and really cant figure out why its occurring , i have a web application that uses springs simpleJdbctemplate to access a database i can use this locally and it has been tested but when i deploy the application jersey has some problems running the queries on the server this is the stacktrace from the tomcat logs
10-Jan-2011 21:15:28 com.sun.jersey.spi.container.ContainerResponse mapMappableContainerException
SEVERE: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
java.lang.NullPointerException
at example.jersey.spring.dao.testDAO.getUsers(testDAO.java:20)
at example.jersey.spring.MyResource.getIt(MyResource.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:168)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:70)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:279)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:86)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:136)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:74)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1357)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1289)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1239)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1229)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:420)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:497)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:684)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
This is my resource
#GET
#Produces("text/plain")
public String getIt() {
return "the number of users are " +db.getUsers();
}
TestDAO.java
SimpleJdbcTemplate simpleJdbcTemplate ;
public void setDataSource(final DataSource dataSource) {
this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
}
applicationContext.xml
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
<bean id="testDAO" class="com.example.testDAOimpl">
<property name="dataSource" ref="dataSource"/>
</bean>
running locally in eclipse the db.getusers returns - the correct value of 1 so i cant understand why it doesnt work when deployed
Any help greatly appreciated
(Seems to be no real difference from the local set up and the server set up ) if anyone has encountered this anyhelp is much appreciated)
Thanks
Chris
Not sure if this is your problem. But I was facing a similar issue. And what ended up happening is I was missing the MimeMultipart.class on my class path in my server code. Jersey was unable to find the class, and therefore unable to map the server request properly. Strangest thing was I never saw any kind of error message on the server side indicating a class not found.
Assuming you use a bean factory, do something like this to get it from spring:
BeanFactoryLocator beanFactoryLocator = SingletonBeanFactoryLocator.getInstance();
BeanFactoryReference beanFactoryReference = beanFactoryLocator.useBeanFactory("ctx");
testDAOimpl myDao = (testDAOimpl)beanFactoryReference.getFactory().getBean("testDAO");
Related
I am aware this issue comes up when no proper jdbc driver jar is configured in the build path, I have tried adding a few jdbc jars for postgres, yet I face the issue. Please find the below jars I tried.
Using
postgres : 1.16.1
Eclipse Version: Indigo Service Release 2
Java version : 8
Jars I tried
postgresql-9.4.1208.jre6
postgresql-connector-jdbc4.jar
postgresql-jdbc.jar
postgresql-9.3-1103.jdbc3
postgresql-9.2-1003-jdbc4-sources.jar
pg73jdbc3
jdbc7.1-1.1
Reading other posts on stack overflow, I even tried setting the system environmental variables as below..
User Variables - Admin - classpath
C:\Program Files\PostgreSQL\9.2\lib
System Variable - path
C:\Program Files\PostgreSQL\9.2\bin
Not sure if this is required
Database details setup in my .properties file
jdbc.driverClassName=org.postgresql.Driver
jdbc.url=postgresql://localhost:5432/postgres
jdbc.username=admin
jdbc.password=admin
Using spring framework based application
Logs :
org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is java.sql.SQLException: No suitable driver found for postgresql://localhost:5432/postgres
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:240)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:335)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:105)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy8.getCollegeDetails(Unknown Source)
at com.cts.bo.HESBO.registerCourse(HESBO.java:42)
at com.cts.facade.HESFacade.registerCourse(HESFacade.java:34)
at com.cts.manager.HESManager.registerCourse(HESManager.java:34)
at com.cts.presentation.Tester.registerCourse(Tester.java:66)
at com.cts.presentation.Tester.main(Tester.java:159)
Caused by: java.sql.SQLException: No suitable driver found for postgresql://localhost:5432/postgres
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:173)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:164)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:149)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:119)
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:202)
... 11 more
Please guide as for what needs to be done.Thanks
You don't add url while filling the database details for postgresql. You instead do the following.
<bean id="dataSource" class="org.postgresql.xa.PGXADataSource">
<property name="user" value="${username}" />
<property name="password" value="${password}" />
<property name="portNumber" value ="${portNumber}" />
<property name="databaseName" value="${databaseName}" />
<property name="serverName" value="${serverName}" />
</bean>
in your application context and
username=yourusername
password=******
portNumber=5432
databaseName=yourdb
serverName=localhost
in your property file.Later ofcourse you need to utilize the datasource bean. Look at the following, https://jdbc.postgresql.org/documentation/publicapi/org/postgresql/xa/PGXADataSource.html.
I have an application that uses the Spring Repository framework and a MySQL database. I currently have it deployed on Tomcat 7.
Once I deploy and attempt to log into the application (the first call to the database) I receive the following exception:
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in URL [file:/opt/apache-tomcat-7.0.62/webapps/waypoint/WEB-INF/classes/repository-context.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
I have enabled query logging on the database and can confirm that a query is being made to the database for a user object. However, on the login page itself, I see the following message:
Your login attempt was not successful, try again.
Reason: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
To make things a bit more confusing, this only happens when I try deploying on a remote server. When I start a local instance of MySQL and run an instance of Tomcat on localhost, everything works as expected.
Below is my repository-context.xml:
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url"
value="jdbc:mysql://localhost:3306/waypoint_dev" />
<beans:property name="username" value="root" />
</beans:bean>
<beans:bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="jpaVendorAdapter">
<beans:bean
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</beans:property>
<!-- spring based scanning for entity classes> -->
<beans:property name="packagesToScan"
value="com.cigna.waypoint.repository, com.cigna.waypoint.core" />
</beans:bean>
<beans:bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<beans:property name="entityManagerFactory" ref="entityManagerFactory" />
</beans:bean>
Does anyone have any ideas what could be causing the problem? Is there a configuration that is needed with Tomcat that I am not aware of, or have forgotten?
Thanks for your help.
=== UPDATE 1 ====
After specifying the dialect, I am receiving the following stack trace:
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 161,752 milliseconds ago. The last packet sent successfully to the server was 0 milliseconds ago.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_45]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.8.0_45]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~[na:1.8.0_45]
at java.lang.reflect.Constructor.newInstance(Unknown Source) ~[na:1.8.0_45]
at com.mysql.jdbc.Util.handleNewInstance(Util.java:377) ~[mysql-connector-java-5.1.33.jar:5.1.33]
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1036) ~[mysql-connector-java-5.1.33.jar:5.1.33]
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3427) ~[mysql-connector-java-5.1.33.jar:5.1.33]
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3327) ~[mysql-connector-java-5.1.33.jar:5.1.33]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814) ~[mysql-connector-java-5.1.33.jar:5.1.33]
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2435) ~[mysql-connector-java-5.1.33.jar:5.1.33]
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2582) ~[mysql-connector-java-5.1.33.jar:5.1.33]
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2530) ~[mysql-connector-java-5.1.33.jar:5.1.33]
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1907) ~[mysql-connector-java-5.1.33.jar:5.1.33]
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2030) ~[mysql-connector-java-5.1.33.jar:5.1.33]
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96) ~[commons-dbcp-1.4.jar:1.4]
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96) ~[commons-dbcp-1.4.jar:1.4]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:82) ~[hibernate-core-4.3.6.Final.jar:4.3.6.Final]
... 80 common frames omitted
Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2914) ~[mysql-connector-java-5.1.33.jar:5.1.33]
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3337) ~[mysql-connector-java-5.1.33.jar:5.1.33]
... 90 common frames omitted
20:48:32.455 [http-bio-8080-exec-34] DEBUG o.s.s.w.a.UsernamePasswordAuthenticationFilter - Authentication request failed: org.springframework.security.authentication.InternalAuthenticationServiceException: could not extract ResultSet; nested exception is org.hibernate.exception.JDBCConnectionException: could not extract ResultSet
Hibernate needs to know the dialect so that it can connect to the underlying database. You need to set the dialect as org.hibernate.dialect.MySQL5Dialect for MySQL along with the Datasource definition.
Here is a link which says why you need dialect.
I was able to resolve this issue by working through the steps listed in #Soheil 's answer found here:
Solving a "communications link failure" with JDBC and MySQL
It turns out that all I needed was add the hibernate dialect, as #Dhanush Gopinath suggested, and add the following to my my.cnf file:
interactive_timeout=180
wait_timeout=180
connect_timeout=180
max_connect_errors=9999
skip-name-resolve
I wrote a server-side application that powers a website and multiple mobile clients. I used Hibernate for data access. I later discovered that the app fails after a day! When I checked around online, I found out that its a well know issue with MySQL terminating a "stale" connection after 8 hours. In order to avoid this, I found many suggestions like including ?autoReconnect=true, using c3P0, etc.
Since autoReconnect is officially discouraged (especially in production environment) and also because it didn't have any effect when I applied it, I decided to go for c3p0. Unfortunately, after introducing the c3p0 configuration in my hibernate.cfg.xml file, the application starts throwing a NullPointerException somewhere in my code where I called dbSession.close()
This means that the HibernateUtil.getSessionFactory() actually returns null. I have added the required jars (c3p0-0.9.2-pre2.jar, hibernate-core-3.3.1.GA.jar, hibernate-c3p0-3.3.2.GA.jar, mchange-commons-java-0.2.1.jar and c3p0-oracle-thin-extras-0.9.2-pre2.jar) even though I don't think its all of them that are required.
I've gone through many of the pages that talked about this issue but I'm still not able to set it up properly. Kindly help me with a "beginner-friendly" easy-to-implement, step-by-step procedure for setting up c3p0 with Hibernate. I'm using Hibernate 3.3.6 on JDK 1.6, MySQL 5.5 and I'm developing in Netbeans 7.0.
Here is my hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/religion_app</property>
<property name="hibernate.connection.username">*****</property>
<property name="hibernate.connection.password">*****</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="connection.autoReconnect">true</property>
<property name="connection.autoReconnectForPools">true</property>
<property name="connection.is-connection-validation-required">true</property>
<!-- configuration pool via c3p0-->
<property name="c3p0.acquire_increment">1</property>
<property name="c3p0.idle_test_period">120</property> <!-- seconds -->
<property name="c3p0.max_size">100</property>
<property name="c3p0.max_statements">0</property>
<property name="c3p0.min_size">10</property>
<property name="c3p0.timeout">180</property> <!-- seconds -->
<property name="c3p0.preferredTestQuery">select 1;</property>
<!--Mappings go here-->
</session-factory>
</hibernate-configuration>
Here is what I got after adding c3p0 (without slf4j):
May 23, 2012 2:42:14 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet LoginChurch threw exception
java.lang.NullPointerException
at com.pacesolutions.religionapp.services.LoginChurch.processRequest(LoginChurch.java:109)
at com.pacesolutions.religionapp.services.LoginChurch.doPost(LoginChurch.java:138)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:859)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1555)
at java.lang.Thread.run(Thread.java:722)
May 23, 2012 2:45:13 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet LoginChurch threw exception
java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1516)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1361)
at org.hibernate.connection.C3P0ConnectionProvider.<clinit>(C3P0ConnectionProvider.java:52)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at java.lang.Class.newInstance0(Class.java:372)
at java.lang.Class.newInstance(Class.java:325)
at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:73)
at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:56)
at org.hibernate.cfg.SettingsFactory.createConnectionProvider(SettingsFactory.java:414)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:62)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2009)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1292)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
at com.pacesolutions.religionapp.HibernateUtil.<clinit>(HibernateUtil.java:23)
at com.pacesolutions.religionapp.services.LoginChurch.processRequest(LoginChurch.java:68)
at com.pacesolutions.religionapp.services.LoginChurch.doPost(LoginChurch.java:143)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:859)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1555)
at java.lang.Thread.run(Thread.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.26 logs.
Most of my Hibernate configuration files where generated by Netbeans. I had the database on ground then I used the Hibernate wizards in Netbeans to generate the configuration files, entity classes and mapping files from it. These were working correctly before I introduced c3p0 (but they fail after 8 hours).
I use Mecurial with my project and reverting the whole project back to a time prior to when I introduced c3p0, it works again (for 8 hours). Even hand-deleting all the c3p0 configurations in hibernate.cfg.xml makes the app work again. What could I be doing wrong?
The jars required for C3P0 configuration are c3p0-0.9.2-pre2.jar & mchange-commons-java-0.2.1.jar. Also, additionally you need to put c3p0.properties in classpath.
Below are the properties, which should be configured while using C3P0 with Hibernate.
hibernate.cfg.xml
<property name="connection.provider_class">
org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.acquire_increment">1</property>
<property name="hibernate.c3p0.idle_test_period">100</property>
<property name="hibernate.c3p0.max_size">100</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.min_size">10</property>
<property name="hibernate.c3p0.timeout">180</property>
c3p0.properties
You can validate connection on each checkout c3p0.testConnectionOnCheckout=true, but this is expensive operation.
Else, you can retry to establish connection periodically.
c3p0.acquireRetryAttempts = 4
c3p0.acquireRetryDelay = 5000
This will retry 4 times with a delay of 5 seconds between each consecutive attempt.
c3p0 has no dependency on SLF4J. If adding that library to your classpath fixed your issue, that is interesting, but not so easy to explain.
A stack trace of the original NPE tomcat logged when you had problems would be helpful. (I'm c3p0's developer.)
Note that c3p0.properties needs to be at the top level of the CLASSPATH of your app, which may not be where other config files are located. c3p0.properties is loaded as a ClassLoader resource.
The bug can be fixed using commercial pooling libraries as suggested above. I used c3p0 exactly as suggested by #NayanWadekar.
Please note that c3p0 is dependent on SLF4J. So after including the c3p0 jars in your classpath, you also have to add SLF4J jars in your classpath. The trick about this thing is that, if those SLF4J jars are not present, the compiler still won't complain, you only get errors after deploying the app.
Also, if you are using Netbeans, avoid creating an SLF4J library from all the jars bundled together here at slf4.org. The reason being that some of the jars are not meant to be used together in the same project. Just use the following two jars alone from the library: slf4j-api-1.6.4.jar and slf4j-jdk14-1.6.4.jar. You can visit www.slf4j.org for details.
I am trying to configure and run spring + hibernate client server project (Spring's HTTP invoker).
I have omitted the httpinvoker configuration and web.xml , because the configuration for httpinvoker is working well .
According to the suggestion from the answers, I removed the TestSimple class, and posting the stacktrace when i try to run the service from client side.
I have posted log (below) when I run mvn tomcat:run at server side and the stacktrace after I call the client code(posted below). I'm getting the NPE for sessionFactory. Could you please suggest some ideas?
My applicationContext.xml looks like :
<?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:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Database Configuration -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>/WEB-INF/config.properties</value>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="dialect">${hibernate.dialect}</prop>
<prop key="show_sql">${hibernate.show_sql}</prop>
<prop key="format_sql">true</prop>
<prop key="use_sql_comments">true</prop>
<prop key="hibernate.connection.autocommit">true</prop>
<prop key="hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
<property name="packagesToScan" value="com.gt.cbpr.model"></property>
</bean>
<!-- auto wired/scan annotation based config -->
<context:annotation-config />
<context:component-scan base-package="com.gt.cbpr.server" />
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="dataSource" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
My LoginUserServiceImpl :
package com.gt.cbpr.server.service.impl;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.gt.cbpr.model.LoginUser;
import com.gt.cbpr.service.LoginUserService;
#Component
public class LoginUserServiceImpl implements LoginUserService {
#Autowired
private SessionFactory sessionFactory;
public void saveLoginUser(LoginUser user) throws Exception {
System.out.println(sessionFactory);
sessionFactory.getCurrentSession().saveOrUpdate(user);
}
}
Client side code :
import com.gt.cbpr.model.LoginUser;
import com.gt.cbpr.service.LoginUserService;
import com.gt.lib.utils.BeanUtils;
public class HelloClient {
public static void main(String[] args) throws Exception{
LoginUserService lus = (LoginUserService) BeanUtils.getBean("loginService");
LoginUser u = new LoginUser();
u.setUsername("AA");
u.setPassword("AAAASS");
lus.saveLoginUser(u); // I get exception here.
}
}
The tomcat log :
http://pastebin.com/Xw92PJv6
The stacktrace when i run the above client code :
10:47:11,938 DEBUG DispatcherServlet:819 - DispatcherServlet with name 'remoting' processing POST request for [/cbpr/remoting/helloService]
10:47:11,942 DEBUG BeanNameUrlHandlerMapping:124 - Mapping [/helloService] to HandlerExecutionChain with handler [org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter#93fd01] and 1 interceptor
10:47:11,946 DEBUG HttpInvokerServiceExporter:73 - Applying RemoteInvocation: method name 'setHello'; parameter types [com.gt.cbpr.model.HelloObject]
10:47:11,950 DEBUG RemoteInvocationTraceInterceptor:66 - Incoming HttpInvokerServiceExporter remote call: com.gt.cbpr.service.HelloService.setHello
10:47:11,950 DEBUG RemoteInvocationTraceInterceptor:72 - Finished processing of HttpInvokerServiceExporter remote call: com.gt.cbpr.service.HelloService.setHello
10:47:11,956 DEBUG DispatcherServlet:957 - Null ModelAndView returned to DispatcherServlet with name 'remoting': assuming HandlerAdapter completed request handling
10:47:11,956 DEBUG DispatcherServlet:913 - Successfully completed request
10:47:11,961 DEBUG DispatcherServlet:819 - DispatcherServlet with name 'remoting' processing POST request for [/cbpr/remoting/helloService]
10:47:11,961 DEBUG BeanNameUrlHandlerMapping:124 - Mapping [/helloService] to HandlerExecutionChain with handler [org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter#93fd01] and 1 interceptor
10:47:11,962 DEBUG HttpInvokerServiceExporter:73 - Applying RemoteInvocation: method name 'getHello'; parameter types []
10:47:11,962 DEBUG RemoteInvocationTraceInterceptor:66 - Incoming HttpInvokerServiceExporter remote call: com.gt.cbpr.service.HelloService.getHello
10:47:11,963 DEBUG RemoteInvocationTraceInterceptor:72 - Finished processing of HttpInvokerServiceExporter remote call: com.gt.cbpr.service.HelloService.getHello
10:47:11,964 DEBUG DispatcherServlet:957 - Null ModelAndView returned to DispatcherServlet with name 'remoting': assuming HandlerAdapter completed request handling
10:47:11,965 DEBUG DispatcherServlet:913 - Successfully completed request
10:47:11,994 DEBUG DispatcherServlet:819 - DispatcherServlet with name 'remoting' processing POST request for [/cbpr/remoting/loginService]
10:47:11,995 DEBUG BeanNameUrlHandlerMapping:124 - Mapping [/loginService] to HandlerExecutionChain with handler [org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter#9036e] and 1 interceptor
10:47:11,997 DEBUG HttpInvokerServiceExporter:73 - Applying RemoteInvocation: method name 'saveLoginUser'; parameter types [com.gt.cbpr.model.LoginUser]
10:47:11,999 DEBUG RemoteInvocationTraceInterceptor:66 - Incoming HttpInvokerServiceExporter remote call: com.gt.cbpr.service.LoginUserService.saveLoginUser
null
10:47:12,009 WARN RemoteInvocationTraceInterceptor:80 - Processing of HttpInvokerServiceExporter remote call resulted in fatal exception: com.gt.cbpr.service.LoginUserService.saveLoginUser
java.lang.NullPointerException
at com.gt.cbpr.server.service.impl.LoginUserServiceImpl.saveLoginUser(LoginUserServiceImpl.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:318)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.remoting.support.RemoteInvocationTraceInterceptor.invoke(RemoteInvocationTraceInterceptor.java:70)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy26.saveLoginUser(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.remoting.support.RemoteInvocation.invoke(RemoteInvocation.java:205)
at org.springframework.remoting.support.DefaultRemoteInvocationExecutor.invoke(DefaultRemoteInvocationExecutor.java:38)
at org.springframework.remoting.support.RemoteInvocationBasedExporter.invoke(RemoteInvocationBasedExporter.java:76)
at org.springframework.remoting.support.RemoteInvocationBasedExporter.invokeAndCreateResult(RemoteInvocationBasedExporter.java:112)
at org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter.handleRequest(HttpInvokerServiceExporter.java:117)
at org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter.handle(HttpRequestHandlerAdapter.java:49)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
10:47:12,020 DEBUG HttpInvokerServiceExporter:92 - Target method failed for RemoteInvocation: method name 'saveLoginUser'; parameter types [com.gt.cbpr.model.LoginUser]
java.lang.NullPointerException
at com.gt.cbpr.server.service.impl.LoginUserServiceImpl.saveLoginUser(LoginUserServiceImpl.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:318)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.remoting.support.RemoteInvocationTraceInterceptor.invoke(RemoteInvocationTraceInterceptor.java:70)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy26.saveLoginUser(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.remoting.support.RemoteInvocation.invoke(RemoteInvocation.java:205)
at org.springframework.remoting.support.DefaultRemoteInvocationExecutor.invoke(DefaultRemoteInvocationExecutor.java:38)
at org.springframework.remoting.support.RemoteInvocationBasedExporter.invoke(RemoteInvocationBasedExporter.java:76)
at org.springframework.remoting.support.RemoteInvocationBasedExporter.invokeAndCreateResult(RemoteInvocationBasedExporter.java:112)
at org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter.handleRequest(HttpInvokerServiceExporter.java:117)
at org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter.handle(HttpRequestHandlerAdapter.java:49)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
10:47:12,064 DEBUG DispatcherServlet:957 - Null ModelAndView returned to DispatcherServlet with name 'remoting': assuming HandlerAdapter completed request handling
10:47:12,067 DEBUG DispatcherServlet:913 - Successfully completed request
I could not figure out what wrong going on. Can you please help me in this?
Just a guess, but you are calling saveUser from the constructor. I am not sure about spring, but in other CDI I have used the beans are not injected when the object is created, but after the object has been created.
For this kind of "initialization", you should use saveUser with #PostConstruct (that will execute the method after the dependencies have been injected). The method should take no parameters. And of course you should remove the method call from the constructor.
The logs you show are the logs of your web application. Your test is a standalone application, where the main method simply instantiate your test class using new. There is no way for Spring to autowire a bean that it doesn't instantiate itself. When you construct a bean using new, you're bypassing Spring completely.
Your main method needs to instantiate an application context, and to ask this context for the bean of type TestSimple.
The anwser of #SJUan76 is correct as well. Spring instantiates the bean , then autowire it. So in the constructor, nothing is autowired yet. It's generally a bad practice to do something other than initialization in a constructor.
You aren't pulling TestSimple out of a Spring context, so the #Autowired tag does nothing. In your main, pull the object out of a spring context instead, this will work better.
If you're writing integration tests to test the behavior of your beans inside an application container then you should consider using Spring TestContext framework (it's the official way to write integration tests for Spring) - there's no magic in - normally JUnit will run Spring Test Context classes which implement JUnit Class Runner Api. So, you run JUnit, JUnit runs TestContext Framework, Test Context Framework creates application context from specified XML configuration file and runs your tests. Simple.
The unit tests are another story , there you test your beans separately by mocking their dependencies. In this part, you have to inject your the dependencies of your beans manually - there is no DI container so you have to call constructors and property setters directly from your test classes. Also that probably means that you'll have to replace your #Autowired fields with the public #Autowired property setters.
I'm trying to register my castor mapping files with spring and I appear to be getting a null pointer exception.
In my application context I have:
<bean id="xmlContext" class="org.castor.spring.xml.XMLContextFactoryBean">
<property name="mappingLocations">
<list>
<value>DistributionSamplerMappings.xml</value>
</list>
</property>
<property name="castorProperties">
<props>
<prop key="org.exolab.castor.xml.strictelements">false</prop>
</props>
</property>
</bean>
<bean id="marshaller"
class="org.castor.spring.xml.CastorMarshallerFactoryBean">
<property name="xmlContext"><ref local="xmlContext"/></property>
</bean>
<bean id="unmarshaller"
class="org.castor.spring.xml.CastorUnmarshallerFactoryBean">
<property name="xmlContext"> <ref local="xmlContext"/></property>
<property name="ignoreExtraElements"><value>true</value></property>
<property name="ignoreExtraAttributes"><value>true</value></property>
</bean>
Where DistributionSamplerMappings.xml lives in the same dir as the application context.
I've tried using the spring-xml jar 1.2.1 and 1.5.3. but none of them seem to help.
The exception being thrown back is:
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'xmlContext' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1338)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:423)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3830)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4337)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:566)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Caused by: java.lang.NullPointerException
at org.castor.spring.xml.XMLContextFactoryBean.afterPropertiesSet(XMLContextFactoryBean.java:118)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1369)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1335)
... 30 more
I'm using Spring 2.5.6 and Castor 1.3.1.
Looking around I find I'm not the only one who has had this problem, but I don't seem to be able to find a solution.
Any help would be much appreciated.
First, look at the code - line 118 of the XMLContextFactoryBean is the last one here. It suggests that somehow mappingResource is null. That suggests that getClass().getClassLoader().getResource(mappingLocation) is returning a null, so perhaps it can't find your file.
mappingLocation = (String) iter.next();
URL mappingResource = getClass().getClassLoader()
.getResource(mappingLocation);
mapping.loadMapping(new InputSource(mappingResource
.openStream())); // NPE occurs on this line.
Now if you want the class loader to find a file, you need to put the file in the same place that it would look for classes. Putting your DistributionSamplerMappings.xml in the same directory as applicationContext isn't good enough. Try WEB-INF/classes, or whichever is the classes folder that has the root of your compiled classes inside it. If you're using Eclipse, you can do this by putting the file inside your source folder -- it looks a bit untidy, since you'd rather have config info elsewhere, but at least it will work.
This exception can also occur if a mapped class doesn't have a default public constructor.