javax.management.InstanceAlreadyExistsException while deploying spring application - spring

<int:poller fixed-delay="${fixedDelay}" default="true">
<int:advice-chain>
<ref bean="pollAdvise"/>
</int:advice-chain>
</int:poller>
<bean id="pollAdvise" class="org.springframework.integration.scheduling.PollSkipAdvice">
<constructor-arg ref="healthCheckStrategy"/>
</bean>
<bean id="healthCheckStrategy" class="test.main.ServiceHealthCheckPollSkipStrategy">
<property name="url" value="${url}"/>
<property name="doHealthCheck" value="${doHealthCheck}"/>
<property name="restTemplate" ref="restTemplate"/>
</bean>
<bean id="restTemplate"
class="org.springframework.web.client.RestTemplate">
<constructor-arg ref="requestFactory"/>
</bean>
<bean id="requestFactory"
class="test.BatchClientHttpRequestFactory">
<constructor-arg ref="verifier"/>
</bean>
and my health check strategy looks like below
#ManagedResource
public class ServiceHealthCheckPollSkipStrategy implements PollSkipStrategy {
private volatile boolean skip=false;
private String url;
private static String doHealthCheck;
private RestTemplate restTemplate;
public RestTemplate getRestTemplate() {
return restTemplate;
}
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDoHealthCheck() {
return doHealthCheck;
}
public void setDoHealthCheck(String doHealthCheck) {
ServiceHealthCheckPollSkipStrategy.doHealthCheck= doHealthCheck;
}
#Override
public boolean skipPoll() {
if(doHealthCheck.equals("false")){
return this.skip;
}
else if(doHealthCheck.equals("true")){
List<String> urlList =getUrlfromEncodedString(url);
for (String url : urlList) {
boolean status =performHealthCheck(url);
if(status==false){
return this.skip = true;
}
}
return this.skip;
}
else {
throw new IllegalArgumentException("do health check can be either true or false");
}
}
/**
* Skip future polls.
*/
#ManagedOperation
public void skipPolls() {
this.skip = true;
}
/**
* Resume polling at the next {#code Trigger} event.
*/
#ManagedOperation
public void reset() {
this.skip = false;
}
private List<String> getUrlfromEncodedString(String urls) throws IllegalArgumentException
{
if(urls==null){
throw new IllegalArgumentException("urls passed is null");
}
List<String> urlList = Arrays.asList(urls.split("\\s*,\\s*"));
return urlList;
}
private boolean performHealthCheck(String url){
if(url==null){
throw new IllegalArgumentException("url passed is null");
}
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("API-Key", "RTM");
HttpEntity<String> request = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> response = restTemplate.
exchange(url, HttpMethod.OPTIONS, request, String.class);
if (response.getStatusCode().toString().equals("200")){
return true;
}
return false;
}
}
I get below exception
Unable to register MBean [test.main.ServiceHealthCheckPollSkipStrategy#73d4b814] with key 'healthCheckStrategy'; nested exception is javax.management.InstanceAlreadyExistsException: test.main:name=healthCheckStrategy,type=ServiceHealthCheckPollSkipStrategy
at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:625)
at org.springframework.jmx.export.MBeanExporter.registerBeans(MBeanExporter.java:550)
at org.springframework.jmx.export.MBeanExporter.afterSingletonsInstantiated(MBeanExporter.java:432)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:775)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:139)
at org.springframework.xd.module.core.SimpleModule.initialize(SimpleModule.java:213)
at org.springframework.xd.dirt.module.ModuleDeployer.doDeploy(ModuleDeployer.java:217)
at org.springframework.xd.dirt.module.ModuleDeployer.deploy(ModuleDeployer.java:200)
at org.springframework.xd.dirt.server.container.DeploymentListener.deployModule(DeploymentListener.java:365)
at org.springframework.xd.dirt.server.container.DeploymentListener.deployStreamModule(DeploymentListener.java:334)
at org.springframework.xd.dirt.server.container.DeploymentListener.onChildAdded(DeploymentListener.java:181)
at org.springframework.xd.dirt.server.container.DeploymentListener.childEvent(DeploymentListener.java:149)
at org.apache.curator.framework.recipes.cache.PathChildrenCache$5.apply(PathChildrenCache.java:509)
at org.apache.curator.framework.recipes.cache.PathChildrenCache$5.apply(PathChildrenCache.java:503)
at org.apache.curator.framework.listen.ListenerContainer$1.run(ListenerContainer.java:92)
at com.google.common.util.concurrent.MoreExecutors$SameThreadExecutorService.execute(MoreExecutors.java:297)
at org.apache.curator.framework.listen.ListenerContainer.forEach(ListenerContainer.java:83)
at org.apache.curator.framework.recipes.cache.PathChildrenCache.callListeners(PathChildrenCache.java:500)
at org.apache.curator.framework.recipes.cache.EventOperation.invoke(EventOperation.java:35)
at org.apache.curator.framework.recipes.cache.PathChildrenCache$10.run(PathChildrenCache.java:762)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
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)
Caused by: javax.management.InstanceAlreadyExistsException: test.main:name=healthCheckStrategy,type=ServiceHealthCheckPollSkipStrategy
at com.sun.jmx.mbeanserver.Repository.addMBean(Repository.java:437)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerWithRepository(DefaultMBeanServerInterceptor.java:1898)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerDynamicMBean(DefaultMBeanServerInterceptor.java:966)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerObject(DefaultMBeanServerInterceptor.java:900)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(DefaultMBeanServerInterceptor.java:324)
at com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(JmxMBeanServer.java:522)
at org.springframework.jmx.support.MBeanRegistrationSupport.doRegister(MBeanRegistrationSupport.java:195)
at org.springframework.jmx.export.MBeanExporter.registerBeanInstance(MBeanExporter.java:678)
at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:615)
... 30 m

