Spring Batch: not able to access jobexecutionConext in flatfileitemwriter - java

hey i am trying to use the jobexecutioncontxt in my flatfileitemwriter and it shows me errors...
My xml is:-
<batch:job id="subrogationJob" incrementer="incrementer">
<batch:step id="subrogation" next="readFromDataBase">
<batch:tasklet ref="filetransferTasklet">
<batch:listeners>
<batch:listener ref="setCurrentFile" />
</batch:listeners>
</batch:tasklet>
</batch:step>
<batch:step id="readFromDataBase" next="hasMoreFilesStep">
<batch:tasklet>
<batch:chunk reader="databaseReader" processor="subrogationProcessor" writer="dbToFileItemWriter"
commit-interval="1" />
</batch:tasklet>
</batch:step>
<batch:decision id="hasMoreFilesStep" decider="hasMoreFilesDecider">
<batch:fail on="FAILED" />
<batch:next on="CONTINUE" to="subrogation" />
<batch:end on="COMPLETED"/>
</batch:decision>
</batch:job>
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations"
value="file:${UNIQUE_DIR}/${APP_NAME}/batch/nonadj_batch.properties" />
</bean>
<bean id="incrementer"
class="org.springframework.batch.core.launch.support.RunIdIncrementer" />
<bean id="setCurrentFile"
class="com.hcsc.ccsp.nonadj.subrogation.batch.SubrogationInputFolderScanner"
scope="step">
<property name="collectionParameter" value="inputFiles" />
<property name="outputFolder" value="${subrogationOutputFolder}" />
<property name="inputFolder" value="${subrogationInputFolder}" />
<property name="archiveFolder" value="${subrogationArchiveFolder}" />
</bean>
<bean id="filetransferTasklet"
class="com.hcsc.ccsp.nonadj.subrogation.integration.SubrogationFileTransferTasklet"
scope="step">
<property name="inputfile" value="file:#{jobExecutionContext['inputFile']}" />
<property name="outputfile" value="file:#{jobExecutionContext['outputFile']}" />
</bean>
<bean id="subrogationProcessor" class="com.hcsc.ccsp.nonadj.subrogation.processor.SubrogationProcessor" scope="step">
</bean>
<bean id="dbToFileItemWriter" class="org.springframework.batch.item.file.FlatFileItemWriter" scope="step">
<property name="resource" value="file:#{jobExecutionContext['outputFile']}" />
<property name="lineAggregator">
<bean class="com.hcsc.ccsp.nonadj.subrogation.writer.SubrogationLineAggregator"/>
</property>
<property name="footerCallback" ref="subroHeaderFooterWriter" />
<property name="headerCallback" ref="subroHeaderFooterWriter" />
<property name="transactional" value="true" />
<property name="appendAllowed" value="true" />
<property name="saveState" value="true" />
</bean>
<bean id="subroHeaderFooterWriter" class="com.hcsc.ccsp.nonadj.subrogation.writer.SubrogationHeaderFooterWriter" scope="step">
<property name="delegate" ref="dbToFileItemWriter" />
</bean>
<bean id="hasMoreFilesDecider"
class="com.hcsc.ccsp.nonadj.subrogation.batch.CollectionEmptyDecider" scope="step">
<property name="collectionParameter" value="inputFiles" />
<property name="outputfile" value="file:#{jobExecutionContext['outputFile']}" />
<property name="archiveFolder" value="file:${subrogationArchiveFolder}" />
</bean>
<context:component-scan base-package="com.hcsc.ccsp.nonadj.subrogation.batch"
use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Component" />
</context:component-scan>
<context:annotation-config />
<bean id="databaseReader"
class="org.springframework.batch.item.database.JdbcCursorItemReader"
scope="step">
<property name="dataSource" ref="subrogrationDataSource" />
<property name="sql"
value="SELECT QUERY" />
<property name="rowMapper">
<bean
class="com.hcsc.ccsp.nonadj.subrogation.integration.SubrogationFieldSetMapper" />
</property>
</bean>
in my listner in beforestep i put parameter in jobcontextn as
ExecutionContext jobContext = stepExecution.getJobExecution().getExecutionContext();
jobContext.put("outputFile", filePath);
and in xml when i m trying to use this in xml in my writer is shows me error.....
but it works fine filetransferTasklet.
error is :-
O inside reader
[5/1/14 10:41:02:303 CDT] 0000001a SystemOut O inside processor........
[5/1/14 10:41:02:303 CDT] 0000001a SystemOut O inside aggregator
[5/1/14 10:41:02:320 CDT] 0000001a AbstractStep E org.springframework.batch.core.step.AbstractStep execute Exception while closing step execution resources
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.subroHeaderFooterWriter' defined in class path resource [subrogation.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type '$Proxy46 implementing org.springframework.batch.item.file.ResourceAwareItemWriterItemStream,org.springframework.beans.factory.InitializingBean,java.io.Serializable,org.springframework.aop.scope.ScopedObject,org.springframework.aop.framework.AopInfrastructureBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised' to required type 'org.springframework.batch.item.file.FlatFileItemWriter' for property 'delegate'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [$Proxy46 implementing org.springframework.batch.item.file.ResourceAwareItemWriterItemStream,org.springframework.beans.factory.InitializingBean,java.io.Serializable,org.springframework.aop.scope.ScopedObject,org.springframework.aop.framework.AopInfrastructureBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised] to required type [org.springframework.batch.item.file.FlatFileItemWriter] for property 'delegate': no matching editors or conversion strategy found
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:329)
at org.springframework.batch.core.scope.StepScope.get(StepScope.java:150)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:325)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:33)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:182)
at $Proxy47.writeFooter(Unknown Source)
at org.springframework.batch.item.file.FlatFileItemWriter.close(FlatFileItemWriter.java:282)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:600)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:131)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy46.close(Unknown Source)
at org.springframework.batch.item.support.CompositeItemStream.close(CompositeItemStream.java:83)
at org.springframework.batch.core.step.tasklet.TaskletStep.close(TaskletStep.java:297)
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:264)
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:135)
at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:61)
at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:60)
at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:144)
at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:124)
at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:135)
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:293)
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:120)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:48)
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:114)
at com.hcsc.ccsp.nonadj.batch.web.JobLauncherController.launch(JobLauncherController.java:64)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:600)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:718)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1661)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:937)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:500)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3826)
at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:276)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:931)
at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1583)
at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:186)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:455)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewInformation(HttpInboundLink.java:384)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:272)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1550)
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type '$Proxy46 implementing org.springframework.batch.item.file.ResourceAwareItemWriterItemStream,org.springframework.beans.factory.InitializingBean,java.io.Serializable,org.springframework.aop.scope.ScopedObject,org.springframework.aop.framework.AopInfrastructureBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised' to required type 'org.springframework.batch.item.file.FlatFileItemWriter' for property 'delegate'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [$Proxy46 implementing org.springframework.batch.item.file.ResourceAwareItemWriterItemStream,org.springframework.beans.factory.InitializingBean,java.io.Serializable,org.springframework.aop.scope.ScopedObject,org.springframework.aop.framework.AopInfrastructureBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised] to required type [org.springframework.batch.item.file.FlatFileItemWriter] for property 'delegate': no matching editors or conversion strategy found
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:462)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:499)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:493)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1371)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1330)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
... 70 more
Caused by: java.lang.IllegalStateException: Cannot convert value of type [$Proxy46 implementing org.springframework.batch.item.file.ResourceAwareItemWriterItemStream,org.springframework.beans.factory.InitializingBean,java.io.Serializable,org.springframework.aop.scope.ScopedObject,org.springframework.aop.framework.AopInfrastructureBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised] to required type [org.springframework.batch.item.file.FlatFileItemWriter] for property 'delegate': no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:231)
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:447)
... 76 more
[5/1/14 10:41:02:386 CDT] 0000001a AbstractJob E org.springframework.batch.core.job.AbstractJob execute Encountered fatal error executing job
org.springframework.batch.core.JobExecutionException: Flow execution ended unexpectedly
at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:141)
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:293)
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:120)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:48)
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:114)
at com.hcsc.ccsp.nonadj.batch.web.JobLauncherController.launch(JobLauncherController.java:64)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:600)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:718)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1661)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:937)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:500)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3826)
at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:276)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:931)
at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1583)
at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:186)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:455)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewInformation(HttpInboundLink.java:384)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:272)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1550)
Caused by: org.springframework.batch.core.job.flow.FlowExecutionException: Ended flow=subrogationJob at state=subrogationJob.hasMoreFilesStep with exception
at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:152)
at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:124)
at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:135)
... 40 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.hasMoreFilesDecider': Scope 'step' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No context holder available for step scope
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:339)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:33)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:182)
at $Proxy45.decide(Unknown Source)
at org.springframework.batch.core.job.flow.support.state.DecisionState.handle(DecisionState.java:43)
at org.springframework.batch.core.configuration.xml.SimpleFlowFactoryBean$DelegateState.handle(SimpleFlowFactoryBean.java:141)
at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:144)
... 42 more
Caused by: java.lang.IllegalStateException: No context holder available for step scope
at org.springframework.batch.core.scope.StepScope.getContext(StepScope.java:197)
at org.springframework.batch.core.scope.StepScope.get(StepScope.java:139)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:325)
... 49 more
[5/1/14 10:41:02:392 CDT] 0000001a SimpleJobLaun I org.springframework.batch.core.launch.support.SimpleJobLauncher$1 run Job: [FlowJob: [name=subrogationJob]] completed with the following parameters: [{param47=47}] and the following status: [FAILED]
SubrogationHeaderFooterWriter is
package com.hcsc.ccsp.nonadj.subrogation.writer;
import java.io.IOException;
import java.io.Writer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.batch.item.file.FlatFileFooterCallback;
import org.springframework.batch.item.file.FlatFileHeaderCallback;
import org.springframework.batch.item.file.FlatFileItemWriter;
import com.hcsc.ccsp.nonadj.subrogation.batch.Subrogation;
import com.hcsc.ccsp.nonadj.subrogation.integration.SubrogationFileTransferTasklet;
import com.hcsc.ccsp.nonadj.subrogation.processor.SubrogationProcessor;
public class SubrogationHeaderFooterWriter implements
FlatFileFooterCallback, FlatFileHeaderCallback{
SubrogationFileTransferTasklet fileTransferTasklet = new SubrogationFileTransferTasklet();
private FlatFileItemWriter<Subrogation> delegate;
public void setDelegate(FlatFileItemWriter<Subrogation> delegate) {
this.delegate = delegate;
}
public FlatFileItemWriter<Subrogation> getDelegate() {
return delegate;
}
/*#Override
public void open(ExecutionContext executionContext)
throws ItemStreamException {
this.delegate.open(executionContext);
}
#Override
public void update(ExecutionContext executionContext)
throws ItemStreamException {
this.delegate.update(executionContext);
}
#Override
public void close() throws ItemStreamException {
this.delegate.close();
}*/
#Override
public void writeHeader(Writer writer) throws IOException {
// TODO Auto-generated method stub
System.out.println("inside header");
writer.write(SubrogationFileTransferTasklet.header);
}
#Override
public void writeFooter(Writer writer) throws IOException {
// TODO Auto-generated method stub
System.out.println("inside header");
String trailer = SubrogationFileTransferTasklet.trailer;
String s1 = StringUtils.substring(trailer, 0, 23);
System.out.println("trailer without contwer is" + s1);
System.out.println("whole traileer is" + s1
+ SubrogationProcessor.totalRecords);
System.out
.println("duplicate data is" + SubrogationProcessor.duplicate);
writer.write(s1 + SubrogationProcessor.totalRecords);
System.out.println("inside Footer");
writer.write("Total Number of Records :: \n\n");
}
/*public void write(List<? extends Subrogation> subrogation) throws Exception {
System.out.println("inside writer");
delegate.write(subrogation);
}*/
}
pls help....

