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

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.

Related

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> {

Springboot : failed while scanning for beans

I am trying to understand a concept in springboot.
I have project structure as mentioned below. There are two packages and I have one class in each package.
src/main/java
> com.emerald.paymentengine
ApplicationRun.java
> com.emerald.paymentengine.config
DataSourceDbConfig.java
When I am trying to run the ApplicationRun.java following above structure, I am getting below error :
Error:
2020-08-19 01:33:08.673 INFO 30128 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-08-19 01:33:08.673 INFO 30128 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-08-19 01:33:08.749 INFO 30128 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-08-19 01:33:08.750 INFO 30128 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 657 ms
2020-08-19 01:33:08.779 WARN 30128 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'applicationRun': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.emerlad.paymentengine.config.DataSourceDbConfig' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2020-08-19 01:33:08.781 INFO 30128 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-08-19 01:33:08.791 INFO 30128 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-08-19 01:33:08.883 ERROR 30128 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.emerald.paymentengine.ApplicationRun required a bean of type 'com.emerlad.paymentengine.config.DataSourceDbConfig' that could not be found.
Action:
Consider defining a bean of type 'com.emerlad.paymentengine.config.DataSourceDbConfig' in your configuration.
But when I moved DataSourceDbConfig.java in the same package as mentioned below, it's running and I am getting below output :
src/main/java
> com.emerald.paymentengine
ApplicationRun.java
DataSourceDbConfig.java
Output :
2020-08-19 01:37:24.726 INFO 34364 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-08-19 01:37:24.726 INFO 34364 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-08-19 01:37:24.810 INFO 34364 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-08-19 01:37:24.810 INFO 34364 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 722 ms
2020-08-19 01:37:24.849 INFO 34364 --- [ restartedMain] f.a.AutowiredAnnotationBeanPostProcessor : Autowired annotation is not supported on static fields: static com.emerald.paymentengine.DataSourceDbConfig com.emerald.paymentengine.ApplicationRun.dbConfig
Connection established !!
2020-08-19 01:37:24.981 INFO 34364 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-19 01:37:25.116 INFO 34364 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2020-08-19 01:37:25.140 INFO 34364 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8082 (http) with context path ''
2020-08-19 01:37:25.148 INFO 34364 --- [ restartedMain] c.emerald.paymentengine.ApplicationRun : Started ApplicationRun in 1.335 seconds (JVM running for 2.406)
I was thinking #SpringBootApplication will automatically scan the main and subpackages and will be able to pick the required bean. How can I make it work by placing Config.java file in different package as mentioned in the very first scenario?
Code :
ApplicationRun.java
package com.emerald.paymentengine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ApplicationRun {
#Autowired
static
DataSourceDbConfig dbConfig;
public ApplicationRun(DataSourceDbConfig dbConfig){
ApplicationRun.dbConfig = dbConfig ;
}
public static void main(String[] args) {
SpringApplication.run(ApplicationRun.class, args);
dbConfig.dataSource();
}
}
DataSourceDbConfig.java
package com.emerlad.paymentengine.config;;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import oracle.jdbc.pool.OracleDataSource;
import java.sql.SQLException;
import javax.sql.DataSource;
#Component
#Configuration
#ConfigurationProperties("spring.datasource")
public class DataSourceDbConfig {
#Value("${spring.datasource.url}")
private String dbUrl;
#Value("${spring.datasource.username}")
private String dbUser;
#Value("${spring.datasource.secure}")
private String dbPasswrd;
#Bean
public DataSource dataSource() {
OracleDataSource dataSource = null;
try {
dataSource = new OracleDataSource();
dataSource.setUser(dbUser);
dataSource.setPassword(dbPasswrd);
dataSource.setURL(dbUrl);
System.out.println("Connection established !!");
} catch (SQLException e) {
System.out.println("An issue occured while establishing connection !!");
e.printStackTrace();
}
return dataSource;
}
}
I'll be honest, I do not understand what it is that you want to accomplish, but this is how to get the DataSource bean in your main method:
ApplicationRun.java:
package com.emerald.paymentengine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.emerlad.paymentengine.config.DataSourceDbConfig;
import org.springframework.context.annotation.Import;
import javax.sql.DataSource;
#SpringBootApplication
#Import(DataSourceDbConfig.class)
public class ApplicationRun {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(ApplicationRun.class, args);
DataSource dataSource = context.getBean(DataSource.class)
}
}
DataSourceDbConfig.java:
package com.emerlad.paymentengine.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import oracle.jdbc.pool.OracleDataSource;
import java.sql.SQLException;
import javax.sql.DataSource;
#Configuration
#ConfigurationProperties("spring.datasource")
public class DataSourceDbConfig {
#Value("${spring.datasource.url}")
private String dbUrl;
#Value("${spring.datasource.username}")
private String dbUser;
#Value("${spring.datasource.secure}")
private String dbPasswrd;
#Bean
public DataSource dataSource() {
OracleDataSource dataSource = null;
try {
dataSource = new OracleDataSource();
dataSource.setUser(dbUser);
dataSource.setPassword(dbPasswrd);
dataSource.setURL(dbUrl);
System.out.println("Connection established !!");
} catch (SQLException e) {
System.out.println("An issue occured while establishing connection !!");
e.printStackTrace();
}
return dataSource;
}
}
class DataSourceDbConfig - using #Configuration includes #Component, so you can get rid of it
class ApplicationRun - I would keep it simple and remove the DataSourceDbConfig
#SpringBootApplication
public class ApplicationRun {
public static void main(String[] args) {
ApplicationContext appContext = SpringApplication.run(ApplicationRun.class, args);
// Getting datasource from application context.
DataSource dataSource = appContext.getBean(DataSource.class);
}
}

