WRONG_DOCUMENT_ERR: A node is used in a different document - error appears only after added scheduller - spring

I created an application based on Spring Batch which basically has a custom itemreader for reading a folder searching for candidate files, a custom itemprocessor for reading the file and transforming it in diferente file and a custom itemwriter in order to delete the file. It works as expected with no errors untill I added a scheduller. After I added the scheduller, I get the error pasted in the question topic. I found some questions with similiar issue but very diferente context. The must strange point is that, in fact, even though I see such error on console, it is working. I mean, the folder is read (itemreader), the file is transformed (itemprocessor) and the input file is deleted (itemwriter).
I am very confused. If either I could reproduce the error without the scheduller, then I could focus on some node or I had not get the result after I introduced the scheduller so I could focus in some possible error in my scheduller configuration but both aren't the case. Any suggestion will be appreciatted.
The next paragraph was added on January 10th:
After depeer investigation, I found that such error happens only once and only with the main thread. I mean, if I have a candidate file when I start my application, then I get WRONG_DOCUMENT_ERR. Let's say, I start my application with no files available to be found by CustomItemReader, wait until the main thread finishes, then I place a candidate file to be found by CustomItemReader, there will be no error at all. In other words, when CustomItemReader is triggered by pool-2-thread-1 and find a file it works correctly. On other hands, when CustomItemReader is triggered by main thread and find a file, which happens only during application startup, it causes the issue.
By using JConsole, I can check that the main thread has gone and the pool-2-thread-1 is up and running. Then, I add my file in the input folder which causes CustomItemReader to return a String instead of null and there will be no errors. Certainly, I missing certain concept about using Spring Scheduller and Spring Batch together. Obviously, I want my application to raise no errors if I start it and it finds the file soon it initialize. Why does it only happen during main thread but if I took Spring Scheduller out it will work as expected one time? Am I missing some synchronization parameter?
The next paragraph was added on January 11th:
I updated only the class where the error happens with larger snippet. All the others remain the same.
#Component
public class Queue {
private Node queue;
#Autowired
private Environment env;
public Element myMethod(String file) {
//...
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document d = docBuilder.parse(env.getProperty("certainFile.xml"));
Element template = d.getDocumentElement();
queue = d.createElement("c:file");
((Element) queue).setAttribute("xmlns:c", "myApp");
queue.appendChild(queue.getOwnerDocument().importNode(template, true));
template = (Element) queue.getLastChild();
addField(template, "someFieldLabel");
}
private void addField(Element message, String field) {
// ....
Element newField = queue.getOwnerDocument().createElement(field);
for (int k = 0; k < certainList.getLength(); k++) {
if ("...certain logic") {
newField = (Element) queue.getOwnerDocument().importNode(fieldFormat, true);
if ("...other logic"){
newField.setAttribute("manual", "true");
}
newField.removeAttribute("indicator");
break;
}
}
for (int j = 0; j < fields.getLength(); j++) {
Element e = (Element) (fields.item(j));
if (e.getNodeName().equals(fieldType)) {
// some cascades "ifs"
// the error happens in next line but only in the main thread
message.insertBefore(newField, e);
// let's ignore the rest
}
}
}
//----
#Configuration
#ComponentScan("com.example")
#EnableBatchProcessing
#EnableAutoConfiguration
#EnableScheduling
#PropertySource(value="classpath:config.properties")
#PropertySource(value="classpath:ipm.properties",ignoreResourceNotFound=true)
public class BatchConfiguration {
#Autowired
private JobBuilderFactory jobBuilderFactory;
#Autowired
private StepBuilderFactory stepBuilderFactory;
#Bean
public Step step1(ItemReader<String> reader, ItemProcessor<String, String> processor, ItemWriter<String> writer) {
return stepBuilderFactory.get("step1").<String, String> chunk(1)
.reader(reader).processor(processor).writer(writer).allowStartIfComplete(true)
.build();
}
#Bean
public ItemProcessor<String , String> processor(){
return new CustomItemProcessor();
}
#Bean
public ItemWriter<String> writer() {
return new CustomItemWriter();
}
#Bean
public Job job(Step step1) throws Exception {
return jobBuilderFactory.get("job1")
.incrementer(new RunIdIncrementer()).start(step1).build();
}
#Bean
#StepScope
public ItemReader<String> reader() {
return new CustomItemReader();
}
}
//-----
public class CustomItemReader implements ItemReader<String> {
private static final Logger log = LoggerFactory
.getLogger(CustomItemReader.class);
#Autowired
private Environment env;
#Override
public String read() throws Exception, UnexpectedInputException,
ParseException, NonTransientResourceException {
String[] stringArray;
try (Stream<Path> stream = Files.list(Paths.get(env
.getProperty("myFile")))) {
stringArray = stream.map(String::valueOf)
.filter(path -> path.endsWith("out"))
.toArray(size -> new String[size]);
}
if (stringArray.length > 0) {
log.info("read method - file found");
return stringArray[0];
} else {
log.info("read method - no file found");
return null;
}
}
}
//----
public class CustomItemProcessor implements ItemProcessor<String , String> {
#Autowired
#Qualifier(value="queue")
private Queue q;
#Autowired
private Environment env;
#Override
public String process(String s) throws Exception {
q.myMethod();
return s;
}
}
//----
public class CustomItemWriter implements ItemWriter<String> {
#Override
public void write(List<? extends String> s) throws Exception {
Path path1 = Paths.get(s, “notImportantDetail”);
java.nio.file.Files.deleteIfExists(path1);
}
}
//----
#Component
public class QueueScheduler {
private static final Logger log = LoggerFactory
.getLogger(QueueScheduler.class);
private Job job;
private JobLauncher jobLauncher;
#Autowired
public QueueScheduler(JobLauncher jobLauncher, #Qualifier("job") Job job){
this.job = job;
this.jobLauncher = jobLauncher;
}
#Scheduled(fixedRate=60000)
public void runJob(){
try{
jobLauncher.run(job, new JobParameters());
}catch(Exception ex){
log.info(ex.getMessage());
}
}
}
//----
:: Spring Boot :: (v1.3.1.RELEASE)
2016-01-08 14:51:44.783 INFO 7716 --- [ main] com.example.DemoApplication : Starting DemoApplication on GH-VDIKCISV252 with PID 7716 (C:\STS\wsRestTemplate\demo\target\classes started by e049447 in C:\STS\wsRestTemplate\demo)
2016-01-08 14:51:44.788 INFO 7716 --- [ main] com.example.DemoApplication : No active profile set, falling back to default profiles: default
2016-01-08 14:51:44.955 INFO 7716 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#6e2c9341: startup date [Fri Jan 08 14:51:44 CST 2016]; root of context hierarchy
2016-01-08 14:51:50.882 WARN 7716 --- [ main] o.s.c.a.ConfigurationClassEnhancer : #Bean method ScopeConfiguration.stepScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as #Autowired, #Resource and #PostConstruct within the method's declaring #Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see #Bean javadoc for complete details.
2016-01-08 14:51:51.030 WARN 7716 --- [ main] o.s.c.a.ConfigurationClassEnhancer : #Bean method ScopeConfiguration.jobScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as #Autowired, #Resource and #PostConstruct within the method's declaring #Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see #Bean javadoc for complete details.
2016-01-08 14:51:51.386 INFO 7716 --- [ main] o.s.j.d.e.EmbeddedDatabaseFactory : Starting embedded database: url='jdbc:hsqldb:mem:testdb', username='sa'
2016-01-08 14:51:52.503 WARN 7716 --- [ main] o.s.b.c.l.AbstractListenerFactoryBean : org.springframework.batch.item.ItemReader is an interface. The implementing class will not be queried for annotation based listener configurations. If using #StepScope on a #Bean method, be sure to return the implementing class so listner annotations can be used.
2016-01-08 14:51:53.572 INFO 7716 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql]
2016-01-08 14:51:53.667 INFO 7716 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql] in 94 ms.
2016-01-08 14:51:54.506 INFO 7716 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-01-08 14:51:54.617 INFO 7716 --- [pool-2-thread-1] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: HSQL
2016-01-08 14:51:54.744 INFO 7716 --- [ main] o.s.b.a.b.JobLauncherCommandLineRunner : Running default command line with: []
2016-01-08 14:51:54.745 INFO 7716 --- [ main] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: HSQL
2016-01-08 14:51:54.912 INFO 7716 --- [pool-2-thread-1] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2016-01-08 14:51:54.961 INFO 7716 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2016-01-08 14:51:55.044 INFO 7716 --- [pool-2-thread-1] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job1]] launched with the following parameters: [{}]
2016-01-08 14:51:55.088 INFO 7716 --- [pool-2-thread-1] o.s.batch.core.job.SimpleStepHandler : Executing step: [step1]
2016-01-08 14:51:55.095 INFO 7716 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job1]] launched with the following parameters: [{run.id=1}]
2016-01-08 14:51:55.176 INFO 7716 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [step1]
2016-01-08 14:51:55.245 INFO 7716 --- [ main] com.example.CustomItemReader : read method - collecting the out file names
2016-01-08 14:51:55.314 INFO 7716 --- [pool-2-thread-1] com.example.CustomItemReader : read method - collecting the out file names
2016-01-08 14:51:55.440 INFO 7716 --- [pool-2-thread-1] com.example.CustomItemReader : read method - file found
2016-01-08 14:51:55.443 INFO 7716 --- [pool-2-thread-1] com.example.CustomItemProcessor : process method:
2016-01-08 14:51:55.461 INFO 7716 --- [ main] com.example.CustomItemReader : read method - file found
2016-01-08 14:51:55.462 INFO 7716 --- [ main] com.example.CustomItemProcessor : process method:
2016-01-08 14:51:57.088 ERROR 7716 --- [pool-2-thread-1] o.s.batch.core.step.AbstractStep : Encountered an error executing step step1 in job job1
org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it.
at com.sun.org.apache.xerces.internal.dom.ParentNode.internalInsertBefore(ParentNode.java:357) ~[na:1.8.0_45]
at com.sun.org.apache.xerces.internal.dom.ParentNode.insertBefore(ParentNode.java:288) ~[na:1.8.0_45]
at com.example.Queue.addField(Queue.java:1555) ~[classes/:na]
at com.example.Queue.addMessagesFromAuth(Queue.java:453) ~[classes/:na]
at com.example.CustomItemProcessor.process(CustomItemProcessor.java:45) ~[classes/:na]
at com.example.CustomItemProcessor.process(CustomItemProcessor.java:1) ~[classes/:na]
at org.springframework.batch.core.step.item.SimpleChunkProcessor.doProcess(SimpleChunkProcessor.java:126) ~[spring-batch-core-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at org.springframework.batch.core.step.item.SimpleChunkProcessor.transform(SimpleChunkProcessor.java:293) ~[spring-batch-core-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at org.springframework.batch.core.step.item.SimpleChunkProcessor.process(SimpleChunkProcessor.java:192) ~[spring-batch-core-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:75) ~[spring-batch-core-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:406) ~[spring-batch-core-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:330) ~[spring-batch-core-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133) ~[spring-tx-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:271) ~[spring-batch-core-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:81) ~[spring-batch-core-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:374) ~[spring-batch-infrastructure-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) ~[spring-batch-infrastructure-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144) ~[spring-batch-infrastructure-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:257) ~[spring-batch-core-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:200) ~[spring-batch-core-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148) [spring-batch-core-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at org.springframework.batch.core.job.AbstractJob.handleStep(AbstractJob.java:392) [spring-batch-core-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at org.springframework.batch.core.job.SimpleJob.doExecute(SimpleJob.java:135) [spring-batch-core-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:306) [spring-batch-core-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135) [spring-batch-core-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) [spring-core-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:128) [spring-batch-core-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_45]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_45]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302) [spring-aop-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) [spring-aop-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) [spring-aop-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127) [spring-batch-core-3.0.6.RELEASE.jar:3.0.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) [spring-aop-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208) [spring-aop-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at com.sun.proxy.$Proxy44.run(Unknown Source) [na:na]
at com.example.QueueScheduler.runJob(QueueScheduler.java:33) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_45]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_45]
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65) [spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) [spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_45]
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) [na:1.8.0_45]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) [na:1.8.0_45]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) [na:1.8.0_45]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_45]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_45]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_45]
2016-01-08 14:51:57.104 INFO 7716 --- [pool-2-thread-1] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job1]] completed with the following parameters: [{}] and the following status: [FAILED]
2016-01-08 14:51:57.754 INFO 7716 --- [ main] com.example.CustomItemWriter : write method: [C:\myApp\from\0000000571900000999674MHlog.txt.out]
2016-01-08 14:51:57.761 INFO 7716 --- [ main] com.example.CustomItemReader : read method - collecting the out file names
2016-01-08 14:51:57.762 INFO 7716 --- [ main] com.example.CustomItemReader : read method - no file found
2016-01-08 14:51:57.783 INFO 7716 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job1]] completed with the following parameters: [{run.id=1}] and the following status: [COMPLETED]
2016-01-08 14:51:57.786 INFO 7716 --- [ main] com.example.DemoApplication : Started DemoApplication in 13.693 seconds (JVM running for 14.853)
2016-01-08 14:52:54.724 INFO 7716 --- [pool-2-thread-1] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job1]] launched with the following parameters: [{}]
2016-01-08 14:52:54.750 INFO 7716 --- [pool-2-thread-1] o.s.batch.core.job.SimpleStepHandler : Executing step: [step1]
2016-01-08 14:52:54.755 INFO 7716 --- [pool-2-thread-1] com.example.CustomItemReader : read method - collecting the out file names
2016-01-08 14:52:54.756 INFO 7716 --- [pool-2-thread-1] com.example.CustomItemReader : read method - no file found
2016-01-08 14:52:54.775 INFO 7716 --- [pool-2-thread-1] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=job1]] completed with the following parameters: [{}] and the following status: [COMPLETED]