You have two exceptions here. The first one is due to the fact that the type for com.hcsc.ccsp.nonadj.subrogation.writer.SubrogationHeaderFooterWriter.delegate does not match the FlatFileItemWriter. What type is that defined as (if you can update your post with the code for this class, it would be helpful)?
The second one is because you are attempting to use a decider that is step scoped. In a regular Spring Batch job (not a JSR-352 based job), a decider is not a step. Because of that, it doesn't get a StepExecution, and therefore step scope is not supported.
Update
Change your setter for the delegate to take ItemWriter (the interface) instead of FlatFileItemWriter (the implementation) to address the first issue.

Related

Spring integration service-activator isn't working

My program sends a json string message to a queue, transforms the message to a json object, then calls the service activator. The service activator is taking the json object as an argument, and checking whether the "employer" property is in a hashtable, and then adds the property "count" to the json object: count is set to 1 if property is in the table and to -1 if it isn't.
Then, the updated json object is transformed back into a string and sent on to another queue.
However, the service-activator isn't working. I get this error (full stack-trace is under the attached code):
java.lang.NoSuchMethodError: org.springframework.messaging.MessageHandlingException:
method <init>(Lorg/springframework/messaging/Message;Ljava/lang/Throwable;)V not found
But the method clearly exists. Why is it asking me to put Throwable in my argument? I tried doing that and then got this error (full stack-trace is under attached code):
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.integration.config.ConsumerEndpointFactoryBean#2': Cannot resolve reference to bean 'org.springframework.integration.config.ServiceActivatorFactoryBean#0' while setting bean property 'handler'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.integration.config.ServiceActivatorFactoryBean#0': FactoryBean threw exception on object creation;
nested exception is java.lang.IllegalArgumentException: Target object of type [class SpringMessaging.MessageImprover] has no eligible methods for handling Messages.
I'm using a class called MessageCreator to create the original json string message, and then a class called MessageImprover to update it.
Code:
package SpringMessaging;
public class MessageCreator {
public String messageJson;
public String employer;
public int sourceID;
public void add(String name, int age) {
messageJson = "{" +
"\"employer\": \"" + name + "\"" +
", \"sourceID\": " + age +
'}';
}
public String getJson(){
return messageJson;
}
}
Message Improver:
package SpringMessaging;
import java.util.HashMap;
import org.json.JSONObject;
public class MessageImprover {
public JSONObject improve(JSONObject object) {
int count;
HashMap<String, Integer> table = new HashMap<String, Integer>();
table.put("Icelantic", 8);
table.put("Nordica", 9);
table.put("Atomic", 10);
table.put("Volkl", 11);
table.put("Marker", 12);
if(table.containsKey(object.getString("employer"))) {
count = 1;
} else {
count = -1;
}
object.put("count", count);
return object;
}
}
String to json object transformer:
import org.json.JSONObject;
public class stringtoJsonObject {
public JSONObject jsonFromString(String messageJson) {
JSONObject object = new JSONObject(messageJson);
return object;
}
}
Config:
Send:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-amqp="http://www.springframework.org/schema/integration/amqp"
xmlns:rabbit="http://www.springframework.org/schema/rabbit" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/amqp
http://www.springframework.org/schema/integration/amqp/spring-integration-amqp.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
<rabbit:connection-factory id="connectionFactory" host="bigdata-rdp" username="myuser" password="mypass" />
<rabbit:template id="amqpTemplate" connection-factory="connectionFactory" />
<rabbit:admin connection-factory="connectionFactory" />
<rabbit:queue name="first" auto-delete="false" durable="true" />
<rabbit:queue name="second" auto-delete="false" durable="true" />
<rabbit:fanout-exchange name="first-exchange" auto-delete="true" durable="true">
<rabbit:bindings>
<rabbit:binding queue="first" />
</rabbit:bindings>
</rabbit:fanout-exchange>
<int:channel id="senderChannel">
</int:channel>
<int-amqp:outbound-channel-adapter channel="senderChannel" exchange-name="first-exchange" amqp-template="amqpTemplate" />
<int-amqp:outbound-gateway id="outbound" request-channel="senderChannel" exchange-name="first-exchange" amqp-template="amqpTemplate" />
<int:gateway id="Sender" service-interface="SpringMessaging.Sender" default-request-channel="senderChannel">
<int:method name="sendMessage" />
</int:gateway>
<int:poller default="true" fixed-rate="100"/>
</beans>
Receiving from first queue, transforming, updating and sending to second queue:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-amqp="http://www.springframework.org/schema/integration/amqp"
xmlns:rabbit="http://www.springframework.org/schema/rabbit" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/amqp
http://www.springframework.org/schema/integration/amqp/spring-integration-amqp.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
<rabbit:connection-factory id="connectionFactory" host="bigdata-rdp" username="myuser" password="mypass" />
<rabbit:template id="amqpTemplate" connection-factory="connectionFactory" />
<rabbit:admin connection-factory="connectionFactory" />
<rabbit:queue name="first" auto-delete="false" durable="true" />
<rabbit:queue name="second" auto-delete="false" durable="true" />
<int:poller default="true" fixed-rate="100"/>
<rabbit:fanout-exchange name="second-exchange" auto-delete="true" durable="true">
<rabbit:bindings>
<rabbit:binding queue="second" />
</rabbit:bindings>
</rabbit:fanout-exchange>
<int-amqp:outbound-channel-adapter channel="messageOutputChannel" exchange-name="second-exchange" amqp-template="amqpTemplate" />
<int-amqp:inbound-channel-adapter channel="messageInputChannel" queue-names="first" connection-factory="connectionFactory" />
<int:channel id="messageInputChannel" />
<int:channel id="jsonInputChannel"/>
<int:channel id="jsonOutputChannel"/>
<int:channel id="messageOutputChannel"/>
<int:transformer input-channel="messageInputChannel" output-channel="jsonInputChannel" ref="messageToJsonObjectConverter" method="jsonFromString" />
<bean id="messageToJsonObjectConverter" class="SpringMessaging.stringtoJsonObject" />
<int:service-activator input-channel="jsonInputChannel" output-channel="jsonOutputChannel" ref="jsonObjectTransformer" method="improve" />
<bean id="jsonObjectTransformer" class="SpringMessaging.MessageImprover" />
<int:object-to-string-transformer input-channel="jsonOutputChannel" output-channel="messageOutputChannel" />
</beans>
Full stack-trace from first error:
java.lang.NoSuchMethodError:
org.springframework.messaging.MessageHandlingException: method <init>(Lorg/springframework/messaging/Message;Ljava/lang/Throwable;)V not found
at org.springframework.integration.handler.MethodInvokingMessageProcessor.processMessage(MethodInvokingMessageProcessor.java:96)
at org.springframework.integration.handler.ServiceActivatingHandler.handleRequestMessage(ServiceActivatingHandler.java:89)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:109)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:116)
at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:148)
at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:121)
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:89)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:423)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:373)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:114)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:44)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:92)
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutput(AbstractMessageProducingHandler.java:358)
at org.springframework.integration.handler.AbstractMessageProducingHandler.produceOutput(AbstractMessageProducingHandler.java:269)
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutputs(AbstractMessageProducingHandler.java:186)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:115)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:116)
at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:148)
at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:121)
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:89)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:423)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:373)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:114)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:44)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:92)
at org.springframework.integration.endpoint.MessageProducerSupport.sendMessage(MessageProducerSupport.java:188)
at org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter.access$1100(AmqpInboundChannelAdapter.java:56)
at org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter$Listener.processMessage(AmqpInboundChannelAdapter.java:246)
at org.springframework.integration.amqp.inbound.AmqpInboundChannelAdapter$Listener.onMessage(AmqpInboundChannelAdapter.java:203)
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:822)
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:745)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$001(SimpleMessageListenerContainer.java:97)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$1.invokeListener(SimpleMessageListenerContainer.java:189)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.invokeListener(SimpleMessageListenerContainer.java:1276)
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:726)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doReceiveAndExecute(SimpleMessageListenerContainer.java:1219)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.receiveAndExecute(SimpleMessageListenerContainer.java:1189)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$1500(SimpleMessageListenerContainer.java:97)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1421)
at java.lang.Thread.run(Thread.java:748)
org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer run
SEVERE: Stopping container from aborted consumer
org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer doShutdown
INFO: Waiting for workers to finish.
org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer doShutdown
INFO: Successfully waited for workers to finish.
Full stack-trace if I put Throwable V in the argument of "improve":
Exception in thread "main"
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.integration.config.ConsumerEndpointFactoryBean#2': Cannot resolve reference to bean 'org.springframework.integration.config.ServiceActivatorFactoryBean#0' while setting bean property 'handler'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.integration.config.ServiceActivatorFactoryBean#0': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: Target object of type [class SpringMessaging.MessageImprover] has no eligible methods for handling Messages.
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1531)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1276)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:742)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at SpringMessaging.Main.main(Main.java:15)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'org.springframework.integration.config.ServiceActivatorFactoryBean#0': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: Target object of type [class SpringMessaging.MessageImprover] has no eligible methods for handling Messages.
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:175)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:103)
at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1634)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:254)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
... 15 more
I don't understand why it's even asking me to put a Throwable as an argument in the "improve" method. Any ideas?
java.lang.NoSuchMethodError:
org.springframework.messaging.MessageHandlingException: method <init>(Lorg/springframework/messaging/Message;Ljava/lang/Throwable;)V not found
There should be some cause below that StackTrace. In other words you don't show the whole picture.
The second case is clear. You have signature like:
JSONObject improve(JSONObject object, Throwable e)
Where Framework can't understand which method parameter treat for the payload in the future messages.
I'm pretty sure that NoSuchMethodError isn't related to the service-activator definition. There is something else downstream.

