Randomly getting java.util.concurrent.TimeoutException at com.rabbitmq.utility.BlockingCell.get(BlockingCell.java:77) sending message on RabbitMQ - spring

While sending message on RabbitMQ, I am getting following exception randomly
2021-05-26 11:31:03.274 INFO 6728 --- [nio-8080-exec-1] o.s.a.r.c.CachingConnectionFactory : Attempting to connect to: [<<My Server IP>>:5672]
2021-05-26 11:31:09.653 WARN 6728 --- [0.3.52.168:5672] c.r.c.impl.ForgivingExceptionHandler : An unexpected connection driver error occured (Exception message: Socket closed)
2021-05-26 11:31:09.660 ERROR 6728 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.amqp.AmqpTimeoutException: java.util.concurrent.TimeoutException] with root cause
java.util.concurrent.TimeoutException: null
at com.rabbitmq.utility.BlockingCell.get(BlockingCell.java:77) ~[amqp-client-5.10.0.jar:5.10.0]
at com.rabbitmq.utility.BlockingCell.uninterruptibleGet(BlockingCell.java:120) ~[amqp-client-5.10.0.jar:5.10.0]
at com.rabbitmq.utility.BlockingValueOrException.uninterruptibleGetValue(BlockingValueOrException.java:36) ~[amqp-client-5.10.0.jar:5.10.0]
at com.rabbitmq.client.impl.AMQChannel$BlockingRpcContinuation.getReply(AMQChannel.java:502) ~[amqp-client-5.10.0.jar:5.10.0]
at com.rabbitmq.client.impl.AMQChannel.privateRpc(AMQChannel.java:330) ~[amqp-client-5.10.0.jar:5.10.0]
at com.rabbitmq.client.impl.AMQChannel.rpc(AMQChannel.java:275) ~[amqp-client-5.10.0.jar:5.10.0]
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:373) ~[amqp-client-5.10.0.jar:5.10.0]
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1139) ~[amqp-client-5.10.0.jar:5.10.0]
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:1087) ~[amqp-client-5.10.0.jar:5.10.0]
at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.connectAddresses(AbstractConnectionFactory.java:638) ~[spring-rabbit-2.3.5.jar:2.3.5]
at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.connect(AbstractConnectionFactory.java:613) ~[spring-rabbit-2.3.5.jar:2.3.5]
at org.springframework.amqp.rabbit.connection.AbstractConnectionFactory.createBareConnection(AbstractConnectionFactory.java:565) ~[spring-rabbit-2.3.5.jar:2.3.5]
at org.springframework.amqp.rabbit.connection.CachingConnectionFactory.createConnection(CachingConnectionFactory.java:724) ~[spring-rabbit-2.3.5.jar:2.3.5]
at org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils.createConnection(ConnectionFactoryUtils.java:214) ~[spring-rabbit-2.3.5.jar:2.3.5]
at org.springframework.amqp.rabbit.core.RabbitTemplate.doExecute(RabbitTemplate.java:2132) ~[spring-rabbit-2.3.5.jar:2.3.5]
at org.springframework.amqp.rabbit.core.RabbitTemplate.execute(RabbitTemplate.java:2105) ~[spring-rabbit-2.3.5.jar:2.3.5]
at org.springframework.amqp.rabbit.core.RabbitTemplate.send(RabbitTemplate.java:1049) ~[spring-rabbit-2.3.5.jar:2.3.5]
at org.springframework.amqp.rabbit.core.RabbitTemplate.convertAndSend(RabbitTemplate.java:1114) ~[spring-rabbit-2.3.5.jar:2.3.5]
at org.springframework.amqp.rabbit.core.RabbitTemplate.convertAndSend(RabbitTemplate.java:1107) ~[spring-rabbit-2.3.5.jar:2.3.5]
at com.ukg.testbed.service.impl.RabbitMQSender.send(RabbitMQSender.java:23) ~[main/:na]
at com.ukg.testbed.service.impl.EmployeeServiceImpl.createEmployee(EmployeeServiceImpl.java:42) ~[main/:na]
at com.ukg.testbed.service.impl.EmployeeServiceImpl$$FastClassBySpringCGLIB$$77b5167b.invoke(<generated>) ~[main/:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.3.4.jar:5.3.4]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.3.4.jar:5.3.4]
at com.ukg.testbed.service.impl.EmployeeServiceImpl$$EnhancerBySpringCGLIB$$70140a97.createEmployee(<generated>) ~[main/:na]
at com.ukg.testbed.controller.EmployeeController.registerNewEmployee(EmployeeController.java:36) ~[main/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[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:566) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197) ~[spring-web-5.3.4.jar:5.3.4]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141) ~[spring-web-5.3.4.jar:5.3.4]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.3.4.jar:5.3.4]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894) ~[spring-webmvc-5.3.4.jar:5.3.4]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.4.jar:5.3.4]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.4.jar:5.3.4]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060) ~[spring-webmvc-5.3.4.jar:5.3.4]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962) ~[spring-webmvc-5.3.4.jar:5.3.4]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.4.jar:5.3.4]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.3.4.jar:5.3.4]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:652) ~[tomcat-embed-core-9.0.43.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.4.jar:5.3.4]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.43.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.43.jar:9.0.43]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.4.jar:5.3.4]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.4.jar:5.3.4]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.4.jar:5.3.4]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.4.jar:5.3.4]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.4.jar:5.3.4]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.4.jar:5.3.4]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:346) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:887) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1684) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.43.jar:9.0.43]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
My code for sending
#Service
public class RabbitMQSender {
#Autowired
private AmqpTemplate kRabbitTemplate;
#Value("${rmq.test.exchange}")
private String exchange;
#Value("${rmq.test.routingkey}")
private String routingkey;
public void send(EmpDTO empDTO) {
System.out.println("Sending msg = " + empDTO);
kRabbitTemplate.convertAndSend(exchange, routingkey, empDTO);
System.out.println("Sent msg = " + empDTO);
}
}
And this is the config :
#Configuration
public class RabbitMQConfig {
#Value("${rmq.test.queue}")
String queueName;
#Value("${rmq.test.exchange}")
String exchange;
#Value("${rmq.test.routingkey}")
private String routingkey;
#Bean
Queue kQueue() {
return new Queue(queueName, false);
}
#Bean
DirectExchange kExchange() {
return new DirectExchange(exchange);
}
#Bean
Binding kBinding(Queue queue, DirectExchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with(routingkey);
}
#Bean
public MessageConverter kJsonMessageConverter() {
return new Jackson2JsonMessageConverter();
}
#Bean
public AmqpTemplate kRabbitTemplate(ConnectionFactory connectionFactory) {
final RabbitTemplate kRabbitTemplate = new RabbitTemplate(connectionFactory);
kRabbitTemplate.setMessageConverter(kJsonMessageConverter());
return kRabbitTemplate;
}
}
I have checked following
Disk / CPU / Memory Utilization are ok on server
Maximum time connection is established so ruling out config issues.
This has been very frequent for multiple queues in Production env.
This is also happening for flows where we send message in Transaction.
"Caused By": {
"com.rabbitmq.client.ChannelContinuationTimeoutException: Continuation call for method #method<tx.commit>() on channel AMQChannel(amqp://myvhost#<RMQHOST>:5672/myvhost,1) (#1) timed out": ["AMQChannel.java", 313, "com.rabbitmq.client.impl.AMQChannel.wrapTimeoutException", "AMQChannel.java", 295, "com.rabbitmq.client.impl.AMQChannel.privateRpc", "AMQChannel.java", 141, "com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc", "ChannelN.java", 1540, "com.rabbitmq.client.impl.ChannelN.txCommit", "ChannelN.java", 52, "com.rabbitmq.client.impl.ChannelN.txCommit", "", -1, "sun.reflect.GeneratedMethodAccessor435.invoke", "DelegatingMethodAccessorImpl.java", 43, "sun.reflect.DelegatingMethodAccessorImpl.invoke", "Method.java", 498, "java.lang.reflect.Method.invoke", "CachingConnectionFactory.java", 1190, "org.springframework.amqp.rabbit.connection.CachingConnectionFactory$CachedChannelInvocationHandler.invoke", "", -1, "com.sun.proxy.$Proxy941.txCommit", "RabbitResourceHolder.java", 153, "org.springframework.amqp.rabbit.connection.RabbitResourceHolder.commitAll"],
"Caused By": {
"java.util.concurrent.TimeoutException": ["BlockingCell.java", 77, "com.rabbitmq.utility.BlockingCell.get", "BlockingCell.java", 120, "com.rabbitmq.utility.BlockingCell.uninterruptibleGet", "BlockingValueOrException.java", 36, "com.rabbitmq.utility.BlockingValueOrException.uninterruptibleGetValue", "AMQChannel.java", 502, "com.rabbitmq.client.impl.AMQChannel$BlockingRpcContinuation.getReply", "AMQChannel.java", 293, "com.rabbitmq.client.impl.AMQChannel.privateRpc"]
}
}