Why Spring Boot Application logs that it started twice after adding spring-cloud-bus dependency

This is simple code in my Spring boot application:
package com.maxxton.SpringBootHelloWorld;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringBootHelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootHelloWorldApplication.class, args);
}
}
And a ApplicationListener class to listen to ApplicationEvent:
package com.maxxton.SpringBootHelloWorld;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
#Component
public class Test implements ApplicationListener {
#Override
public void onApplicationEvent(ApplicationEvent event) {
if (event.getClass().getSimpleName().equals("ApplicationReadyEvent")) {
System.out.println("-------------------------------------");
System.out.println(event.getClass().getSimpleName());
System.out.println("-------------------------------------");
}
}
}
build.gradle contains these dependencies:
dependencies {
compile("org.springframework.boot:spring-boot-starter-amqp")
compile("org.springframework.cloud:spring-cloud-starter-bus-amqp")
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter')
compile("org.springframework.cloud:spring-cloud-starter")
compile("org.springframework.cloud:spring-cloud-starter-security")
compile("org.springframework.cloud:spring-cloud-starter-eureka")
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Now, when I run this spring boot application, I see this log printed twice:
[main] c.m.S.SpringBootHelloWorldApplication : Started SpringBootHelloWorldApplication in ... seconds (JVM running for ...)
Usually, this log get printed only once, but it get printed twice if I add these dependencies:
compile("org.springframework.boot:spring-boot-starter-amqp")
compile("org.springframework.cloud:spring-cloud-starter-bus-amqp")
This is complete log:
2017-11-17 15:44:07.372 INFO 5976 --- [ main] o.s.c.support.GenericApplicationContext : Refreshing org.springframework.context.support.GenericApplicationContext#31c7c281: startup date [Fri Nov 17 15:44:07 IST 2017]; root of context hierarchy
-------------------------------------
ApplicationReadyEvent
-------------------------------------
2017-11-17 15:44:07.403 INFO 5976 --- [ main] c.m.S.SpringBootHelloWorldApplication : Started SpringBootHelloWorldApplication in 1.19 seconds (JVM running for 10.231)
2017-11-17 15:44:09.483 WARN 5976 --- [ main] o.s.amqp.rabbit.core.RabbitAdmin : Failed to declare exchange: Exchange [name=springCloudBus, type=topic, durable=true, autoDelete=false, internal=false, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:09.492 INFO 5976 --- [ main] o.s.integration.channel.DirectChannel : Channel 'a-bootiful-client.springCloudBusOutput' has 1 subscriber(s).
2017-11-17 15:44:09.493 INFO 5976 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0
2017-11-17 15:44:09.530 INFO 5976 --- [ main] o.s.i.endpoint.EventDrivenConsumer : Adding {logging-channel-adapter:_org.springframework.integration.errorLogger} as a subscriber to the 'errorChannel' channel
2017-11-17 15:44:09.530 INFO 5976 --- [ main] o.s.i.channel.PublishSubscribeChannel : Channel 'a-bootiful-client.errorChannel' has 1 subscriber(s).
2017-11-17 15:44:09.530 INFO 5976 --- [ main] o.s.i.endpoint.EventDrivenConsumer : started _org.springframework.integration.errorLogger
2017-11-17 15:44:09.530 INFO 5976 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147482647
2017-11-17 15:44:09.539 INFO 5976 --- [ main] c.s.b.r.p.RabbitExchangeQueueProvisioner : declaring queue for inbound: springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ, bound to: springCloudBus
2017-11-17 15:44:11.562 WARN 5976 --- [ main] o.s.amqp.rabbit.core.RabbitAdmin : Failed to declare exchange: Exchange [name=springCloudBus, type=topic, durable=true, autoDelete=false, internal=false, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:13.587 WARN 5976 --- [ main] o.s.amqp.rabbit.core.RabbitAdmin : Failed to declare queue: Queue [name=springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ, durable=false, autoDelete=true, exclusive=true, arguments={}], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:15.611 WARN 5976 --- [ main] o.s.amqp.rabbit.core.RabbitAdmin : Failed to declare binding: Binding [destination=springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ, exchange=springCloudBus, routingKey=#], continuing... org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect
2017-11-17 15:44:17.662 INFO 5976 --- [ main] o.s.i.a.i.AmqpInboundChannelAdapter : started inbound.springCloudBus.anonymous.kZ1vvxHaRfChKe1TncH-MQ
2017-11-17 15:44:17.662 INFO 5976 --- [ main] o.s.i.endpoint.EventDrivenConsumer : Adding {message-handler:inbound.springCloudBus.default} as a subscriber to the 'bridge.springCloudBus' channel
2017-11-17 15:44:17.662 INFO 5976 --- [ main] o.s.i.endpoint.EventDrivenConsumer : started inbound.springCloudBus.default
2017-11-17 15:44:17.663 INFO 5976 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647
2017-11-17 15:44:17.714 INFO 5976 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
-------------------------------------
ApplicationReadyEvent
-------------------------------------
2017-11-17 15:44:17.717 INFO 5976 --- [ main] c.m.S.SpringBootHelloWorldApplication : Started SpringBootHelloWorldApplication in 20.131 seconds (JVM running for 20.545)
As you can see, ApplicationReadyEvent is happening twice.
Why is this happening?
Is there any way to avoid this?
spring-cloud-bus uses spring-cloud-stream which puts the binder in a separate boot child application context.
You should make your event listener aware of the application context it is running in. You can also use generics to select the event type you are interested in...
#Component
public class Test implements ApplicationListener<ApplicationReadyEvent>,
ApplicationContextAware {
private ApplicationContext applicationContext;
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
#Override
public void onApplicationEvent(ApplicationReadyEvent event) {
if (event.getApplicationContext().equals(this.applicationContext)) {
System.out.println("-------------------------------------");
System.out.println(event.getClass().getSimpleName());
System.out.println("-------------------------------------");
}
}
}
Are u using multiple binders rabbitmq configuration in your application.yml/.xml ?
If it's a yes, then u can try to exclude RabbitAutoConfiguration.
#EnableDiscoveryClient
#EnableAutoConfiguration(exclude = {RabbitAutoConfiguration.class})
#SpringBootApplication
public class SpringBootHelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootHelloWorldApplication.class, args);
}
}

Spring Boot AMQP Receiver

I'm creating a simple Spring Boot app that I want to receive messages sent to an AMQP (Rabbit) exchange (from another application).
I am getting an error stating that the queue i'm to receive on does not exists. When I look at http://localhost:15672/#/queues i can see that it does; i delete it before starting this application.
I read on another post that if a queue does not exists, RabbitAdmin has to be declared and declareExchange() and declareQueue() used to overcome this.
Even with this in place I'm still seeing the same error. Furthermore, the error is confusing b/c it states:
Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method(reply-code=404, reply-text=NOT_FOUND - no queue 'from-logger-exchange' in vhost '/', class-id=50, method-id=10)
Note the 'no queue' indicates my exchange name.
Here's the configuration code (i realize that Boot creates the connectionFactory & RabbitAdmin but started adding these when that wasn't working):
'import javax.annotation.PostConstruct;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class Config {
#Value("${spring.activemq.broker-url}")
String host;
#Value("${spring.activemq.user}")
String userName;
#Value("${spring.activemq.password}")
String password;
#Value("${config.exchangeName}")
String exchangeName;
#Value("${config.queueName}")
String queueName;
#PostConstruct
public void printVariables() {
System.out.println("host " + host);
System.out.println("userName " + userName);
System.out.println("password " + password);
System.out.println("exchangeName " + exchangeName);
System.out.println("queueName " + queueName);
System.out.println("queue.name " + queue().getName());
System.out.println("exchange.name " + topicExchange().getName());
System.out.println("binding " + binding().toString());
System.out.println("connectionFactory " + connectionFactory().toString());
System.out.println("rabbitAdmin " + rabbitAdmin().toString());
}
#Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host);
connectionFactory.setUsername(userName);
connectionFactory.setPassword(password);
return connectionFactory;
}
#Bean
public RabbitAdmin rabbitAdmin() {
RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory());
rabbitAdmin.declareExchange(topicExchange());
rabbitAdmin.declareQueue(queue());
return rabbitAdmin;
}
#Bean
public Queue queue() {
return new Queue(queueName);
}
// #Bean
// public FanoutExchange fanoutExchange() {
// return new FanoutExchange(exchangeName);
// }
public TopicExchange topicExchange() {
return new TopicExchange(exchangeName, false, true);
}
#Bean
public Binding binding() {
//return BindingBuilder.bind(queue()).to(fanoutExchange());
return BindingBuilder.bind(queue()).to(topicExchange()).with("my.routing.key");
}
#Bean
public Receiver receiver() {
return new Receiver();
}
}
'
Here's the Receiver:
import org.springframework.amqp.rabbit.annotation.RabbitListener;
public class Receiver {
#RabbitListener(queues="${config.exchangeName}")
public void receive(String input) {
System.out.println(" Receiver#receive input: " + input);
}
}
Here's the first bit of the console output:
. ____ _ __
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.3.2.RELEASE)
2016-02-23 10:20:47.710 INFO 18804 --- [ main] c.i.logging.receiver.Application : Starting Application on INT002520 with PID 18804 (C:\Users\matt.aspen\Documents\_logging\log-message-receiver2\target\classes started by matt.aspen in C:\Users\matt.aspen\Documents\_logging\log-message-receiver2)
2016-02-23 10:20:47.710 INFO 18804 --- [ main] c.i.logging.receiver.Application : No active profile set, falling back to default profiles: default
2016-02-23 10:20:47.710 DEBUG 18804 --- [ main] o.s.boot.SpringApplication : Loading source class com.intelligrated.logging.receiver.Application
2016-02-23 10:20:47.750 DEBUG 18804 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Loaded config file 'classpath:/application.properties'
2016-02-23 10:20:47.750 DEBUG 18804 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped (empty) config file 'classpath:/application.properties' for profile default
2016-02-23 10:20:47.750 INFO 18804 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#679b62af: startup date [Tue Feb 23 10:20:47 PST 2016]; root of context hierarchy
2016-02-23 10:20:48.482 INFO 18804 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.amqp.rabbit.annotation.RabbitBootstrapConfiguration' of type [class org.springframework.amqp.rabbit.annotation.RabbitBootstrapConfiguration$$EnhancerBySpringCGLIB$$68858653] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
host localhost
userName guest
password guest
exchangeName from-logger-exchange
queueName from-logger-queue
queue.name from-logger-queue
exchange.name from-logger-exchange
binding Binding [destination=from-logger-queue, exchange=from-logger-exchange, routingKey=my.routing.key]
connectionFactory CachingConnectionFactory [channelCacheSize=1, host=localhost, port=5672, active=true connectionFactory]
2016-02-23 10:20:48.642 INFO 18804 --- [ main] o.s.a.r.c.CachingConnectionFactory : Created new connection: SimpleConnection#6239aba6 [delegate=amqp://guest#127.0.0.1:5672/]
rabbitAdmin org.springframework.amqp.rabbit.core.RabbitAdmin#5f354bcf
2016-02-23 10:20:48.753 DEBUG 18804 --- [ main] inMXBeanRegistrar$SpringApplicationAdmin : Application Admin MBean registered with name 'org.springframework.boot:type=Admin,name=SpringApplication'
2016-02-23 10:20:48.998 INFO 18804 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-02-23 10:20:49.208 INFO 18804 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase -2147482648
2016-02-23 10:20:49.208 INFO 18804 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647
2016-02-23 10:20:49.218 WARN 18804 --- [cTaskExecutor-1] o.s.a.r.listener.BlockingQueueConsumer : Failed to declare queue:from-logger-exchange
2016-02-23 10:20:49.228 WARN 18804 --- [cTaskExecutor-1] o.s.a.r.listener.BlockingQueueConsumer : Queue declaration failed; retries left=3
org.springframework.amqp.rabbit.listener.BlockingQueueConsumer$DeclarationException: Failed to declare queue(s):[from-logger-exchange]
at org.springframework.amqp.rabbit.listener.BlockingQueueConsumer.attemptPassiveDeclarations(BlockingQueueConsumer.java:571) ~[spring-rabbit-1.5.3.RELEASE.jar:na]
at org.springframework.amqp.rabbit.listener.BlockingQueueConsumer.start(BlockingQueueConsumer.java:470) ~[spring-rabbit-1.5.3.RELEASE.jar:na]
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1171) [spring-rabbit-1.5.3.RELEASE.jar:na]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_40]
Caused by: java.io.IOException: null
at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:106) ~[amqp-client-3.5.7.jar:na]
at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:102) ~[amqp-client-3.5.7.jar:na]
at com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc(AMQChannel.java:124) ~[amqp-client-3.5.7.jar:na]
at com.rabbitmq.client.impl.ChannelN.queueDeclarePassive(ChannelN.java:885) ~[amqp-client-3.5.7.jar:na]
at com.rabbitmq.client.impl.ChannelN.queueDeclarePassive(ChannelN.java:61) ~[amqp-client-3.5.7.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_40]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_40]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_40]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_40]
at org.springframework.amqp.rabbit.connection.CachingConnectionFactory$CachedChannelInvocationHandler.invoke(CachingConnectionFactory.java:764) ~[spring-rabbit-1.5.3.RELEASE.jar:na]
at com.sun.proxy.$Proxy31.queueDeclarePassive(Unknown Source) ~[na:na]
at org.springframework.amqp.rabbit.listener.BlockingQueueConsumer.attemptPassiveDeclarations(BlockingQueueConsumer.java:550) ~[spring-rabbit-1.5.3.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 'from-logger-exchange' in vhost '/', class-id=50, method-id=10)
at com.rabbitmq.utility.ValueOrException.getValue(ValueOrException.java:67) ~[amqp-client-3.5.7.jar:na]
at com.rabbitmq.utility.BlockingValueOrException.uninterruptibleGetValue(BlockingValueOrException.java:33) ~[amqp-client-3.5.7.jar:na]
at com.rabbitmq.client.impl.AMQChannel$BlockingRpcContinuation.getReply(AMQChannel.java:361) ~[amqp-client-3.5.7.jar:na]
at com.rabbitmq.client.impl.AMQChannel.privateRpc(AMQChannel.java:226) ~[amqp-client-3.5.7.jar:na]
at com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc(AMQChannel.java:118) ~[amqp-client-3.5.7.jar:na]
... 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 'from-logger-exchange' in vhost '/', class-id=50, method-id=10)
at com.rabbitmq.client.impl.ChannelN.asyncShutdown(ChannelN.java:484) ~[amqp-client-3.5.7.jar:na]
at com.rabbitmq.client.impl.ChannelN.processAsync(ChannelN.java:321) ~[amqp-client-3.5.7.jar:na]
at com.rabbitmq.client.impl.AMQChannel.handleCompleteInboundCommand(AMQChannel.java:144) ~[amqp-client-3.5.7.jar:na]
at com.rabbitmq.client.impl.AMQChannel.handleFrame(AMQChannel.java:91) ~[amqp-client-3.5.7.jar:na]
at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:554) ~[amqp-client-3.5.7.jar:na]
... 1 common frames omitted
2016-02-23 10:20:54.226 WARN 18804 --- [cTaskExecutor-1] o.s.a.r.listener.BlockingQueueConsumer : Failed to declare queue:from-logger-exchange
2016-02-23 10:20:54.226 WARN 18804 --- [cTaskExecutor-1] o.s.a.r.listener.BlockingQueueConsumer : Queue declaration failed; retries left=2
What's even more confusing is that when i look at http://localhost:15672/#/connections i see the connection, http://localhost:15672/#/channels i see the channel, http://localhost:15672/#/exchanges i see "from-logger-exchange", and http://localhost:15672/#/queues i see "from-logger-queue"
One problem is your exchange is not a #Bean.
I get
reply-code=404, reply-text=NOT_FOUND - no exchange 'from.logging.exchange' in vhost '/', class-id=50, method-id=20)
with your config. Adding #Bean to the exchange fixes it.
EDIT
Also (as Artem points out below), you have the wrong property on the listener
#RabbitListener(queues="${config.exchangeName}")
should be
#RabbitListener(queues="${config.queueName}")

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

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]

Resources