I got the javax.management.InstanceAlreadyExistsException as part of the stacktrace, however the leading error was java.lang.IllegalStateException:
javax.management.InstanceAlreadyExistsException: jboss.deployment:id="jboss.web.deployment:war=/my_application", type=Component already registered.
Caused by: java.lang.IllegalStateException: jboss.web.deployment:war=/my_application is already installed.
The reason was that I accidentally kept two .ear files in the /deploy folder of my JBOSS server - both the previous and the current .ear of my application.
As it was stated here: https://www.theserverside.com/discussions/thread/22674.html
I'm not sure there is a way to deploy two ear files with the same
classes inside and not have problems.
Since the two .ears had classes in common, that lead to InstanceAlreadyExistsException.

What has worked for me is:
Delete the war file from /webapps
Copy war file from /target and paste into /webapps
Hope it will work for you too.

It's because you also declare another bean with the same id as 'healthCheckStrategy' in another spring application. You probably put these two spring applications in the same server.
Solution 1:
change the bean id either in this spring application or the other one will solve your problem.
Solution 2:
add EnableMBeanExport annotation and set different defaultDomain for each spring application
#Configuration
#EnableMBeanExport(defaultDomain="first")
public class BeanGenerator {...}
#Configuration
#EnableMBeanExport(defaultDomain="second")
public class BeanGenerator {...}

Related

Caused by: java.lang.IllegalArgumentException: Unable to deserialize the execution context in Spring Batch