You can add a RetryTemplate to the RabbitTemplate to retry sends when there are connection problems.
As I commented, you should check the server logs to see if there are clues for the failure.
EDIT
This test shows it works as expected:
#Test
public void testRetryOnCommitException() throws Exception {
ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
final AtomicInteger count = new AtomicInteger();
Connection mockConnection = mock(Connection.class);
Channel mockChannel = mock(Channel.class);
given(mockConnectionFactory.newConnection(any(ExecutorService.class), anyString())).willReturn(mockConnection);
given(mockConnection.isOpen()).willReturn(true);
given(mockConnection.createChannel()).willReturn(mockChannel);
willAnswer(invocation -> {
count.incrementAndGet();
throw new IOException("commitFailed");
}).given(mockChannel).txCommit();
SingleConnectionFactory connectionFactory = new SingleConnectionFactory(mockConnectionFactory);
connectionFactory.setExecutor(mock(ExecutorService.class));
RabbitTemplate template = new RabbitTemplate(connectionFactory);
template.setChannelTransacted(true);
template.setRetryTemplate(new RetryTemplate());
try {
template.convertAndSend("foo", "bar", "baz");
}
catch (Exception e) {
assertThat(e.getMessage()).contains("commitFailed");
}
assertThat(count.get()).isEqualTo(3);
}
EDIT2
This test simulates your ChannelContinuationTimeoutException problem:
#Test
public void testRetryOnCommitException() throws Exception {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory("localhost");
connectionFactory.getRabbitConnectionFactory().setChannelRpcTimeout(1);
RabbitTemplate template = new RabbitTemplate(connectionFactory);
template.setChannelTransacted(true);
template.setRetryTemplate(new RetryTemplate());
assertThatExceptionOfType(AmqpIOException.class).isThrownBy(() -> template.convertAndSend(ROUTE, "commitError"))
.withCauseExactlyInstanceOf(ChannelContinuationTimeoutException.class);
}
And in the debugger, I see the send being tried 3 times, as expected.
And here are debug logs...
2021-06-10 09:23:20,135 INFO org.springframework.amqp.rabbit.junit.LogLevelsCondition [main] : +++++++++++++++++++++++++++++ Begin testRetryOnCommitException
2021-06-10 09:23:20,169 DEBUG org.springframework.retry.support.RetryTemplate [main] : Retry: count=0
2021-06-10 09:23:20,175 INFO org.springframework.amqp.rabbit.connection.CachingConnectionFactory [main] : Attempting to connect to: localhost:5672
2021-06-10 09:23:20,185 INFO org.springframework.amqp.rabbit.connection.CachingConnectionFactory [main] : Created new connection: SpringAMQP#706ddbc8:0/SimpleConnection#6397248c [delegate=amqp://guest#127.0.0.1:5672/, localPort= 53720]
2021-06-10 09:23:20,199 DEBUG org.springframework.amqp.rabbit.core.RabbitTemplate [main] : Executing callback RabbitTemplate$$Lambda$548/0x0000000800cffdb8 on RabbitMQ Channel: Cached Rabbit Channel: AMQChannel(amqp://guest#127.0.0.1:5672/,1), conn: Proxy#2d2b6960 Shared Rabbit Connection: SimpleConnection#6397248c [delegate=amqp://guest#127.0.0.1:5672/, localPort= 53720]
2021-06-10 09:23:20,199 DEBUG org.springframework.amqp.rabbit.core.RabbitTemplate [main] : Publishing message [(Body:'commitError' MessageProperties [headers={}, contentType=text/plain, contentEncoding=UTF-8, contentLength=11, deliveryMode=PERSISTENT, priority=0, deliveryTag=0])] on exchange [], routingKey = [test.queue.RabbitTemplateIntegrationTests]
2021-06-10 09:23:20,204 INFO org.springframework.amqp.rabbit.connection.CachingConnectionFactory [main] : Attempting to connect to: localhost:5672
09:23:20.206 [AMQP Connection 127.0.0.1:5672] WARN c.r.c.impl.ForgivingExceptionHandler - An unexpected connection driver error occured (Exception message: Connection reset)
2021-06-10 09:23:20,211 INFO org.springframework.amqp.rabbit.connection.CachingConnectionFactory [main] : Created new connection: SpringAMQP#706ddbc8:1/SimpleConnection#76ff68c5 [delegate=amqp://guest#127.0.0.1:5672/, localPort= 53721]
2021-06-10 09:23:20,213 DEBUG org.springframework.retry.support.RetryTemplate [main] : Checking for rethrow: count=1
2021-06-10 09:23:20,213 DEBUG org.springframework.retry.support.RetryTemplate [main] : Retry: count=1
2021-06-10 09:23:20,213 DEBUG org.springframework.amqp.rabbit.core.RabbitTemplate [main] : Executing callback RabbitTemplate$$Lambda$548/0x0000000800cffdb8 on RabbitMQ Channel: Cached Rabbit Channel: AMQChannel(amqp://guest#127.0.0.1:5672/,1), conn: Proxy#2d2b6960 Shared Rabbit Connection: SimpleConnection#76ff68c5 [delegate=amqp://guest#127.0.0.1:5672/, localPort= 53721]
2021-06-10 09:23:20,213 DEBUG org.springframework.amqp.rabbit.core.RabbitTemplate [main] : Publishing message [(Body:'commitError' MessageProperties [headers={}, contentType=text/plain, contentEncoding=UTF-8, contentLength=11, deliveryMode=PERSISTENT, priority=0, deliveryTag=0])] on exchange [], routingKey = [test.queue.RabbitTemplateIntegrationTests]
2021-06-10 09:23:20,216 INFO org.springframework.amqp.rabbit.connection.CachingConnectionFactory [main] : Attempting to connect to: localhost:5672
09:23:20.216 [AMQP Connection 127.0.0.1:5672] WARN c.r.c.impl.ForgivingExceptionHandler - An unexpected connection driver error occured (Exception message: Connection reset)
2021-06-10 09:23:20,226 INFO org.springframework.amqp.rabbit.connection.CachingConnectionFactory [main] : Created new connection: SpringAMQP#706ddbc8:2/SimpleConnection#1da1380b [delegate=amqp://guest#127.0.0.1:5672/, localPort= 53722]
2021-06-10 09:23:20,228 DEBUG org.springframework.retry.support.RetryTemplate [main] : Checking for rethrow: count=2
2021-06-10 09:23:20,228 DEBUG org.springframework.retry.support.RetryTemplate [main] : Retry: count=2
2021-06-10 09:23:20,228 DEBUG org.springframework.amqp.rabbit.core.RabbitTemplate [main] : Executing callback RabbitTemplate$$Lambda$548/0x0000000800cffdb8 on RabbitMQ Channel: Cached Rabbit Channel: AMQChannel(amqp://guest#127.0.0.1:5672/,1), conn: Proxy#2d2b6960 Shared Rabbit Connection: SimpleConnection#1da1380b [delegate=amqp://guest#127.0.0.1:5672/, localPort= 53722]
2021-06-10 09:23:20,228 DEBUG org.springframework.amqp.rabbit.core.RabbitTemplate [main] : Publishing message [(Body:'commitError' MessageProperties [headers={}, contentType=text/plain, contentEncoding=UTF-8, contentLength=11, deliveryMode=PERSISTENT, priority=0, deliveryTag=0])] on exchange [], routingKey = [test.queue.RabbitTemplateIntegrationTests]
2021-06-10 09:23:20,231 INFO org.springframework.amqp.rabbit.connection.CachingConnectionFactory [main] : Attempting to connect to: localhost:5672
09:23:20.232 [AMQP Connection 127.0.0.1:5672] WARN c.r.c.impl.ForgivingExceptionHandler - An unexpected connection driver error occured (Exception message: Connection reset)
2021-06-10 09:23:20,239 INFO org.springframework.amqp.rabbit.connection.CachingConnectionFactory [main] : Created new connection: SpringAMQP#706ddbc8:3/SimpleConnection#2accaec2 [delegate=amqp://guest#127.0.0.1:5672/, localPort= 53723]
2021-06-10 09:23:20,240 DEBUG org.springframework.retry.support.RetryTemplate [main] : Checking for rethrow: count=3
2021-06-10 09:23:20,240 DEBUG org.springframework.retry.support.RetryTemplate [main] : Retry failed last attempt: count=3

Related

Exception Handler method not getting invoked spring boot

#ControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler{
#ExceptionHandler
public final ResponseEntity<Object> handleOrgIdException(OrgIdException ex, WebRequest request){
GeneralExceptionResponse exceptionResponse = new GeneralExceptionResponse("-1", ex.getMessage());
return new ResponseEntity(exceptionResponse, HttpStatus.BAD_REQUEST);
}
}
public class OrgIdException extends RuntimeException{
private static final long serialVersionUID = 1L;
public OrgIdException(String message){
super(message);
}
}
#RestController
#Api(tags = "sample")
#RequestMapping(path = "v1", produces = { MediaType.APPLICATION_JSON_VALUE})
public class SampleEndpoint extends AbstractEndpoint {
#GetMapping("badrequest")
public ResponseEntity<SampleObject> doBadRequest(Principal p) throws Exception {
throw new OrgIdException("exception thrown.....");
}
}
Server Logs :
2020-01-27 19:16:34,708 INFO [http-nio-8080-exec-1] [] [] [] org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-01-27 19:16:34,713 INFO [http-nio-8080-exec-1] [] [] [] org.springframework.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-01-27 19:16:34,748 INFO [http-nio-8080-exec-1] [] [] [] org.springframework.web.servlet.DispatcherServlet : Completed initialization in 34 ms
2020-01-27 19:16:34,893 ERROR [http-nio-8080-exec-1] [] [LOCAL] [] com.mckesson.lib.spring.controller.RestController : Failed to process the request
com.mckesson.ms.template.v1.exception.OrgIdException: exception thrown.....
at com.mckesson.ms.template.v1.endpoint.SampleEndpoint.doBadRequest(SampleEndpoint.java:32) ~[main/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_221]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_221]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_221]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_221]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) [spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) [spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:645) [javax.servlet-api-4.0.1.jar:4.0.1]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) [spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:750) [javax.servlet-api-4.0.1.jar:4.0.1]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-9.0.16.jar:9.0.16]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.16.jar:9.0.16]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) [tomcat-embed-websocket-9.0.16.jar:9.0.16]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.16.jar:9.0.16]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.16.jar:9.0.16]
I am using spring boot application. Can anyone please suggest, why Exception handler method is not getting called? When I add the exception handler method to my controller itself then it works fine.
Just try with a simple class like this.
#ControllerAdvice
public class MyControllerAdvice {
#ResponseBody
#ExceptionHandler(OrgIdException.class)
#ResponseStatus(HttpStatus.BAD_REQUEST)
public GeneralExceptionResponse handlePersonNotFound(OrgIdException ex) {
return new GeneralExceptionResponse("-1", ex.getMessage());
}
}
Can create one global exception handler to handle http exception via extent ResponseEntityExceptionHandler
#ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
#Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", new Date());
body.put("status", status.value());
//Get all errors
List<String> errors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(x -> x.getDefaultMessage())
.collect(Collectors.toList());
body.put("errors", errors);
return new ResponseEntity<>(body, headers, status);
}

