Spring/MongoDB/Junit: Unit test with Fongo is giving the Null Pointer Exception - spring

I am fairly new to unit testing and trying to test a simple function that returns a query. In my unit test, I am getting the NullPointerException after calling the method. I assume mongoOperations is null, and guessing that is the reason why it is returning NPE. I am using fongo to mock the mongoDB and I configured the spring context in testConfigurationContext.xml file.
This is the class I want to test:
#Repository
public class DataVersionDaoMongo extends MongoBaseDao<DataVersion> implements DataVersionDao {
public DataVersionDaoMongo() {
initType();
}
#Override
public DataVersion
findByDBAndCollection(String dbName, String collectionName) {
//below is the line 27 on error console
return mongoOperations.findOne(Query.query(Criteria.where("dbName").is(dbName).and("collectionName").is(collectionName)), DataVersion.class);
}
}
This is my unit test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:/testApplicationContext.xml")
public class DataVersionDaoMongoTest {
private DataVersionDaoMongo dataVersionDaoMongo = new DataVersionDaoMongo();
private MongoOperations mongoOperations;
private DataVersion dataVersion;
#Rule
public FongoRule fongoRule = new FongoRule();
#Test
public void findByDBAndCollection() {
String dbname = "mydb";
String collectionName = "mycollection";
DB db = fongoRule.getDB(dbname);
DBCollection collection = db.getCollection(collectionName);
Mongo mongo = fongoRule.getMongo();
collection.insert(new BasicDBObject("name", "randomName"));
//below is the line 63 on error console
assertThat(dataVersionDaoMongo.findByDBAndCollection(dbname, collectionName)).isNotNull();
}
}
This is the applicationContext file:
<?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:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">
<bean name="fongo" class="com.github.fakemongo.Fongo">
<constructor-arg value="InMemoryMongo" />
</bean>
<bean id="mongo" factory-bean="fongo" factory-method="getMongo" />
<mongo:db-factory id="mongoDbFactory" mongo-ref="mongo" />
<!-- localhost settings for mongo -->
<!--<mongo:db-factory id="mongoDbFactory" />-->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongoDbFactory"/>
</bean>
</beans>
This is the error on console:
java.lang.NullPointerException
at com.absolute.common.repository.mongodb.springdata.DataVersionDaoMongo.findByDBAndCollection(DataVersionDaoMongo.java:27)
at com.absolute.common.repository.mongodb.springdata.DataVersionDaoMongoTest.findByDBAndCollection(DataVersionDaoMongoTest.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:48)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
I am guessing I am missing something. Any help would be greatly appreciated!

I have never used Fongo, but usually I mock the mongo server with flapdoodle. This is easy to implements.
I would like to recommend it.
https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<version>2.1.1</version>
<scope>test</scope>
</dependency>

You are not auto-wiring DataVersionDaoMongo in you unit test, also mongoOperations bean either need to be auto-wired or injected via constructor.
In you Repo class
#Repository
public class DataVersionDaoMongo extends MongoBaseDao<DataVersion> implements DataVersionDao {
#Autowire MongoOperations mongoOperations;
public DataVersionDaoMongo() {
initType();
}
#Override
public DataVersion findByDBAndCollection(String dbName, String collectionName) {
//below is the line 27 on error console
return mongoOperations.findOne(Query.query(Criteria.where("dbName").is(dbName).and("collectionName").is(collectionName)), DataVersion.class);
}
}
and in your unit test, you no need to use new for bean creation.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:/testApplicationContext.xml")
public class DataVersionDaoMongoTest {
#Autowire
private DataVersionDaoMongo dataVersionDaoMongo;
#Autowire
private MongoOperations mongoOperations; // you can remove this, if not using it
private DataVersion dataVersion;
#Rule
public FongoRule fongoRule = new FongoRule();
#Test
public void findByDBAndCollection() {
String dbname = "mydb";
String collectionName = "mycollection";
DB db = fongoRule.getDB(dbname);
DBCollection collection = db.getCollection(collectionName);
Mongo mongo = fongoRule.getMongo();
collection.insert(new BasicDBObject("name", "randomName"));
//below is the line 63 on error console
assertThat(dataVersionDaoMongo.findByDBAndCollection(dbname, collectionName)).isNotNull();
}
}

