HTTP headers difference and Bouncy Castle error with Spring Boot version upgrade - spring

I'm working on Kotlin Gradle Spring Boot project which uses:
Spring version: 5.1.0.RELEASE
Spring Boot version: 1.5.4.RELEASE
Bouncy Castle version: 1.66
In order to remove the vulnerabilities from the project I upgraded above versions to the following:
Spring version: 5.2.20.RELEASE
Spring Boot version: 2.6.6
Bouncy Castle version: 1.68
But the above change gave me the following error:
2022-05-11 21:58:11,277 ERROR [https-openssl-nio-8443-exec-14] com.organisation.abc.def.api.InstrumentServiceWrapper Communication error with underlying service for abc instrument
com.organisation.abc.def.exception.abcServiceException: Downstream Error from abc-vault-instrument-service (PVIS)
at com.organisation.abc.def.api.pi.impl.abcInstrumentServiceExecutor.sendRequest(abcInstrumentServiceExecutor.java:82)
at com.organisation.abc.def.api.pi.impl.abcInstrumentServiceExecutor.execute(abcInstrumentServiceExecutor.java:51)
at com.organisation.abc.def.api.pi.impl.abcInstrumentServiceExecutor.execute(abcInstrumentServiceExecutor.java:30)
at com.organisation.abc.def.api.InstrumentServiceWrapper.callabcInstrumentSummaryProvider(InstrumentServiceWrapper.java:69)
at com.organisation.abc.def.api.pi.impl.abcInstrumentServiceImpl.retrieveabcInstrument(abcInstrumentServiceImpl.java:61)
at com.organisation.abc.def.service.impl.VerifyabcdefService.populateRequestWithApplicationState(VerifyabcdefService.java:340)
at com.organisation.abc.def.service.impl.VerifyabcdefService.persistabcPlan(VerifyabcdefService.java:187)
at com.organisation.abc.def.service.impl.VerifyabcdefService.execute(VerifyabcdefService.java:150)
at com.organisation.abc.def.handler.VerifyMessageHandler.process(VerifyMessageHandler.java:135)
at com.organisation.abc.def.handler.VerifyMessageHandler.process(VerifyMessageHandler.java:32)
at com.organisation.abc.def.handler.AbstractMessageHandler.processMessage(AbstractMessageHandler.java:52)
at com.organisation.abc.def.webservice.v2.abcProcessorPortTypeImpl.verifyabc(abcProcessorPortTypeImpl.java:189)
at jdk.internal.reflect.GeneratedMethodAccessor505.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.apache.cxf.service.invoker.AbstractInvoker.performInvocation(AbstractInvoker.java:179)
at org.apache.cxf.jaxws.JAXWSMethodInvoker.performInvocation(JAXWSMethodInvoker.java:66)
at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
at org.apache.cxf.jaxws.AbstractJAXWSMethodInvoker.invoke(AbstractJAXWSMethodInvoker.java:232)
at org.apache.cxf.jaxws.JAXWSMethodInvoker.invoke(JAXWSMethodInvoker.java:85)
at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:74)
at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:59)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at org.apache.cxf.interceptor.ServiceInvokerInterceptor$2.run(ServiceInvokerInterceptor.java:126)
at org.apache.cxf.workqueue.SynchronousExecutor.execute(SynchronousExecutor.java:37)
at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:131)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:265)
at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:234)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:208)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:160)
at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:225)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:304)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:217)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:279)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at com.organisation.abc.def.monitoring.EndpointLoggingServletFilter.doFilter(EndpointLoggingServletFilter.java:83)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:660)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:359)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:889)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1743)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: org.springframework.web.client.ResourceAccessException: I/O error on GET request for "https://SCRAMBLED/F447596B-256F-6080-F62E-EC467967B745": Could not generate secret; nested exception is javax.net.ssl.SSLHandshakeException: Could not generate secret
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:746)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:712)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:630)
at com.organisation.abc.def.api.pi.impl.abcInstrumentServiceExecutor.sendRequest(abcInstrumentServiceExecutor.java:63)
... 63 more
Caused by: javax.net.ssl.SSLHandshakeException: Could not generate secret
at java.base/sun.security.ssl.KAKeyDerivation.t13DeriveKey(KAKeyDerivation.java:128)
at java.base/sun.security.ssl.KAKeyDerivation.deriveKey(KAKeyDerivation.java:63)
at java.base/sun.security.ssl.ServerHello$T13ServerHelloConsumer.consume(ServerHello.java:1251)
at java.base/sun.security.ssl.ServerHello$ServerHelloConsumer.onServerHello(ServerHello.java:985)
at java.base/sun.security.ssl.ServerHello$ServerHelloConsumer.consume(ServerHello.java:873)
at java.base/sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:392)
at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:443)
at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:421)
at java.base/sun.security.ssl.TransportContext.dispatch(TransportContext.java:182)
at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:172)
at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1501)
at java.base/sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1411)
at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:451)
at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:422)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:395)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:354)
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:134)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:87)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
at org.springframework.http.client.BufferingClientHttpRequestWrapper.executeInternal(BufferingClientHttpRequestWrapper.java:63)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:109)
at com.organisation.abc.def.logging.LoggingInterceptor.intercept(LoggingInterceptor.java:91)
at com.organisation.abc.def.logging.abcInstrumentServiceLoggingInterceptor.intercept(abcInstrumentServiceLoggingInterceptor.java:36)
at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:93)
at org.springframework.http.client.InterceptingClientHttpRequest.executeInternal(InterceptingClientHttpRequest.java:77)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:737)
... 66 more
Caused by: java.security.InvalidKeyException: cannot identify XDH private key
at org.bouncycastle.jcajce.provider.asymmetric.edec.KeyAgreementSpi.engineDoPhase(Unknown Source)
at java.base/javax.crypto.KeyAgreement.doPhase(KeyAgreement.java:579)
at java.base/sun.security.ssl.KAKeyDerivation.t13DeriveKey(KAKeyDerivation.java:104)
... 105 more
What I perceive from the above error is that there might be some compatibility issue between Spring and Bouncy Castle versions.
Also, I later found that the HTTP request headers formed before and after the versions upgrades are different. I tried making changes one by one to see exactly at what point headers are getting changed and I found it's due to Spring version 5.2.20.RELEASE.
Before version upgrade:
#RequestHeaders={Accept=[application/json, application/*+json], Authorization=[Bearer#SCRAMBLED#], Content-Type=[application/json], Content-Length=[0]}
After version upgrade:
#RequestHeaders=[Accept:"application/json, application/*+json", Authorization:"Bearer#SCRAMBLED#", Content-Type:"application/json", Content-Length:"0”]
I'm scratching my head for a week already.
Can anyone help me to figure out if the change in HTTP headers is
causing this or there might be some different reason?
And how can I make my headers look like "before this headers issue" with Spring version 5.2.20.RELEASE?
It's extremely important for me to move forward.
Thanks in advance!

