Why getting connection refused with elasticsearch 8 and springboot 3 - spring-boot

I am trying to connect to elasticsearch 8 from my springboot 3 project floowing this official doc. But getting connection refused error without much details.
Here is my configuration
#Configuration
#Slf4j
#EnableElasticsearchRepositories(basePackages = "com....elastic")
public class ElasticConfig {
#Bean
public ClientConfiguration clientConfiguration() {
ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo("192.168.19.23:9200")
.usingSsl()
.withConnectTimeout(Duration.ofSeconds(5))
.withSocketTimeout(Duration.ofSeconds(3))
.withBasicAuth("elastic", "abc")
.build();
return clientConfiguration;
}
}
I have my SSL certificate in my jdk. The project runs properly but when it tries to save data on elasticsearch, it gets this error
org.springframework.dao.DataAccessResourceFailureException: Connection refused
at org.springframework.data.elasticsearch.client.elc.ElasticsearchExceptionTranslator.translateExceptionIfPossible(ElasticsearchExceptionTranslator.java:100)
at org.springframework.data.elasticsearch.client.elc.ElasticsearchExceptionTranslator.translateException(ElasticsearchExceptionTranslator.java:62)
at org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate.execute(ElasticsearchTemplate.java:540)
at org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate.doIndex(ElasticsearchTemplate.java:213)
at org.springframework.data.elasticsearch.core.AbstractElasticsearchTemplate.save(AbstractElasticsearchTemplate.java:204)
at org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository.lambda$save$5(SimpleElasticsearchRepository.java:172)
at org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository.executeAndRefresh(SimpleElasticsearchRepository.java:344)
at org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository.save(SimpleElasticsearchRepository.java:172)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:288)
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:136)
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:120)
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:516)
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:285)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:628)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:168)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:143)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:218)
at jdk.proxy2/jdk.proxy2.$Proxy131.save(Unknown Source)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:196)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:218)
at jdk.proxy2/jdk.proxy2.$Proxy131.save(Unknown Source)
at com...ServiceImpl.sendToElastic(ServiceImpl.java:171)
at com...ServiceImpl.getIdAndSend(ServiceImpl.java:132)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:196)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:752)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:752)
at org.springframework.aop.interceptor.AsyncExecutionInterceptor.lambda$invoke$0(AsyncExecutionInterceptor.java:115)
at org.springframework.util.concurrent.FutureUtils.lambda$toSupplier$0(FutureUtils.java:74)
at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1768)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.lang.RuntimeException: Connection refused
at org.springframework.data.elasticsearch.client.elc.ElasticsearchExceptionTranslator.translateException(ElasticsearchExceptionTranslator.java:61)
... 56 common frames omitted
Caused by: java.net.ConnectException: Connection refused
at org.elasticsearch.client.RestClient.extractAndWrapCause(RestClient.java:930)
at org.elasticsearch.client.RestClient.performRequest(RestClient.java:300)
at org.elasticsearch.client.RestClient.performRequest(RestClient.java:288)
at co.elastic.clients.transport.rest_client.RestClientTransport.performRequest(RestClientTransport.java:147)
at co.elastic.clients.elasticsearch.ElasticsearchClient.index(ElasticsearchClient.java:962)
at org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate.lambda$doIndex$6(ElasticsearchTemplate.java:213)
at org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate.execute(ElasticsearchTemplate.java:538)
... 55 common frames omitted
Caused by: java.net.ConnectException: Connection refused
at java.base/sun.nio.ch.Net.pollConnect(Native Method)
at java.base/sun.nio.ch.Net.pollConnectNow(Net.java:672)
at java.base/sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:946)
at org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor.processEvent(DefaultConnectingIOReactor.java:174)
at org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor.processEvents(DefaultConnectingIOReactor.java:148)
at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor.execute(AbstractMultiworkerIOReactor.java:351)
at org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager.execute(PoolingNHttpClientConnectionManager.java:221)
at org.apache.http.impl.nio.client.CloseableHttpAsyncClientBase$1.run(CloseableHttpAsyncClientBase.java:64)
... 1 common frames omitted
I have double checked my url, port and credentials. How do i solve this problem?

In springboot 3 just creating ClientConfiguration bean is not enough, the configuration class needs to extend the class ElasticsearchConfiguration as well.
#Configuration
#Slf4j
#EnableElasticsearchRepositories(basePackages = "com....elastic")
public class ElasticConfig extends ElasticsearchConfiguration {
#Override
public ClientConfiguration clientConfiguration() {
ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo("192.168.19.23:9200")
.usingSsl()
.withConnectTimeout(Duration.ofSeconds(5))
.withSocketTimeout(Duration.ofSeconds(3))
.withBasicAuth("elastic", "abc")
.build();
return clientConfiguration;
}
}
With this configuration ElasticsearchOperations, ElasticsearchClient and RestClient can be autowired as well.
Edit (P.J.Meisch): This is documented as well: https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.clients.restclient