Related

How to get DataSource bean from config in the Junit5

Dears,
I have created a junit5 test case ( UserDaoTests.java) but I am not able to get DataSource Bean defined in the spring configuration file (data.xml).
Project Structure:
test cases are defined in test/com/caveofprogramming/spring/test/tests package, UserDaoTests.java class.
data.xml
configuration file for junit. I have defined datasource bean in it.
<?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:jee="http://www.springframework.org/schema/jee"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
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/context/spring-context-4.3.xsd">
<context:component-scan
base-package="com.caveofprogramming.spring.test.tests">
</context:component-scan>
<context:annotation-config></context:annotation-config>
<mvc:annotation-driven></mvc:annotation-driven>
<context:property-placeholder
location="test/com/caveofprogramming/spring/test/config/jdbc.properties" />
<beans profile="dev">
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="username" value="${jdbc.username}"></property>
</bean>
</beans>
</beans>
jdbc.properties:
jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:#(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = TESTD01)))
jdbc.password=1234
jdbc.username=offerTest
Junit test(UserDaoTests.java)
package com.caveofprogramming.spring.test.tests;
import javax.sql.DataSource;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import com.offers.DAO.UserDAO;
#ActiveProfiles("dev")
#ContextConfiguration(locations = {
"classpath:test/com/caveofprogramming/spring/test/config/data.xml",
"classpath:com/offers/config/offerDAO-context.xml",
"classpath:com/offers/config/offerService-context.xml" })
public class UserDaoTests {
#Autowired
private UserDAO userDao;
private static DataSource dataSource;
private JdbcTemplate jdbc;
#Autowired
public UserDaoTests() {
ApplicationContext context = new FileSystemXmlApplicationContext("test/com/caveofprogramming/spring/test/config/data.xml");
this.dataSource = (DataSource) context.getBean("dataSource");
}
#Test
public void testCreateUser() {
if ( dataSource == null) {
System.out.println("DataSource is null");
}
else {
System.out.println("DataSource is not null!!!! ");
}
}
}
Logs:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataSource' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:816)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1288)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
I would also like to clarify that I am using static DataSource because I need to use #BeforeAll, which require static fields only.
I have tested for non static Data Source as well but result is still the same.
--Update----
I removed <beans profile="dev"> tag from data.xml config file and it's working fine. But I don't understand why it's not working with profile.
--- Update 2 ( Update on on Bhushan's answer) -----
UserDaoTests - updated code
#ExtendWith(SpringExtension.class)
//Add all required depency xml
#ContextConfiguration(locations = { "classpath:test/com/caveofprogramming/spring/test/config/data.xml",
"classpath:com/offers/config/offerDAO-context.xml",
"classpath:com/offers/config/offerService-context.xml" })
#ActiveProfiles("dev")
public class UserDaoTests {
#Autowired
private UserDAO userDao;
#Autowired
private DataSource dataSource;
#Autowired
private JdbcTemplate jdbc;
#Test
public void testCreateUser() {
Assertions.assertNotNull(dataSource);
// Assertions.assertNotNull(jdbc);
}
}
Error Stacktrace:
org.opentest4j.AssertionFailedError: expected: not <null>
at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:39)
at org.junit.jupiter.api.Assertions.fail(Assertions.java:109)
at org.junit.jupiter.api.AssertNotNull.failNull(AssertNotNull.java:47)
at org.junit.jupiter.api.AssertNotNull.assertNotNull(AssertNotNull.java:36)
at org.junit.jupiter.api.AssertNotNull.assertNotNull(AssertNotNull.java:31)
at org.junit.jupiter.api.Assertions.assertNotNull(Assertions.java:283)
at com.caveofprogramming.spring.test.tests.UserDaoTests.testCreateUser(UserDaoTests.java:38)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:43)
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:82)
at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:73)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:141)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Here you are creating multipe application context, one is creating with #ContextConfiguration and another one with FileSystemXmlApplicationContext, so avoid FileSystemXmlApplicationContext and update your code following
#ExtendWith(SpringExtension.class)
//Add all required depency xml
#ContextConfiguration(locations = {
"classpath:test/com/caveofprogramming/spring/test/config/data.xml",
"classpath:com/offers/config/offerDAO-context.xml",
"classpath:com/offers/config/offerService-context.xml" })
#ActiveProfiles("dev")
public class UserDaoTests {
#Autowired
private UserDAO userDao;
#Autowired
private DataSource dataSource;
#Autowired
private JdbcTemplate jdbc;
#Test
public void testCreateUser() {
Assertions.assertNotNull(dataSource);
Assertions.assertNotNull(jdbc);
}
}
Also avoid #BeforeAll as its coupled with static memory, and ours Beans are managed by spring so can't go with it, instead of it you can you for #BeforeEach and if you want perform some logic witch you want run only once for all test cases so you can do hack something like
private AtomicBoolean executed = new AtomicBoolean(false);
#BeforeEach
public void runOnce() {
if(!executed.getAndSet(true)) {
// write you logic which you want will run only once for all test cases
}
}