Related

Error occur when i creating spring batch multiple JobBuild

I'm using kotlin, spring boot 3.0.1 and batch .
I create two of job/step configuration. but when i build the project, i've saw the below errors.
I'm asking a question because it's hard to change the previous batch example to the latest version. Has anyone solved this problem?
Strangely enough, if you take one job out on config, it can running it.
errors
Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2023-01-03T13:47:34.101+09:00 ERROR 68470 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobLauncherApplicationRunner': Invocation of init method failed
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:195) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:420) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1743) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:599) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:521) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:961) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:915) ~[spring-context-6.0.3.jar:6.0.3]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:584) ~[spring-context-6.0.3.jar:6.0.3]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:432) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1302) ~[spring-boot-3.0.1.jar:3.0.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1291) ~[spring-boot-3.0.1.jar:3.0.1]
at com.linetest.batch.SpringBatchApplicationKt.main(SpringBatchApplication.kt:15) ~[main/:na]
Caused by: java.lang.IllegalArgumentException: Job name must be specified in case of multiple jobs
at org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner.validate(JobLauncherApplicationRunner.java:116) ~[spring-boot-autoconfigure-3.0.1.jar:3.0.1]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:424) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:368) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:192) ~[spring-beans-6.0.3.jar:6.0.3]
... 17 common frames omitted
config/SingleStepJobConfig.kt
import com.linetest.batch.tasklet.SimpleTasklet
import mu.KotlinLogging
import org.springframework.batch.core.Job
import org.springframework.batch.core.Step
import org.springframework.batch.core.StepContribution
import org.springframework.batch.core.job.builder.JobBuilder
import org.springframework.batch.core.repository.JobRepository
import org.springframework.batch.core.scope.context.ChunkContext
import org.springframework.batch.core.step.builder.StepBuilder
import org.springframework.batch.repeat.RepeatStatus
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.transaction.PlatformTransactionManager
private val log = KotlinLogging.logger {}
#Configuration
class SingleStepJobConfig(
private val transactionManager: PlatformTransactionManager,
private val jobRepository: JobRepository,
) {
#Bean
fun singleStepJob(): Job {
return JobBuilder("singleStepJob", jobRepository)
.start(singleStep())
.build()
}
#Bean
fun singleStep(): Step {
return StepBuilder("singleStep", jobRepository)
.tasklet(myTaskletAsBean(), transactionManager)
.build()
}
#Bean
fun singleStep2(): Step {
return StepBuilder("singleStep2", jobRepository)
.tasklet({
_: StepContribution,
_: ChunkContext ->
log.info { "single step2 tasklet 2 test" }
RepeatStatus.FINISHED
}, transactionManager)
.build()
}
#Bean
fun myTaskletAsBean(): SimpleTasklet {
val simpleTasklet = SimpleTasklet()
simpleTasklet.setValue("Single Step Job Properties Setup!!!<<--")
return simpleTasklet
}
}
config/MultipleStepJobConfig.kt
import com.linetest.batch.tasklet.SimpleTasklet
import mu.KotlinLogging
import org.apache.logging.log4j.util.Strings
import org.springframework.batch.core.Job
import org.springframework.batch.core.Step
import org.springframework.batch.core.StepContribution
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing
import org.springframework.batch.core.job.builder.JobBuilder
import org.springframework.batch.core.repository.JobRepository
import org.springframework.batch.core.scope.context.ChunkContext
import org.springframework.batch.core.step.builder.StepBuilder
import org.springframework.batch.repeat.RepeatStatus
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.batch.BatchProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.transaction.PlatformTransactionManager
private val log = KotlinLogging.logger {}
#Configuration
class MultipleStepJobConfig(
private val transactionManager: PlatformTransactionManager,
private val jobRepository: JobRepository,
) {
#Bean
fun multipleStepJob(): Job {
return JobBuilder("multipleStepJob", jobRepository)
.start(startStep())
.next(processStep())
.next(writeStep())
.build()
}
#Bean
fun startStep(): Step {
return StepBuilder("startStep", jobRepository)
.tasklet({
_: StepContribution,
_: ChunkContext ->
log.info { "multiple Step Start" }
RepeatStatus.FINISHED
}, transactionManager)
.build()
}
#Bean
fun processStep(): Step {
return StepBuilder("processStep", jobRepository)
.tasklet({_: StepContribution,
_: ChunkContext ->
log.info { "Execute processStep >>>>" }
RepeatStatus.FINISHED
}, transactionManager)
.build()
}
#Bean
fun writeStep(): Step {
return StepBuilder("writeStep", jobRepository)
.tasklet({_: StepContribution,
_: ChunkContext ->
log.info { "Execute writeStep >>>>" }
RepeatStatus.FINISHED
}, transactionManager)
.build()
}
}
tasklet/SimpleTasklet.kt
import mu.KotlinLogging
import org.springframework.batch.core.StepContribution
import org.springframework.batch.core.configuration.annotation.StepScope
import org.springframework.batch.core.scope.context.ChunkContext
import org.springframework.batch.core.step.tasklet.Tasklet
import org.springframework.batch.repeat.RepeatStatus
import org.springframework.beans.factory.InitializingBean
import org.springframework.stereotype.Component
private val log = KotlinLogging.logger { }
#Component
#StepScope
class SimpleTasklet : Tasklet, InitializingBean {
private var resource: String? = null
#Throws(Exception::class)
override fun execute(
contribution: StepContribution,
chunkContext: ChunkContext
): RepeatStatus? {
log.info { "Execute SimpleTasklet >>>>" }
return RepeatStatus.FINISHED
}
fun setValue(text:String){
this.resource = text
log.info { "$resource"}
}
#Throws(Exception::class)
override fun afterPropertiesSet() {
log.info { "AfterPropertiesSet" }
}
}
SpringBatchApplication.kt
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
#SpringBootApplication
class SpringBatchApplication
fun main(args: Array<String>) {
runApplication<SpringBatchApplication>(*args)
}
Strangely enough, if you take one job out on config, it can running it.
Existing Example can running.
ref. https://www.devkuma.com/docs/spring-batch/start/
the result
spring boot 2.5.5
2023-01-04 00:05:48.365 INFO 7829 --- [ main] com.linetest.batch.BatchApplicationKt : Starting BatchApplicationKt using Java 17.0.5 on mC02YR40ALVDL with PID 7829 (/Users/ParkJiho/Documents/workspace/kotlin/spring-batch-test-0102/build/classes/kotlin/main started by ParkJiho in /Users/ParkJiho/Documents/workspace/kotlin/spring-batch-test-0102)
2023-01-04 00:05:48.366 INFO 7829 --- [ main] com.linetest.batch.BatchApplicationKt : No active profile set, falling back to default profiles: default
2023-01-04 00:05:49.267 INFO 7829 --- [ main] c.linetest.batch.tasklet.SimpleTasklet : TESTTESTTEST has been set!!!!!!!!!!1
2023-01-04 00:05:49.267 INFO 7829 --- [ main] c.linetest.batch.tasklet.SimpleTasklet : AfterPropertiesSet
2023-01-04 00:05:49.282 INFO 7829 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2023-01-04 00:05:49.433 INFO 7829 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2023-01-04 00:05:49.538 INFO 7829 --- [ main] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: H2
2023-01-04 00:05:49.665 INFO 7829 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2023-01-04 00:05:49.722 INFO 7829 --- [ main] com.linetest.batch.BatchApplicationKt : Started BatchApplicationKt in 1.659 seconds (JVM running for 2.351)
2023-01-04 00:05:49.723 INFO 7829 --- [ main] o.s.b.a.b.JobLauncherApplicationRunner : Running default command line with: []
2023-01-04 00:05:49.766 INFO 7829 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [FlowJob: [name=flowStepJob]] launched with the following parameters: [{}]
2023-01-04 00:05:49.799 INFO 7829 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [flowStartStep]
2023-01-04 00:05:49.806 INFO 7829 --- [ main] c.l.batch.config.FlowStepJobConfig : Flow Start Step!!<------
2023-01-04 00:05:49.811 INFO 7829 --- [ main] o.s.batch.core.step.AbstractStep : Step: [flowStartStep] executed in 12ms
2023-01-04 00:05:49.816 INFO 7829 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [flowProcessStep]
2023-01-04 00:05:49.818 INFO 7829 --- [ main] c.l.batch.config.FlowStepJobConfig : flowProcessStep
2023-01-04 00:05:49.819 INFO 7829 --- [ main] o.s.batch.core.step.AbstractStep : Step: [flowProcessStep] executed in 3ms
2023-01-04 00:05:49.823 INFO 7829 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [flowWriteStep]
2023-01-04 00:05:49.825 INFO 7829 --- [ main] c.l.batch.config.FlowStepJobConfig : flowWriteStep
2023-01-04 00:05:49.827 INFO 7829 --- [ main] o.s.batch.core.step.AbstractStep : Step: [flowWriteStep] executed in 3ms
2023-01-04 00:05:49.830 INFO 7829 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [FlowJob: [name=flowStepJob]] completed with the following parameters: [{}] and the following status: [COMPLETED] in 40ms
2023-01-04 00:05:49.833 INFO 7829 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=multipleStepJob]] launched with the following parameters: [{}]
2023-01-04 00:05:49.837 INFO 7829 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [startStep]
2023-01-04 00:05:49.839 INFO 7829 --- [ main] c.l.batch.config.MultipleStepJobConfig : Start Step<--------
2023-01-04 00:05:49.841 INFO 7829 --- [ main] o.s.batch.core.step.AbstractStep : Step: [startStep] executed in 4ms
2023-01-04 00:05:49.844 INFO 7829 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [nextStep]
2023-01-04 00:05:49.846 INFO 7829 --- [ main] c.l.batch.config.MultipleStepJobConfig : Next Step<--------
2023-01-04 00:05:49.847 INFO 7829 --- [ main] o.s.batch.core.step.AbstractStep : Step: [nextStep] executed in 3ms
2023-01-04 00:05:49.850 INFO 7829 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [lastStep]
2023-01-04 00:05:49.852 INFO 7829 --- [ main] c.l.batch.config.MultipleStepJobConfig : Last Step<--------
2023-01-04 00:05:49.853 INFO 7829 --- [ main] o.s.batch.core.step.AbstractStep : Step: [lastStep] executed in 3ms
2023-01-04 00:05:49.855 INFO 7829 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=multipleStepJob]] completed with the following parameters: [{}] and the following status: [COMPLETED] in 21ms
2023-01-04 00:05:49.858 INFO 7829 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=singleStepJob]] launched with the following parameters: [{}]
2023-01-04 00:05:49.861 INFO 7829 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [simpleStep]
2023-01-04 00:05:49.862 INFO 7829 --- [ main] c.linetest.batch.tasklet.SimpleTasklet : Execute SimpleTasklet >>>>
2023-01-04 00:05:49.864 INFO 7829 --- [ main] o.s.batch.core.step.AbstractStep : Step: [simpleStep] executed in 3ms
2023-01-04 00:05:49.865 INFO 7829 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [SimpleJob: [name=singleStepJob]] completed with the following parameters: [{}] and the following status: [COMPLETED] in 7ms
2023-01-04 00:05:49.869 INFO 7829 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2023-01-04 00:05:49.871 INFO 7829 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
The issue very clear from logs.
Caused by: java.lang.IllegalArgumentException: Job name must be specified in case of multiple jobs
at org.springframework.boot.autoconfigure.batch.JobLauncherApplicationRunner.validate(JobLauncherApplicationRunner.java:116) ~[spring-boot-autoconfigure-3.0.1.jar:3.0.1]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:424) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:368) ~[spring-beans-6.0.3.jar:6.0.3]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:192) ~[spring-beans-6.0.3.jar:6.0.3]
... 17 common frames omitted
If only one job is present in Spring Context then Spring run that job by default on startup but If multiple jobs are present in Spring Context then we need to tell Spring which job to run on startup.
So you can specify this property in application.properties file and try again.
spring.batch.job.name=singleStepJob
or
spring.batch.job.name=multipleStepJob
or you can disable running job on startup by this property and run the job programmatically using JobLauncher.
spring.batch.job.enabled=false
How to run job programmatically?
public class JobLauncherService {
private final JobLauncher jobLauncher;
private final Job job;
#Autowired
public JobLauncherService(JobLauncher jobLauncher, #Qualifier("multipleStepJob") Job job) {
this.jobLauncher = jobLauncher;
this.job = job;
}
public void runJob() {
try {
final JobExecution jobExecution = jobLauncher.run(job, new JobParameters());
System.out.println("Job Status : " + jobExecution.getStatus());
System.out.println("Job completed");
} catch (Exception e) {
e.printStackTrace();
System.out.println("Job failed");
}
}
}