Related

MockRestServiceServer.verify() is failed when the test did not mock all of API in the project

My project have 2 APIs and I want to separate test for each API.
So I am trying to use MockRestServiceServer to mock my API but MockRestServiceServer requires all of API that I have in my project have to mock even it does not need.
My spring boot version:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
There are my code: using 2 schedules to call 2 APIs
#Scheduled(fixedDelay = 3000)
public void schedule1() {
restTemplate.getForEntity(URI.create("http://localhost:9090/api1"), String.class);
}
#Scheduled(fixedDelay = 3000)
public void schedule2() {
restTemplate.getForEntity(URI.create("http://localhost:9090/api2"), String.class);
}
And my test
#Test
void testSchedule1() {
mockServer = MockRestServiceServer.bindTo(restTemplate).ignoreExpectOrder(true).build();
mockServer
.expect(ExpectedCount.manyTimes(),
MockRestRequestMatchers.requestTo(new StringStartsWith("http://localhost:9090/api1")))
.andExpect(MockRestRequestMatchers.method(HttpMethod.GET))
.andRespond(MockRestResponseCreators.withStatus(HttpStatus.OK).body(""));
mockServer.verify(Duration.ofSeconds(10));
}
#Test
void testSchedule2() {
mockServer = MockRestServiceServer.bindTo(restTemplate).ignoreExpectOrder(true).build();
mockServer
.expect(ExpectedCount.manyTimes(),
MockRestRequestMatchers.requestTo(new StringStartsWith("http://localhost:9090/api2")))
.andExpect(MockRestRequestMatchers.method(HttpMethod.GET))
.andRespond(MockRestResponseCreators.withStatus(HttpStatus.OK).body(""));
mockServer.verify(Duration.ofSeconds(10));
}
As default, 2 schedules will run in the same thread. So schedule1 executed first, then the testSchedule1 passed and testSchedule2 always failed.
2022-04-02 21:50:30.374 ERROR 2284 --- \[ scheduling-1\] o.s.s.s.TaskUtils$LoggingErrorHandler : Unexpected error occurred in scheduled task
org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:9090/api1": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:785) \~\[spring-web-5.3.18.jar:5.3.18\]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:751) \~\[spring-web-5.3.18.jar:5.3.18\]
at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:377) \~\[spring-web-5.3.18.jar:5.3.18\]
at com.example.demo1.test.Test.schedule1(Test.java:18) \~\[classes/:na\]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) \~\[na:na\]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) \~\[na:na\]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) \~\[na:na\]
at java.base/java.lang.reflect.Method.invoke(Method.java:568) \~\[na:na\]
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84) \~\[spring-context-5.3.18.jar:5.3.18\]
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) \~\[spring-context-5.3.18.jar:5.3.18\]
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:539) \~\[na:na\]
at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305) \~\[na:na\]
at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305) \~\[na:na\]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136) \~\[na:na\]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) \~\[na:na\]
at java.base/java.lang.Thread.run(Thread.java:833) \~\[na:na\]
Caused by: java.net.ConnectException: Connection refused: connect
at java.base/sun.nio.ch.Net.connect0(Native Method) \~\[na:na\]
at java.base/sun.nio.ch.Net.connect(Net.java:579) \~\[na:na\]
at java.base/sun.nio.ch.Net.connect(Net.java:568) \~\[na:na\]
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:588) \~\[na:na\]
at java.base/java.net.Socket.connect(Socket.java:633) \~\[na:na\]
at java.base/java.net.Socket.connect(Socket.java:583) \~\[na:na\]
at java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:183) \~\[na:na\]
at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:498) \~\[na:na\]
at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:603) \~\[na:na\]
at java.base/sun.net.www.http.HttpClient.\<init\>(HttpClient.java:246) \~\[na:na\]
at java.base/sun.net.www.http.HttpClient.New(HttpClient.java:351) \~\[na:na\]
at java.base/sun.net.www.http.HttpClient.New(HttpClient.java:373) \~\[na:na\]
at java.base/sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1309) \~\[na:na\]
at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1242) \~\[na:na\]
at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1128) \~\[na:na\]
at java.base/sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:1057) \~\[na:na\]
at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:76) \~\[spring-web-5.3.18.jar:5.3.18\]
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48) \~\[spring-web-5.3.18.jar:5.3.18\]
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:66) \~\[spring-web-5.3.18.jar:5.3.18\]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:776) \~\[spring-web-5.3.18.jar:5.3.18\]
... 15 common frames omitted
2022-04-02 21:50:30.376 ERROR 2284 --- \[ scheduling-1\] o.s.s.s.TaskUtils$LoggingErrorHandler : Unexpected error occurred in scheduled task
org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:9090/api2": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:785) \~\[spring-web-5.3.18.jar:5.3.18\]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:751) \~\[spring-web-5.3.18.jar:5.3.18\]
at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:377) \~\[spring-web-5.3.18.jar:5.3.18\]
at com.example.demo1.test.Test.schedule2(Test.java:23) \~\[classes/:na\]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) \~\[na:na\]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) \~\[na:na\]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) \~\[na:na\]
at java.base/java.lang.reflect.Method.invoke(Method.java:568) \~\[na:na\]
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84) \~\[spring-context-5.3.18.jar:5.3.18\]
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) \~\[spring-context-5.3.18.jar:5.3.18\]
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:539) \~\[na:na\]
at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305) \~\[na:na\]
at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305) \~\[na:na\]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136) \~\[na:na\]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) \~\[na:na\]
at java.base/java.lang.Thread.run(Thread.java:833) \~\[na:na\]
Caused by: java.net.ConnectException: Connection refused: connect
at java.base/sun.nio.ch.Net.connect0(Native Method) \~\[na:na\]
at java.base/sun.nio.ch.Net.connect(Net.java:579) \~\[na:na\]
at java.base/sun.nio.ch.Net.connect(Net.java:568) \~\[na:na\]
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:588) \~\[na:na\]
at java.base/java.net.Socket.connect(Socket.java:633) \~\[na:na\]
at java.base/java.net.Socket.connect(Socket.java:583) \~\[na:na\]
at java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:183) \~\[na:na\]
at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:498) \~\[na:na\]
at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:603) \~\[na:na\]
at java.base/sun.net.www.http.HttpClient.\<init\>(HttpClient.java:246) \~\[na:na\]
at java.base/sun.net.www.http.HttpClient.New(HttpClient.java:351) \~\[na:na\]
at java.base/sun.net.www.http.HttpClient.New(HttpClient.java:373) \~\[na:na\]
at java.base/sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1309) \~\[na:na\]
at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1242) \~\[na:na\]
at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1128) \~\[na:na\]
at java.base/sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:1057) \~\[na:na\]
at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:76) \~\[spring-web-5.3.18.jar:5.3.18\]
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48) \~\[spring-web-5.3.18.jar:5.3.18\]
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:66) \~\[spring-web-5.3.18.jar:5.3.18\]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:776) \~\[spring-web-5.3.18.jar:5.3.18\]
... 15 common frames omitted
2022-04-02 21:50:33.392 ERROR 2284 --- \[ scheduling-1\] o.s.s.s.TaskUtils$LoggingErrorHandler : Unexpected error occurred in scheduled task
java.lang.AssertionError: No further requests expected: HTTP GET http://localhost:9090/api1
0 request(s) executed.
at org.springframework.test.web.client.AbstractRequestExpectationManager.createUnexpectedRequestError(AbstractRequestExpectationManager.java:213) ~[spring-test-5.3.18.jar:5.3.18]
at org.springframework.test.web.client.UnorderedRequestExpectationManager.matchRequest(UnorderedRequestExpectationManager.java:44) ~[spring-test-5.3.18.jar:5.3.18]
at org.springframework.test.web.client.AbstractRequestExpectationManager.validateRequest(AbstractRequestExpectationManager.java:97) ~[spring-test-5.3.18.jar:5.3.18]
at org.springframework.test.web.client.MockRestServiceServer$MockClientHttpRequestFactory$1.executeInternal(MockRestServiceServer.java:338) ~[spring-test-5.3.18.jar:5.3.18]
at org.springframework.mock.http.client.MockClientHttpRequest.execute(MockClientHttpRequest.java:110) ~[spring-test-5.3.18.jar:5.3.18]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:776) ~[spring-web-5.3.18.jar:5.3.18]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:751) ~[spring-web-5.3.18.jar:5.3.18]
at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:377) ~[spring-web-5.3.18.jar:5.3.18]
at com.example.demo1.test.Test.schedule1(Test.java:18) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84) ~[spring-context-5.3.18.jar:5.3.18]
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-5.3.18.jar:5.3.18]
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:539) ~[na:na]
at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305) ~[na:na]
at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) ~[na:na]
at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]
After checked, I recognized If any schedule run first, the test case of that schedule will be passed.
I have checked the source code of MockRestServiceServer. It comes to AbstractRequestExpectationManager
in the verify method will call verifyInternal()
private int verifyInternal() {
if (this.expectations.isEmpty()) {
return 0;
}
if (!this.requestFailures.isEmpty()) {
throw new AssertionError("Some requests did not execute successfully.\n" +
this.requestFailures.entrySet().stream()
.map(entry -> "Failed request:\n" + entry.getKey() + "\n" + entry.getValue())
.collect(Collectors.joining("\n", "\n", "")));
}
int count = 0;
for (RequestExpectation expectation : this.expectations) {
if (!expectation.isSatisfied()) {
count++;
}
}
return count;
}
And the requestFailures is the map stores all failed requests (expected and unexpected)
#Override
public ClientHttpResponse validateRequest(ClientHttpRequest request) throws IOException {
RequestExpectation expectation;
synchronized (this.requests) {
if (this.requests.isEmpty()) {
afterExpectationsDeclared();
}
try {
// Try this first for backwards compatibility
ClientHttpResponse response = validateRequestInternal(request);
if (response != null) {
return response;
}
else {
expectation = matchRequest(request);
}
}
catch (Throwable ex) {
this.requestFailures.put(request, ex);
throw ex;
}
finally {
this.requests.add(request);
}
}
return expectation.createResponse(request);
}
If the schedule1 will be executed first, then it satisfied the condition: if (this.expectations.isEmpty()) first and the test case will be passed.
If the schedule1 executed after schedule1, the requestFailures will store the error of API 1, then it satisfied this condition: if (!this.requestFailures.isEmpty()) and the test case will be failed.
Is that MockRestServiceServer behavior? They want to mock all APIs?
If yes, please help me some alternative solution for my scenario.
Thanks