How to make Weld lookup class on generated-sources

I have a maven project which i'm using MapStruct to generate mappers to help in the job of translating entities into DTOs and vice-versa.
This mappers are generated during the generate-sources phase of maven, and stored into target/generated-sources and target/AppName/WEB-INF/classes folders.
For example, I have this Mapper
#Mapper
public interface RuleMapper {
RuleDto ruletoDto(Rule rule);
//other cool stuf
}
I configurated MapStruct to use CDI, so it will generate the following:
#Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2016-12-19T23:19:36-0200",
comments = "version: 1.1.0.CR1, compiler: javac, environment: Java 1.8.0_112"
)
#Singleton
#Named
public class RuleMapperImpl implements RuleMapper {
#Override
public RuleDto ruletoDto(Rule rule) {
ruleDto ruleDto = new ruleDto();
if ( rule != null ) {
ruleDto.setIdRule( rule.getIdRule() );
}
return ruleDto;
}
}
It works perfectely when running on Wildfly server, the problem is that I'm trying to junit test this class, for this, I implemented a custom runner as shown bellow:
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;
public class WeldJUnit4Runner extends BlockJUnit4ClassRunner {
public WeldJUnit4Runner(Class<Object> clazz) throws InitializationError {
super(clazz);
}
#Override
protected Object createTest() throws Exception {
final Class<?> test = getTestClass().getJavaClass();
return WeldContext.INSTANCE.getBean(test);
}
}
And:
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
public class WeldContext {
public static final WeldContext INSTANCE = new WeldContext();
private final Weld weld;
private final WeldContainer container;
private WeldContext() {
this.weld = new Weld();
this.container = weld.initialize();
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
weld.shutdown();
}
});
}
public <T> T getBean(Class<T> type) {
return container.instance().select(type).get();
}
}
These implementations were taken from here.
Finally, the test:
#RunWith(WeldJUnit4Runner.class)
public class RuleMapperTest {
#Inject
private RuleMapper ruleMapper;
#Test
public void coolTestName() {
Assert.assertTrue(Boolean.TRUE);
}
}
When I try to run, this is the console output:
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
warning about logs, and the following exception:
java.lang.ExceptionInInitializerError
at br.com.treinoos.common.cdi.WeldJUnit4Runner.createTest(WeldJUnit4Runner.java:15)
at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:266)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type RuleMapper with qualifiers #Default
at injection point [BackedAnnotatedField] #Inject private br.com.treinoos.model.core.business.treinoos.mappers.RuleMapperTest.ruleMapper
at br.com.treinoos.model.core.business.treinoos.mappers.RuleMapperTest.ruleMapper(RuleMapperTest.java:0)
at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:359)
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:281)
at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:134)
at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:155)
at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:518)
at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:68)
at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:66)
at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:63)
at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:56)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Like Weld wasn't abble to lookup the generated class.
The beans.xml is already created under src/test/resources/META-INF/beans.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all">
</beans>
Can anybody point me a solution to this problem? I've already searched something simillar, but no success.
Here's a full explanation to your problem and why what I wrote fixes it.
In Maven, you have at least 2 classloader. Your test classpath and your main classpath each have their own classloader. You can have others depending on your dependency structure. CDI identifies each classloader as a separate bean archive when running this way. src/main/webapp is explicitly for your WAR file. The beans.xml there does not give you a bean archive. Adding one to src/main/resources does. This problem is specific to how you're instantiating weld.
There are other projects that do this correctly - CDI-unit and Arquillian, specifically the Weld Embedded container. If you were to use one of these, this would not be an issue.