JobParametersValidator.validate() method parameters returns null in spring batch

I am writing simple helloworld application in spring batch, and I'm trying to validate the JobParameters with custom implementation of JobParametersValidator.
public class ParameterValidator implements JobParametersValidator{
#Override
public void validate(JobParameters parameters) throws JobParametersInvalidException {
//String parameter = parameters.getParameters().get("outputText");
System.out.println("jobparameters are ............ " + parameters);
//System.out.println("parameter is " + parameter);
//if(!StringUtils.hasText(parameter)) {
throw new JobParametersInvalidException("Parameter is missing.........");
//}
}
}
But when I tried to Sysout the JobParameters inside the validate method, parameters return null.
Here is my console out.
2021-11-26 10:06:32.457 INFO 11912 --- [ restartedMain] com.pack.SpringBatchDemo2Application : Starting SpringBatchDemo2Application using Java 16.0.2 on DESKTOP-T1L7IA7 with PID 11912 (D:\Workspace\EclipseWorkspaceSpringPractise\SpringBatchDemo2\target\classes started by arepa in D:\Workspace\EclipseWorkspaceSpringPractise\SpringBatchDemo2)
2021-11-26 10:06:32.458 INFO 11912 --- [ restartedMain] com.pack.SpringBatchDemo2Application : No active profile set, falling back to default profiles: default
2021-11-26 10:06:32.536 INFO 11912 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2021-11-26 10:06:33.575 INFO 11912 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-11-26 10:06:33.784 INFO 11912 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2021-11-26 10:06:33.920 INFO 11912 --- [ restartedMain] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: POSTGRES
2021-11-26 10:06:34.262 INFO 11912 --- [ restartedMain] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2021-11-26 10:06:34.484 INFO 11912 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2021-11-26 10:06:34.539 INFO 11912 --- [ restartedMain] com.pack.SpringBatchDemo2Application : Started SpringBatchDemo2Application in 2.596 seconds (JVM running for 4.056)
2021-11-26 10:06:34.544 INFO 11912 --- [ restartedMain] o.s.b.a.b.JobLauncherApplicationRunner : Running default command line with: []
jobparameters are ............ {}
2021-11-26 10:06:34.713 INFO 11912 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-11-26 10:06:34.756 ERROR 11912 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
Here is my Job creation code.
#Component
public class HelloWorldJob {
#Autowired
private JobBuilderFactory jobBuilderFactory;
#Autowired
private StepBuilderFactory stepBuilderFactory;
public Step step() {
Tasklet tasklet = (contribution, chunkContext) -> {
return RepeatStatus.FINISHED;
};
return this.stepBuilderFactory.get("step1")
.tasklet(tasklet).build();
}
#Bean
public Job job() {
return this.jobBuilderFactory.get("job1").start(step()).validator(new ParameterValidator()).build();
}
}
Here is my code for triggering jobs.
#Component
public class TriggerJobLauncher {
#Autowired
private JobLauncher launcher;
#Autowired
private Job job;
public void triggerJob() throws JobExecutionAlreadyRunningException,
JobRestartException,
JobInstanceAlreadyCompleteException,
JobParametersInvalidException {
JobParameters parameters = new JobParametersBuilder().addParameter("aa", new JobParameter("Hello World")).toJobParameters();
launcher.run(job, parameters);
}
}