I am developing Spring Boot + Batch XML based approach. In this example, I have created following classes. When I simply load or class the Spring Batch Job. I get the below error.
I web search links like : Migration to Spring Boot 2 and using Spring Batch 4 , but it did not solve my problem.
Could anyone please guide what exact solution needs to be applied here ?
Error:
Caused by: java.lang.IllegalArgumentException: Unable to deserialize the execution context
at org.springframework.batch.core.repository.dao.JdbcExecutionContextDao$ExecutionContextRowMapper.mapRow(JdbcExecutionContextDao.java:325) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.batch.core.repository.dao.JdbcExecutionContextDao$ExecutionContextRowMapper.mapRow(JdbcExecutionContextDao.java:309) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:93) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:60) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:667) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:605) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:657) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:688) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:700) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:756) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.batch.core.repository.dao.JdbcExecutionContextDao.getExecutionContext(JdbcExecutionContextDao.java:112) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.batch.core.explore.support.SimpleJobExplorer.getJobExecutionDependencies(SimpleJobExplorer.java:202) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.batch.core.explore.support.SimpleJobExplorer.getJobExecutions(SimpleJobExplorer.java:83) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_162]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_162]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_162]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_162]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343) ~[spring-aop-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197) ~[spring-aop-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at com.sun.proxy.$Proxy70.getJobExecutions(Unknown Source) ~[na:na]
at org.springframework.batch.core.JobParametersBuilder.getNextJobParameters(JobParametersBuilder.java:264) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.execute(JobLauncherCommandLineRunner.java:162) ~[spring-boot-autoconfigure-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.executeLocalJobs(JobLauncherCommandLineRunner.java:179) ~[spring-boot-autoconfigure-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.launchJobFromProperties(JobLauncherCommandLineRunner.java:134) ~[spring-boot-autoconfigure-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.run(JobLauncherCommandLineRunner.java:128) ~[spring-boot-autoconfigure-2.0.4.RELEASE.jar:2.0.4.RELEASE]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:800) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
... 5 common frames omitted
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Unexpected token (START_OBJECT), expected VALUE_STRING: need JSON String that contains type id (for subtype of java.lang.Object)
at [Source: (ByteArrayInputStream); line: 1, column: 9] (through reference chain: java.util.HashMap["map"])
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.9.6.jar:2.9.6]
at com.fasterxml.jackson.databind.DeserializationContext.wrongTokenException(DeserializationContext.java:1498) ~[jackson-databind-2.9.6.jar:2.9.6]
at com.fasterxml.jackson.databind.DeserializationContext.reportWrongTokenException(DeserializationContext.java:1273) ~[jackson-databind-2.9.6.jar:2.9.6]
at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer._locateTypeId(AsArrayTypeDeserializer.java:151) ~[jackson-databind-2.9.6.jar:2.9.6]
at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer._deserialize(AsArrayTypeDeserializer.java:96) ~[jackson-databind-2.9.6.jar:2.9.6]
at com.fasterxml.jackson.databind.jsontype.impl.AsArrayTypeDeserializer.deserializeTypedFromAny(AsArrayTypeDeserializer.java:71) ~[jackson-databind-2.9.6.jar:2.9.6]
at com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer$Vanilla.deserializeWithType(UntypedObjectDeserializer.java:712) ~[jackson-databind-2.9.6.jar:2.9.6]
at com.fasterxml.jackson.databind.deser.std.MapDeserializer._readAndBindStringKeyMap(MapDeserializer.java:529) ~[jackson-databind-2.9.6.jar:2.9.6]
at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:364) ~[jackson-databind-2.9.6.jar:2.9.6]
at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:29) ~[jackson-databind-2.9.6.jar:2.9.6]
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013) ~[jackson-databind-2.9.6.jar:2.9.6]
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3077) ~[jackson-databind-2.9.6.jar:2.9.6]
at org.springframework.batch.core.repository.dao.Jackson2ExecutionContextStringSerializer.deserialize(Jackson2ExecutionContextStringSerializer.java:70) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.batch.core.repository.dao.Jackson2ExecutionContextStringSerializer.deserialize(Jackson2ExecutionContextStringSerializer.java:50) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
at org.springframework.batch.core.repository.dao.JdbcExecutionContextDao$ExecutionContextRowMapper.mapRow(JdbcExecutionContextDao.java:322) ~[spring-batch-core-4.0.1.RELEASE.jar:4.0.1.RELEASE]
... 34 common frames omitted
CommonConfig.java
#Configuration
#ComponentScan("com.XXXX")
#EnableBatchProcessing
#EnableScheduling
#PropertySource("classpath:database.properties")
#ImportResource({ "classpath:jobs/XYZ.xml"})
public class CommonConfig {
#Bean
BatchConfigurer configurer(#Qualifier("dataSource") DataSource dataSource) {
return new DefaultBatchConfigurer(dataSource);
}
}
XYZ.xml
<bean id="databaseConfig" class="com.XX.config.DatabaseConfig" />
<bean id="transactionManager" class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" />
<bean id="job_Repository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<property name="transactionManager" ref="transactionManager" />
</bean>
<bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="job_Repository" />
</bean>
<bean id="stepScope" class="org.springframework.batch.core.scope.StepScope">
<property name="autoProxy" value="true"/>
</bean>
<batch:job id="myXYZBatchJob">
<batch:step id="XYZContextStep" >
<batch:tasklet ref=XYZContextTasklet" />
</batch:step>
</batch:job>
......
........
</bean>
DatabaseConfig.java
#Configuration
#EnableTransactionManagement
#ComponentScan({ "com.XXX" })
#EnableJpaRepositories(basePackages = {"com.XX.repository", "com.XX.custom.repository"},
entityManagerFactoryRef = "entityManagerFactory",
transactionManagerRef = "transactionManager")
public class DatabaseConfig {
#Bean
#Primary
#ConfigurationProperties("abc.datasource")
public DataSourceProperties dataSourceProperties() {
return new DataSourceProperties();
}
#Primary
#Bean(name = "dataSource")
#ConfigurationProperties(prefix = "abc.datasource")
public DataSource dataSource() {
return dataSourceProperties().initializeDataSourceBuilder().build();
}
#Primary
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(#Qualifier("dataSource") DataSource dataSource) {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource);
em.setPackagesToScan(new String[] { "com.XX.Entity" });
em.setPersistenceUnitName("devcloud");
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
return em;
}
#Primary
#Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(#Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
EDIT-1:
I am using Spring Boot Parent version 2.0.4.RELEASE, which is latest. It pulls all the Spring versions including Context version of 5.0.8.RELEASE.
Request you to post code snippet and detailed description to support your answer.
Edit-2:
public class BillingConfig implements BatchConfigurer{
private PlatformTransactionManager transactionManager;
private JobRepository jobRepository;
private JobLauncher jobLauncher;
private JobExplorer jobExplorer;
#Override
public JobRepository getJobRepository() {
return jobRepository;
}
#Override
public PlatformTransactionManager getTransactionManager() {
return transactionManager;
}
#Override
public JobLauncher getJobLauncher() throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException {
return jobLauncher;
}
#Override
public JobExplorer getJobExplorer() {
return jobExplorer;
}
#PostConstruct
void initialize() throws Exception {
if (this.transactionManager == null) {
this.transactionManager = new ResourcelessTransactionManager();
}
// A FactoryBean that automates the creation of a SimpleJobRepository using non-persistent in-memory DAO implementations.
MapJobRepositoryFactoryBean jobRepositoryFactory = new MapJobRepositoryFactoryBean(this.transactionManager);
jobRepositoryFactory.afterPropertiesSet();
this.jobRepository = jobRepositoryFactory.getObject();
// A FactoryBean that automates the creation of a SimpleJobRepository using non-persistent in-memory DAO implementations.
MapJobExplorerFactoryBean jobExplorerFactory = new MapJobExplorerFactoryBean(jobRepositoryFactory);
jobExplorerFactory.afterPropertiesSet();
this.jobExplorer = jobExplorerFactory.getObject();
this.jobLauncher = createJobLauncher();
}
private JobLauncher createJobLauncher() throws Exception {
SimpleJobLauncher simpleJobLauncher = new SimpleJobLauncher();
simpleJobLauncher.setJobRepository(jobRepository);
simpleJobLauncher.afterPropertiesSet();
return simpleJobLauncher;
}
}
This error happens when the execution context of your job is serialized with version 3 (using XStream by default) and then deserialized with version 4 (using Jackson by default). So either downgrade Spring Batch to version 3 or configure your job repository to use the XStreamExecutionContextStringSerializer.
In your case, you have already defined a bean of type BatchConfigurer, so you can override the createJobRepository method and configure the XStream serializer. For example:
#Bean
BatchConfigurer configurer(#Qualifier("dataSource") DataSource dataSource, PlatformTransactionManager transactionManager) {
return new DefaultBatchConfigurer(dataSource) {
#Override
protected JobRepository createJobRepository() throws Exception {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
factory.setDataSource(dataSource);
factory.setTransactionManager(transactionManager);
factory.setSerializer(new XStreamExecutionContextStringSerializer());
factory.afterPropertiesSet();
return factory.getObject();
}
};
}
Try cleaning up the spring batch tables.
Use following link :
--cleaning spring batch tables ----
http://forum.spring.io/forum/spring-projects/batch/122103-clean-spring-batch-metadata-tables
Since XStreamExecutionContextStringSerializer is deprecated with the latest Spring BATCH release.
If you are adding a complex object to Execution Context Check if the object you are trying to add is Serializable.
For example, if your class looks like:
class Sample{
String data;
List<DataItem> dataItems;
}
Make sure DataItem which is present inside the object is also Serializable.
This helped me solve my issue.

How to solve NullPointerException at mailSender when using some organization as a host

I'm trying to send emails using an organisation mailSender.
Controller
#RequestMapping(value="/forgetPassword", method = RequestMethod.POST, consumes={"application/json"})
public #ResponseBody User forgetPassword(#RequestBody User user) throws Exception {
user=userService.forgetPassword(user, newPassword);
if(user !=null)
{
SendEmail callsendEmail = new SendEmail();
callsendEmail.emailSender(user);
return user;
}
else
{
return user;
}
}
SendEmail
public class SendEmail {
private JavaMailSender mailSender;
private VelocityEngine velocityEngine;
private SimpleMailMessage templateMessage;
public void emailSender(final User user) throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
message.setFrom(templateMessage.getFrom());
message.setTo(user.getEmail());
message.setSubject(templateMessage.getSubject());
Map<String, User> model = new HashMap<String, User>();
model.put("user", user);
/*String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "org/utility/mailTemplate.vm", model);
message.setText(text, true);*/
if (mailSender != null) {
mailSender.send(mimeMessage);
}
}
public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
public JavaMailSender getMailSender() {
return mailSender;
}
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public SimpleMailMessage getTemplateMessage() {
return templateMessage;
}
public void setTemplateMessage(SimpleMailMessage templateMessage) {
this.templateMessage = templateMessage;
}
}
Configuration
<bean id="emailSender" class="org.utility.SendEmail">
<property name="mailSender" ref="mailSender" />
<property name="velocityEngine" ref="velocityEngine" />
<property name="templateMessage" ref="templateMessage" />
</bean>
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="10.6.12.229" />
<property name="port" value="25" />
</bean>
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="velocityProperties">
<value>resource.loader=class class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader</value>
</property>
</bean>
<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="noreply#scrumtracker.com" />
<property name="subject" value="Scrum Tracker Login Details" />
</bean>
Here's the stack trace:
SEVERE: Servlet.service() for servlet [spring] in context with path [/OLPV] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at org.utility.SendEmail.emailSender(SendEmail.java:24)
at org.controller.UserController.forgetPassword(UserController.java:125)
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.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.web.multipart.support.MultipartFilter.doFilterInternal(MultipartFilter.java:119)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:242)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:243)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:201)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:163)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:108)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:556)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:401)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:242)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:267)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:245)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:260)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I'm getting nullpointer exception on running the above code. Data is passing to the SendEmail class from Controller. Any idea on this?
Set #autowired from calling class (Don't do New) to the mailSend class.
Write #Service in mailSend class.
Directly call the mailSend.Send() method from the calling class.
All prop will be set automatically. No null point exception.
Namaste !
In your Controller class you don't need to instantiante the SendEmail like you do
SendEmail callsendEmail = new SendEmail();
But instead inject it as a spring bean
#Controller
class MyController {
#Autowired
private SendEmail callsendEmail;
#RequestMapping(value="/forgetPassword", method = RequestMethod.POST, consumes={"application/json"})
public #ResponseBody User forgetPassword(#RequestBody User user) throws Exception {
user=userService.forgetPassword(user, newPassword);
if(user !=null)
{
callsendEmail.emailSender(user);
return user;
}
else
{
return user;
}
}
}
If your application context is not configured to autowire beans by annotations, then use a regular setter in the class
#Required
public void setSendEmail( SendEmail sendEmail ) {
this.callsendEmail = sendEmail;
}