Pure JerseyTest without letting Spring messing with services

I am having hard time with JerseyTest and Spring. Previously in non-Spring Java projects what I usually did for my REST APIs was to extend my Test from JerseyTest, mocking the Service classes and simply (unit)testing my REST API. Now I'm using spring in my project where in my REST resource classes the Services are annotated with #Autowired. Now that I'm using the same scenario. Spring jumps in and nags about stuff like lack of applicationcontext.xml. I do want to use spring in my production but for my unit test I don't need my test know anything about Spring and all its autowiring and classpath annotation processing! How can I get this right? The classes look like this:
public class RESTResource{
#Autowired
MyService service;
#GET
public Response getSomeStuff(){
...
service.getStuff()
}
}
And here is the Test class
public class RESTResourceTest extends JerseyTest{
private Service service;
#Override
public Application configure(){
RESTResource resource = new RESTResource();
service = Mockito.mock(Service.class);
resource.setService(service);
ResourceConfig config = new ResourceConfig();
config.register(resource);
return config;
}
}
This is the stacktrace:
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:252)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127)
at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:538)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:452)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
at org.glassfish.jersey.server.spring.SpringComponentProvider.createXmlSpringConfiguration(SpringComponentProvider.java:173)
at org.glassfish.jersey.server.spring.SpringComponentProvider.createSpringContext(SpringComponentProvider.java:164)
at org.glassfish.jersey.server.spring.SpringComponentProvider.initialize(SpringComponentProvider.java:99)
at org.glassfish.jersey.server.ApplicationHandler$4.get(ApplicationHandler.java:408)
at org.glassfish.jersey.server.ApplicationHandler$4.get(ApplicationHandler.java:399)
at org.glassfish.jersey.internal.util.collection.Values$LazyValueImpl.get(Values.java:340)
at org.glassfish.jersey.server.ApplicationHandler$3.call(ApplicationHandler.java:350)
at org.glassfish.jersey.server.ApplicationHandler$3.call(ApplicationHandler.java:347)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:255)
at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:347)
at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:299)
at org.glassfish.jersey.test.inmemory.InMemoryTestContainerFactory$InMemoryTestContainer.<init>(InMemoryTestContainerFactory.java:77)
at org.glassfish.jersey.test.inmemory.InMemoryTestContainerFactory$InMemoryTestContainer.<init>(InMemoryTestContainerFactory.java:63)
at org.glassfish.jersey.test.inmemory.InMemoryTestContainerFactory.create(InMemoryTestContainerFactory.java:111)
at org.glassfish.jersey.test.JerseyTest.createTestContainer(JerseyTest.java:277)
at org.glassfish.jersey.test.JerseyTest.setUp(JerseyTest.java:609)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
... 56 more
P.S. I'm using spring boot.
What you can do is to simply exclude the jersey-spring3 using the the sure-fire plugin for test phase.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<classpathDependencyExcludes>
<classpathDependencyExclude>
org.glassfish.jersey.ext:jersey-spring3
</classpathDependencyExclude>
</classpathDependencyExcludes>
</configuration>
</plugin>
Here is some code snippets that might help in your case :
Option 1. Your REST resource class :
#Component
#Path("/api/helloworld")
public class RESTResource{
#Autowired
MyService service;
#GET
#Produces(MediaType.TEXT_PLAIN)
public String helloMessage() {
return "Hello World Jersey Way!";
}
}
Your test config class :
#Component
public class JerseyConfig extends ResourceConfig {
/**
* In constructor we can define Jersey Resources & Other Components
*/
public JerseyConfig() {
register(RESTResource.class);
}
}
3.Your test base class :
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = Application.class)//NOTE : Application is a spring boot main class,or if you have specific configuration class similar to test config class above use #ContextConfiguration(classes = MyServiceSpringConfig.class)
public class RESTResourceTest extends JerseyTest {
#Override
protected Application configure() {
return new JerseyConfig();
}
#Test
public void contextLoads() {
}
#Test
public void someTest() throws Exception {
// Very useful test
}
}
Option 2 :
#Priority(value = 1)
public class MySpringWebInitializer implements WebApplicationInitializer
{
#Override
public void onStartup(ServletContext container)
{
//Tell jersey-spring3 the context is already initialized
container.setInitParameter("contextConfigLocation", "NOTNULL");
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(RESTResource.class);
container.addListener(new ContextLoaderListener(appContext));
}
}
Also,for spring boot you can run test cases using an active profile or a config name ,pass runtime VM args with -Dspring.config.name=test for running test cases etc..
Hope this help and the rest is self explanatory.
The better way to integrate JerseyTest with Spring
No inheritance from JerseyTest in junit test class
No dependencies on Jersey in junit test class, just pure jax-rs dependency
perfectly integrate SpringJUnit4ClassRunner and #ContextConfiguration
My solution is hosted on github. Hope this help for you.