Related

org.dataloader.DataLoaderRegistry error while initialization of Graphql application

I am using below set of jar in my application.
compile files('libs/latest/graphql-java-servlet-6.1.3.jar')
compile files('libs/latest/graphql-java-16.2.jar')
compile files('libs/latest/graphql-java-tools-5.2.4.jar')
compile files('libs/latest/graphql-spring-boot-autoconfigure-5.0.2.jar')
compile files('libs/latest/graphql-spring-boot-starter-5.0.2.jar')
compile files('libs/latest/antlr4-runtime-4.9.2.jar')
compile files('libs/lombok-1.16.18.jar')
compile files('libs/latest/graphql-java-extended-scalars-16.0.1.jar')
While initializing the beans during startup I am getting below error which is leading to failure of the application.
org/dataloader/DataLoaderRegistry ,"ERR": { org.apache.cxf.interceptor.Fault: org/dataloader/DataLoaderRegistry
at org.apache.cxf.service.invoker.AbstractInvoker.createFault(AbstractInvoker.java:162)
at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:128)
at org.apache.cxf.jaxrs.LazyJAXRSInvoker.invoke(LazyJAXRSInvoker.java:197)
at org.apache.cxf.jaxrs.LazyJAXRSInvoker.invoke(LazyJAXRSInvoker.java:107)
at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:59)
at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:96)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:267)
at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:234)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:208)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:160)
at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:216)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:301)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:220)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:276)
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)
Caused by: java.lang.NoClassDefFoundError: org/dataloader/DataLoaderRegistry
at graphql.ExecutionInput$Builder.(ExecutionInput.java:198)
at graphql.ExecutionInput.newExecutionInput(ExecutionInput.java:172)
at graphql.GraphQL.execute(GraphQL.java:256)
at com.sample.PublishReportRestServiceImpl.getReports(PublishReportRestServiceImpl.java:120)
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.apache.cxf.service.invoker.AbstractInvoker.performInvocation(AbstractInvoker.java:179)
at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
... 145 more
Caused by: java.lang.ClassNotFoundException: org.dataloader.DataLoaderRegistry
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1358)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1180)
... 155 more
Can someone please help in resolving this issue.
I was able to resolve this issue by adding java-dataloader-2.2.3.jar in WEB-INF/lib folder and application is now up & running.
Thanks for your time.