How to send Emails via Spring

In my JavaFx project I inject my controllers like so, which works fine:
#Configuration
public class AppFactory {
#Bean
public HomeController homeController() throws IOException {
return (HomeController) loadController("/wakiliproject/Home.fxml");
}
FXMLLoader loader = null;
protected Object loadController(String url) throws IOException {
loader = new FXMLLoader(getClass().getResource(url));
loader.load();
return loader.getController();
}
}
However, for non-controller classes, I get a null pointer exception, probably because the class never gets injected. Say, for example, I try to call a method in a non-controller class from another non-controller class like so:
Sending email via Spring, for example:
public class HomeController extends Application {
#Autowired
MailMail mailMail;
// Send email here
public void sendEmailMethod() {
System.out.println("Here ----------------------------------------------------------------");
mailMail.sendMail("olireylikesyou#gmail.com", "tryrevilo#yahoo.com", "Hello", "Subjecto");
}
// The other class methods
The other classes:
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="username" value="mygmailusername#gmail.com" />
<property name="password" value="gmailpassword" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean>
<bean id="mailMail" class="wakiliproject.ServerSide.EMail.MailMail">
<property name="mailSender" ref="mailSender" />
</bean>
--
public class MailMail {
private MailSender mailSender;
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
public void sendMail(String from, String to, String subject, String msg) {
//creating message
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(msg);
//sending message
mailSender.send(message);
}
}
The stacktrace:
Exception in Application start method
java.lang.reflect.InvocationTargetException
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:483)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:367)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:305)
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:483)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:894)
at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:56)
at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:158)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.mail.MailSendException: Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. k10sm2188955lae.42 - gsmtp
; message exceptions (1) are:
Failed message 1: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. k10sm2188955lae.42 - gsmtp
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:448)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:308)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:297)
at wakiliproject.ServerSide.EMail.MailMail.sendMail(MailMail.java:22)
at wakiliproject.HomeController$HomeInit.homeInit(HomeController.java:618)
at wakiliproject.HomeController$HomeInit.access$100(HomeController.java:613)
at wakiliproject.HomeController.initHomeController(HomeController.java:319)
at wakiliproject.WakiliProject.start(WakiliProject.java:34)
at com.sun.javafx.application.LauncherImpl$8.run(LauncherImpl.java:837)
at com.sun.javafx.application.PlatformImpl$7.run(PlatformImpl.java:335)
at com.sun.javafx.application.PlatformImpl$6$1.run(PlatformImpl.java:301)
at com.sun.javafx.application.PlatformImpl$6$1.run(PlatformImpl.java:298)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl$6.run(PlatformImpl.java:298)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$300(WinApplication.java:39)
at com.sun.glass.ui.win.WinApplication$4$1.run(WinApplication.java:112)
... 1 more
Exception running application wakiliproject.WakiliProject
Java Result: 1
had a similar problem... got me some attempts to configure it right in my application.properties (I'm injecting JavaMailSender using spring)
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.auth = true;
spring.mail.properties.mail.socketFactory.port=587
spring.mail.properties.mail.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.socketFactory.fallback=false
later i was required to enable looser security to my account during the test:
"change your settings at https://www.google.com/settings/security/lesssecureapps so that your account is no longer protected by modern security standards"
or i got an authentication error.
I hope that helps
According to Mladen Uzelac You need to set some properties for your SMTP connection.
Link related:
http://forum.spring.io/forum/spring-projects/web/68425-javax-mail-messagingexception-530-5-7-0-must-issue-a-starttls-command-first-5sm505

dataSource.getConnection throwing NullpointerException in Spring

I am trying to connect to MySQL database in my spring application. I am able to connect to it if I use DriverManager.getConnection(DB_URL,USER, PASS) but unable to get connection with dataSource which is configured with bean.
App context
<bean id="jdbcTest" class="org.springdemo.jdbc.JdbcTest">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="xxxx"></property>
<property name="password" value="xxxx"></property>
</bean>
Class
public class JdbcTest {
private DataSource dataSource;
public JdbcTest(){
try {
Class.forName("com.mysql.jdbc.Driver");
//conn = DriverManager.getConnection(DB_URL,USER,PASS); This worked!!!!
conn = dataSource.getConnection();
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet executeQuery(String query){
//executing query; it works as I tested with DriverManager
}
public static void main(String[] args) {
AbstractApplicationContext context =
new ClassPathXmlApplicationContext("spring.xml");
JdbcTest test = context.getBean("jdbcTest", JdbcTest.class);
ResultSet rs = test.executeQuery("select * from employee");
try {
while(rs.next()){
System.out.println(rs.getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
It worked perfectly fine when I use DriverManager but, when I use DataSource object to get connection which is configured with bean, it gives NullPointerException
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jdbcTest' defined in class path resource [spring.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springdemo.jdbc.JdbcTest]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1011)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:957)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at org.springdemo.DrawingApp.main(DrawingApp.java:21)
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springdemo.jdbc.JdbcTest]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:162)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1004)
... 13 more
Caused by: java.lang.NullPointerException
at org.springdemo.jdbc.JdbcTest.<init>(JdbcTest.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
... 15 more
You cannot access dataSource in the constructor. Spring first instantiates the bean (using the default constructor in your case) and then wires the properties.
There are a number of ways to deal with that.
Constructor injection
<bean id="jdbcTest" class="org.springdemo.jdbc.JdbcTest">
<constructor-arg ref="dataSource"/>
</bean>
And class
public class JdbcTest {
private DataSource dataSource;
public JdbcTest(DataSource dataSource) throws SQLException {
this.dataSource = dataSource;
conn = dataSource.getConnection();
stmt = conn.createStatement();
}
}
InitializingBean
public class JdbcTest implements InitializingBean {
private DataSource dataSource;
// setter for dataSource
public void afterPropertiesSet() {
// run the actual test
onn = dataSource.getConnection();
stmt = conn.createStatement();
}
}
Init method
<bean id="jdbcTest" class="org.springdemo.jdbc.JdbcTest" init-method="runTest">
<property name="dataSource" ref="dataSource"/>
</bean>
And class
public class JdbcTest {
private DataSource dataSource;
// setter for dataSource
public void runTest() {
// run the actual test
}
}
When using the DataSource injected by Spring the DataSource is not available until after the constructor is invoked. Essentially Spring, due to your configuration, is doing the following:
JdbcTest jdbcTest = new JdbcTest(); // NPE
jdbcTest.setDataSource(dataSource);
What you probably want to do is something like this:
JdbcTest jdbcTest = new JdbcTest(dataSource);
To do that update your configuration to look like:
<bean id="jdbcTest" class="org.springdemo.jdbc.JdbcTest">
<constructor-arg ref="dataSource"/>
</bean>
And your JdbcTest class to look like:
public class JdbcTest {
private DataSource dataSource;
pubic JdbcTest(DataSource dataSource) throws SQLException {
this.dataSource = dataSource;
conn = dataSource.getConnection();
stmt = conn.createStatement();
}
}

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