How can I read multiple xml files from two different folders in Spring Batch?

I have multiple files to read and write from two different directories with same parent path.
Is it possible to select particular directory in "org.springframework.batch.item.file.MultiResourceItemReader" if one of the directory has no files to read?
<!-- multi xml reader -->
<bean id="multiResourceReader" class="org.springframework.batch.item.file.MultiResourceItemReader">
<property name="resources" ref="vinFeedFileResouce" />
<property name="delegate" ref="vinFeedReader" />
</bean>
<bean id="vinFeedFileResouce" class="org.springframework.core.io.FileSystemResource" scope="step">
<constructor-arg>
<list>
<ref bean="read_ONE" />
<ref bean="read_TWO" />
</list>
</constructor-arg>
</bean>
<bean id="read_ONE" class="org.springframework.core.io.FileSystemResource" scope="step">
<constructor-arg value="#{path_ONE}"></constructor-arg>
</bean>
<bean id="read_TWO" class="org.springframework.core.io.FileSystemResource" scope="step">
<constructor-arg value="#{path_TWO}"></constructor-arg>
</bean>
I am getting following error for reader:
[pool-1-thread-1](batch.listener.ModelMasterFailureListener:13)-Encountered error on Model master read
org.springframework.batch.item.ItemStreamException: Failed to initialize the reader
at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.open(AbstractItemCountingItemStreamItemReader.java:137)
at org.springframework.batch.item.file.MultiResourceItemReader.read(MultiResourceItemReader.java:105)
at org.springframework.batch.core.step.item.SimpleChunkProvider.doRead(SimpleChunkProvider.java:90)
at org.springframework.batch.core.step.item.FaultTolerantChunkProvider.read(FaultTolerantChunkProvider.java:87)
at org.springframework.batch.core.step.item.SimpleChunkProvider$1.doInIteration(SimpleChunkProvider.java:108)
at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:367)
at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:214)
at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:143)
at org.springframework.batch.core.step.item.SimpleChunkProvider.provide(SimpleChunkProvider.java:103)
at org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:68)
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:386)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:130)
at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:264)
at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:76)
at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:367)
at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:214)
at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:143)
at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:250)
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:195)
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:135)
at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:61)
at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:60)
at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:144)
at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:124)
at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:135)
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:281)
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:120)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:48)
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:114)
at com.ahm.ngt.cbo.feed.batch.scheduler.RunScheduler.run(RunScheduler.java:80)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.util.MethodInvoker.invoke(MethodInvoker.java:273)
at org.springframework.scheduling.support.MethodInvokingRunnable.run(MethodInvokingRunnable.java:65)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:51)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:206)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:662)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'scopedTarget.vinFeedFileResouce' defined in class path resource [spring/batch/jobs/ca-vin-feed-config.xml]: Unsatisfied dependency expressed through constructor argument with index 0 of type [java.io.File]: Could not convert constructor argument value of type [java.util.ArrayList] to required type [java.io.File]: Failed to convert value of type 'java.util.ArrayList' to required type 'java.io.File'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [java.util.ArrayList] to required type [java.io.File]: PropertyEditor [org.springframework.beans.propertyeditors.FileEditor] returned inappropriate value
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:702)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:196)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:907)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:329)
at org.springframework.batch.core.scope.StepScope.get(StepScope.java:150)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:325)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:33)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:184)
at com.sun.proxy.$Proxy1.exists(Unknown Source)
at org.springframework.batch.item.xml.StaxEventItemReader.doOpen(StaxEventItemReader.java:187)
at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.open(AbstractItemCountingItemStreamItemReader.java:134)
... 45 more
If you see the source code of FileSystemResource, you would find the constructor can take either File or String not list of files or String. You can write custom Resource Reader to read the files from multiple directory. Here is an example
<bean id="multiResourceReader" class="org.springframework.batch.item.file.MultiResourceItemReader">
<property name="resources" value="#{myResourceReader.read()}" />
<property name="delegate" ref="vinFeedReader" />
</bean>
<bean id="myResourceReader" class="com.kp.swasthik.MyResourceReader">
<property name="resource" value="file:///path1/*.txt, file:///path2/*.txt"></property>
</bean>
The ResourceReader class.
public class MyResourceReader {
private String resource;
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
public Resource[] read(){
List<Resource> resources = new ArrayList<>();
if(resource == null || resource.isEmpty()){
return new Resource[]{};
}
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Arrays.stream(resource.split(",")).forEach(v->{
try {
Collections.addAll(resources, resolver.getResources(v));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
return resources.toArray(new Resource[0]);
}
}
Switch to annotation based configuration. There you could add all your resources (from different dirs) to the reader:
#Bean
public ItemReader<?> reader() {
Resource[] res = ... //get eg using PathMatchingResourcePatternResolver multiple times on different dirs
MultiResourceItemReader<?> r = new MultiResourceItemReader<>();
r.setResources(res);
return r;
}

redis.clients.jedis.exceptions.JedisException: Could not get a resource from the pool

redis.properties
#jedisPoolConfig
redis.minIdle=100
redis.maxIdle=500
redis.maxTotal=50000
redis.maxWaitMillis=10000
redis.testOnBorrow=true
#jedisPool
redis.host=192.168.13.169
redis.port=6379
redis.timeout=3000
redis.port2=6380
#redis-sentinel
redis.sentinel=192.168.13.169:26379
redis.master=mymaster
spring-redis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--properties配置-->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:redis.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
<!-- 连接池配置信息 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxTotal" value="${redis.maxTotal}" />
<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<!--初级版:单实例-->
<bean id="jedisPool" class="redis.clients.jedis.JedisPool" scope="singleton">
<constructor-arg name="poolConfig" ref="jedisPoolConfig" />
<constructor-arg name="host" value="${redis.host}" />
<constructor-arg name="port" value="${redis.port}" type="int" />
</bean>
<!--主从-->
<bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool">
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1">
<list>
<bean class="redis.clients.jedis.JedisShardInfo">
<constructor-arg name="host" value="${redis.host}" />
<constructor-arg name="port" value="${redis.port}" />
<constructor-arg name="timeout" value="${redis.timeout}" />
<constructor-arg name="name" value="master" />
</bean>
<bean class="redis.clients.jedis.JedisShardInfo">
<constructor-arg name="host" value="${redis.host}" />
<constructor-arg name="port" value="${redis.port2}" />
<constructor-arg name="timeout" value="${redis.timeout}" />
<constructor-arg name="name" value="slave1" />
</bean>
</list>
</constructor-arg>
</bean>
<!--sentinel模式-->
<bean id="redisSentinelConfiguration" class="org.springframework.data.redis.connection.RedisSentinelConfiguration">
<constructor-arg name="master" value="${redis.master}" />
<constructor-arg name="sentinelHostAndPorts">
<set>
<value>${redis.sentinel}</value>
</set>
</constructor-arg>
</bean>
<!--Jedis连接池-->
<bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:use-pool="true">
<property name="hostName" value="${redis.host}"/>
<constructor-arg ref="redisSentinelConfiguration" />
<constructor-arg ref="jedisPoolConfig" />
</bean>
<!-- redis template definition -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate" p:connection-factory-ref="jedisConnFactory"/>
<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
Code
Controller
#Controller
public class JedisController {
......
#Autowired
private RedisService redisService;
#RequestMapping(value = "test2")
#ResponseBody
public String test2(){
redisService.set("key2","v2");
return redisService.get("key1");
}
......
}
Service
#Service
public class RedisService extends BinaryRedisService {
public RedisService() {}
public String set(final String key, final String value) {
return (String)this.execute(new Function<ShardedJedis, String>() {
public String callBack(ShardedJedis shardedJedis) {
return shardedJedis.set(key, value);
}
});
}
......
}
public class BinaryRedisService {
#Autowired
protected ShardedJedisPool shardedJedisPool;
public BinaryRedisService() {
}
protected <T> T execute(Function<ShardedJedis, T> fun) {
ShardedJedis shardedJedis = null;
T t = null;
try {
shardedJedis = this.shardedJedisPool.getResource();
t = fun.callBack(shardedJedis);
} catch (Exception var8) {
var8.printStackTrace();
} finally {
if(null != shardedJedis) {
shardedJedis.close();
}
return t;
}
}
......
}
Problem
redis.clients.jedis.exceptions.JedisException: Could not get a
resource from the pool at
redis.clients.util.Pool.getResource(Pool.java:51) at
redis.clients.jedis.ShardedJedisPool.getResource(ShardedJedisPool.java:36)
at
org.henry.service.BinaryRedisService.execute(BinaryRedisService.java:29)
at org.henry.service.RedisService.set(RedisService.java:25) at
org.henry.service.RedisService$$FastClassBySpringCGLIB$$f57afd3.invoke()
at
org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at
org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:721)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
at
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at
org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656)
at
org.henry.service.RedisService$$EnhancerBySpringCGLIB$$d4e52321.set()
at
org.henry.controller.JedisController.test2(JedisController.java:51)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) at
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at
org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:837)
at
org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:583)
at
org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at
org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
at
org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
at
org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1180)
at
org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511)
at
org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
at
org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112)
at
org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at
org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:213)
at
org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:119)
at
org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
at org.eclipse.jetty.server.Server.handle(Server.java:524) at
org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:319) at
org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:253)
at
org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
at
org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)
at
org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303)
at
org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148)
at
org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136)
at
org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
at
org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
at java.lang.Thread.run(Thread.java:745) Caused by:
java.util.NoSuchElementException: Unable to validate object at
org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:506)
at
org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:363)
at redis.clients.util.Pool.getResource(Pool.java:49) ... 58 more
You need to make sure that a) Redis is running b) that it is able to accept connections from remote hosts and c) if you have enabled password protection, provide a password in your code.
To make sure that it can accept connections from remote hosts you have to look at the redis.conf file. Find the line with the binding addresses (it should look something like: bind 127.0.0.1) and either comment it out (so it can accept requests from all remote hosts - not recommended for production, but it's OK for testing), or add the remote IPs you want your Redis service to accept connections from.

org.springframework.beans.factory.BeanCreationException in spring mvc project

1.I am very new in spring and this question has been asked many times but still i am not able to figure out the wrong things.And getting these exceptions.
This is my console output
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sidSearchController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.jlcindia.spring.mvc.SidValidator com.jlcindia.spring.mvc.SidSearchController.sidValidator; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.web.servlet.handeler.SimpleMappingExceptionResolver] for bean with name 'org.springframework.web.servlet.handeler.SimpleMappingExceptionResolver#0' defined in ServletContext resource [/WEB-INF/jlcindia-servlet.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.web.servlet.handeler.SimpleMappingExceptionResolver
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1055)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:511)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:562)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:443)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:459)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:340)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:307)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
javax.servlet.GenericServlet.init(GenericServlet.java:212)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
java.lang.Thread.run(Thread.java:619)
Controller class
#Controller
public class SidSearchController
{
#Autowired
private SidValidator sidValidator;
#RequestMapping(value="/searchStudent",method=RequestMethod.POST)
#ExceptionHandler({StudentNotFoundException.class})
public String searchStudent(#ModelAttribute("sidSearchCommand")SidSearchCommand sidCommand,Errors errors,HttpServletRequest req,Model model){
System.out.println("contact controller");
sidValidator.validate(sidCommand, errors);
if(errors.hasErrors()){
return "sidsearch";
}
String sid=sidCommand.getSid();
String results="";
if(sid.equals("sim-123")||sid.equals("sim-999")) {
StudentTO sto=new StudentTO();
sto.setSid(sid);
sto.setBid("B-99");
sto.setSname("srinivas");
sto.setPhone("99999");
model.addAttribute("STO", sto);
req.setAttribute("STO",sto);
results="sidresults";
}
else
{
req.setAttribute("sidSearchCommand",sidCommand);
throw new StudentNotFoundException(sid);
}return results;
}#RequestMapping(value="/sidsearch")
protected String showSearchPage(Map model) throws ServletException{
System.out.println("show search page");
SidSearchCommand sidCommand=new SidSearchCommand();
model.put("sidSearchCommand", sidCommand);
return "sidsearch";
}
}
3.mvc-dispatcher-servlet.xml:
<context:component-scan base-package="com.jlcindia.spring.mvc" />
<bean id="sidValidator" class="com.jlcindia.spring.mvc.SidValidator"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView"/>
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
<bean class="org.springframework.web.servlet.handeler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.jlcindia.spring.mvc.StudentNotFoundException">sidsearch
</prop>
</props>
</property>
</bean>
</beans>
in your mvc-dispatcher-servlet.xml you misspelled the following: org.springframework.web.servlet.handeler.SimpleMappingExceptionResolver
handeler is written instead of handler