Autowire doesn't work after enabling Hystrix

I'm encountering a issue, where autowiring doesn't work when I add Hystrix(EnableHystrix) in my microservice.
Controller class:
#RestController
#RequestMapping("/login")
#Slf4j
public class LoginController {
#Autowired
ILoginService loginService;
#ApiOperation(value = "Validate user credentials", response = LoginUser.class)
#PostMapping(value = "/validateCredentials")
private ResponseEntity<LoginUser> validateUserCredentials(#RequestBody LoginUser logginUser) {
LoginUser user=loginService.validateUser(logginUser);
......
.....
}
}
Autowiring of ILoginService works perfectively without Hystrix.
But when I add the dependency( Version 2.2.6 Release)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
And enable Hystrix as:
#EnableFeignClients("com.abcd")
#SpringBootApplication
#EnableHystrix
public class MyApplication{
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
The Autowire of ILoginService fails and NullPointerException is thrown when trying to access the autowired property.
I have this configuration working fine in other microservices, But fails in this particular microservice. What is going wrong here?
EDIT:
StackTrace is:
java.lang.NullPointerException
at com.demo.login.controller.LoginController.validateUserCredentials(LoginController.java:46)
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:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
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:53)
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:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
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.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
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:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
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:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)2021-01-28 17:09:12.999 DEBUG 1800 --- [nio-9200-exec-8] com.demo.login.ExceptionsHelper : Exception:
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
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)
In the current form, its kind of hard to tell what exactly happens.
So I'll provide some thoughts that can lead to the solution:
You say,
The Autowire of ILoginService fails and NullPointerException is thrown when trying to access the autowired property.
Usually when its possible to autowire a bean because it doesn't exist or something, spring should throw an exception during the startup and it will be impossible to "access" the autowired property during the statrup because the system won't start, so this is confusing. Maybe if you could provide a stacktrace and the place where you're trying to access the property it could become more clear...
Its possible in theory (again the stacktrace could show that) that someone tries to access the property before the autowiring actually executes. Technically its implemented in spring via BeanPostProcessor with certain priority that might compete with other bean post processors.
Try to rewrite the controller to use constructor injection (so that spring would inject the ILoginService during the construction of the controller:
#RestController
public class LoginController {
// Note, no autowiring here
private final ILoginService loginService;
// If you are on old spring you need to mark this constructor with #Autowired,
// in the recent spring versions its not required anymore as long as this is the only
// constructor of your class
public LoginController(ILoginService loginService) {
this.loginService = loginService;
}
After you're doing this, try to place a breakpoint in the constructor and see what exactly gets injected (this is an advantage of constructor injection in this case)

Communications link failure error while deploying from Google Cloud Run with Cloud SQL:MySQL

Followed this link for continuous deployment using Cloud Build and GitHub actions in spring-boot app.
petomalina.medium.com/
Everything is working fine except for when service is trying to access the database using the following command to deploy.
gcloud run deploy my-service \
--region europe-west1 \
--image gcr.io/${{ secrets.GCP_PROJECT_ID }}/my-service \
--platform managed \
--allow-unauthenticated \
--project ${{ secrets.GCP_PROJECT_ID }} \
--add-cloudsql-instances [instance-name] \
--set-env-vars DATASOURCE_URL=jdbc:mysql://google/[dbname]?cloudSqlInstance=[instance-name]&socketFactory=com.google.cloud.sql.mysql.SocketFactory&useSSL=false
I have also added role for Cloud SQL client against the service account, tried using both public ip, private ip and this format
jdbc:mysql://google/[dbname]?cloudSqlInstance=[instance-name]&socketFactory=com.google.cloud.sql.mysql.SocketFactory&useSSL=false
This is my app.prop file:
spring.datasource.url=${DATASOURCE_URL}
spring.datasource.username=sa
spring.datasource.password=pswd
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
But still it gives this error:
com.mysql.cj.jdbc.exceptions.CommunicationsException: \
Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. \
The driver has not received any packets from the server.
com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174)
[mysql-connector-java-8.0.22.jar!/:8.0.22] com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64)
[mysql-connector-java-8.0.22.jar!/:8.0.22] com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
[mysql-connector-java-8.0.22.jar!/:8.0.22] com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
[mysql-connector-java-8.0.22.jar!/:8.0.22] com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
[mysql-connector-java-8.0.22.jar!/:8.0.22] com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:198) [mysql-connector-java-8.0.22.jar!/:8.0.22]
Can someone please point me in the right direction?
These are the dependencies added:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
I have also added this:
<dependency>
<!-- MySQL Socket Factory for Cloud SQL -->
<groupId>com.google.cloud.sql</groupId>
<artifactId>mysql-socket-factory</artifactId>
<version>1.0.3</version>
</dependency>
And now the error has changed to this:
[nio-8080-exec-2] 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.dao.DataAccessResourceFailureException: \
Unable to acquire JDBC Connection; nested exception is org.hibernate.exception.JDBCConnectionException: \
Unable to acquire JDBC Connection] with root cause
java.net.SocketTimeoutException: connect timed out at java.net.PlainSocketImpl.socketConnect(Native Method)
[na:1.8.0_202] at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
[na:1.8.0_202] at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
[na:1.8.0_202] at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
[na:1.8.0_202] at java.net.SocksSocketImpl.connect(Unknown Source)
[na:1.8.0_202] at java.net.Socket.connect(Unknown Source)
[na:1.8.0_202] at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:155)
[mysql-connector-java-8.0.22.jar!/:8.0.22] at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:63)
[mysql-connector-java-8.0.22.jar!/:8.0.22] at com.mysql.cj.NativeSession.connect(NativeSession.java:144)
[mysql-connector-java-8.0.22.jar!/:8.0.22] at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:956)
[mysql-connector-java-8.0.22.jar!/:8.0.22] at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:826)
[mysql-connector-java-8.0.22.jar!/:8.0.22] at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
[mysql-connector-java-8.0.22.jar!/:8.0.22] at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
[mysql-connector-java-8.0.22.jar!/:8.0.22] at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:198)
[mysql-connector-java-8.0.22.jar!/:8.0.22] at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138)
[HikariCP-3.4.5.jar!/:na] at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358)
[HikariCP-3.4.5.jar!/:na] at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206)
[HikariCP-3.4.5.jar!/:na] at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:477)
[HikariCP-3.4.5.jar!/:na] at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:560)
[HikariCP-3.4.5.jar!/:na] at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115)
[HikariCP-3.4.5.jar!/:na] at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112)
[HikariCP-3.4.5.jar!/:na] at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.internal.NonContextualJdbcConnectionAccess.obtainConnection(NonContextualJdbcConnectionAccess.java:38)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:108)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:138)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.connection(StatementPreparerImpl.java:50)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:149)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:176)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:151)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:2104)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:2041)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:2019)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.loader.Loader.doQuery(Loader.java:948)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:349)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.loader.Loader.doList(Loader.java:2850)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.loader.Loader.doList(Loader.java:2832)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2664)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.loader.Loader.list(Loader.java:2659)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:506)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:400)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:219)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1414)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1565)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1533)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.hibernate.query.Query.getResultList(Query.java:165)
[hibernate-core-5.4.23.Final.jar!/:5.4.23.Final] at org.springframework.data.jpa.repository.query.JpaQueryExecution$PagedExecution.doExecute(JpaQueryExecution.java:177)
[spring-data-jpa-2.4.1.jar!/:2.4.1] at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:88)
[spring-data-jpa-2.4.1.jar!/:2.4.1] at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:155)
[spring-data-jpa-2.4.1.jar!/:2.4.1] at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:143)
[spring-data-jpa-2.4.1.jar!/:2.4.1] at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137)
[spring-data-commons-2.4.1.jar!/:2.4.1] at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121)
[spring-data-commons-2.4.1.jar!/:2.4.1] at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:152)
[spring-data-commons-2.4.1.jar!/:2.4.1] at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:131)
[spring-data-commons-2.4.1.jar!/:2.4.1] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
[spring-aop-5.3.1.jar!/:5.3.1] at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80)
[spring-data-commons-2.4.1.jar!/:2.4.1] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
[spring-aop-5.3.1.jar!/:5.3.1] at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:371)
[spring-tx-5.3.1.jar!/:5.3.1] at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:134)
[spring-tx-5.3.1.jar!/:5.3.1] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
[spring-aop-5.3.1.jar!/:5.3.1] at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)
[spring-tx-5.3.1.jar!/:5.3.1] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
[spring-aop-5.3.1.jar!/:5.3.1] at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:145)
[spring-data-jpa-2.4.1.jar!/:2.4.1] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
[spring-aop-5.3.1.jar!/:5.3.1] at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)
[spring-aop-5.3.1.jar!/:5.3.1] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
[spring-aop-5.3.1.jar!/:5.3.1] at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)
[spring-aop-5.3.1.jar!/:5.3.1] at com.sun.proxy.$Proxy121.fetchRestaurants(Unknown Source)
[na:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[na:1.8.0_202] at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
[na:1.8.0_202] at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
[na:1.8.0_202] at java.lang.reflect.Method.invoke(Unknown Source)
[na:1.8.0_202] at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344)
[spring-aop-5.3.1.jar!/:5.3.1] at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
[spring-aop-5.3.1.jar!/:5.3.1] at com.sun.proxy.$Proxy62.fetchRestaurants(Unknown Source)
[na:na] at october.foods.services.restaurant.RestaurantService.fetchRestaurants(RestaurantService.java:100)
[classes!/:0.0.1-SNAPSHOT] at october.foods.controller.restaurant.RestaurantController.fetchRestaurants(RestaurantController.java:50)
[classes!/:0.0.1-SNAPSHOT] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[na:1.8.0_202] at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
[na:1.8.0_202] at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
[na:1.8.0_202] at java.lang.reflect.Method.invoke(Unknown Source)
[na:1.8.0_202] at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)
[spring-web-5.3.1.jar!/:5.3.1] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)
[spring-web-5.3.1.jar!/:5.3.1] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
[spring-webmvc-5.3.1.jar!/:5.3.1] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:893)
[spring-webmvc-5.3.1.jar!/:5.3.1] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:807)
[spring-webmvc-5.3.1.jar!/:5.3.1] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
[spring-webmvc-5.3.1.jar!/:5.3.1] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1061)
[spring-webmvc-5.3.1.jar!/:5.3.1] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:961)
[spring-webmvc-5.3.1.jar!/:5.3.1] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
[spring-webmvc-5.3.1.jar!/:5.3.1] at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
[spring-webmvc-5.3.1.jar!/:5.3.1] at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
[tomcat-embed-core-9.0.39.jar!/:4.0.FR] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
[spring-webmvc-5.3.1.jar!/:5.3.1] at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
[tomcat-embed-core-9.0.39.jar!/:4.0.FR] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
[tomcat-embed-websocket-9.0.39.jar!/:9.0.39] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
[spring-web-5.3.1.jar!/:5.3.1] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
[spring-web-5.3.1.jar!/:5.3.1] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
[spring-web-5.3.1.jar!/:5.3.1] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
[spring-web-5.3.1.jar!/:5.3.1] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
[spring-web-5.3.1.jar!/:5.3.1] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
[spring-web-5.3.1.jar!/:5.3.1] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
[na:1.8.0_202] at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
[na:1.8.0_202] at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
[tomcat-embed-core-9.0.39.jar!/:9.0.39] at java.lang.Thread.run(Unknown Source) [na:1.8.0_202]
As suggested by Andrew, added ConnectionPoolContextListener,
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.sql.DataSource;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
#WebListener("Creates a connection pool that is stored in the Servlet's context for later use.")
public class ConnectionPoolContextListener implements ServletContextListener {
private static final String CLOUD_SQL_CONNECTION_NAME = "CLOUD_SQL_CONNECTION_NAME";
private static final String DB_USER = "DB_USER";
private static final String DB_PASS = "DB_PASS";
private static final String DB_NAME = "DB_NAME";
private DataSource createConnectionPool() {
// [START cloud_sql_mysql_servlet_create]
// The configuration object specifies behaviors for the connection pool.
HikariConfig config = new HikariConfig();
// The following URL is equivalent to setting the config options below:
// jdbc:mysql:///<DB_NAME>?cloudSqlInstance=<CLOUD_SQL_CONNECTION_NAME>&
// socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=<DB_USER>&password=<DB_PASS>
// See the link below for more info on building a JDBC URL for the Cloud SQL JDBC Socket Factory
// https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory#creating-the-jdbc-url
// Configure which instance and what database user to connect with.
config.setJdbcUrl(String.format("jdbc:mysql:///%s", DB_NAME));
config.setUsername(DB_USER); // e.g. "root", "mysql"
config.setPassword(DB_PASS); // e.g. "my-password"
// For Java users, the Cloud SQL JDBC Socket Factory can provide authenticated connections.
// See https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory for details.
config.addDataSourceProperty("socketFactory", "com.google.cloud.sql.mysql.SocketFactory");
config.addDataSourceProperty("cloudSqlInstance", CLOUD_SQL_CONNECTION_NAME);
// The ipTypes argument can be used to specify a comma delimited list of preferred IP types
// for connecting to a Cloud SQL instance. The argument ipTypes=PRIVATE will force the
// SocketFactory to connect with an instance's associated private IP.
config.addDataSourceProperty("ipTypes", "PUBLIC,PRIVATE");
// ... Specify additional connection properties here.
// [START_EXCLUDE]
// [START cloud_sql_mysql_servlet_limit]
// maximumPoolSize limits the total number of concurrent connections this pool will keep. Ideal
// values for this setting are highly variable on app design, infrastructure, and database.
config.setMaximumPoolSize(5);
// minimumIdle is the minimum number of idle connections Hikari maintains in the pool.
// Additional connections will be established to meet this value unless the pool is full.
config.setMinimumIdle(5);
// [END cloud_sql_mysql_servlet_limit]
// [START cloud_sql_mysql_servlet_timeout]
// setConnectionTimeout is the maximum number of milliseconds to wait for a connection checkout.
// Any attempt to retrieve a connection from this pool that exceeds the set limit will throw an
// SQLException.
config.setConnectionTimeout(10000); // 10 seconds
// idleTimeout is the maximum amount of time a connection can sit in the pool. Connections that
// sit idle for this many milliseconds are retried if minimumIdle is exceeded.
config.setIdleTimeout(600000); // 10 minutes
// [END cloud_sql_mysql_servlet_timeout]
// [START cloud_sql_mysql_servlet_backoff]
// Hikari automatically delays between failed connection attempts, eventually reaching a
// maximum delay of `connectionTimeout / 2` between attempts.
// [END cloud_sql_mysql_servlet_backoff]
// [START cloud_sql_mysql_servlet_lifetime]
// maxLifetime is the maximum possible lifetime of a connection in the pool. Connections that
// live longer than this many milliseconds will be closed and reestablished between uses. This
// value should be several minutes shorter than the database's timeout value to avoid unexpected
// terminations.
config.setMaxLifetime(1800000); // 30 minutes
// [END cloud_sql_mysql_servlet_lifetime]
// [END_EXCLUDE]
// Initialize the connection pool using the configuration object.
DataSource pool = new HikariDataSource(config);
// [END cloud_sql_mysql_servlet_create]
return pool;
}
#Override
public void contextDestroyed(ServletContextEvent event) {
// This function is called when the Servlet is destroyed.
HikariDataSource pool = (HikariDataSource) event.getServletContext().getAttribute("my-pool");
if (pool != null) {
pool.close();
}
}
#Override
public void contextInitialized(ServletContextEvent event) {
// This function is called when the application starts and will safely create a connection pool
// that can be used to connect to.
ServletContext servletContext = event.getServletContext();
DataSource pool = (DataSource) servletContext.getAttribute("my-pool");
if (pool == null) {
pool = createConnectionPool();
servletContext.setAttribute("my-pool", pool);
}
}
}
And now the error has changed to:
com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:826) ~[mysql-connector-java-8.0.22.jar!/:8.0.22]
... 33 common frames omitted
Caused by: java.net.SocketTimeoutException: connect timed out
java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:1.8.0_202]
java.net.AbstractPlainSocketImpl.doConnect(Unknown Source) ~[na:1.8.0_202]
java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source) ~[na:1.8.0_202]
java.net.AbstractPlainSocketImpl.connect(Unknown Source) ~[na:1.8.0_202]
java.net.SocksSocketImpl.connect(Unknown Source) ~[na:1.8.0_202]
java.net.Socket.connect(Unknown Source) ~[na:1.8.0_202]
com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:155) ~[mysql-connector-java-8.0.22.jar!/:8.0.22]
com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:63) ~[mysql-connector-java-8.0.22.jar!/:8.0.22]
It is working locally though with ConnectionPoolContextListener
java.net.SocketTimeoutException refers to a connection time out before a remote host's response can be received. The cause can be a local network issue, proxy or firewall incorrectly configured. If you are using a private IP, you need to check that the docker bridge network's IP range. Here is what the documentation says:
If a client cannot connect to the Cloud SQL instance using private IP, check to see if the client is using any IP in the range 172.17.0.0/16. Connections fail from any IP within the 172.17.0.0/16 range to Cloud SQL instances using private IP. Similarly, Cloud SQL instances created with an IP in that range are unreachable. This range is reserved for the docker bridge network.
To resolve some of the issues, you are experiencing, follow the documentation here and post any error messages you receive, for example, you could try:
Try the gcloud sql connect command to connect to your instance. This command authorizes your IP address for a short time. You can run this command in an environment with Cloud SDK and mysql client installed. You can also run this command in Cloud Shell, which is available in the Google Cloud Console and has Cloud SDK and the mysql client pre-installed.
Temporarily allow all IP addresses to connect to an instance. For IPv4 authorize 0.0.0.0/0 (for IPv6, authorize ::/0. After you have tested this, please make sure you remove it again as it opens up to the world!
Are you using connection pools?
If not, I would create a cache of connections so that when your application needs to link to the database, it can get a temporary connection from the pool. Once the application has finished its operation, the connection returns to the pool again for later use. For this to work correctly, the connection needs to be open and closed efficiently and not waste any resources.

mockmvc mocking token does not work and tries to validate on tokenstore

I have an example of an API in spring that provides some services and I'm trying to secure them with OAuth2.
The API with security seems somehow to work when I use but now that I have all my tests failing and because of that, I'm taking a look at lost of examples of how to mock security.
I'm currently trying to make this example run (the Strategy #1)
http://engineering.pivotal.io/post/faking_oauth_sso/
It should be quite easy but for some reason, I'm having some problems.
First I had a problem when starting the application because I cannot Autowire one OAuth2RestTemplate Bean.
***************************
APPLICATION FAILED TO START
***************************
Description:
Field oauthRestTemplate in com.example.fakingOauthSSO.TokenController required a bean of type 'org.springframework.security.oauth2.client.OAuth2RestTemplate' that could not be found.
(fixed based on How to use OAuth2RestTemplate?)
I've put the code on GitHub just for simpler viewing https://github.com/cstmgl/testfakingoauthsso
the current probem is when I try to use the getAuthenticationInfo based on the mockmvc I get an error
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is error="access_denied", error_description="Error requesting access token."
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
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 org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:165)
at com.example.fakingOauthSSO.FakingOauthSsoApplicationTests.testGetAuthenticationInfo(FakingOauthSsoApplicationTests.java:50)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: error="access_denied", error_description="Error requesting access token."
at org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport.retrieveToken(OAuth2AccessTokenSupport.java:145)
at org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordAccessTokenProvider.obtainAccessToken(ResourceOwnerPasswordAccessTokenProvider.java:47)
at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainNewAccessTokenInternal(AccessTokenProviderChain.java:148)
at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainAccessToken(AccessTokenProviderChain.java:121)
at org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:221)
at org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken(OAuth2RestTemplate.java:173)
at com.example.fakingOauthSSO.TokenController.getAuthenticationInfo(TokenController.java:39)
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)
... 71 more
Caused by: org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://graph.facebook.com/oauth/access_token": Connection timed out: connect; nested exception is java.net.ConnectException: Connection timed out: connect
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:732)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:690)
at org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport.retrieveToken(OAuth2AccessTokenSupport.java:137)
... 90 more
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:668)
at sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:173)
at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:432)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:527)
at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:264)
at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:367)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1138)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1032)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153)
at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:76)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:723)
... 92 more
2018-05-22 12:52:52.650 INFO 6024 --- [ Thread-7] o.s.w.c.s.GenericWebApplicationContext : Closing org.springframework.web.context.support.GenericWebApplicationContext#56de6d6b: startup date [Tue May 22 12:47:45 SGT 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext#665df3c6
Disconnected from the target VM, address: '127.0.0.1:58294', transport: 'socket'
Process finished with exit code -1
Any idea why the mockMvc does not inject the token information? and why does the token try to contact the access token store?
shouldn't that be mocked by my mock service? It looks like it's still trying to connect the token redirect url but I was expecting this to be faked by my OAuthRequest
I did some debug and I think the problem is because when doing
return new AuthenticationInfo(oauthRestTemplate.getAccessToken(), userDetails);
it still tries to use the actual token and since it's null it tries to retrive again
I was expecting that the mockmvc would allow me to mock those variables
I've tried something like this:
private OAuth2ClientContext getOauth2ClientContext() {
System.out.println("in FakingOauthSsoApplicationTests.getOauth2ClientContext");
OAuth2ClientContext mockClient = mock(OAuth2ClientContext.class);
OAuth2RestTemplate mockTemplate = mock(OAuth2RestTemplate.class);
when(mockClient.getAccessToken()).thenReturn(new DefaultOAuth2AccessToken("my-fake-token"));
when(mockTemplate.getOAuth2ClientContext()).thenReturn(mockClient);
when(mockTemplate.getAccessToken()).thenReturn(new DefaultOAuth2AccessToken("my-fake-token"));
return mockClient;
}
still when I execute the code in debug mode seems the mock didn't eject all the instances only a few
the user details contain my fake data but the token does not
now it's working the main problem was that I was miss-understanding how to use the mock bean
using something like this fixed my problem
#MockBean
OAuth2RestTemplate template;
#Before
public void setup() {
mvc = webAppContextSetup(wac).build();
when(template.getOAuth2ClientContext()).thenReturn(new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest()));
when(template.getAccessToken()).thenReturn(new DefaultOAuth2AccessToken("my-fake-token"));
}