Spring Transactional not working

I'v setup a Spring/Hibernate backend based on following example using Spring 4.1 and Hibernate 4.3.6:
http://www.sivalabs.in/2011/02/springhibernate-application-with-zero.html
I basically got everything working so far, but there is one little configuration problem I can't overcome: If I try to save an Entity I get the following StackTrace:
org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
at org.springframework.orm.hibernate4.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1135)
at org.springframework.orm.hibernate4.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:620)
at org.springframework.orm.hibernate4.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:617)
at org.springframework.orm.hibernate4.HibernateTemplate.doExecute(HibernateTemplate.java:340)
at org.springframework.orm.hibernate4.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:308)
at org.springframework.orm.hibernate4.HibernateTemplate.save(HibernateTemplate.java:617)
at com.test.database.dao.UserSecurityQuestionDAOImpl.save(UserSecurityQuestionDAOImpl.java:40)
at com.test.database.service.UserSecurityQuestionService.save(UserSecurityQuestionService.java:20)
at com.test.database.UserSecurityQuestionTest.basicCreationAndRetrievalTest(UserSecurityQuestionTest.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:24)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
My transactional directive is placed in the Service Bean and looks like this:
#Service
#Transactional
public class UserSecurityQuestionService implements UserSecurityQuestionDAO{
#Autowired
private UserSecurityQuestionDAO userSecurityQuerstionDAO;
#Override
#Transactional(readOnly=false)
public void save(UserSecurityQuestion userSecurityQuestion) {
userSecurityQuerstionDAO.save(userSecurityQuestion);
}
This is my DAO Implementation of the save Method:
#Repository
public class UserSecurityQuestionDAOImpl implements UserSecurityQuestionDAO {
#Autowired
private HibernateTransactionManager transactionManager;
public void save(UserSecurityQuestion userSecurityQuestion) {
Session session = transactionManager.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
session.persist(userSecurityQuestion);
tx.commit();
session.close();
}
Selecting from the Database works fine, but Inserts/Updates are refused throwing above Error Message. What am I missing?
UPDATE
UserSecurityQuestionDAOImpl:
public class UserSecurityQuestionDAOImpl implements UserSecurityQuestionDAO{
#Autowired
private SessionFactory sessionFactory;
public void save(UserSecurityQuestion userSecurityQuestion) {
this.sessionFactory.getCurrentSession().save(userSecurityQuestion);
}
UserSecurityQuestionDAO / UserSecurityQuestionService - Interfaces:
public interface UserSecurityQuestionService {
public void save(UserSecurityQuestion userSecurityQuestion);
public UserSecurityQuestion findById(Short id);
public List<UserSecurityQuestion> findAll();
public void delete(UserSecurityQuestion userSecurityQuestion);
public void deleteById(Short... id);
}
Service Implementation:
#Service
public class UserSecurityQuestionServiceImpl implements UserSecurityQuestionService {
#Autowired
private UserSecurityQuestionDAO userSecurityQuestionDAO;
#Transactional
public void save(UserSecurityQuestion userSecurityQuestion) {
userSecurityQuestionDAO.save(userSecurityQuestion);
}
Unit test code Used for Testing:
public class UserSecurityQuestionTest {
private AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
private UserSecurityQuestionService usqService;
#Before
public void setUp(){
//Setup App Context
ctx.scan("com.test.database");
ctx.refresh();
//Initilize Service Bean
usqService = ctx.getBean("userSecurityQuestionService",UserSecurityQuestionServiceImpl.class);
}
New Problem: If I add #Autowired to the private UserSecurityQuestionService usqService; and omit the Setup-Part, I will get a Null pointer Exception. If I leave the code as it is, I get org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'userSecurityQuestionService' is defined
I can see that both you service class and your dao implements same interface, and that you autowire the dao in service by its class.
I assume your service is also autowired by its class in your controller. It would be better to have separate interfaces for service and dao to allow autowiring by type using an interface. That way, Spring will use a JDK proxy (the default) to implement the transactional proxy around your service bean.
The alternative would be to use <tx:annotation-driven proxy-target-class="true/>", but you then need to have CGLIB in your path.

NPE when invoking getter of managed property

I am learning Spring with Hibernate and am creating a movie rental application using JSF as front end framework.
I have an application scoped managed property in my registration bean which is view scoped. In the register() method to insert the user details in the database, I invoke the service locator implementation bean to get a reference to the required service implementation. However, I get an NPE when I invoke the getter of the service locator property.
Following are my managed beans...
Registration Bean
#ManagedBean
#ViewScoped
public class RegistrationBean extends BaseBean implements Serializable
{
private static final long serialVersionUID = -6449858513581500971L;
private String userID;
private String password;
private String firstName;
private String lastName;
private String email;
private String addressLine1;
private String addressLine2;
private String city;
private String state;
private String pincode;
public RegistrationBean() {
super();
}
// getter / setters...
public String register()
{
String nextPage = null;
try {
RegistrationDetails userDetails = ModelBuilder.populateRegistrationData(this);
// NPE at this line. getServiceLocator() returns null
int registrationID = getServiceLocator().getUserService().registerUser(userDetails);
nextPage = "success";
}
catch (RegistrationException e) {
LOGGER.error(e.getMessage());
}
return nextPage;
}
}
Base Bean
public class BaseBean
{
#ManagedProperty("#{serviceLocator}")
protected IServiceLocator serviceLocator;
protected IServiceLocator getServiceLocator() {
return serviceLocator;
}
public void setServiceLocator(IServiceLocator serviceLocator) {
this.serviceLocator = serviceLocator;
}
}
Service Locator Bean
#ManagedBean
#ApplicationScoped
public class ServiceLocator implements IServiceLocator
{
private static final String USER_SERVICE = "userService";
public ServiceLocator() {
super();
final ServletContext sc = FacesUtils.getServletContext();
this.webAppContext = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
this.userService = (IUserService) webAppContext.getBean(USER_SERVICE);
}
private ApplicationContext webAppContext;
private IUserService userService;
#Override
public IUserService getUserService() {
return userService;
}
public ApplicationContext getWebAppContext() {
return webAppContext;
}
}
And here is the stacktrace as seen in my Eclipse console
Oct 14, 2012 10:28:39 PM com.sun.faces.lifecycle.InvokeApplicationPhase execute
WARNING: #{registrationBean.register}: java.lang.NullPointerException
javax.faces.FacesException: #{registrationBean.register}: java.lang.NullPointerException
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 23 more
Caused by: java.lang.NullPointerException
at com.clixflix.managedbeans.RegistrationBean.register(RegistrationBean.java:118)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
... 24 more
I am using
JSF 2.1 (Mojarra)
Hibernate 4.1
Spring 3.2
Tomcat 7
Eclipse 3.7
Could someone please point out if I have missed something??
UPDATE: Spring config file
<?xml version="1.0" encoding="UTF-8"?>
<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-2.5.xsd">
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="configLocation" value="/WEB-INF/hibernate.cfg.xml" />
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="userDAO" class="com.clixflix.dao.impl.UserDAOImpl">
<constructor-arg index="0" ref="hibernateTemplate" />
</bean>
<bean id="userService" class="com.clixflix.services.impl.UserService">
<constructor-arg index="0" ref="userDAO" />
</bean>
</beans>
This post helped me to make the code work : http://www.javacodegeeks.com/2012/04/jsf-2-primefaces-3-spring-3-hibernate-4.html
However, the code does not work if I keep the Registration Bean as view scoped. Can anyone please help me figure out the reason for the same?
UPDATE: Found the solution for the ViewScope issue : http://blog.harezmi.com.tr/spring-view-scope-for-jsf-2-users/

Resources