Concurrent testing with TestNG and Spring Transaction

I have a service class, the service class is annotated with #Transactional(propagation = Propagation.REQUIRES_NEW) and its public method is defined in an interface:
public interface UniqueKeyGeneratorService {
void initializeUniqueKeys(Entity entity);
}
#Transactional(propagation = Propagation.REQUIRES_NEW)
public final class KeyGeneratorServiceImpl implements UniqueKeyGeneratorService, DisposableBean {
private final UniqueKeyGeneratorStrategy strategy;
private KeyGeneratorServiceImpl(final UniqueKeyGeneratorStrategy strategy) {
this.strategy = strategy;
}
#Override
public void initializeUniqueKeys(final Entity entity) {
// ... the business logic
}
// ... some private methods
#Override
public void destroy() {
strategy.destroy();
}
}
And the bean is created using a FactoryBean (to initialize the strategy).
I want to test the service, so I configured an embedded H2 database, defined a connection pool using Apache Commons DBCP and write proper test code as:
#ContextConfiguration("/path/to/xml/config/file.xml")
#Transactional
public class TestUniqueKeyGeneratorService extends AbstractTransactionalTestNGSpringContextTests {
#Autowired
private UniqueKeyGeneratorService service;
#Test
#Rollback(false)
public void testCodeGeneration() {
final Department department1 = new Department();
department1.setName("Abcd");
service.initializeUniqueKeys(department1);
final String code = department1.getCode();
Assert.assertNotNull(code);
}
// ... some more test methods
}
and have
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:mem:db1"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven/>
<bean id="uniqueKeyGeneratorService"
class="com.mycompany.uniquekey.UniqueKeyGeneratorServiceFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
the test passes, but when I change the #Test annotation to #Test(invocationCount = 10, singleThreaded = false, threadPoolSize = 2) following exception occures:
org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is java.sql.SQLException: Connection is closed.
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:240) ~[org.springframework.jdbc-3.1.3.RELEASE.jar:3.1.3.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371) ~[org.springframework.transaction-3.1.3.RELEASE.jar:3.1.3.RELEASE]
at org.springframework.test.context.transaction.TransactionalTestExecutionListener$TransactionContext.startTransaction(TransactionalTestExecutionListener.java:514) ~[org.springframework.test-3.1.3.RELEASE.jar:3.1.3.RELEASE]
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.startNewTransaction(TransactionalTestExecutionListener.java:272) ~[org.springframework.test-3.1.3.RELEASE.jar:3.1.3.RELEASE]
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.beforeTestMethod(TransactionalTestExecutionListener.java:165) ~[org.springframework.test-3.1.3.RELEASE.jar:3.1.3.RELEASE]
at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:358) ~[org.springframework.test-3.1.3.RELEASE.jar:3.1.3.RELEASE]
at org.springframework.test.context.testng.AbstractTestNGSpringContextTests.springTestContextBeforeTestMethod(AbstractTestNGSpringContextTests.java:146) [org.springframework.test-3.1.3.RELEASE.jar:3.1.3.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.6.0_31]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.6.0_31]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.6.0_31]
at java.lang.reflect.Method.invoke(Method.java:597) ~[na:1.6.0_31]
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:564) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.Invoker.invokeMethod(Invoker.java:653) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.thread.ThreadUtil$2.call(ThreadUtil.java:64) [org.testng-6.8.jar:6.8-201210030754]
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) [na:1.6.0_31]
at java.util.concurrent.FutureTask.run(FutureTask.java:138) [na:1.6.0_31]
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [na:1.6.0_31]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [na:1.6.0_31]
at java.lang.Thread.run(Thread.java:662) [na:1.6.0_31]
Caused by: java.sql.SQLException: Connection is closed.
at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.checkOpen(PoolingDataSource.java:185) ~[org.apache.commons-dbcp-1.4.jar:1.4]
at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.getAutoCommit(PoolingDataSource.java:234) ~[org.apache.commons-dbcp-1.4.jar:1.4]
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:218) ~[org.springframework.jdbc-3.1.3.RELEASE.jar:3.1.3.RELEASE]
... 24 common frames omitted
any idea how to handle this exception?
p.s. I reviewed H2 documentations, and it supports multiple connections in embedded mode.
The answer is located in TestNG multithreaded test with Spring #Transactional

Categories