Spring WebSocket Stomp Exception Handling

I am trying to use Websockets and STOMP 1.2. I want to authenticate user using JWT on CONNECT frame and to return error message if authorization is not valid. Here is channel interceptor
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer
{
// ... Removed for readability
#Override
public void configureClientInboundChannel(ChannelRegistration registration)
{
registration.interceptors(new ChannelInterceptor()
{
#Override
public Message<?> preSend(Message<?> message, MessageChannel channel)
{
StompHeaderAccessor accessor =
MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
if (accessor != null && StompCommand.CONNECT.equals(accessor.getCommand()))
{
String token = accessor.getFirstNativeHeader(authorizationHeader);
if (token != null)
{
Authentication authentication = tokenUtil.getAuthentication(resolveToken(token));
accessor.setUser(authentication);
}
else
{
throw new UnauthorizedException();
}
}
return message;
}
});
}
}
This way the error stack will have
Failed to send client message to application via MessageChannel in session a63cf95f-4a5b-ef34-b74b-3264ec6dd61f. Sending STOMP ERROR to client.
org.springframework.messaging.MessageDeliveryException: Failed to send message to ExecutorSubscribableChannel[clientInboundChannel]; nested exception is com.example.error.exception.UnauthorizedException: You are not authorized. Please log in.
at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:146) ~[spring-messaging-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:122) ~[spring-messaging-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.web.socket.messaging.StompSubProtocolHandler.handleMessageFromClient(StompSubProtocolHandler.java:284) ~[spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.web.socket.messaging.SubProtocolWebSocketHandler.handleMessage(SubProtocolWebSocketHandler.java:324) [spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.web.socket.handler.WebSocketHandlerDecorator.handleMessage(WebSocketHandlerDecorator.java:75) [spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.web.socket.handler.LoggingWebSocketHandlerDecorator.handleMessage(LoggingWebSocketHandlerDecorator.java:56) [spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.web.socket.handler.ExceptionWebSocketHandlerDecorator.handleMessage(ExceptionWebSocketHandlerDecorator.java:58) [spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.handleTextMessage(StandardWebSocketHandlerAdapter.java:113) [spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.access$000(StandardWebSocketHandlerAdapter.java:42) [spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter$3.onMessage(StandardWebSocketHandlerAdapter.java:84) [spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter$3.onMessage(StandardWebSocketHandlerAdapter.java:81) [spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.apache.tomcat.websocket.WsFrameBase.sendMessageText(WsFrameBase.java:395) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
at org.apache.tomcat.websocket.server.WsFrameServer.sendMessageText(WsFrameServer.java:119) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
at org.apache.tomcat.websocket.WsFrameBase.processDataText(WsFrameBase.java:495) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
at org.apache.tomcat.websocket.WsFrameBase.processData(WsFrameBase.java:294) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
at org.apache.tomcat.websocket.WsFrameBase.processInputBuffer(WsFrameBase.java:133) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
at org.apache.tomcat.websocket.server.WsFrameServer.onDataAvailable(WsFrameServer.java:82) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
at org.apache.tomcat.websocket.server.WsFrameServer.doOnDataAvailable(WsFrameServer.java:171) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
at org.apache.tomcat.websocket.server.WsFrameServer.notifyDataAvailable(WsFrameServer.java:151) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler.upgradeDispatch(WsHttpUpgradeHandler.java:148) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
at org.apache.coyote.http11.upgrade.UpgradeProcessorInternal.dispatch(UpgradeProcessorInternal.java:54) [tomcat-embed-core-9.0.12.jar:9.0.12]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:53) [tomcat-embed-core-9.0.12.jar:9.0.12]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:770) [tomcat-embed-core-9.0.12.jar:9.0.12]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415) [tomcat-embed-core-9.0.12.jar:9.0.12]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.12.jar:9.0.12]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.12.jar:9.0.12]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]
Caused by: com.example.error.exception.UnauthorizedException: You are not authorized. Please log in.
at com.exampleconfig.WebSocketConfig$1.preSend(WebSocketConfig.java:74) ~[classes/:na]
at org.springframework.messaging.support.AbstractMessageChannel$ChannelInterceptorChain.applyPreSend(AbstractMessageChannel.java:178) ~[spring-messaging-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:132) ~[spring-messaging-5.1.2.RELEASE.jar:5.1.2.RELEASE]
... 28 common frames omitted
And similar error will be sent to client end connection will be closed.
But after the connection is closed, other stack trace is written as output:
2018-11-11 01:06:48.077 DEBUG 7259 --- [nio-8080-exec-2] s.w.s.h.LoggingWebSocketHandlerDecorator : StandardWebSocketSession[id=a63cf95f-4a5b-ef34-b74b-3264ec6dd61f, uri=/api/ws] closed with CloseStatus[code=1000, reason=null]
2018-11-11 01:06:48.077 DEBUG 7259 --- [nio-8080-exec-2] o.s.w.s.m.SubProtocolWebSocketHandler : Clearing session a63cf95f-4a5b-ef34-b74b-3264ec6dd61f
2018-11-11 01:06:48.084 DEBUG 7259 --- [nio-8080-exec-2] org.springframework.web.SimpLogging : Detected unsent DISCONNECT message. Processing anyway.
2018-11-11 01:06:48.085 DEBUG 7259 --- [nio-8080-exec-2] org.springframework.web.SimpLogging : Processing DISCONNECT session=a63cf95f-4a5b-ef34-b74b-3264ec6dd61f
2018-11-11 01:06:48.086 DEBUG 7259 --- [tboundChannel-1] o.s.w.s.m.SubProtocolWebSocketHandler : No session for GenericMessage [payload=byte[0], headers={simpMessageType=DISCONNECT_ACK, simpDisconnectMessage=GenericMessage [payload=byte[0], headers={simpMessageType=DISCONNECT, stompCommand=DISCONNECT, simpSessionAttributes={org.springframework.messaging.simp.SimpAttributes.COMPLETED=true}, simpSessionId=a63cf95f-4a5b-ef34-b74b-3264ec6dd61f}], simpSessionId=a63cf95f-4a5b-ef34-b74b-3264ec6dd61f}]
2018-11-11 01:06:48.087 WARN 7259 --- [nio-8080-exec-2] w.s.h.ExceptionWebSocketHandlerDecorator : Unhandled exception after connection closed for ExceptionWebSocketHandlerDecorator [delegate=LoggingWebSocketHandlerDecorator [delegate=SubProtocolWebSocketHandler[StompSubProtocolHandler[v10.stomp, v11.stomp, v12.stomp]]]]
org.springframework.messaging.MessageDeliveryException: Failed to send message to ExecutorSubscribableChannel[clientInboundChannel]; nested exception is org.springframework.security.access.AccessDeniedException: Access is denied
at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:146) ~[spring-messaging-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:122) ~[spring-messaging-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.web.socket.messaging.StompSubProtocolHandler.afterSessionEnded(StompSubProtocolHandler.java:611) ~[spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.web.socket.messaging.SubProtocolWebSocketHandler.clearSession(SubProtocolWebSocketHandler.java:516) ~[spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.web.socket.messaging.SubProtocolWebSocketHandler.afterConnectionClosed(SubProtocolWebSocketHandler.java:385) ~[spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.web.socket.handler.WebSocketHandlerDecorator.afterConnectionClosed(WebSocketHandlerDecorator.java:85) ~[spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.web.socket.handler.LoggingWebSocketHandlerDecorator.afterConnectionClosed(LoggingWebSocketHandlerDecorator.java:72) ~[spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.web.socket.handler.ExceptionWebSocketHandlerDecorator.afterConnectionClosed(ExceptionWebSocketHandlerDecorator.java:78) ~[spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.onClose(StandardWebSocketHandlerAdapter.java:144) [spring-websocket-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.apache.tomcat.websocket.WsSession.fireEndpointOnClose(WsSession.java:535) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
at org.apache.tomcat.websocket.WsSession.onClose(WsSession.java:513) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
at org.apache.tomcat.websocket.WsFrameBase.processDataControl(WsFrameBase.java:347) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
at org.apache.tomcat.websocket.WsFrameBase.processData(WsFrameBase.java:289) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
at org.apache.tomcat.websocket.WsFrameBase.processInputBuffer(WsFrameBase.java:133) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
at org.apache.tomcat.websocket.server.WsFrameServer.onDataAvailable(WsFrameServer.java:82) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
at org.apache.tomcat.websocket.server.WsFrameServer.doOnDataAvailable(WsFrameServer.java:171) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
at org.apache.tomcat.websocket.server.WsFrameServer.notifyDataAvailable(WsFrameServer.java:151) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler.upgradeDispatch(WsHttpUpgradeHandler.java:148) [tomcat-embed-websocket-9.0.12.jar:9.0.12]
at org.apache.coyote.http11.upgrade.UpgradeProcessorInternal.dispatch(UpgradeProcessorInternal.java:54) [tomcat-embed-core-9.0.12.jar:9.0.12]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:53) [tomcat-embed-core-9.0.12.jar:9.0.12]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:770) [tomcat-embed-core-9.0.12.jar:9.0.12]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415) [tomcat-embed-core-9.0.12.jar:9.0.12]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.12.jar:9.0.12]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.12.jar:9.0.12]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]
Caused by: org.springframework.security.access.AccessDeniedException: Access is denied
at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) ~[spring-security-core-5.1.1.RELEASE.jar:5.1.1.RELEASE]
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) ~[spring-security-core-5.1.1.RELEASE.jar:5.1.1.RELEASE]
at org.springframework.security.messaging.access.intercept.ChannelSecurityInterceptor.preSend(ChannelSecurityInterceptor.java:69) ~[spring-security-messaging-5.1.1.RELEASE.jar:5.1.1.RELEASE]
at org.springframework.messaging.support.AbstractMessageChannel$ChannelInterceptorChain.applyPreSend(AbstractMessageChannel.java:178) ~[spring-messaging-5.1.2.RELEASE.jar:5.1.2.RELEASE]
at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:132) ~[spring-messaging-5.1.2.RELEASE.jar:5.1.2.RELEASE]
... 26 common frames omitted
I have no idea where AccessDeniedException came from and how can I handle this.
If I do not throw UnauthorizedException in preSend method, client will be connected and when it tries to send something, it will receive AccessDeniedException, because all endpoints needs authenticated user, and then connection will be closed and stack trace for AccessDeniedException printed few times.
What am I doing incorrect here and what is the correct way to handle this kind of use case?
As solution for AccessDenied exception is that I didn't configured to allow DISCONNECT messages to pass through security. This is my configuration now:
#Configuration
public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer
{
#Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages)
{
messages
.simpTypeMatchers(SimpMessageType.CONNECT,
SimpMessageType.DISCONNECT, SimpMessageType.OTHER).permitAll()
.anyMessage().authenticated();
}
}
Also, I overrode StompSubProtocolErrorHandler so I could send custom message to my client about error.
Here is example:
#Override
public Message<byte[]> handleClientMessageProcessingError(Message<byte[]>clientMessage, Throwable ex)
{
Throwable exception = ex;
if (exception instanceof MessageDeliveryException)
{
exception = exception.getCause();
}
if (exception instanceof UnauthorizedException)
{
return handleUnauthorizedException(clientMessage, exception);
}
if (exception instanceof AccessDeniedException)
{
return handleAccessDeniedException(clientMessage, exception);
}
return super.handleClientMessageProcessingError(clientMessage, ex);
}
...
private Message<byte[]> handleUnauthorizedException(Message<byte[]> clientMessage, Throwable ex)
{
ApiError apiError = new ApiError(ErrorCodeConstants.UNAUTHORIZED, ex.getMessage());
return prepareErrorMessage(clientMessage, apiError, ErrorCodeConstants.UNAUTHORIZED_STRING);
}
private Message<byte[]> prepareErrorMessage(Message<byte[]> clientMessage, ApiError apiError, String errorCode)
{
String message = transformApiErrorToJSONString(apiError);
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.ERROR);
setReceiptIdForClient(clientMessage, accessor);
accessor.setMessage(errorCode);
accessor.setLeaveMutable(true);
return MessageBuilder.createMessage(message != null ? message.getBytes() : EMPTY_PAYLOAD, accessor.getMessageHeaders());
}

Can't connect to Hive via JDBC using Zookeeper connection string

val driverClassName = "org.apache.hive.jdbc.HiveDriver";
Class.forName(driverClassName);
// The below connection string works
// val jdbcUrl = String.format("jdbc:hive2://sandbox-hdp.hortonworks.com:10000/%s", database);
// The next one doesn't...
val jdbcUrl = String.format("jdbc:hive2://sandbox-hdp.hortonworks.com:2181/;serviceDiscoveryMode=zooKeeper;zooKeeperNamespace=hiveserver2", database);
val jdbcUsername = "amy_ds";
val jdbcPassword = "amy_ds";
return DriverManager.getConnection(jdbcUrl, jdbcUsername, jdbcPassword);
I'm using the above code to establish a JDBC connection to the Hive instance packaged with the Hortonworks Data Platform Sandbox 2.6.4. If I connect using the first (commented-out) connection string then the connection is established and usable later in the method. If, however, I try to connect via Zookeeper then an exception is thrown:
2018-05-23 10:14:08 INFO Utils:310 - Supplied authorities: sandbox-hdp.hortonworks.com:2181
2018-05-23 10:14:08 INFO CuratorFrameworkImpl:230 - Starting
2018-05-23 10:14:13 INFO ZooKeeper:100 - Client environment:zookeeper.version=3.4.6-1569965, built on 02/20/2014 09:09 GMT
2018-05-23 10:14:13 INFO ZooKeeper:100 - Client environment:host.name=[OMITTED FOR SECURITY]
2018-05-23 10:14:13 INFO ZooKeeper:100 - Client environment:java.version=1.8.0_172
2018-05-23 10:14:13 INFO ZooKeeper:100 - Client environment:java.vendor=Oracle Corporation
2018-05-23 10:14:13 INFO ZooKeeper:100 - Client environment:java.home=[OMITTED FOR SECURITY]
2018-05-23 10:14:13 INFO ZooKeeper:100 - Client environment:java.class.path=[OMITTED FOR SECURITY]
2018-05-23 10:14:13 INFO ZooKeeper:100 - Client environment:java.io.tmpdir=[OMITTED FOR SECURITY]
2018-05-23 10:14:13 INFO ZooKeeper:100 - Client environment:java.compiler=<NA>
2018-05-23 10:14:13 INFO ZooKeeper:100 - Client environment:os.name=[OMITTED FOR SECURITY]
2018-05-23 10:14:13 INFO ZooKeeper:100 - Client environment:os.arch=amd64
2018-05-23 10:14:13 INFO ZooKeeper:100 - Client environment:os.version=10.0
2018-05-23 10:14:13 INFO ZooKeeper:100 - Client environment:user.name=[OMITTED FOR SECURITY]
2018-05-23 10:14:13 INFO ZooKeeper:100 - Client environment:user.home=[OMITTED FOR SECURITY]
2018-05-23 10:14:13 INFO ZooKeeper:100 - Client environment:user.dir=[OMITTED FOR SECURITY]
2018-05-23 10:14:13 INFO ZooKeeper:438 - Initiating client connection, connectString=sandbox-hdp.hortonworks.com:2181 sessionTimeout=60000 watcher=org.apache.curator.ConnectionState#17935b13
2018-05-23 10:14:13 INFO ClientCnxn:975 - Opening socket connection to server sandbox-hdp.hortonworks.com/[OMITTED FOR SECURITY]:2181. Will not attempt to authenticate using SASL (unknown error)
2018-05-23 10:14:13 INFO ClientCnxn:852 - Socket connection established to sandbox-hdp.hortonworks.com/[OMITTED FOR SECURITY]:2181, initiating session
2018-05-23 10:14:13 INFO ClientCnxn:1235 - Session establishment complete on server sandbox-hdp.hortonworks.com/[OMITTED FOR SECURITY]:2181, sessionid = 0x163891b08d300ed, negotiated timeout = 60000
2018-05-23 10:14:13 INFO ConnectionStateManager:228 - State change: CONNECTED
2018-05-23 10:14:14 INFO ZooKeeperHiveClientHelper:83 - Selected HiveServer2 instance with uri: hive.server2.authentication=NONE;hive.server2.transport.mode=binary;hive.server2.thrift.sasl.qop=auth;hive.server2.thrift.bind.host=sandbox-hdp.hortonworks.com;hive.server2.thrift.port=10000;hive.server2.use.SSL=false
2018-05-23 10:14:14 INFO ZooKeeper:684 - Session: 0x163891b08d300ed closed
2018-05-23 10:14:14 INFO ClientCnxn:512 - EventThread shut down
2018-05-23 10:14:14 INFO Utils:397 - Resolved authority: hive.server2.authentication=NONE;hive.server2.transport.mode=binary;hive.server2.thrift.sasl.qop=auth;hive.server2.thrift.bind.host=sandbox-hdp.hortonworks.com;hive.server2.thrift.port=10000;hive.server2.use.SSL=false
2018-05-23 10:14:14 INFO HiveConnection:203 - Will try to open client transport with JDBC Uri: jdbc:hive2://hive.server2.authentication=NONE;hive.server2.transport.mode=binary;hive.server2.thrift.sasl.qop=auth;hive.server2.thrift.bind.host=sandbox-hdp.hortonworks.com;hive.server2.thrift.port=10000;hive.server2.use.SSL=false/;serviceDiscoveryMode=zooKeeper;zooKeeperNamespace=hiveserver2
May 23, 2018 10:14:14 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at org.apache.thrift.transport.TSocket.open(TSocket.java:170)
at org.apache.thrift.transport.TSaslTransport.open(TSaslTransport.java:266)
at org.apache.thrift.transport.TSaslClientTransport.open(TSaslClientTransport.java:37)
at org.apache.hive.jdbc.HiveConnection.openTransport(HiveConnection.java:204)
at org.apache.hive.jdbc.HiveConnection.<init>(HiveConnection.java:176)
at org.apache.hive.jdbc.HiveDriver.connect(HiveDriver.java:105)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at mil.navy.navair.ecbm.widgets.example.TestController.getHiveJdbcConnection(TestController.java:59)
at mil.navy.navair.ecbm.widgets.example.TestController.allRecords(TestController.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Any ideas? Most of the literature that I've seen says to either change the JDBC driver version or try a different connection string format. I've tried 1.2.1, 2.3.0, and 3.0.0 and none work (unless I connect directly to Hive using the known working connection string).
I suspect that the JDBC driver is having issues interpreting the URL returned by Zookeeper, as it says it can't find the host if I attempt to use the URL reported to be returned by Zookeeper from the logs.
I came across the same issue and was struggling to resolve it.Found out that jdbc url can't handle semicolon, try adding quotation after the endpoint and port like this.
jdbc:hive2://sandbox-hdp.hortonworks.com:2181/';serviceDiscoveryMode=zooKeeper;zooKeeperNamespace=hiveserver2'
This resolved my issue.

PUT request resulted in 500 (Server Error); invoking error handler

Method to update metadata info of my model through Rest client
my requirement is to do a PUT operation based on a key,along ith this i am sending request parameter for my model which is ProjectMetadata here.
#RequestMapping(value = "/api/di/v1/app/{projectKey}/metadata", method = RequestMethod.PUT, consumes = "application/json")
public ResponseEntity<?> updateProject(#PathVariable(value = "projectKey")
String projectKey,
#RequestBody ProjectMetadata metadata) throws JSONException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Basic <aut key>");
JSONObject requestBody = new JSONObject();
requestBody.put("label", metadata.getLabel());
requestBody.put("description", metadata.getDescription());
requestBody.put("shortDesc", metadata.getShortDesc());
requestBody.put("tag", metadata.getTags());
logger.debug("requestBody" + requestBody);
HttpEntity<String> requestEntity = new HttpEntity<String>(requestBody.toString(), headers);
logger.debug("requestentity" + requestEntity.toString());
RestTemplate restTemplate = new RestTemplate();
String url = "http://<>/public/api/projects/{projectKey}/metadata";
logger.debug("trying to send request to create project");
ResponseEntity<?> createResponse = null;
try {
createResponse = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, String.class, projectKey);
// restTemplate.put(url, requestEntity,projectKey);
} catch (HttpClientErrorException e) {
logger.error("Exceptions occurred while processing the request::");
return new ResponseEntity<String>(e.getResponseBodyAsString(), HttpStatus.BAD_REQUEST);
}
return createResponse;
}
ProjectMetadata Model
public class ProjectMetadata
{
private String label;
private String description;
private String shortDesc;
private List<String> tags;
public ProjectMetadata() {
super();
}
public ProjectMetadata(String label, String description, String shortDesc, List<String> tags) {
super();
this.label = label;
this.description = description;
this.shortDesc = shortDesc;
this.tags = tags;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getShortDesc() {
return shortDesc;
}
public void setShortDesc(String shortDesc) {
this.shortDesc = shortDesc;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
}
error stack
>2018-04-10 11:48:00,342 11345 [http-nio-9080-exec-1] DEBUG o.s.core.annotation.AnnotationUtils - Failed to meta-introspect annotation [interface org.springframework.web.bind.annotation.RequestBody]: java.lang.NullPointerException
2018-04-10 11:48:00,350 11353 [http-nio-9080-exec-1] DEBUG c.p.controller.ProjectController - requestBody{"description":"adsfy","shortDesc":"nsfdf","label":"testapp","tag":["tag12"]}
2018-04-10 11:48:00,354 11357 [http-nio-9080-exec-1] DEBUG c.p.controller.ProjectController - requestentity<{"description":"adsfy","shortDesc":"nsfdf","label":"testapp","tag":["tag12"]},{Content-Type=[application/json], Authorization=[Basic <>]}>
2018-04-10 11:48:00,366 11369 [http-nio-9080-exec-1] DEBUG c.p.controller.ProjectController - trying to send request to create project
2018-04-10 11:48:00,394 11397 [http-nio-9080-exec-1] DEBUG o.s.web.client.RestTemplate - Created PUT request for "http://<>/public/api/projects/abcde/metadata"
2018-04-10 11:48:00,394 11397 [http-nio-9080-exec-1] DEBUG o.s.web.client.RestTemplate - Setting request Accept header to [text/plain, application/json, application/*+json, */*]
2018-04-10 11:48:00,394 11397 [http-nio-9080-exec-1] DEBUG o.s.web.client.RestTemplate - Writing [{"description":"adsfy","shortDesc":"nsfdf","label":"testapp","tag":["tag12"]}] as "application/json" using [org.springframework.http.converter.StringHttpMessageConverter#6c0f36de]
2018-04-10 11:48:00,954 11957 [http-nio-9080-exec-1] DEBUG o.s.web.client.RestTemplate - PUT request for "http://<>/public/api/projects/abcde/metadata" resulted in 500 (Server Error); invoking error handler
2018-04-10 11:48:00,954 11957 [http-nio-9080-exec-1] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Resolving exception from handler [public org.springframework.http.ResponseEntity<?> com.project.controller.ProjectController.updateProject(java.lang.String,com.model.project.ProjectMetadata) throws org.json.JSONException]: org.springframework.web.client.HttpServerErrorException: 500 Server Error
2018-04-10 11:48:00,958 11961 [http-nio-9080-exec-1] DEBUG o.s.w.s.m.a.ResponseStatusExceptionResolver - Resolving exception from handler [public org.springframework.http.ResponseEntity<?> com.project.controller.ProjectController.updateProject(java.lang.String,com.model.project.ProjectMetadata) throws org.json.JSONException]: org.springframework.web.client.HttpServerErrorException: 500 Server Error
2018-04-10 11:48:00,958 11961 [http-nio-9080-exec-1] DEBUG o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolving exception from handler [public org.springframework.http.ResponseEntity<?> com.project.controller.ProjectController.updateProject(java.lang.String,com.model.project.ProjectMetadata) throws org.json.JSONException]: org.springframework.web.client.HttpServerErrorException: 500 Server Error
2018-04-10 11:48:00,962 11965 [http-nio-9080-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - Could not complete request
org.springframework.web.client.HttpServerErrorException: 500 Server Error
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:97)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79)
at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:777)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:730)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:686)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:602)
at com.project.controller.ProjectController.updateProject(ProjectController.java:120)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:870)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:892)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:664)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
2018-04-10 11:48:00,962 11965 [http-nio-9080-exec-1] DEBUG o.s.b.w.s.f.OrderedRequestContextFilter - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade#440e2d74
2018-04-10 11:48:00,966 11969 [http-nio-9080-exec-1] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpServerErrorException: 500 Server Error] with root cause
org.springframework.web.client.HttpServerErrorException: 500 Server Error
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:97)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79)
at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:777)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:730)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:686)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:602)
at com.project.controller.ProjectController.updateProject(ProjectController.java:120)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:870)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:892)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:664)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
2018-04-10 11:48:00,970 11973 [http-nio-9080-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - DispatcherServlet with name 'dispatcherServlet' processing PUT request for [/error]
2018-04-10 11:48:00,970 11973 [http-nio-9080-exec-1] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Looking up handler method for path /error
2018-04-10 11:48:00,974 11977 [http-nio-9080-exec-1] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Returning handler method [public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)]
2018-04-10 11:48:00,974 11977 [http-nio-9080-exec-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'basicErrorController'
2018-04-10 11:48:01,006 12009 [http-nio-9080-exec-1] DEBUG o.s.w.s.m.m.a.HttpEntityMethodProcessor - Written [{timestamp=Tue Apr 10 11:48:00 IST 2018, status=500, error=Internal Server Error, message=500 Server Error, path=/rfi/api/di/v1/app/abcde/metadata/}] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#4e9658b5]
2018-04-10 11:48:01,006 12009 [http-nio-9080-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2018-04-10 11:48:01,006 12009 [http-nio-9080-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request
What is causing this error?Plase help
request and response image
headers
request
The error is not linked to your code.
The 500 error is returned from the external service your are calling.
Try to call your external service using another client like postman to be sure the service works the way you are using it .
Based on the conversation we had in the comments.
The only thing that is different between your code and the screenshot of your request via postman is the missing s in "tags" (in the code in your question you wrote "tag" instead of "tags")

Spring Boot ClassCastException on composite micro service, after some time - OK

I have strange behavior of my composite microservice (API gateway) of 2 microservices. On first HTTP request it returns the ClassCastException, but after some time it returns normal JSON. How can I set the application to return normal JSON right on the first HTTP request?
Configuration for all 3 services is similar: spring.application.name, server port, Eureka registration address.
There are 2 microservices: car-service (annotated with #Controller) and truck-service (annotated with #RestController), the methods which return List<Car> and List<Truck> are correspondingly:
#HystrixCommand(commandKey = "getCars", groupKey = "Cars")
#RequestMapping(value = "/cars", method = RequestMethod.GET)
public List<Car> getCars() {
return carService.getAllCars();
}
and
#ResponseBody
#RequestMapping(value = "/trucks", method = RequestMethod.GET)
public List<Truck> getTrucks() {
return truckService.getAllTrucks();
}
(setting both services to #Controller or #RestController doesn't affect the behavior)
Composite Vehicle service has 2 interfaces injected with #FeignClient annotation and returns composite object VehicleSummary which has List<Car> and List<Truck> fields with standard getters and setters:
#Component
public class VehicleService {
#Inject
private CarClient carClient;
#Inject
private TruckClient truckClient;
public VehicleSummary getAllVehicles() {
List<Car> cars = carClient.getAllCars();
List<Truck> trucks = truckClient.getTrucks();
VehicleSummary summary = new VehicleSummary();
summary.setCars(cars);
summary.setTrucks(trucks);
return summary;
}
}
The full source code is available at https://github.com/t3rmin41/simple-microservices-app
The stacktrace of the exception is below :
2015-12-21 21:17:00.560 INFO 26207 --- [nio-8883-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2015-12-21 21:17:00.560 INFO 26207 --- [nio-8883-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2015-12-21 21:17:00.612 INFO 26207 --- [nio-8883-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 52 ms
2015-12-21 21:17:00.967 INFO 26207 --- [trix-Vehicles-1] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext#31eb7d: startup date [Mon Dec 21 21:17:00 EET 2015]; parent: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#2db9fb
2015-12-21 21:17:01.020 INFO 26207 --- [trix-Vehicles-1] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2015-12-21 21:17:01.383 INFO 26207 --- [trix-Vehicles-1] c.netflix.config.ChainedDynamicProperty : Flipping property: car-service.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2015-12-21 21:17:01.525 INFO 26207 --- [trix-Vehicles-1] c.netflix.loadbalancer.BaseLoadBalancer : Client:car-service instantiated a LoadBalancer:DynamicServerListLoadBalancer:{NFLoadBalancer:name=car-service,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:null
2015-12-21 21:17:01.593 INFO 26207 --- [trix-Vehicles-1] c.netflix.config.ChainedDynamicProperty : Flipping property: car-service.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2015-12-21 21:17:01.600 INFO 26207 --- [trix-Vehicles-1] c.n.l.DynamicServerListLoadBalancer : DynamicServerListLoadBalancer for client car-service initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=car-service,current list of Servers=[nikzgs-Latitude-E5420:8881],Load balancer stats=Zone stats: {defaultzone=[Zone:defaultzone; Instance count:1; Active connections count: 0; Circuit breaker tripped count: 0; Active connections per server: 0.0;]
},Server stats: [[Server:nikzgs-Latitude-E5420:8881; Zone:defaultZone; Total Requests:0; Successive connection failure:0; Total blackout seconds:0; Last connection made:Thu Jan 01 03:00:00 EET 1970; First connection made: Thu Jan 01 03:00:00 EET 1970; Active Connections:0; total failure count in last (1000) msecs:0; average resp time:0.0; 90 percentile resp time:0.0; 95 percentile resp time:0.0; min resp time:0.0; max resp time:0.0;stddev resp time:0.0]
]}ServerList:org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList#a14ec6
2015-12-21 21:17:02.054 ERROR 26207 --- [nio-8883-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: java.lang.String cannot be cast to my.vehicle.entity.VehicleSummary] with root cause
java.lang.ClassCastException: java.lang.String cannot be cast to my.vehicle.entity.VehicleSummary
at my.simple.vehicle.VehicleController$$EnhancerBySpringCGLIB$$3b97a077.getAllVehicles(<generated>) ~[composite-vehicle-service-0.0.1-SNAPSHOT.jar!/:0.0.1-SNAPSHOT]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_65]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_65]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_65]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_65]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222) ~[spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) ~[spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) ~[spring-webmvc-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814) ~[spring-webmvc-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737) ~[spring-webmvc-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) ~[spring-webmvc-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) ~[spring-webmvc-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) ~[spring-webmvc-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) ~[tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) ~[tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) ~[tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.0.28.jar!/:8.0.28]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$ApplicationContextHeaderFilter.doFilterInternal(EndpointWebMvcAutoConfiguration.java:242) ~[spring-boot-actuator-1.3.0.RELEASE.jar!/:1.3.0.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:111) ~[spring-boot-actuator-1.3.0.RELEASE.jar!/:1.3.0.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87) ~[spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) ~[spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121) ~[spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:103) ~[spring-boot-actuator-1.3.0.RELEASE.jar!/:1.3.0.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.2.3.RELEASE.jar!/:4.2.3.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) ~[tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) ~[tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217) ~[tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_65]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_65]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.0.28.jar!/:8.0.28]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_65]
2015-12-21 21:17:02.535 INFO 26207 --- [ool-10-thread-1] c.netflix.config.ChainedDynamicProperty : Flipping property: car-service.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2015-12-21 21:17:07.778 INFO 26207 --- [pool-6-thread-1] com.netflix.discovery.DiscoveryClient : DiscoveryClient_VEHICLE-SERVICE/nikzgs-Latitude-E5420 - Re-registering apps/VEHICLE-SERVICE
2015-12-21 21:17:07.778 INFO 26207 --- [pool-6-thread-1] com.netflix.discovery.DiscoveryClient : DiscoveryClient_VEHICLE-SERVICE/nikzgs-Latitude-E5420: registering service...
2015-12-21 21:17:07.791 INFO 26207 --- [pool-6-thread-1] com.netflix.discovery.DiscoveryClient : DiscoveryClient_VEHICLE-SERVICE/nikzgs-Latitude-E5420 - registration status: 204
The problem was caused by VehicleController class methods:
#ResponseBody
#HystrixCommand(commandKey = "getAllVehicles", groupKey = "Vehicles", fallbackMethod = "returnErrorMessage")
#RequestMapping(value = "/vehicles", method = RequestMethod.GET)
public VehicleSummary getAllVehicles() {
return vehicleService.getAllVehicles();
}
#HystrixCommand
private String returnErrorMessage() {
return "Fallback error message";
}
The problem was that Hystrix is trying to construct the response with returnErrorMessage() method which returns String and getAllVehicles() returns VehicleSummary class. Hence, it cannot cast String to VehicleSummary.
The correct way is to return the same class on the fallback:
#ResponseBody
#HystrixCommand(commandKey = "getAllVehicles", groupKey = "Vehicles", fallbackMethod = "returnErrorMessage")
#RequestMapping(value = "/vehicles", method = RequestMethod.GET)
public VehicleSummary getAllVehicles() {
return vehicleService.getAllVehicles();
}
#HystrixCommand
private VehicleSummary returnErrorMessage() {
return new VehicleSummary();
}

Resources