Unable to bind with active directory

I'm new in this domain and trying to bind with active directory using spring ldap client in java. I have already googled this and tried every given solution on internet but it didn't work for me. I'm getting following exception:
021-08-02T14:14:04,377 DEBUG [AbstractContextSource] - Got Ldap context on server [********]
2021-08-02T14:14:04,381 ERROR [UserService] - #### NamingException #### {}
org.springframework.ldap.UncategorizedLdapException: Uncategorized exception occured during LDAP processing; nested exception is javax.naming.NamingException: [LDAP: error code 1 - 000004DC: LdapErr: DSID-0C090A71, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v3839�]; remaining name ‘/’
at org.springframework.ldap.support.LdapUtils.convertLdapException(LdapUtils.java:228) ~[spring-ldap-core-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:397) ~[spring-ldap-core-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:309) ~[spring-ldap-core-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:642) ~[spring-ldap-core-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:578) ~[spring-ldap-core-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.ldap.core.LdapTemplate.find(LdapTemplate.java:1840) ~[spring-ldap-core-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.ldap.core.LdapTemplate.find(LdapTemplate.java:1861) ~[spring-ldap-core-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.ldap.core.LdapTemplate.findOne(LdapTemplate.java:1869) ~[spring-ldap-core-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.ldap.repository.query.AbstractLdapRepositoryQuery.execute(AbstractLdapRepositoryQuery.java:70) ~[spring-data-ldap-2.3.9.RELEASE.jar:2.3.9.RELEASE]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker$RepositoryQueryMethodInvoker$$Lambda$1419/947388427.invoke(Unknown Source) ~[?:?]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137) ~[spring-data-commons-2.5.1.jar:2.5.1]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121) ~[spring-data-commons-2.5.1.jar:2.5.1]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:159) ~[spring-data-commons-2.5.1.jar:2.5.1]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:138) ~[spring-data-commons-2.5.1.jar:2.5.1]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.7.jar:5.3.7]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.7.jar:5.3.7]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.7.jar:5.3.7]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.7.jar:5.3.7]
at com.sun.proxy.$Proxy79.findUserByUsername(Unknown Source) ~[?:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_45]
at java.lang.reflect.Method.invoke(Method.java:497) ~[?:1.8.0_45]
Dependencies:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-ldap</artifactId>
<version>${data.ldap.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
<version>${ldap.core.version}</version>
</dependency>
Following is what I've tried:
#Bean
public LdapContextSource contextSource()
{
LOGGER.atDebug().log("using given ldap server config: {}", ldapServerConfig);
LdapContextSource contextSource = new LdapContextSource();
contextSource.setUrl(ldapServerConfig.getUrl());
contextSource.setBase(ldapServerConfig.getBaseDn());
contextSource.setUserDn(ldapServerConfig.getUsername());
contextSource.setPassword(ldapServerConfig.getPassword());
contextSource.setAnonymousReadOnly(ldapServerConfig.isReadOnlyConnection());
//TODO: To add the support of TLS v1.0/v1.2/v1.3
if (ldapServerConfig.isTlsEnabled())
{
ExternalTlsDirContextAuthenticationStrategy dirContextAuthenticationStrategy = new ExternalTlsDirContextAuthenticationStrategy();
contextSource.setAuthenticationStrategy(dirContextAuthenticationStrategy);
}
return contextSource;
}
#Bean
public LdapTemplate ldapTemplate(ContextSource pooledContextSource, ContextSource contextSource)
{
LOGGER.atInfo().log("connection pooling enabled: {}", ldapServerConfig.isConnectionPooling());
return ldapServerConfig.isConnectionPooling() ? new LdapTemplate(pooledContextSource) : new LdapTemplate(contextSource);
}
private ResponseEntity<ILdapResponse> authenticate(String username)
{
ResponseEntity<ILdapResponse> responseEntity;
ILdapResponse ldapResponse;
try
{
User user = userRepository.findUserByUsername(username);
Furthermore I've tried to connect with the test server and it's working fine and successfully connected. Following are the test server details
ldap.server.url=ldap://ldap.forumsys.com:389/
ldap.server.baseDn=dc=example,dc=com
ldap.server.username=cn=read-only-admin,dc=example,dc=com
ldap.server.password=password
Also I've tried to connect with the ldap console and got the successful PROD environment connection.I don't know what i'm missing in client due to which i'm unable to connect. Please guide me if i'm missing anything. Thanks in advance
ldapsearch -d 3 -x -h <url> -p 389 -D <DN/username> -W -b <base dn> cn

Spring boot LDAP get memberOf in ODM

I'm currenly building an application using Spring boot LDAP, but have some problems accessing the 'memberOf' property to determine which groups the users belongs to.
I have seen Spring LDAP and MemberOf but I am using the ODM to get the user from LDAP, when trying to add the 'memberOf' property I get the following error:
org.springframework.ldap.odm.core.impl.MetaDataException: Can't determine destination type for field private java.util.ArrayList nl.quintor.afstudeermanagementtool.entitiy.LdapUser.memberOf in class class nl.quintor.afstudeermanagementtool.entitiy.LdapUser
at org.springframework.ldap.odm.core.impl.AttributeMetaData.determineFieldType(AttributeMetaData.java:167) ~[spring-ldap-core-2.3.3.RELEASE.jar:2.3.3.RELEASE]
at org.springframework.ldap.odm.core.impl.AttributeMetaData.<init>(AttributeMetaData.java:234) ~[spring-ldap-core-2.3.3.RELEASE.jar:2.3.3.RELEASE]
at org.springframework.ldap.odm.core.impl.ObjectMetaData.<init>(ObjectMetaData.java:132) ~[spring-ldap-core-2.3.3.RELEASE.jar:2.3.3.RELEASE]
at org.springframework.ldap.odm.core.impl.DefaultObjectDirectoryMapper.addManagedClass(DefaultObjectDirectoryMapper.java:151) ~[spring-ldap-core-2.3.3.RELEASE.jar:2.3.3.RELEASE]
at org.springframework.ldap.odm.core.impl.DefaultObjectDirectoryMapper.getEntityData(DefaultObjectDirectoryMapper.java:108) ~[spring-ldap-core-2.3.3.RELEASE.jar:2.3.3.RELEASE]
at org.springframework.ldap.odm.core.impl.DefaultObjectDirectoryMapper.filterFor(DefaultObjectDirectoryMapper.java:468) ~[spring-ldap-core-2.3.3.RELEASE.jar:2.3.3.RELEASE]
at org.springframework.ldap.core.LdapTemplate.find(LdapTemplate.java:1824) ~[spring-ldap-core-2.3.3.RELEASE.jar:2.3.3.RELEASE]
at org.springframework.ldap.core.LdapTemplate.findAll(LdapTemplate.java:1806) ~[spring-ldap-core-2.3.3.RELEASE.jar:2.3.3.RELEASE]
at org.springframework.ldap.core.LdapTemplate.findAll(LdapTemplate.java:1814) ~[spring-ldap-core-2.3.3.RELEASE.jar:2.3.3.RELEASE]
at org.springframework.data.ldap.repository.support.SimpleLdapRepository.findAll(SimpleLdapRepository.java:183) ~[spring-data-ldap-2.3.9.RELEASE.jar:2.3.9.RELEASE]
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.data.repository.core.support.ImplementationInvocationMetadata.invoke(ImplementationInvocationMetadata.java:72) ~[spring-data-commons-2.3.9.RELEASE.jar:2.3.9.RELEASE]
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:382) ~[spring-data-commons-2.3.9.RELEASE.jar:2.3.9.RELEASE]
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:205) ~[spring-data-commons-2.3.9.RELEASE.jar:2.3.9.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:550) ~[spring-data-commons-2.3.9.RELEASE.jar:2.3.9.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.14.RELEASE.jar:5.2.14.RELEASE]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:155) ~[spring-data-commons-2.3.9.RELEASE.jar:2.3.9.RELEASE]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:130) ~[spring-data-commons-2.3.9.RELEASE.jar:2.3.9.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.14.RELEASE.jar:5.2.14.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95) ~[spring-aop-5.2.14.RELEASE.jar:5.2.14.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.14.RELEASE.jar:5.2.14.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.2.14.RELEASE.jar:5.2.14.RELEASE]
at com.sun.proxy.$Proxy82.findAll(Unknown Source) ~[na: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.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344) ~[spring-aop-5.2.14.RELEASE.jar:5.2.14.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198) ~[spring-aop-5.2.14.RELEASE.jar:5.2.14.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.2.14.RELEASE.jar:5.2.14.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.2.14.RELEASE.jar:5.2.14.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.14.RELEASE.jar:5.2.14.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.2.14.RELEASE.jar:5.2.14.RELEASE]
at com.sun.proxy.$Proxy82.findAll(Unknown Source) ~[na:na]
at nl.quintor.afstudeermanagementtool.seeders.DatabaseSeeder.seedUserTable(DatabaseSeeder.java:59) ~[classes/:na]
at nl.quintor.afstudeermanagementtool.seeders.DatabaseSeeder.seed(DatabaseSeeder.java:39) ~[classes/: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.context.event.ApplicationListenerMethodAdapter.doInvoke(ApplicationListenerMethodAdapter.java:305) ~[spring-context-5.2.14.RELEASE.jar:5.2.14.RELEASE]
at org.springframework.context.event.ApplicationListenerMethodAdapter.processEvent(ApplicationListenerMethodAdapter.java:190) ~[spring-context-5.2.14.RELEASE.jar:5.2.14.RELEASE]
at org.springframework.context.event.ApplicationListenerMethodAdapter.onApplicationEvent(ApplicationListenerMethodAdapter.java:153) ~[spring-context-5.2.14.RELEASE.jar:5.2.14.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172) ~[spring-context-5.2.14.RELEASE.jar:5.2.14.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165) ~[spring-context-5.2.14.RELEASE.jar:5.2.14.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139) ~[spring-context-5.2.14.RELEASE.jar:5.2.14.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:404) ~[spring-context-5.2.14.RELEASE.jar:5.2.14.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:361) ~[spring-context-5.2.14.RELEASE.jar:5.2.14.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:898) ~[spring-context-5.2.14.RELEASE.jar:5.2.14.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:554) ~[spring-context-5.2.14.RELEASE.jar:5.2.14.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.10.RELEASE.jar:2.3.10.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:755) ~[spring-boot-2.3.10.RELEASE.jar:2.3.10.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) ~[spring-boot-2.3.10.RELEASE.jar:2.3.10.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:402) ~[spring-boot-2.3.10.RELEASE.jar:2.3.10.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:312) ~[spring-boot-2.3.10.RELEASE.jar:2.3.10.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1247) ~[spring-boot-2.3.10.RELEASE.jar:2.3.10.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1236) ~[spring-boot-2.3.10.RELEASE.jar:2.3.10.RELEASE]
at nl.quintor.afstudeermanagementtool.AfstudeermanagementtoolApplication.main(AfstudeermanagementtoolApplication.java:16) ~[classes/: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.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.3.10.RELEASE.jar:2.3.10.RELEASE]
2021-05-18 16:14:16.109 INFO 14468 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2021-05-18 16:14:16.112 INFO 14468 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2021-05-18 16:14:16.139 INFO 14468 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
Process finished with exit code 0
The code I'm using is:
#Entry(
objectClasses = { "user, Person", "top", "organizationalPerson" })
public class LdapUser {
private #Id Name id;
private #Attribute(name = "cn") String fullName;
private #Attribute(name = "sAMAccountName") String username;
private #Attribute(name ="memberof", readonly = true)
ArrayList<?> memberOf;
public LdapUser() { }
public LdapUser(String fullName, String username, ArrayList<?> memberOf) {
this.fullName = fullName;
this.username = username;
this.memberOf = memberOf;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public ArrayList<?> getMemberOf() {
return memberOf;
}
public void setMemberOf(ArrayList<?> memberOf) {
this.memberOf = memberOf;
}
}
This appears to be a "shortcoming" common to reflection-based object mapping frameworks in Java.
Annotating Java class fields with #Attribute only works if the annotated field is a concrete type: that is why the annotation works with ArrayList<String> but not List<String> or ArrayList<?>, because in the latter two cases the object mapper would have to 'guess' which concrete type to use when populating that field. In other words, the object mapper cannot call new List<String>(), so it throws an exception.
You can read about a similar problem affecting the JPA ORM standard. JPA appears to have a workaround by providing the targetEntity attribute element, but this is only present on some of their annotations (like #ManyToMany), and not on #Column, which is roughly equivalent to #Attribute here.

PowerMockRunner Tests working on Eclipse fail on STS by java.lang.reflect.InvocationTargetException

I'm running a project with some JUnit4 tests that are using PowerMockRunner on Eclipse with no problem, all tests ok.
But running the same on Spring Tool Suite (over Eclipse), those tests that use PowerMockRunner fail by initializationError caused by the following trace:
org.objenesis.ObjenesisException: java.lang.reflect.InvocationTargetException
at org.objenesis.instantiator.sun.SunReflectionFactoryHelper.newConstructorForSerialization(SunReflectionFactoryHelper.java:55)
at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.(SunReflectionFactoryInstantiator.java:38)
at org.objenesis.strategy.StdInstantiatorStrategy.newInstantiatorOf(StdInstantiatorStrategy.java:58)
at org.objenesis.ObjenesisBase.getInstantiatorOf(ObjenesisBase.java:91)
at org.powermock.reflect.internal.WhiteboxImpl.newInstance(WhiteboxImpl.java:222)
at org.powermock.reflect.Whitebox.newInstance(Whitebox.java:139)
at org.powermock.tests.utils.impl.AbstractTestSuiteChunkerImpl.registerProxyframework(AbstractTestSuiteChunkerImpl.java:158)
at org.powermock.tests.utils.impl.AbstractTestSuiteChunkerImpl.chunkClass(AbstractTestSuiteChunkerImpl.java:181)
at org.powermock.tests.utils.impl.AbstractTestSuiteChunkerImpl.(AbstractTestSuiteChunkerImpl.java:96)
at org.powermock.tests.utils.impl.AbstractTestSuiteChunkerImpl.(AbstractTestSuiteChunkerImpl.java:89)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.(JUnit4TestSuiteChunkerImpl.java:49)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.(AbstractCommonPowerMockRunner.java:32)
at org.powermock.modules.junit4.PowerMockRunner.(PowerMockRunner.java:34)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:90)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:76)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:49)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:526)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.objenesis.instantiator.sun.SunReflectionFactoryHelper.newConstructorForSerialization(SunReflectionFactoryHelper.java:45)
... 30 more
Caused by: java.lang.IllegalAccessError: class jdk.internal.reflect.ConstructorAccessorImpl loaded by org.powermock.core.classloader.MockClassLoader #37883b97 cannot access jdk/internal/reflect superclass jdk.internal.reflect.MagicAccessorImpl
at java.base/java.lang.ClassLoader.defineClass1(Native Method)
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
at org.powermock.core.classloader.MockClassLoader.loadUnmockedClass(MockClassLoader.java:238)
at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:182)
at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:70)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
at java.base/java.lang.ClassLoader.defineClass1(Native Method)
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
at org.powermock.core.classloader.MockClassLoader.loadUnmockedClass(MockClassLoader.java:238)
at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:182)
at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:70)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
at java.base/java.lang.ClassLoader.defineClass1(Native Method)
at java.base/java.lang.System$2.defineClass(System.java:2189)
at java.base/jdk.internal.reflect.ClassDefiner.defineClass(ClassDefiner.java:65)
at java.base/jdk.internal.reflect.MethodAccessorGenerator$1.run(MethodAccessorGenerator.java:400)
at java.base/jdk.internal.reflect.MethodAccessorGenerator$1.run(MethodAccessorGenerator.java:394)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:312)
at java.base/jdk.internal.reflect.MethodAccessorGenerator.generate(MethodAccessorGenerator.java:393)
at java.base/jdk.internal.reflect.MethodAccessorGenerator.generateSerializationConstructor(MethodAccessorGenerator.java:112)
at java.base/jdk.internal.reflect.ReflectionFactory.generateConstructor(ReflectionFactory.java:466)
at java.base/jdk.internal.reflect.ReflectionFactory.newConstructorForSerialization(ReflectionFactory.java:379)
at jdk.unsupported/sun.reflect.ReflectionFactory.newConstructorForSerialization(ReflectionFactory.java:98)
... 35 more
I'm using PowerMock as follows:
#RunWith(PowerMockRunner.class)
#PrepareForTest(SecurityContextHolder.class) //the static class that I have to acces
public class ClassToTest {
#Mock
SecurityContext mockSecurityContext;
//... #Before injecting the mocks to the sut
public void methodThatUsesPowerMockClass {
//... some stuff here
PowerMockito.mockStatic(SecurityContextHolder.class):
Mockito.when(SecurityContextHolder.getContext()).thenReturn(mockSecurityContext):
}
I've been trying using:
#PowerMockIgnore({ "javax.management.", "com.sun.org.apache.xerces.", "javax.xml.",
"org.xml.", "org.w3c.dom.", "com.sun.org.apache.xalan.", "javax.activation.*" })
at the beginning of the class but problem persists.