Issue with spring boot's thymeleaf auto configuration trying to resolve error template for rest application

My Spring Boot REST application only uses Thymeleaf for mail templates.
Unfortunately my boot configuration tries to resolve an error template when an error is encountered.
See exception below:
21:25:30.030 [http-nio-8080-exec-8] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet dispatcherServlet threw exception
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "error", template might not exist or might not be accessible by any of the configured Template Resolvers
at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:246)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011)
at org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:335)
at org.thymeleaf.spring4.view.ThymeleafView.render(ThymeleafView.java:190)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1257)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1037)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:980)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:726)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:471)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:394)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:311)
at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:395)
at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:254)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:177)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
21:25:30.030 [http-nio-8080-exec-8] ERROR o.a.c.c.C.[Tomcat].[localhost] - Exception Processing ErrorPage[errorCode=0, location=/error]
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: Error resolving template "error", template might not exist or might not be accessible by any of the configured Template Resolvers
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:726)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:471)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:394)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:311)
at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:395)
at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:254)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:177)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.thymeleaf.exceptions.TemplateInputException: Error resolving template "error", template might not exist or might not be accessible by any of the configured Template Resolvers
at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:246)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011)
at org.thymeleaf.spring4.view.ThymeleafView.renderFragment(ThymeleafView.java:335)
at org.thymeleaf.spring4.view.ThymeleafView.render(ThymeleafView.java:190)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1257)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1037)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:980)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
... 25 common frames omitted
This seems to indicate that Spring Boot has configured a Thymeleaf view resolver for pages (whereas I only uses Thymeleaf for mail templates).
How can I make sure Spring Boot only uses Thymeleaf for mail templates and thus avoid the above exception?
edit: I have the following line to my application.properties
server.error.whitelabel.enabled=false
but it does not seem to make any difference.
Using this property in application.properties:
spring.thymeleaf.enabled=false
seems to disable thymeleaf for spring mvc - whilst still keeping thymeleaf for mail templates.
see spring boot source code here.
edit:
Furthermore, it seems necessary to disable the default error controller registered by Spring Boot: see here.
One can for instance implement a custom error controller as described here: https://stackoverflow.com/a/25362790/536299
#SpringBootApplication(
exclude = {
ThymeleafAutoConfiguration.class,
})
public class ApiApplication {
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
}
}

Resources