No matter what I try, I cannot disable auto-configuration of spring-data-mongodb-reactive.
Properties
spring:
profiles: dev
data:
mongodb:
uri: "mongodb://user:pw#some-ip.amazonaws.com:27017/my-db"
repositories:
type: reactive
authentication-database: admin
Repository
#Repository
interface IMembersRepository: ReactiveMongoRepository<Member, String> {}
MongoConfig
#Configuration
#EnableReactiveMongoRepositories(basePackages = ["com.my.package.repository"])
class MongoConfig : AbstractReactiveMongoConfiguration() {
override fun reactiveMongoClient(): MongoClient = mongoClient()
override fun getDatabaseName(): String = "my-db"
#Bean()
fun mongoClient() = MongoClients.create()
#Bean()
override fun reactiveMongoTemplate() = ReactiveMongoTemplate(mongoClient(), databaseName)
}
AppConfig
#Configuration
#EnableWebFlux
#ComponentScan("com.my.package")
class AppConfig: WebFluxConfigurer {
override fun addCorsMappings(registry: CorsRegistry) {
registry.addMapping("api/**")
}
}
SpringBootApplication
#SpringBootApplication(exclude = [
MongoReactiveAutoConfiguration::class,
MongoReactiveDataAutoConfiguration::class,
MongoReactiveRepositoriesAutoConfiguration::class,
MongoAutoConfiguration::class,
MongoDataAutoConfiguration::class,
MongoRepositoriesAutoConfiguration::class,
EmbeddedMongoAutoConfiguration::class
])
class AstridServerApplication
fun main(args: Array<String>) {
runApplication<AstridServerApplication>(*args)
}
As you can see, I even went as far as disabling all available MongoDB auto-configs, and Boot still tries to establish connection to a local instance, which I do not have. But I did also try different combinations.
[localhost:27017] org.mongodb.driver.cluster : Exception in monitor thread while connecting to server localhost:27017
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.internal.connection.AsynchronousSocketChannelStream$OpenCompletionHandler.failed(AsynchronousSocketChannelStream.java:117) ~[mongodb-driver-core-3.11.2.jar:na]
at java.base/sun.nio.ch.Invoker.invokeUnchecked(Invoker.java:129) ~[na:na]
at java.base/sun.nio.ch.Invoker.invokeDirect(Invoker.java:158) ~[na:na]
at java.base/sun.nio.ch.Invoker.invoke(Invoker.java:186) ~[na:na]
at java.base/sun.nio.ch.Invoker.invoke(Invoker.java:298) ~[na:na]
at java.base/sun.nio.ch.WindowsAsynchronousSocketChannelImpl$ConnectTask.failed(WindowsAsynchronousSocketChannelImpl.java:308) ~[na:na]
at java.base/sun.nio.ch.Iocp$EventHandlerTask.run(Iocp.java:389) ~[na:na]
at java.base/sun.nio.ch.AsynchronousChannelGroupImpl$1.run(AsynchronousChannelGroupImpl.java:112) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) ~[na:na]
at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]
Caused by: java.io.IOException: The remote computer refused the network connection
at java.base/sun.nio.ch.Iocp.translateErrorToIOException(Iocp.java:299) ~[na:na]
... 5 common frames omitted
The client is connecting to the default address. I would focus on understanding why your config file isn't taking effect rather than on "disabling auto-configuration". The behavior you are seeing is consistent with the client not receiving any external configuration and using its built-in defaults.
Related
I developped spring remoting amqp rpc applications.
That's works well for methods that don't use bean with Scope SESSION.
For the other methods, the client can't use spring session, and I get this exception
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.userSession': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:362) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35) ~[spring-aop-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673) ~[spring-aop-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at io.kzreactive.akwtype.akwtypeback.common.service.UserSession$$EnhancerBySpringCGLIB$$55d53e95.setUser(<generated>) ~[classes/:na]
at io.kzreactive.akwtype.akwtypeback.engine.service.AppService.login(AppService.kt:30) ~[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:564) ~[na:na]
at org.springframework.remoting.support.RemoteInvocation.invoke(RemoteInvocation.java:215) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.remoting.support.DefaultRemoteInvocationExecutor.invoke(DefaultRemoteInvocationExecutor.java:39) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at io.kzreactive.akwtype.akwtypeback.gateway.rabbitmq.SessionDefaultRemoteInvocationExecutor.invoke(RabbitMQSession.kt:48) ~[classes/:na]
at org.springframework.remoting.support.RemoteInvocationBasedExporter.invoke(RemoteInvocationBasedExporter.java:78) [spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.remoting.support.RemoteInvocationBasedExporter.invokeAndCreateResult(RemoteInvocationBasedExporter.java:114) [spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.amqp.remoting.service.AmqpInvokerServiceExporter.onMessage(AmqpInvokerServiceExporter.java:80) [spring-amqp-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:1457) [spring-rabbit-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.actualInvokeListener(AbstractMessageListenerContainer.java:1348) [spring-rabbit-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:1324) [spring-rabbit-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:1303) [spring-rabbit-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doReceiveAndExecute(SimpleMessageListenerContainer.java:785) ~[spring-rabbit-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.receiveAndExecute(SimpleMessageListenerContainer.java:769) ~[spring-rabbit-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$700(SimpleMessageListenerContainer.java:77) ~[spring-rabbit-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1010) ~[spring-rabbit-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at java.base/java.lang.Thread.run(Thread.java:844) ~[na:na]
Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131) ~[spring-web-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.web.context.request.SessionScope.get(SessionScope.java:55) ~[spring-web-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:350) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
... 24 common frames omitted
So I would create and use a spring session over rabbit mq
First, I managed to pass the sessionId in RPC call
on the server I add an attribute
class SessionDefaultRemoteInvocationFactory : DefaultRemoteInvocationFactory() {
override fun createRemoteInvocation(methodInvocation: MethodInvocation?): RemoteInvocation {
return super.createRemoteInvocation(methodInvocation)
.apply { addAttribute("sessionId", RequestContextHolder.currentRequestAttributes().sessionId) }
}
}
on the client I can read it
class SessionDefaultRemoteInvocationExecutor : DefaultRemoteInvocationExecutor() {
override fun invoke(invocation: RemoteInvocation?, targetObject: Any?): Any {
if (invocation is RemoteInvocation) {
invocation.getAttribute("sessionId")?.let {
val sessionId = it.toString()
SecurityContextHolder.getContext().authentication = AnonymousAuthenticationToken(sessionId,
"anonymousUser", listOf(SimpleGrantedAuthority("ROLE_ANONYMOUS")))
val attr = RequestContextHolder.currentRequestAttributes() as ServletRequestAttributes // <= ERROR here
attr.request.getSession(true)
}
}
return super.invoke(invocation, targetObject)
}
}
but I don't manage to use it to create a spring session
How can I create a spring session in this NON http context
I tried to create a request context listener
#Configuration
#WebListener
class MyRequestContextListener : RequestContextListener()
but same error
For the moment I bypass the spring session and I inject a bean with the same behavior
#Component
#Scope("singleton")
class EngineThread(var engineSession: ThreadLocal<EngineSession> = ThreadLocal()) : IEngineSession by engineSession.getOrSet( { EngineSession() })
#Component
#Profile("engine & !test")
class SessionDefaultRemoteInvocationExecutor(val engineThread: EngineThread) : DefaultRemoteInvocationExecutor() {
val engineSessionStore : MutableMap<String, EngineSession> = mutableMapOf()
override fun invoke(invocation: RemoteInvocation?, targetObject: Any?): Any {
if (invocation is RemoteInvocation) {
invocation.getAttribute(SESSION_ID)?.let {
val sessionId = it.toString()
SecurityContextHolder.getContext().authentication = AnonymousAuthenticationToken(sessionId,
"anonymousUser", listOf(SimpleGrantedAuthority("ROLE_ANONYMOUS")))
if (! engineSessionStore.contains(sessionId)) {
engineSessionStore.put(sessionId, EngineSession())
}
engineThread.engineSession.set(engineSessionStore.getValue(sessionId))
}
}
return super.invoke(invocation, targetObject)
}
}
The job is done but I'm not very well with this solution
(I will add clean by softreference… but all this work is reinvent session instead of use spring session)
I am creating a spring cloud setup. I have Eureka Server, Auth Server, Gateway and two Micro-services. I am using Zuul for Gateway. Below is configuration of Eureka Server:
Main Class
#SpringBootApplication
#EnableEurekaServer
#EnableAdminServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
Application properties:
server.port: 8761
spring.application.name: discovery-server
logging.level.org.springframework.cloud.netflix.eureka: TRACE
eureka.instance.hostname: localhost
eureka.client.registerWithEureka: false
eureka.client.fetchRegistry: false
eureka.client.serviceUrl.defaultZone:
http://${eureka.instance.hostname}:${server.port}/eureka/
spring.boot.admin.context-path= /admin
Gateway:
Main Class:
#SpringBootApplication
#EnableZuulProxy
#EnableOAuth2Sso
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
properties:
server.port= 8765
spring.application.name= gateway-server
spring.jpa.database-platform= org.hibernate.dialect.MySQL5Dialect
spring.jpa.database= MYSQL
spring.jpa.open-in-view= false
spring.jpa.hibernate.ddl-auto= create
spring.jpa.properties.hibernate.implicit_naming_strategy=
org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl
spring.jpa.properties.hibernate.id.new_generator_mappings= false # id
generation defaults to table otherwise
spring.jpa.properties.hibernate.enable_lazy_load_no_trans= true
spring.jpa.properties.hibernate.generate_statistics= false
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.jdbc-url= jdbc:mysql://localhost:3306/cloudDB?
useUnicode=true&createDatabaseIfNotExist=true&useSSL=false
spring.datasource.username= root
spring.datasource.password= root
spring.datasource.dbcp2.max-idle= 10000
logging.level.org.springframework.cloud.netflix.zuul= TRACE
zuul.routes.uaa.path= /uaa/**
zuul.routes.uaa.sensitiveHeaders=""
zuul.routes.uaa.serviceId= auth-server
zuul.routes.account.path= /account/**
zuul.routes.account.sensitiveHeaders= ""
zuul.routes.account.serviceId= account-service
zuul.routes.customer.path= /customer/**
zuul.routes.customer.sensitiveHeaders=
zuul.routes.customer.serviceId= customer
zuul.routes.fsp.path= /fsp/**
zuul.routes.fsp.sensitiveHeaders=
zuul.routes.fsp.serviceId= fsp-marketplace
eureka.client.registerWithEureka= false
eureka.client.serviceUrl.defaultZone= http://localhost:8761/eureka/
security.oauth2.sso.loginPath= /uaa/login
security.oauth2.client.accessTokenUri= http://localhost:8765/uua/oauth/token
security.oauth2.client.userAuthorizationUri= http://localhost:8765/uua/oauth/authorize
security.oauth2.client.clientId= acem
security.oauth2.client.clientSecret= secret
security.oauth2.client.clientAuthenticationScheme= form
security.oauth2.resource.userInfoUri= http://localhost:8765/user
security.oauth2.resource.preferTokenInfo= false
security.sessions= ALWAYS
Micro Service:
#SpringBootApplication
#EnableAutoConfiguration
#EnableDiscoveryClient
public class FspApplication {
public static void main(String[] args) {
SpringApplication.run(FspApplication.class, args);
}
}
properties:
server.port= ${PORT:4444}
spring.application.name= fsp-marketplace
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.database= MYSQL
spring.jpa.hibernate.ddl-auto= update
spring.jpa.properties.hibernate.implicit_naming_strategy=
org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.jdbc-url= jdbc:mysql://localhost:3306/cloudDB?
useUnicode=true&createDatabaseIfNotExist=true&useSSL=false
spring.datasource.username= root
spring.datasource.password= root
spring.datasource.dbcp2.max-idle= 10000
logging.level.org.springframework.security= TRACE
security.user.name= root
security.user.password= password
security.oauth2.resource.userInfoUri= http://localhost:8999/user
eureka.client.serviceUrl.defaultZone= http://localhost:8761/eureka/
If any can help me on this, Thanks in advance. :)
All application are working fine individually. But when I start in cluster after service discovery
Eureka Server
hang in few mins.
I get this exception in discovery client:
DiscoveryClient_AUTH-SERVER/192.168.3.180:auth-server:8999 - de-
registration failedCannot execute request on any known server
com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server
at com.netflix.discovery.shared.transport.decorator.RetryableEurekaHttpClient.execute(RetryableEurekaHttpClient.java:112) ~[eureka-client-1.9.0.jar:1.9.0]
at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.cancel(EurekaHttpClientDecorator.java:71) ~[eureka-client-1.9.0.jar:1.9.0]
at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$2.execute(EurekaHttpClientDecorator.java:74) ~[eureka-client-1.9.0.jar:1.9.0]
at com.netflix.discovery.shared.transport.decorator.SessionedEurekaHttpClient.execute(SessionedEurekaHttpClient.java:77) ~[eureka-client-1.9.0.jar:1.9.0]
at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.cancel(EurekaHttpClientDecorator.java:71) ~[eureka-client-1.9.0.jar:1.9.0]
at com.netflix.discovery.DiscoveryClient.unregister(DiscoveryClient.java:923) [eureka-client-1.9.0.jar:1.9.0]
at com.netflix.discovery.DiscoveryClient.shutdown(DiscoveryClient.java:901) [eureka-client-1.9.0.jar:1.9.0]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_101]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_101]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_101]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_101]
at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:223) [spring-core-5.0.6.RELEASE.jar:5.0.6.RELEASE]
at org.springframework.cloud.context.scope.GenericScope$LockedScopedProxyFactoryBean.invoke(GenericScope.java:483) [spring-cloud-context-2.0.0.RC2.jar:2.0.0.RC2]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) [spring-aop-5.0.6.RELEASE.jar:5.0.6.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) [spring-aop-5.0.6.RELEASE.jar:5.0.6.RELEASE]
at com.sun.proxy.$Proxy129.shutdown(Unknown Source) [na:na]
at org.springframework.cloud.netflix.eureka.serviceregistry.EurekaRegistration.close(EurekaRegistration.java:207) [spring-cloud-netflix-eureka-client-2.0.0.RC2.jar:2.0.0.RC2]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_101]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_101]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_101]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_101]
at org.springframework.beans.factory.support.DisposableBeanAdapter.invokeCustomDestroyMethod(DisposableBeanAdapter.java:337) [spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
at org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:271) [spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:577) [spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingleton(DefaultSingletonBeanRegistry.java:549) [spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingleton(DefaultListableBeanFactory.java:957) [spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons(DefaultSingletonBeanRegistry.java:510) [spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingletons(DefaultListableBeanFactory.java:964) [spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1041) [spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]
Auth Server:
#SpringBootApplication
#EnableAuthorizationServer
#EnableDiscoveryClient
#EnableResourceServer
public class AuthServerApplication {
public static void main(String[] args) {
SpringApplication.run(AuthServerApplication.class, args);
}
#Bean
#Primary
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource datasource() {
return DataSourceBuilder.create().build();
}
}
Application properties:
server.port= 8999
spring.application.name= auth-server
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.database= MYSQL
spring.jpa.hibernate.ddl-auto= update
spring.jpa.properties.hibernate.implicit_naming_strategy= org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.jdbc-url= jdbc:mysql://localhost:3306/cloudDB1?useUnicode=true&createDatabaseIfNotExist=true&useSSL=false
spring.datasource.username= root
spring.datasource.password= root
spring.datasource.dbcp2.max-idle= 10000
logging.level.org.springframework.security= TRACE
security.basic.enabled= false
security.user.name= root
security.user.password= password
security.oauth2.client.client-id= acem
security.oauth2.client.client-secret= secret
eureka.client.serviceUrl.defaultZone= http://localhost:8761/eureka/
I have built a microservice using Java 8 and SpringBoot 2. From this microservice, I'm trying to consume another REST API service. However, I'm getting the following error on Chrome. I have already disabled the windows firewall and McAfee antivirus firewall but still getting the same error. I can call the REST API directly using the Postman tool but not through my microservice.
Error:-
java.lang.IllegalStateException: The underlying HTTP client completed
without emitting a response.
2018-06-12 15:21:29.300 ERROR 17996 --- [ctor-http-nio-3]
.a.w.r.e.DefaultErrorWebExceptionHandler : Failed to handle request
[GET http://localhost:8080/category/search]
io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection
timed out: no further information: test.usdemo.xyz.com/92.54.41.24:443
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
~[na:1.8.0_171] at
sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
~[na:1.8.0_171] at
io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:325)
~[netty-transport-4.1.24.Final.jar:4.1.24.Final] at
io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:340)
~[netty-transport-4.1.24.Final.jar:4.1.24.Final] at
io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:633)
~[netty-transport-4.1.24.Final.jar:4.1.24.Final] at
io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:580)
~[netty-transport-4.1.24.Final.jar:4.1.24.Final] at
io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:497)
~[netty-transport-4.1.24.Final.jar:4.1.24.Final] at
io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:459)
~[netty-transport-4.1.24.Final.jar:4.1.24.Final] at
io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:884)
~[netty-common-4.1.24.Final.jar:4.1.24.Final] at
java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_171] Caused by:
java.net.ConnectException: Connection timed out: no further
information ... 10 common frames omitted
Controller class:-
#RestController
public class CategorySearchController {
private final CategorySearchService categorySearchService;
#Autowired
public CategorySearchController(CategorySearchService categorySearchService) {
this.categorySearchService = categorySearchService;
}
#GetMapping(path = "/search-category")
public Mono<CategoryResponse> searchCategories(SearchRequest categorySearchRequest){
return categorySearchService
.searchCategories()
.switchIfEmpty(Mono.error(
new EntityNotFoundException("No category matching " + categorySearchRequest.getSearchTerm() + " was found")));
}
}
Service class:-
#Service
public class CategorySearchServiceImpl implements CategorySearchService {
private String baseUrl = "https://demo0954903.mockable.io";
#Override
public Mono<CategoryResponse> searchCategories() {
WebClient webClient = WebClient.create(baseUrl);
return webClient.
get()
.uri("/category-search")
.retrieve()
.bodyToMono(CategoryResponse.class);
}
}
I found the solution for this issue. I need to add the proxy in the webclient as follows:-
private final WebClient webClient;
ReactorClientHttpConnector connector = new ReactorClientHttpConnector(
options -> options.httpProxy(addressSpec -> {
return addressSpec.host(PROXY_HOST).port(PROXY_PORT);
}));
this.webClient = webClientBuilder.baseUrl(BASE_URL).clientConnector(connector).build();
I'm writing a simple spring boot backend application which uses MongoDB. I'm using spring data rest for the classic rest api calls and then developing a couple of custom controllers. I started develop it with a local mongo db instance and everything worked fine. Now I'm moving to a proper mongo db instance in another server and I've some problem using the custom controllers. I set spring.data.mongodb.host and spring.data.mongodb.port on my application.properties and the rest apis provided by spring data rest work successfully: I can insert and get data with no problem. But when I try to call the custom controller it looks like is still trying to connect to a local instance as I get this error message from the log:
com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused (Connection refused)}}]
This is my repository
#RepositoryRestResource(collectionResourceRel = "deployment", path = "deployment")
public interface DeploymentRepository extends MongoRepository<DeploymentRecord, String> {
public List<DeploymentRecord> findByVmNameOrderByDeploymentTimeDesc(#Param("vmName") String vmName);
public DeploymentRecord findFirstByVmNameOrderByDeploymentTimeDesc(#Param("vmName") String vmName);
}
and this is the start of the custom controller:
#RestController
#EnableHypermediaSupport(type = {HypermediaType.HAL})
public class EnvironmentController {
#Autowired
private DeploymentRepository deploymentRepository;
#RequestMapping(value = "/listEnvironmentResources", method = RequestMethod.GET, produces = MediaTypes.HAL_JSON_VALUE)
public Resources<Resource<EnvironmentRecordResource>> getEnvironmentResourceList(){
This is the application (the default, basically)
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
The object data it's very simple, string fields and just getters.
How can I configure the custom controller to use the same configuration used by the self generated rest api that are on the application.properties?
Thanks,
Michele.
UPDATE
I tried to override the configuration creating my own
#Configuration
public class SpringMongoConfig extends AbstractMongoConfiguration{
#Autowired
private Environment env;
#Override
#Bean
public Mongo mongo() throws Exception
{
return new MongoClient(env.getProperty("spring.data.mongodb.host") , Integer.valueOf(env.getProperty("spring.data.mongodb.port")) );
}
public #Bean MongoTemplate mongoTemplate() throws Exception
{
return new MongoTemplate(mongo(), getDatabaseName());
}
#Override
protected String getDatabaseName() {
return "test";
}
}
Still, this is read only by the standard api, custom controller wants to connect to 127.0.0.1:
2017-11-23 11:44:02.441 INFO 7 --- [nio-8080-exec-3] org.mongodb.driver.cluster : Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2017-11-23 11:44:02.452 INFO 7 --- [127.0.0.1:27017] org.mongodb.driver.cluster : Exception in monitor thread while connecting to server 127.0.0.1:27017
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.connection.SocketStream.open(SocketStream.java:63) ~[mongodb-driver-core-3.4.3.jar!/:na]
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115) ~[mongodb-driver-core-3.4.3.jar!/:na]
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:113) ~[mongodb-driver-core-3.4.3.jar!/:na]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_151]
Caused by: java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:1.8.0_151]
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[na:1.8.0_151]
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_151]
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_151]
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_151]
at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_151]
at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:57) ~[mongodb-driver-core-3.4.3.jar!/:na]
at com.mongodb.connection.SocketStream.open(SocketStream.java:58) ~[mongodb-driver-core-3.4.3.jar!/:na]
... 3 common frames omitted
Why is my spring test set up failing with the following not-so-useful error messages below? All suggestions are appreciated.
JUnit Output
java.lang.NoClassDefFoundError: org/junit/runners/model/MultipleFailureException
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.withAfterClasses(SpringJUnit4ClassRunner.java:188)
at org.junit.runners.ParentRunner.classBlock(ParentRunner.java:145)
at org.junit.runners.ParentRunner.run(ParentRunner.java:235)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run (SpringJUnit4ClassRunner.java:163)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.ClassNotFoundException: org.junit.runners.model.MultipleFailureException
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 10 more
Console Output
INFO : org.springframework.test.context.support.DefaultTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
INFO : org.springframework.test.context.support.DefaultTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
INFO : org.springframework.test.context.support.DefaultTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
INFO : org.springframework.test.context.support.DefaultTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener#76959acc, org.springframework.test.context.support.DependencyInjectionTestExecutionListener#57e603e6, org.springframework.test.context.support.DirtiesContextTestExecutionListener#3e0a1e1f]
Here is the target snippet
#Service
public class PipApps {
#Resource( name = "apps" )
private Properties apps;
#Autowired
private SitePreferenceHandler sitePreferenceHandler;
#Autowired
private PipsTable pipsTable;
private SitePreference sitePreference;
private Device device;
public PipApps( HttpServletRequest request, HttpServletResponse response ){
sitePreference = sitePreferenceHandler.handleSitePreference( request, response );
device = DeviceUtils.getRequiredCurrentDevice( request );
}
public Properties getApps(){
return apps;
}
public Device getDevice(){
return device;
}
public SitePreference getSitePreference(){
return sitePreference;
}
public DeviceRouteTable getPipsTable(){
return pipsTable;
}
}
And the test snippet
#RunWith( SpringJUnit4ClassRunner.class )
#ContextConfiguration( locations={"src/test/resources/PipAppsTest-context.xml"} )
public class PipAppsTest {
#Mock
SitePreferenceHandler sitePreferenceHandler;
#Autowired
PipApps pipApps;
...
}
Update -- September 2015
Spring Framework 4.2.2 throws a more meaningful exception if JUnit 4.9 is not in the classpath. See SPR-13521 for details.
The following is an excerpt from the class-level Javadoc for SpringJUnit4ClassRunner:
NOTE: As of Spring Framework 4.1, this class requires JUnit 4.9 or higher.
The class in question, MultipleFailureException, was introduced in JUnit 4.9.
So that's why your test is failing with the ClassNotFoundException.
Upgrading to JUnit 4.9 (or preferably 4.12) will therefore solve your problem.
Regards,
Sam (author of the Spring TestContext Framework)