Turning off exception logging in HikariPool

I have two databases that are connected to my application and therefore I have two connectors like that:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = DMP_SAP_ENTITY_MANAGER_FACTORY_BEAN_NAME)
class SapHanaConnectionConfiguration #Autowired constructor(private val environment: Environment) {
private val driverClassName by lazy { environment.getProperty(DMP_SAP_DRIVER_CLASS_NAME) }
private val jdbcString by lazy { environment.getProperty(DMP_SAP_JDBC_STRING) }
private val username by lazy { environment.getProperty(DMP_SAP_USERNAME) }
private val password by lazy { environment.getProperty(DMP_SAP_PASSWORD) }
#Bean(name = [DMP_SAP_DATA_SOURCE_BEAN_NAME])
fun dataSource(): DataSource = DataSourceBuilder.create()
.driverClassName(driverClassName)
.url(jdbcString)
.username(username)
.password(password)
.build()
#Bean(name = [DMP_SAP_ENTITY_MANAGER_FACTORY_BEAN_NAME])
fun entityManagerFactory(
builder: EntityManagerFactoryBuilder,
#Qualifier(DMP_SAP_DATA_SOURCE_BEAN_NAME) dataSource: DataSource
): LocalContainerEntityManagerFactoryBean = builder
.dataSource(dataSource)
.packages(DMP_SAP_MODEL_PACKAGE)
.persistenceUnit(DMP_SAP_PERSISTENCE_UNIT_NAME)
.build()
#Bean(name = [DMP_SAP_TRANSACTION_MANAGER_BEAN_NAME])
fun transactionManager(#Qualifier(DMP_SAP_ENTITY_MANAGER_FACTORY_BEAN_NAME) entityManagerFactory: EntityManagerFactory): PlatformTransactionManager =
JpaTransactionManager(entityManagerFactory)
}
Problem is that this particular connector should be working only in production environment, because it connects to the database with clients data (which is located int the inner local network and it is not accessible outside of client's network). Right now while developing in my local environment both connectors start and therefore this SapHanaConnection throws exception because it can't establish connection to given DB.
2018-10-25 14:04:09.187 ERROR 13680 --- [n(14)-127.0.0.1] com.zaxxer.hikari.pool.HikariPool : HikariPool-2 - Exception during pool initialization.
com.sap.db.jdbc.exceptions.JDBCDriverException: SAP DBTech JDBC: Cannot connect to jdbc:sap://CLIENTS_MACHINE/ [Unknown host CLIENTS_MACHINE [CLIENTS_MACHINE], -709].
at com.sap.db.jdbc.exceptions.SQLExceptionSapDB._newInstance(SQLExceptionSapDB.java:126)
at com.sap.db.jdbc.exceptions.SQLExceptionSapDB._newInstance(SQLExceptionSapDB.java:203)
at com.sap.db.jdbc.exceptions.SQLExceptionSapDB.newInstance(SQLExceptionSapDB.java:50)
at com.sap.db.jdbc.DriverSapDB._connect(DriverSapDB.java:1404)
at com.sap.db.jdbc.DriverSapDB.connect(DriverSapDB.java:1102)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:117)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:123)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:365)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:194)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:460)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:534)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115)
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112)
at org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:151)
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:115)
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:78)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:324)
at org.springframework.boot.actuate.jdbc.DataSourceHealthIndicator.getProduct(DataSourceHealthIndicator.java:122)
at org.springframework.boot.actuate.jdbc.DataSourceHealthIndicator.doDataSourceHealthCheck(DataSourceHealthIndicator.java:109)
at org.springframework.boot.actuate.jdbc.DataSourceHealthIndicator.doHealthCheck(DataSourceHealthIndicator.java:104)
at org.springframework.boot.actuate.health.AbstractHealthIndicator.health(AbstractHealthIndicator.java:84)
at org.springframework.boot.actuate.health.CompositeHealthIndicator.health(CompositeHealthIndicator.java:68)
at org.springframework.boot.actuate.health.CompositeHealthIndicator.health(CompositeHealthIndicator.java:68)
at org.springframework.boot.actuate.health.HealthEndpoint.health(HealthEndpoint.java:47)
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.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:223)
at org.springframework.boot.actuate.endpoint.invoke.reflect.ReflectiveOperationInvoker.invoke(ReflectiveOperationInvoker.java:76)
at org.springframework.boot.actuate.endpoint.annotation.AbstractDiscoveredOperation.invoke(AbstractDiscoveredOperation.java:61)
at org.springframework.boot.actuate.endpoint.jmx.EndpointMBean.invoke(EndpointMBean.java:104)
at org.springframework.boot.actuate.endpoint.jmx.EndpointMBean.invoke(EndpointMBean.java:93)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1468)
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1309)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1401)
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:829)
at sun.reflect.GeneratedMethodAccessor193.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:357)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
I would like to somehow say that this connector should run only while some profile is active, is it possible?
I'm using Spring Boot with Kotlin.

Resources