How to fix The injection point has the following annotations: - #org.springframework.beans.factory.annotation.Autowired(required=true)

I am new to spring boot, i am getting this error since a while, unfortunately can't fix it. I am googling since then but still not find what i did wrong. Find below my code:
Entity
#Entity
#Table(name="compagnie")
public class Compagnie implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id_compagnie")
private int idCompagnie;
#Column(name="nom_compagnie")
private String nomCompagnie;
#Column(name="nom_court_compagnie")
private String nomCourtCompagnie;
#Column(name="logo_compagnie")
private String logoCompagnie;
public int getIdCompagnie() {
return idCompagnie;
}
public void setIdCompagnie(int idCompagnie) {
this.idCompagnie = idCompagnie;
}
public String getNomCompagnie() {
return nomCompagnie;
}
public void setNomCompagnie(String nomCompagnie) {
this.nomCompagnie = nomCompagnie;
}
public String getNomCourtCompagnie() {
return nomCourtCompagnie;
}
public void setNomCourtCompagnie(String nomCourtCompagnie) {
this.nomCourtCompagnie = nomCourtCompagnie;
}
public String getLogoCompagnie() {
return logoCompagnie;
}
public void setLogoCompagnie(String logoCompagnie) {
this.logoCompagnie = logoCompagnie;
}
}
Dao
#Component
public interface CompagnieDao extends JpaRepository<Compagnie, Integer> {
#Query("select c from Compagnie c where idCompagnie != :idCompagnie")
List<Compagnie> getAllCompagnieNonAssurAstuce(#Param("idCompagnie") int idCompagnie);
#Query("select c from Compagnie c where nomCompagnie = :nomCompagnie")
Compagnie getCompagnieByNom(#Param("nomCompagnie") String nomCompagnie);
}
Main
#SpringBootApplication
public class Application implements CommandLineRunner {
#Autowired
private CompagnieDao compagnieDao;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println("tic toc");
List<Compagnie> compagnies = compagnieDao.findAll();
compagnies.forEach(compagnie -> System.out.println(compagnie.getNomCompagnie()));
}
}
Error
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-12-30 11:54:42.817 ERROR 10136 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
APPLICATION FAILED TO START
Description:
Field compagnieDao in com.assurastuce.Application required a bean of type 'com.dao.CompagnieDao' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.dao.CompagnieDao' in your configuration.
Thank you for your help
I changed the spring version from 2.4.1 to 2.3.4.RELEASE and now getting this error
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:798) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:779) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:322) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at com.assurastuce.Application.main(Application.java:20) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_271]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_271]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_271]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_271]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.3.4.RELEASE.jar:2.3.4.RELEASE]
Caused by: java.lang.NullPointerException: null
at com.assurastuce.Application.run(Application.java:26) [classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:795) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
... 10 common frames omitted
2020-12-31 08:26:45.401 INFO 11520 --- [ restartedMain] o.e.jetty.server.AbstractConnector : Stopped ServerConnector#19b4bd36{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
2020-12-31 08:26:45.401 INFO 11520 --- [ restartedMain] org.eclipse.jetty.server.session : node0 Stopped scavenging
2020-12-31 08:26:45.405 INFO 11520 --- [ restartedMain] o.e.j.s.h.ContextHandler.application : Destroying Spring FrameworkServlet 'dispatcherServlet'
2020-12-31 08:26:45.407 INFO 11520 --- [ restartedMain] o.e.jetty.server.handler.ContextHandler : Stopped o.s.b.w.e.j.JettyEmbeddedWebAppContext#4bfa6d74{application,/,[file:///C:/Users/LAKATAN%20Adebayo%20G.%20W/AppData/Local/Temp/jetty-docbase.8010039629830210588.8080/],UNAVAILABLE}
2020-12-31 08:26:45.430 INFO 11520 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-12-31 08:26:45.434 INFO 11520 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2020-12-31 08:26:45.438 INFO 11520 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2020-12-31 08:26:45.465 INFO 11520 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
Probably the folder structure is not correct.
Could you please add this line of code and check if this works for you.
#SpringBootApplication
#ComponentScan(value = "com.dao.CompagnieDao")
public class Application implements CommandLineRunner {
Also, I think it would be more correct if you replace the #Component with the #Repository annotation.
#Repository
public interface CompagnieDao extends JpaRepository<Compagnie, Integer> {

RabbitMQ Failed to declare queue and Listener is not able to get queue on server

I have spring boot rabbitmq application where i have to send an Employee object to queue. Then i have set up a listener application. Do some processing on employee object and put this object in call back queue.
For this, i have created below objects in my appication.
Created ConnectionFactory.
Created RabbitAdmin object using ConnectionFactory..
Request Queue.
Callback Queue.
Direct Exchange.
Request Queue Binding.
Callback Queue Binding.
MessageConverter.
RabbitTemplate object.
And finally object of SimpleMessageListenerContainer.
My Application files looks like below.
application.properties
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.virtual-host=foo
emp.rabbitmq.directexchange=EMP_EXCHANGE1
emp.rabbitmq.requestqueue=EMP_QUEUE1
emp.rabbitmq.routingkey=EMP_ROUTING_KEY1
MainClass.java
package com.employee;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class MainClass {
public static void main(String[] args) {
SpringApplication.run(
MainClass.class, args);
}
}
ApplicationContextProvider.java
package com.employee.config;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext context;
public ApplicationContext getApplicationContext(){
return context;
}
#Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException {
context = arg0;
}
public Object getBean(String name){
return context.getBean(name, Object.class);
}
public void addBean(String beanName, Object beanObject){
ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext)context).getBeanFactory();
beanFactory.registerSingleton(beanName, beanObject);
}
public void removeBean(String beanName){
BeanDefinitionRegistry reg = (BeanDefinitionRegistry) context.getAutowireCapableBeanFactory();
reg.removeBeanDefinition(beanName);
}
}
Constants.java
package com.employee.constant;
public class Constants {
public static final String CALLBACKQUEUE = "_CBQ";
}
Employee.java
package com.employee.model;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
#JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "#id", scope = Employee.class)
public class Employee {
private String empName;
private String empId;
private String changedValue;
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getChangedValue() {
return changedValue;
}
public void setChangedValue(String changedValue) {
this.changedValue = changedValue;
}
}
EmployeeProducerInitializer.java
package com.employee.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.employee.constant.Constants;
import com.employee.service.EmployeeResponseReceiver;
#Configuration
#EnableAutoConfiguration
#ComponentScan(value="com.en.*")
public class EmployeeProducerInitializer {
#Value("${emp.rabbitmq.requestqueue}")
String requestQueueName;
#Value("${emp.rabbitmq.directexchange}")
String directExchange;
#Value("${emp.rabbitmq.routingkey}")
private String requestRoutingKey;
#Autowired
private ConnectionFactory rabbitConnectionFactory;
#Bean
ApplicationContextProvider applicationContextProvider(){
System.out.println("inside app ctx provider");
return new ApplicationContextProvider();
};
#Bean
RabbitAdmin rabbitAdmin(){
System.out.println("inside rabbit admin");
return new RabbitAdmin(rabbitConnectionFactory);
};
#Bean
Queue empRequestQueue() {
System.out.println("inside request queue");
return new Queue(requestQueueName, true);
}
#Bean
Queue empCallBackQueue() {
System.out.println("inside call back queue");
return new Queue(requestQueueName + Constants.CALLBACKQUEUE, true);
}
#Bean
DirectExchange empDirectExchange() {
System.out.println("inside exchange");
return new DirectExchange(directExchange);
}
#Bean
Binding empRequestBinding() {
System.out.println("inside request binding");
return BindingBuilder.bind(empRequestQueue()).to(empDirectExchange()).with(requestRoutingKey);
}
#Bean
Binding empCallBackBinding() {
return BindingBuilder.bind(empCallBackQueue()).to(empDirectExchange()).with(requestRoutingKey + Constants.CALLBACKQUEUE);
}
#Bean
public MessageConverter jsonMessageConverter(){
System.out.println("inside json msg converter");
return new Jackson2JsonMessageConverter();
}
#Bean
public RabbitTemplate empFixedReplyQRabbitTemplate() {
System.out.println("inside rabbit template");
RabbitTemplate template = new RabbitTemplate(this.rabbitConnectionFactory);
template.setExchange(empDirectExchange().getName());
template.setRoutingKey(requestRoutingKey);
template.setMessageConverter(jsonMessageConverter());
template.setReceiveTimeout(100000);
template.setReplyTimeout(100000);
return template;
}
#Bean
public SimpleMessageListenerContainer empReplyListenerContainer() {
System.out.println("inside listener");
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
try{
container.setConnectionFactory(this.rabbitConnectionFactory);
container.setQueues(empCallBackQueue());
container.setMessageListener(new EmployeeResponseReceiver());
container.setMessageConverter(jsonMessageConverter());
container.setConcurrentConsumers(10);
container.setMaxConcurrentConsumers(20);
container.start();
}catch(Exception e){
e.printStackTrace();
}finally{
System.out.println("inside listener finally");
}
return container;
}
#Autowired
#Qualifier("empReplyListenerContainer")
private SimpleMessageListenerContainer empReplyListenerContainer;
}
EmployeeResponseReceiver.java
package com.employee.service;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Component;
import com.employee.config.ApplicationContextProvider;
import com.employee.model.Employee;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
#Component
#EnableAutoConfiguration
public class EmployeeResponseReceiver implements ChannelAwareMessageListener {
ApplicationContextProvider applicationContextProvider = new ApplicationContextProvider();
String msg = null;
ObjectMapper mapper = new ObjectMapper();
Employee employee = null;
#Override
public void onMessage(Message message, Channel arg1) throws Exception {
try {
msg = new String(message.getBody());
System.out.println("Received Message : " + msg);
employee = mapper.readValue(msg, Employee.class);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The problem is whenever i start my application, i get below exceptions.
2018-03-17 14:18:36.695 INFO 12472 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-03-17 14:18:36.696 INFO 12472 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 5060 ms
2018-03-17 14:18:37.004 INFO 12472 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2018-03-17 14:18:37.010 INFO 12472 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-03-17 14:18:37.010 INFO 12472 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-03-17 14:18:37.011 INFO 12472 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-03-17 14:18:37.011 INFO 12472 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
inside listener
inside call back queue
inside json msg converter
2018-03-17 14:18:37.576 INFO 12472 --- [cTaskExecutor-8] o.s.a.r.c.CachingConnectionFactory : Created new connection: SimpleConnection#3d31af39 [delegate=amqp://guest#127.0.0.1:5672/foo, localPort= 50624]
2018-03-17 14:18:37.654 WARN 12472 --- [cTaskExecutor-7] o.s.a.r.listener.BlockingQueueConsumer : Failed to declare queue:EMP_QUEUE1_CBQ
2018-03-17 14:18:37.655 WARN 12472 --- [cTaskExecutor-6] o.s.a.r.listener.BlockingQueueConsumer : Failed to declare queue:EMP_QUEUE1_CBQ
2018-03-17 14:18:37.655 WARN 12472 --- [cTaskExecutor-5] o.s.a.r.listener.BlockingQueueConsumer : Failed to declare queue:EMP_QUEUE1_CBQ
2018-03-17 14:18:37.655 WARN 12472 --- [cTaskExecutor-3] o.s.a.r.listener.BlockingQueueConsumer : Failed to declare queue:EMP_QUEUE1_CBQ
2018-03-17 14:18:37.657 WARN 12472 --- [cTaskExecutor-1] o.s.a.r.listener.BlockingQueueConsumer : Failed to declare queue:EMP_QUEUE1_CBQ
2018-03-17 14:18:37.658 WARN 12472 --- [cTaskExecutor-8] o.s.a.r.listener.BlockingQueueConsumer : Failed to declare queue:EMP_QUEUE1_CBQ
2018-03-17 14:18:37.661 WARN 12472 --- [cTaskExecutor-2] o.s.a.r.listener.BlockingQueueConsumer : Failed to declare queue:EMP_QUEUE1_CBQ
2018-03-17 14:18:37.660 WARN 12472 --- [cTaskExecutor-4] o.s.a.r.listener.BlockingQueueConsumer : Failed to declare queue:EMP_QUEUE1_CBQ
2018-03-17 14:18:37.661 WARN 12472 --- [cTaskExecutor-9] o.s.a.r.listener.BlockingQueueConsumer : Failed to declare queue:EMP_QUEUE1_CBQ
2018-03-17 14:18:37.666 WARN 12472 --- [TaskExecutor-10] o.s.a.r.listener.BlockingQueueConsumer : Failed to declare queue:EMP_QUEUE1_CBQ
2018-03-17 14:18:37.667 WARN 12472 --- [cTaskExecutor-2] o.s.a.r.listener.BlockingQueueConsumer : Queue declaration failed; retries left=3
org.springframework.amqp.rabbit.listener.BlockingQueueConsumer$DeclarationException: Failed to declare queue(s):[EMP_QUEUE1_CBQ]
at org.springframework.amqp.rabbit.listener.BlockingQueueConsumer.attemptPassiveDeclarations(BlockingQueueConsumer.java:636) ~[spring-rabbit-1.7.2.RELEASE.jar:na]
at org.springframework.amqp.rabbit.listener.BlockingQueueConsumer.start(BlockingQueueConsumer.java:535) ~[spring-rabbit-1.7.2.RELEASE.jar:na]
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1389) [spring-rabbit-1.7.2.RELEASE.jar:na]
at java.lang.Thread.run(Unknown Source) [na:1.8.0_151]
Caused by: java.io.IOException: null
at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:105) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:101) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc(AMQChannel.java:123) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.ChannelN.queueDeclarePassive(ChannelN.java:992) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.ChannelN.queueDeclarePassive(ChannelN.java:50) ~[amqp-client-4.0.2.jar:4.0.2]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_151]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_151]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_151]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_151]
at org.springframework.amqp.rabbit.connection.CachingConnectionFactory$CachedChannelInvocationHandler.invoke(CachingConnectionFactory.java:955) ~[spring-rabbit-1.7.2.RELEASE.jar:na]
at com.sun.proxy.$Proxy58.queueDeclarePassive(Unknown Source) ~[na:na]
at org.springframework.amqp.rabbit.listener.BlockingQueueConsumer.attemptPassiveDeclarations(BlockingQueueConsumer.java:615) ~[spring-rabbit-1.7.2.RELEASE.jar:na]
... 3 common frames omitted
Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.close>(reply-code=404, reply-text=NOT_FOUND - no queue 'EMP_QUEUE1_CBQ' in vhost 'foo', class-id=50, method-id=10)
at com.rabbitmq.utility.ValueOrException.getValue(ValueOrException.java:66) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.utility.BlockingValueOrException.uninterruptibleGetValue(BlockingValueOrException.java:32) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.AMQChannel$BlockingRpcContinuation.getReply(AMQChannel.java:366) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.AMQChannel.privateRpc(AMQChannel.java:229) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc(AMQChannel.java:117) ~[amqp-client-4.0.2.jar:4.0.2]
... 12 common frames omitted
Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.close>(reply-code=404, reply-text=NOT_FOUND - no queue 'EMP_QUEUE1_CBQ' in vhost 'foo', class-id=50, method-id=10)
at com.rabbitmq.client.impl.ChannelN.asyncShutdown(ChannelN.java:505) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.ChannelN.processAsync(ChannelN.java:336) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.AMQChannel.handleCompleteInboundCommand(AMQChannel.java:143) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.AMQChannel.handleFrame(AMQChannel.java:90) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.AMQConnection.readFrame(AMQConnection.java:634) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.AMQConnection.access$300(AMQConnection.java:47) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:572) ~[amqp-client-4.0.2.jar:4.0.2]
... 1 common frames omitted
2018-03-17 14:08:36.689 WARN 11076 --- [cTaskExecutor-4] o.s.a.r.listener.BlockingQueueConsumer : Failed to declare queue:EMP_QUEUE1_CBQ
2018-03-17 14:08:36.695 ERROR 11076 --- [cTaskExecutor-4] o.s.a.r.l.SimpleMessageListenerContainer : Consumer received fatal exception on startup
org.springframework.amqp.rabbit.listener.QueuesNotAvailableException: Cannot prepare queue for listener. Either the queue doesn't exist or the broker will not allow us to use it.
at org.springframework.amqp.rabbit.listener.BlockingQueueConsumer.start(BlockingQueueConsumer.java:563) ~[spring-rabbit-1.7.2.RELEASE.jar:na]
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1389) ~[spring-rabbit-1.7.2.RELEASE.jar:na]
at java.lang.Thread.run(Unknown Source) [na:1.8.0_151]
Caused by: org.springframework.amqp.rabbit.listener.BlockingQueueConsumer$DeclarationException: Failed to declare queue(s):[EMP_QUEUE1_CBQ]
at org.springframework.amqp.rabbit.listener.BlockingQueueConsumer.attemptPassiveDeclarations(BlockingQueueConsumer.java:636) ~[spring-rabbit-1.7.2.RELEASE.jar:na]
at org.springframework.amqp.rabbit.listener.BlockingQueueConsumer.start(BlockingQueueConsumer.java:535) ~[spring-rabbit-1.7.2.RELEASE.jar:na]
... 2 common frames omitted
Caused by: java.io.IOException: null
at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:105) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:101) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc(AMQChannel.java:123) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.ChannelN.queueDeclarePassive(ChannelN.java:992) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.ChannelN.queueDeclarePassive(ChannelN.java:50) ~[amqp-client-4.0.2.jar:4.0.2]
at sun.reflect.GeneratedMethodAccessor27.invoke(Unknown Source) ~[na:na]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_151]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_151]
at org.springframework.amqp.rabbit.connection.CachingConnectionFactory$CachedChannelInvocationHandler.invoke(CachingConnectionFactory.java:955) ~[spring-rabbit-1.7.2.RELEASE.jar:na]
at com.sun.proxy.$Proxy58.queueDeclarePassive(Unknown Source) ~[na:na]
at org.springframework.amqp.rabbit.listener.BlockingQueueConsumer.attemptPassiveDeclarations(BlockingQueueConsumer.java:615) ~[spring-rabbit-1.7.2.RELEASE.jar:na]
... 3 common frames omitted
Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.close>(reply-code=404, reply-text=NOT_FOUND - no queue 'EMP_QUEUE1_CBQ' in vhost 'foo', class-id=50, method-id=10)
at com.rabbitmq.utility.ValueOrException.getValue(ValueOrException.java:66) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.utility.BlockingValueOrException.uninterruptibleGetValue(BlockingValueOrException.java:32) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.AMQChannel$BlockingRpcContinuation.getReply(AMQChannel.java:366) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.AMQChannel.privateRpc(AMQChannel.java:229) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc(AMQChannel.java:117) ~[amqp-client-4.0.2.jar:4.0.2]
... 11 common frames omitted
Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.close>(reply-code=404, reply-text=NOT_FOUND - no queue 'EMP_QUEUE1_CBQ' in vhost 'foo', class-id=50, method-id=10)
at com.rabbitmq.client.impl.ChannelN.asyncShutdown(ChannelN.java:505) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.ChannelN.processAsync(ChannelN.java:336) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.AMQChannel.handleCompleteInboundCommand(AMQChannel.java:143) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.AMQChannel.handleFrame(AMQChannel.java:90) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.AMQConnection.readFrame(AMQConnection.java:634) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.AMQConnection.access$300(AMQConnection.java:47) ~[amqp-client-4.0.2.jar:4.0.2]
at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:572) ~[amqp-client-4.0.2.jar:4.0.2]
... 1 common frames omitted
2018-03-17 14:08:36.697 INFO 11076 --- [TaskExecutor-10] o.s.a.r.l.SimpleMessageListenerContainer : Successfully waited for workers to finish.
2018-03-17 14:08:36.699 INFO 11076 --- [cTaskExecutor-5] o.s.a.r.l.SimpleMessageListenerContainer : Successfully waited for workers to finish.
2018-03-17 14:08:36.700 INFO 11076 --- [cTaskExecutor-1] o.s.a.r.l.SimpleMessageListenerContainer : Successfully waited for workers to finish.
2018-03-17 14:08:36.701 INFO 11076 --- [cTaskExecutor-3] o.s.a.r.l.SimpleMessageListenerContainer : Successfully waited for workers to finish.
2018-03-17 14:08:36.700 INFO 11076 --- [cTaskExecutor-2] o.s.a.r.l.SimpleMessageListenerContainer : Successfully waited for workers to finish.
2018-03-17 14:08:36.702 INFO 11076 --- [cTaskExecutor-7] o.s.a.r.l.SimpleMessageListenerContainer : Successfully waited for workers to finish.
2018-03-17 14:08:36.765 ERROR 11076 --- [cTaskExecutor-8] o.s.a.r.l.SimpleMessageListenerContainer : Stopping container from aborted consumer
2018-03-17 14:08:36.766 ERROR 11076 --- [cTaskExecutor-6] o.s.a.r.l.SimpleMessageListenerContainer : Stopping container from aborted consumer
2018-03-17 14:08:36.779 ERROR 11076 --- [cTaskExecutor-9] o.s.a.r.l.SimpleMessageListenerContainer : Stopping container from aborted consumer
2018-03-17 14:08:36.791 ERROR 11076 --- [cTaskExecutor-4] o.s.a.r.l.SimpleMessageListenerContainer : Stopping container from aborted consumer
inside app ctx provider
inside rabbit admin
inside exchange
inside request queue
inside request binding
inside rabbit template
2018-03-17 14:08:38.978 INFO 11076 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#33b37288: startup date [Sat Mar 17 14:08:16 IST 2018]; root of context hierarchy
2018-03-17 14:08:39.395 INFO 11076 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-03-17 14:08:39.398 INFO 11076 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-03-17 14:08:39.663 INFO 11076 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-17 14:08:39.663 INFO 11076 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-17 14:08:39.826 INFO 11076 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-17 14:08:40.648 INFO 11076 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-03-17 14:08:40.677 INFO 11076 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'rabbitConnectionFactory' has been autodetected for JMX exposure
2018-03-17 14:08:40.685 INFO 11076 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'rabbitConnectionFactory': registering with JMX server as MBean [org.springframework.amqp.rabbit.connection:name=rabbitConnectionFactory,type=CachingConnectionFactory]
2018-03-17 14:08:40.746 INFO 11076 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase -2147482648
2018-03-17 14:08:40.747 INFO 11076 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647
2018-03-17 14:08:41.258 INFO 11076 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-03-17 14:08:41.270 INFO 11076 --- [ main] com.employee.MainClass : Started MainClass in 26.141 seconds (JVM running for 28.02)
Can anybody help me resolving my issue? As per my understanding, when object of SimpleMessageListenerContainer is being created, callback queue is not created on rabbitmq server. I tried declaring queue using RabbitAdmin object, but then execution stops and nothing goes ahead. This problem was not there when i was declaring queue in default virtual host. But when i added virtual host foo all of it sudden stopped working. You can replicate this issue using above code. I have pasted all my code. Kindly let me know if anything else is to be posted.
Interesting point is even if i am getting this exceptions, my application is up and running. That means somehow my callback queue is created and object of SimpleMessageListenerContainer gets the queue. I read somewhere that, when queue is created, my SimpleMessageListenerContainer object will listen to it.
Please help me resolving this issue.
This problem was not there when i was declaring queue in default virtual host. But when i added virtual host foo all of it sudden stopped working.
Does the user that accesses the new virtual host have configure permissions? Configure permissions are required to declare queues.
A RabbitAdmin is required to declare the queues/bindings; the container only does a passive declaration to check the queue is present.
EDIT
container.start();
You must not start() the container within a bean definition. The application context will do that after the application context is completely built, if the container's autoStartUp is true (default).
It is clear from your logs that the container is starting too early - before the other beans (admin, queue etc) have been declared.

Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered

I know this has been asked many time but I could not
find answer for I problem. I am Trying to schedule my spring batch for every 20 second but its getting fail.
QuartzConfiguration.java
#Configuration
public class QuartzConfiguration {
#Autowired
private JobLauncher jobLauncher;
#Autowired
private JobLocator jobLocator;
#Bean
public JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor(JobRegistry jobRegistry) {
JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor = new JobRegistryBeanPostProcessor();
jobRegistryBeanPostProcessor.setJobRegistry(jobRegistry);
return jobRegistryBeanPostProcessor;
}
#Bean
public JobDetailFactoryBean jobDetailFactoryBean() {
JobDetailFactoryBean jobfactory = new JobDetailFactoryBean();
jobfactory.setJobClass(QuartzJobLauncher.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("jobName", "Test_Job");
map.put("jobLauncher", jobLauncher);
map.put("jobLocator", jobLocator);
jobfactory.setJobDataAsMap(map);
jobfactory.setGroup("group");
jobfactory.setName("job");
return jobfactory;
}
// Job is scheduled after every 20 sec
#Bean
public CronTriggerFactoryBean cronTriggerFactoryBean() {
CronTriggerFactoryBean ctFactory = new CronTriggerFactoryBean();
ctFactory.setJobDetail(jobDetailFactoryBean().getObject());
ctFactory.setStartDelay(3000);
ctFactory.setName("cron_trigger");
ctFactory.setGroup("cron_group");
ctFactory.setCronExpression("0/20 * * * * ?");
return ctFactory;
}
#Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean scheduler = new SchedulerFactoryBean();
scheduler.setTriggers(cronTriggerFactoryBean().getObject());
return scheduler;
}
}
QuartzJobLauncher.java
public class QuartzJobLauncher extends QuartzJobBean {
private static final Logger log = LoggerFactory.getLogger(QuartzJobLauncher.class);
private String jobName;
private JobLauncher jobLauncher;
private JobLocator jobLocator;
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public JobLauncher getJobLauncher() {
return jobLauncher;
}
public void setJobLauncher(JobLauncher jobLauncher) {
this.jobLauncher = jobLauncher;
}
public JobLocator getJobLocator() {
return jobLocator;
}
public void setJobLocator(JobLocator jobLocator) {
this.jobLocator = jobLocator;
}
#Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
try {
Job job = jobLocator.getJob(jobName);
JobExecution jobExecution = jobLauncher.run(job, new JobParameters());
log.info("{}_{} was completed successfully", job.getName(), jobExecution.getId());
} catch (Exception e) {
log.error("Encountered job execution exception!");
}
}
}
BatchConfig.java
#Configuration
public class BatchConfig {
#Autowired
JobBuilderFactory jobBuilderFactory;
#Autowired
StepBuilderFactory stepBuilderFactory;
#Bean
public Tasklet task1()
{
return new Tasklet(){
#Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
// TODO Auto-generated method stub
System.out.println("hello world");
return RepeatStatus.FINISHED;
}
};
}
#Bean
public Step step1(){
return stepBuilderFactory.get("step1")
.tasklet(task1())
.build();
}
#Bean
public Job job1()
{
return jobBuilderFactory.get("job1")
.start(step1())
.build();
}
}
BatchApplication.java
#SpringBootApplication
#EnableBatchProcessing
#Import(QuartzConfiguration.class)
public class BatchApplication {
public static void main(String[] args) {
SpringApplication.run(BatchApplication.class, args);
}
}
error log
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.4.RELEASE)
2017-07-11 14:35:59.370 INFO 8868 --- [ main] com.schwab.cat.BatchApplication : Starting BatchApplication on KVMOF0487DVLBDC with PID 8868 (started by pankaj.k.singh in C:\Users\pankaj.k.singh\Desktop\batch\sample hello world)
2017-07-11 14:35:59.377 INFO 8868 --- [ main] com.schwab.cat.BatchApplication : No active profile set, falling back to default profiles: default
2017-07-11 14:35:59.511 INFO 8868 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#221af3c0: startup date [Tue Jul 11 14:35:59 IST 2017]; root of context hierarchy
2017-07-11 14:36:00.992 WARN 8868 --- [ main] o.s.c.a.ConfigurationClassEnhancer : #Bean method ScopeConfiguration.stepScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as #Autowired, #Resource and #PostConstruct within the method's declaring #Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see #Bean javadoc for complete details.
2017-07-11 14:36:01.013 WARN 8868 --- [ main] o.s.c.a.ConfigurationClassEnhancer : #Bean method ScopeConfiguration.jobScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as #Autowired, #Resource and #PostConstruct within the method's declaring #Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see #Bean javadoc for complete details.
2017-07-11 14:36:01.230 INFO 8868 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat' of type [org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-11 14:36:01.253 INFO 8868 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$1bb5301] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-11 14:36:01.435 INFO 8868 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'spring.datasource-org.springframework.boot.autoconfigure.jdbc.DataSourceProperties' of type [org.springframework.boot.autoconfigure.jdbc.DataSourceProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-11 14:36:01.632 INFO 8868 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'dataSource' of type [org.apache.tomcat.jdbc.pool.DataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-11 14:36:01.641 INFO 8868 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration' of type [org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$$EnhancerBySpringCGLIB$$e3aef661] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-11 14:36:01.672 INFO 8868 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'dataSourceInitializer' of type [org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-11 14:36:01.679 INFO 8868 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration' of type [org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$$EnhancerBySpringCGLIB$$17e2d67] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-11 14:36:01.718 INFO 8868 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'jobLauncher' of type [com.sun.proxy.$Proxy41] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-11 14:36:01.732 INFO 8868 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'jobRegistry' of type [com.sun.proxy.$Proxy43] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-11 14:36:01.733 INFO 8868 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'com.quantvalley.batch.quartz.QuartzConfiguration' of type [com.quantvalley.batch.quartz.QuartzConfiguration$$EnhancerBySpringCGLIB$$88291ebb] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-11 14:36:03.256 INFO 8868 --- [ main] o.s.b.c.r.s.JobRepositoryFactoryBean : No database type set, using meta data indicating: HSQL
2017-07-11 14:36:03.606 INFO 8868 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : No TaskExecutor has been set, defaulting to synchronous executor.
2017-07-11 14:36:03.912 INFO 8868 --- [ main] org.quartz.impl.StdSchedulerFactory : Using default implementation for ThreadExecutor
2017-07-11 14:36:03.980 INFO 8868 --- [ main] org.quartz.core.SchedulerSignalerImpl : Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
2017-07-11 14:36:03.984 INFO 8868 --- [ main] org.quartz.core.QuartzScheduler : Quartz Scheduler v.2.2.3 created.
2017-07-11 14:36:03.987 INFO 8868 --- [ main] org.quartz.simpl.RAMJobStore : RAMJobStore initialized.
2017-07-11 14:36:03.991 INFO 8868 --- [ main] org.quartz.core.QuartzScheduler : Scheduler meta-data: Quartz Scheduler (v2.2.3) 'schedulerFactoryBean' with instanceId 'NON_CLUSTERED'
Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
NOT STARTED.
Currently in standby mode.
Number of jobs executed: 0
Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 10 threads.
Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.
2017-07-11 14:36:03.993 INFO 8868 --- [ main] org.quartz.impl.StdSchedulerFactory : Quartz scheduler 'schedulerFactoryBean' initialized from an externally provided properties instance.
2017-07-11 14:36:03.993 INFO 8868 --- [ main] org.quartz.impl.StdSchedulerFactory : Quartz scheduler version: 2.2.3
2017-07-11 14:36:03.998 INFO 8868 --- [ main] org.quartz.core.QuartzScheduler : JobFactory set to: org.springframework.scheduling.quartz.AdaptableJobFactory#20312893
2017-07-11 14:36:04.335 INFO 8868 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql]
2017-07-11 14:36:04.366 INFO 8868 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql] in 25 ms.
2017-07-11 14:36:04.733 INFO 8868 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-07-11 14:36:04.748 INFO 8868 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647
2017-07-11 14:36:04.749 INFO 8868 --- [ main] o.s.s.quartz.SchedulerFactoryBean : Starting Quartz Scheduler now
2017-07-11 14:36:04.750 INFO 8868 --- [ main] org.quartz.core.QuartzScheduler : Scheduler schedulerFactoryBean_$_NON_CLUSTERED started.
2017-07-11 14:36:04.773 INFO 8868 --- [ main] com.schwab.cat.BatchApplication : Started BatchApplication in 6.481 seconds (JVM running for 11.417)
2017-07-11 14:36:20.039 ERROR 8868 --- [ryBean_Worker-1] c.q.batch.quartz.QuartzJobLauncher : Encountered job execution exception!
2017-07-11 14:36:40.006 ERROR 8868 --- [ryBean_Worker-2] c.q.batch.quartz.QuartzJobLauncher : Encountered job execution exception!
2017-07-11 14:37:00.001 ERROR 8868 --- [ryBean_Worker-3] c.q.batch.quartz.QuartzJobLauncher : Encountered job execution exception!
2017-07-11 14:37:20.002 ERROR 8868 --- [ryBean_Worker-4] c.q.batch.quartz.QuartzJobLauncher : Encountered job execution exception!
2017-07-11 14:37:40.002 ERROR 8868 --- [ryBean_Worker-5] c.q.batch.quartz.QuartzJobLauncher : Encountered job execution exception!
2017-07-11 14:38:00.002 ERROR 8868 --- [ryBean_Worker-6] c.q.batch.quartz.QuartzJobLauncher : Encountered job execution exception!
Please someone look into it and let me know the problem.
You swallowed the exception in your try/catch and instead, you logged only the fact that exception occurrent, but not what kind of exception it was. If you change logging statement to this:
log.error("Encountered job execution exception!", e);
You'll see that the error says:
org.springframework.batch.core.launch.NoSuchJobException: No job configuration with the name [Test_Job] was registered
You have declared a job with name job1, not Test_Job so that's why you're getting the exception. You have to change job data map to:
map.put("jobName", "job1");
This will remove the exception, but your job will still run once as Spring Batch requires unique job parameters to restart it, see this answer for explanation.
So because of that, you have to modify your job execution to something like this (the simplest) to be able to run it continually:
#Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
try {
Job job = jobLocator.getJob(jobName);
Map<String, JobParameter> parametersMap = new HashMap<>();
parametersMap.put("timestamp", new JobParameter(System.currentTimeMillis()));
JobParameters jobParameters = new JobParameters(parametersMap);
JobExecution jobExecution = jobLauncher.run(job, jobParameters);
log.info("{}_{} was completed successfully", job.getName(), jobExecution.getId());
} catch (Exception e) {
log.error("Encountered job execution exception!", e);
}
}

Resources