Spring Reactive MongoDB connected to MongoDB cloud - java

I downloaded the example from Spring Data MongoDB 2.0 - Reactive examples.
I'm failing to understand how to make it work.
I set up a cluster in cloud.mongodb.com and they supply me with:
If I am using driver 3.6 or later:
mongodb+srv://stavalfi:<PASSWORD>#cluster0-9yjy8.mongodb.net/test
Else, if I am using driver 3.4 or earlier:
mongodb://stavalfi:<PASSWORD>#cluster0-shard-00-00-
9yjy8.mongodb.net:27017,cluster0-shard-00-01-
9yjy8.mongodb.net:27017,cluster0-shard-00-02-
9yjy8.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-
0&authSource=admin
I don't know what is the version of the driver which spring uses so I chose the first one:
#SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
#EnableReactiveMongoRepositories
#AutoConfigureAfter(EmbeddedMongoAutoConfiguration.class)
#RequiredArgsConstructor
class ApplicationConfiguration extends AbstractReactiveMongoConfiguration {
private final Environment environment;
public static void main(String args[]) throws InterruptedException {
ConfigurableApplicationContext run = SpringApplication.run(ApplicationConfiguration.class);
run.getBean(ReactiveMongoTemplate.class)
.save("something to push")
.subscribe(System.out::println, Throwable::printStackTrace, () -> System.out.println("success"));
Thread.sleep(1000000);
}
#Bean
public LoggingEventListener mongoEventListener() {
return new LoggingEventListener();
}
#Override
#Bean
#DependsOn("embeddedMongoServer")
public MongoClient reactiveMongoClient() {
return MongoClients.create(String.format("mongodb+srv://stavalfi:<MyAccountPassword!>#cluster0-9yjy8.mongodb.net/test"));
// int port = environment.getProperty("local.mongo.port", Integer.class);
// return MongoClients.create(String.format("mongodb://localhost:%d", port));
}
#Override
protected String getDatabaseName() {
return "reactive";
}
}
I'm sure I'm not doing anything as Spring Data MongoDB project expected me to do.
The Exception I get while creating the Bean: MongoClient
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'reactiveMongoClient' defined in example.springdata.mongodb.people.ApplicationConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.reactivestreams.client.MongoClient]: Factory method 'reactiveMongoClient' threw exception; nested exception is java.lang.UnsupportedOperationException: No SSL support in java.nio.channels.AsynchronousSocketChannel. For SSL support use com.mongodb.connection.netty.NettyStreamFactoryFactory
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:587) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1250) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:752) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:388) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1234) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
at example.springdata.mongodb.people.ApplicationConfiguration.main(ApplicationConfiguration.java:53) [classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.reactivestreams.client.MongoClient]: Factory method 'reactiveMongoClient' threw exception; nested exception is java.lang.UnsupportedOperationException: No SSL support in java.nio.channels.AsynchronousSocketChannel. For SSL support use com.mongodb.connection.netty.NettyStreamFactoryFactory
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:579) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
... 17 common frames omitted
Caused by: java.lang.UnsupportedOperationException: No SSL support in java.nio.channels.AsynchronousSocketChannel. For SSL support use com.mongodb.connection.netty.NettyStreamFactoryFactory
at com.mongodb.connection.AsynchronousSocketChannelStreamFactory.<init>(AsynchronousSocketChannelStreamFactory.java:58) ~[mongodb-driver-core-3.6.3.jar:na]
at com.mongodb.connection.AsynchronousSocketChannelStreamFactory.<init>(AsynchronousSocketChannelStreamFactory.java:43) ~[mongodb-driver-core-3.6.3.jar:na]
at com.mongodb.async.client.MongoClients.getStreamFactory(MongoClients.java:237) ~[mongodb-driver-async-3.6.3.jar:na]
at com.mongodb.async.client.MongoClients.create(MongoClients.java:181) ~[mongodb-driver-async-3.6.3.jar:na]
at com.mongodb.async.client.MongoClients.create(MongoClients.java:172) ~[mongodb-driver-async-3.6.3.jar:na]
at com.mongodb.reactivestreams.client.MongoClients.create(MongoClients.java:90) ~[mongodb-driver-reactivestreams-1.7.1.jar:na]
at com.mongodb.reactivestreams.client.MongoClients.create(MongoClients.java:75) ~[mongodb-driver-reactivestreams-1.7.1.jar:na]
at example.springdata.mongodb.people.ApplicationConfiguration.reactiveMongoClient(ApplicationConfiguration.java:70) [classes/:na]
at example.springdata.mongodb.people.ApplicationConfiguration$$EnhancerBySpringCGLIB$$6152c801.CGLIB$reactiveMongoClient$1(<generated>) ~[classes/:na]
at example.springdata.mongodb.people.ApplicationConfiguration$$EnhancerBySpringCGLIB$$6152c801$$FastClassBySpringCGLIB$$4cbf5891.invoke(<generated>) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at example.springdata.mongodb.people.ApplicationConfiguration$$EnhancerBySpringCGLIB$$6152c801.reactiveMongoClient(<generated>) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_161]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_161]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_161]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_161]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
... 18 common frames omitted
How can I fix this?

Played around with this some. You can find details from Mongo Java Driver tutorials.
First I tried using the DSL approach, which would be neat to have all the setup as code:
application.yml
mongo:
user: training_mongo
password: <my_password>
hosts:
- training-abcde.mongodb.net
database: training
MongoProperties.java
#ConfigurationProperties("mongo")
#Component
public class MongoProperties {
private String user;
private String password;
private List<String> hosts;
private String database;
ApplicationConfiguration.java
#Configuration
#EnableWebFlux
#EnableReactiveMongoRepositories
public class ApplicationConfig extends AbstractReactiveMongoConfiguration {
[...]
#Override
public MongoClient reactiveMongoClient() {
return create(MongoClientSettings.builder()
.clusterSettings(ClusterSettings.builder()
.hosts(mongoProperties.getHosts()
.stream()
.map(ServerAddress::new)
.collect(toList()))
.build())
.streamFactoryFactory(NettyStreamFactory::new)
.sslSettings(SslSettings.builder()
.enabled(true)
.build())
.credential(MongoCredential.createCredential(
mongoProperties.getUser(),
mongoProperties.getDatabase(),
mongoProperties.getPassword().toCharArray()))
.build());
}
#Override
protected String getDatabaseName() {
return DB_NAME;
}
This however crashes, because Netty fires a DNS lookup through the Java stack and that fails:
[DEBUG] [TestEventLogger] 2018-08-06 17:22:17.147 INFO 16148 --- [localhost:27017] org.mongodb.driver.cluster : Exception in monitor thread while connecting to server localhost:27017
[DEBUG] [TestEventLogger]
[DEBUG] [TestEventLogger] com.mongodb.MongoSocketOpenException: Exception opening socket
[ ... stacktrace ...]
[DEBUG] [TestEventLogger]
[DEBUG] [TestEventLogger] 2018-08-06 17:22:17.278 INFO 16148 --- [ Test worker] org.mongodb.driver.cluster : Cluster created with settings {hosts=[training-abcde.mongodb.net:27017], mode=MULTIPLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
[DEBUG] [TestEventLogger] 2018-08-06 17:22:17.279 INFO 16148 --- [ Test worker] org.mongodb.driver.cluster : Adding discovered server training-abcde.mongodb.net:27017 to client view of cluster
[DEBUG] [TestEventLogger] 2018-08-06 17:22:17.975 INFO 16148 --- [ Test worker] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
[TestEventLogger] 2018-08-06 17:22:18.006 INFO 16148 --- [ngodb.net:27017] org.mongodb.driver.cluster : Exception in monitor thread while connecting to server training-abcde.mongodb.net:27017
[DEBUG] [TestEventLogger]
[DEBUG] [TestEventLogger] com.mongodb.MongoSocketOpenException: Exception opening socket
[... stacktrace ...]
[DEBUG] [TestEventLogger] Caused by: java.net.UnknownHostException: No such host is known (training-abcde.mongodb.net)
[DEBUG] [TestEventLogger] at java.base/java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method) ~[na:na]
[DEBUG] [TestEventLogger] at java.base/java.net.InetAddress$PlatformNameService.lookupAllHostAddr(InetAddress.java:925) ~[na:na]
[DEBUG] [TestEventLogger] at java.base/java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1505) ~[na:na]
[DEBUG] [TestEventLogger] at java.base/java.net.InetAddress$NameServiceAddresses.get(InetAddress.java:844) ~[na:na]
[DEBUG] [TestEventLogger] at java.base/java.net.InetAddress.getAllByName0(InetAddress.java:1495) ~[na:na]
[DEBUG] [TestEventLogger] at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1354) ~[na:na]
[DEBUG] [TestEventLogger] at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1288) ~[na:na]
[DEBUG] [TestEventLogger] at java.base/java.net.InetAddress.getByName(InetAddress.java:1238) ~[na:na]
[DEBUG] [TestEventLogger] at io.netty.util.internal.SocketUtils$8.run(SocketUtils.java:146) ~[netty-common-4.1.25.Final.jar:4.1.25.Final]
[DEBUG] [TestEventLogger] at io.netty.util.internal.SocketUtils$8.run(SocketUtils.java:143) ~[netty-common-4.1.25.Final.jar:4.1.25.Final]
[DEBUG] [TestEventLogger] at java.base/java.security.AccessController.doPrivileged(Native Method) ~[na:na]
But doing things less elegantly via the connection URL seem to work:
ApplicationConfiguration.java:
#Configuration
#EnableWebFlux
#EnableReactiveMongoRepositories
public class ApplicationConfig extends AbstractReactiveMongoConfiguration {
private static final String CONNECTION_URL = "mongodb+srv://%s:%s#%s/%s?retryWrites=true&streamType=netty&ssl=true";
[...]
#Override
public MongoClient reactiveMongoClient() {
return MongoClients.create(getMongoConnectionUrl());
}
#Override
protected String getDatabaseName() {
return DB_NAME;
}
private String getMongoConnectionUrl() {
String connectionUrl = String.format(CONNECTION_URL, mongoProperties.getUser(), mongoProperties.getPassword(),
mongoProperties.getHosts().get(0), mongoProperties.getDatabase());
return connectionUrl;
}
[DEBUG] [TestEventLogger] 2018-08-06 18:25:37.132 INFO 4252 --- [ Test worker] org.mongodb.driver.cluster : Cluster created with settings {hosts=[training-shard-00-00-abcde.mongodb.net:27017, training-shard-00-01-abcde.mongodb.net:27017, training-shard-00-02-abcde.mongodb.net:27017], mode=MULTIPLE, requiredClusterType=REPLICA_SET, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500, requiredReplicaSetName='training-shard-0'}
[DEBUG] [TestEventLogger] 2018-08-06 18:25:37.132 INFO 4252 --- [ Test worker] org.mongodb.driver.cluster : Adding discovered server training-shard-00-00-abcde.mongodb.net:27017 to client view of cluster
[DEBUG] [TestEventLogger] 2018-08-06 18:25:37.135 INFO 4252 --- [ Test worker] org.mongodb.driver.cluster : Adding discovered server training-shard-00-01-abcde.mongodb.net:27017 to client view of cluster
[DEBUG] [TestEventLogger] 2018-08-06 18:25:37.139 INFO 4252 --- [ Test worker] org.mongodb.driver.cluster : Adding discovered server training-shard-00-02-abcde.mongodb.net:27017 to client view of cluster
[DEBUG] [TestEventLogger] 2018-08-06 18:25:37.831 INFO 4252 --- [ Test worker] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
[DEBUG] [TestEventLogger] 2018-08-06 18:25:38.450 INFO 4252 --- [ngodb.net:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:161155}] to training-shard-00-00-abcde.mongodb.net:27017
[DEBUG] [TestEventLogger] 2018-08-06 18:25:38.468 INFO 4252 --- [ngodb.net:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=training-shard-00-00-abcde.mongodb.net:27017, type=REPLICA_SET_PRIMARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 6]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=16287599, setName='training-shard-0', canonicalAddress=training-shard-00-00-abcde.mongodb.net:27017, hosts=[training-shard-00-00-abcde.mongodb.net:27017, training-shard-00-02-abcde.mongodb.net:27017, training-shard-00-01-abcde.mongodb.net:27017], passives=[], arbiters=[], primary='training-shard-00-00-abcde.mongodb.net:27017', tagSet=TagSet{[]}, electionId=7fffffff0000000000000008, setVersion=1, lastWriteDate=Mon Aug 06 18:25:37 SRET 2018, lastUpdateTimeNanos=70366873909383}
[DEBUG] [TestEventLogger] 2018-08-06 18:25:38.473 INFO 4252 --- [ngodb.net:27017] org.mongodb.driver.cluster : Setting max election id to 7fffffff0000000000000008 from replica set primary training-shard-00-00-abcde.mongodb.net:27017
[DEBUG] [TestEventLogger] 2018-08-06 18:25:38.474 INFO 4252 --- [ngodb.net:27017] org.mongodb.driver.cluster : Setting max set version to 1 from replica set primary training-shard-00-00-abcde.mongodb.net:27017
[DEBUG] [TestEventLogger] 2018-08-06 18:25:38.475 INFO 4252 --- [ngodb.net:27017] org.mongodb.driver.cluster : Discovered replica set primary training-shard-00-00-abcde.mongodb.net:27017
[DEBUG] [TestEventLogger] 2018-08-06 18:25:38.479 INFO 4252 --- [ngodb.net:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:4, serverValue:71172}] to training-shard-00-02-abcde.mongodb.net:27017
[DEBUG] [TestEventLogger] 2018-08-06 18:25:38.496 INFO 4252 --- [ngodb.net:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=training-shard-00-02-abcde.mongodb.net:27017, type=REPLICA_SET_SECONDARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 6]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=16406907, setName='training-shard-0', canonicalAddress=training-shard-00-02-abcde.mongodb.net:27017, hosts=[training-shard-00-00-abcde.mongodb.net:27017, training-shard-00-02-abcde.mongodb.net:27017, training-shard-00-01-abcde.mongodb.net:27017], passives=[], arbiters=[], primary='training-shard-00-00-abcde.mongodb.net:27017', tagSet=TagSet{[]}, electionId=null, setVersion=1, lastWriteDate=Mon Aug 06 18:25:37 SRET 2018, lastUpdateTimeNanos=70366902099001}
[DEBUG] [TestEventLogger] 2018-08-06 18:25:38.497 INFO 4252 --- [ngodb.net:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:3, serverValue:224436}] to training-shard-00-01-abcde.mongodb.net:27017
[DEBUG] [TestEventLogger] 2018-08-06 18:25:38.512 INFO 4252 --- [ngodb.net:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=training-shard-00-01-abcde.mongodb.net:27017, type=REPLICA_SET_SECONDARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 6]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=14614118, setName='training-shard-0', canonicalAddress=training-shard-00-01-abcde.mongodb.net:27017, hosts=[training-shard-00-00-abcde.mongodb.net:27017, training-shard-00-02-abcde.mongodb.net:27017, training-shard-00-01-abcde.mongodb.net:27017], passives=[], arbiters=[], primary='training-shard-00-00-abcde.mongodb.net:27017', tagSet=TagSet{[]}, electionId=null, setVersion=1, lastWriteDate=Mon Aug 06 18:25:37 SRET 2018, lastUpdateTimeNanos=70366918148773}

I think it haven't SSL Certificate or may be the wrong or dummy SSL Certificate are there. That's why it's display No SSL support in java.nio.channels.AsynchronousSocketChannel

From the docs:
If you are using the reactive driver, Netty is required for SSL. The auto-configuration configures this factory automatically if Netty is available and the factory to use hasn’t been customized already.
Make sure that you have netty on the classpath (either selected modules or netty-all).

Related

Java cannot access Elasticsearch running in Docker on Windows 11

EDIT: it works if I disable transport client sniffing.
Settings settings = Settings.builder()
.put("cluster.name", clusterName)
.put("client.transport.sniff", false)
.build();
Any ideas how to fix it?
First of all, everything works fine in Ubuntu 20.04, but when I try to run the same project using Docker Desktop on Windows 10, 11, and macOS, it fails.
When the Spring service starts it tries to find the Elasticsearch node and it fails, the exception is the following:
2022-12-27 16:20:40.459 INFO 23752 --- [ main] o.e.p.PluginsService : no modules loaded
2022-12-27 16:20:40.459 INFO 23752 --- [ main] o.e.p.PluginsService : loaded plugin [org.elasticsearch.index.reindex.ReindexPlugin]
2022-12-27 16:20:40.460 INFO 23752 --- [ main] o.e.p.PluginsService : loaded plugin [org.elasticsearch.join.ParentJoinPlugin]
2022-12-27 16:20:40.460 INFO 23752 --- [ main] o.e.p.PluginsService : loaded plugin [org.elasticsearch.percolator.PercolatorPlugin]
2022-12-27 16:20:40.460 INFO 23752 --- [ main] o.e.p.PluginsService : loaded plugin [org.elasticsearch.script.mustache.MustachePlugin]
2022-12-27 16:20:40.460 INFO 23752 --- [ main] o.e.p.PluginsService : loaded plugin [org.elasticsearch.transport.Netty4Plugin]
2022-12-27 16:21:02.679 INFO 23752 --- [ main] c.u.OnStartup : -----> APPLICATION INITIALIZATION <-----
2022-12-27 16:21:02.679 INFO 23752 --- [ main] c.u.OnStartup : -----> SETTING TIMEZONE
2022-12-27 16:21:02.679 INFO 23752 --- [ main] c.u.OnStartup : -----> CREATE INDEXES AND MAPPINGS NOW
2022-12-27 16:21:02.683 ERROR 23752 --- [ main] c.u.OnStartup : Elasticsearch unavailable, skipping creating of indexes
org.elasticsearch.client.transport.NoNodeAvailableException: None of the configured nodes are available: [{#transport#-1}{CA1SJmWMQfe1sRIDTY_Lpw}{localhost}{127.0.0.1:9300}]
at org.elasticsearch.client.transport.TransportClientNodesService.ensureNodesAreAvailable(TransportClientNodesService.java:347) ~[elasticsearch-6.2.4.jar:6.2.4]
at org.elasticsearch.client.transport.TransportClientNodesService.execute(TransportClientNodesService.java:245) ~[elasticsearch-6.2.4.jar:6.2.4]
at org.elasticsearch.client.transport.TransportProxyClient.execute(TransportProxyClient.java:60) ~[elasticsearch-6.2.4.jar:6.2.4]
at org.elasticsearch.client.transport.TransportClient.doExecute(TransportClient.java:371) ~[elasticsearch-6.2.4.jar:6.2.4]
at org.elasticsearch.client.support.AbstractClient.execute(AbstractClient.java:405) ~[elasticsearch-6.2.4.jar:6.2.4]
at org.elasticsearch.client.support.AbstractClient.execute(AbstractClient.java:394) ~[elasticsearch-6.2.4.jar:6.2.4]
at org.elasticsearch.client.support.AbstractClient$IndicesAdmin.execute(AbstractClient.java:1247) ~[elasticsearch-6.2.4.jar:6.2.4]
at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:46) ~[elasticsearch-6.2.4.jar:6.2.4]
at com.mymy.service.services.impl.IndexAndTypeManagementServiceImpl.indexExists(IndexAndTypeManagementServiceImpl.java:65) ~[classes/:?]
at com.mymy.service.services.impl.IndexAndTypeManagementServiceImpl.createIndex(IndexAndTypeManagementServiceImpl.java:95) ~[classes/:?]
at com.mymy.OnStartup.createIndexes(OnStartup.java:87) ~[classes/:?]
at com.mymy.OnStartup.init(OnStartup.java:55) ~[classes/:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_352]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_352]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_352]
at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_352]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:363) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:307) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:136) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:414) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1770) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) [spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) [spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) [spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:845) [spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) [spring-context-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) [spring-context-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) [spring-boot-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:742) [spring-boot-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:389) [spring-boot-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:311) [spring-boot-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at
The docker-compose file looks like:
version: '3.5'
services:
elasticsearch:
image: docker.elastic.co/elasticsearch/elasticsearch:6.2.4
container_name: elasticsearch
ports:
- 9200:9200
- 9300:9300
environment:
- discovery.type=single-node
- cluster.name=mycluster
- "ES_JAVA_OPTS=-Xms512m -Xmx512m"
- xpack.security.enabled=false
ulimits:
memlock:
soft: -1
hard: -1
volumes:
- elastic_data:/usr/share/elasticsearch/data
kibana:
image: docker.elastic.co/kibana/kibana:6.2.4
container_name: kibana
environment:
SERVER_NAME: localhost
ELASTICSEARCH_URL: http://elasticsearch:9200/
ports:
- 5601:5601
volumes:
- kibana_data:/var/log
depends_on:
- elasticsearch
volumes:
elastic_data:
kibana_data:
Java version is 1.8. Any suggestion on how to fix it?
Elasticsearch is accessible via Elasticsearch tools in the browser.
The answer is to add the following environment variables to docker-compose.yaml of the elasticsearch service:
environment:
- discovery.type=single-node
- network.host=_local_,_site_
- network.publish_host=_local_
or to start the elasticsearch with the command:
command: elasticsearch -Enetwork.host=_local_,_site_ -Enetwork.publish_host=_local_
Solution thanks to https://github.com/olivere/elastic-with-docker/

Not able to Run Jar file on AWS EC2 - Could not create the directory where the uploaded files will be stored

I can able to run the JAR file from local. But When I did uploaded the code to the Ubuntu 18.4 server AWS EC2, I am not able to run the JAR file.
By saying java -jar MyjarfileName.jar
Getting Error -
Could not create the directory where the uploaded files will be stored.
Details Error -
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/home/ubuntu/echeckinfo-backend/target/seamlesscheque-api-0.0.1-SNAPSHOT.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/home/ubuntu/.m2/repository/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v0.0.1-SNAPSHOT)
2022-06-20 16:44:41.543 INFO 21492 --- [ main] c.s.app.SeamlesschequeApiApplication : Starting SeamlesschequeApiApplication v0.0.1-SNAPSHOT on ip-172-26-5-71 with PID 21492 (/home/ubuntu/echeckinfo-backend/target/seamlesscheque-api-0.0.1-SNAPSHOT.jar started by ubuntu in /home/ubuntu/echeckinfo-backend/target)
2022-06-20 16:44:41.566 INFO 21492 --- [ main] c.s.app.SeamlesschequeApiApplication : No active profile set, falling back to default profiles: default
2022-06-20 16:44:41.717 INFO 21492 --- [ main] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-06-20 16:44:41.718 INFO 21492 --- [ main] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-06-20 16:44:45.398 INFO 21492 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2022-06-20 16:44:45.402 INFO 21492 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2022-06-20 16:44:45.817 INFO 21492 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 407ms. Found 25 repository interfaces.
2022-06-20 16:44:46.706 INFO 21492 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'seamlesschequeApiApplication' of type [com.seamlesscheque.app.SeamlesschequeApiApplication$$EnhancerBySpringCGLIB$$be13dd17] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2022-06-20 16:44:47.528 INFO 21492 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 5000 (http)
2022-06-20 16:44:47.602 INFO 21492 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-06-20 16:44:47.603 INFO 21492 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/9.0.13
2022-06-20 16:44:47.621 INFO 21492 --- [ main] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/usr/java/packages/lib/amd64:/usr/lib/x86_64-linux-gnu/jni:/lib/x86_64-linux-gnu:/usr/lib/x86_64-linux-gnu:/usr/lib/jni:/lib:/usr/lib]
2022-06-20 16:44:47.792 INFO 21492 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-06-20 16:44:47.793 INFO 21492 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 6075 ms
2022-06-20 16:44:48.534 INFO 21492 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[139.59.18.83:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2022-06-20 16:44:48.799 INFO 21492 --- [.59.18.83:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:6108}] to 139.59.18.83:27017
2022-06-20 16:44:48.833 INFO 21492 --- [.59.18.83:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=139.59.18.83:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[5, 0, 0]}, minWireVersion=0, maxWireVersion=13, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=29872868}
2022-06-20 16:44:50.226 INFO 21492 --- [ main] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:6109}] to 139.59.18.83:27017
2022-06-20 16:44:51.877 WARN 21492 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'fileController': Unsatisfied dependency expressed through field 'fileService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileServiceImpl' defined in URL [jar:file:/home/ubuntu/echeckinfo-backend/target/seamlesscheque-api-0.0.1-SNAPSHOT.jar!/com/seamlesscheque/app/service/FileServiceImpl.class]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.seamlesscheque.app.service.FileServiceImpl]: Constructor threw exception; nested exception is com.seamlesscheque.app.exception.FileStorageException: Could not create the directory where the uploaded files will be stored.
2022-06-20 16:44:51.890 INFO 21492 --- [ main] org.mongodb.driver.connection : Closed connection [connectionId{localValue:2, serverValue:6109}] to 139.59.18.83:27017 because the pool has been closed.
2022-06-20 16:44:51.895 INFO 21492 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2022-06-20 16:44:51.943 INFO 21492 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-06-20 16:44:51.955 ERROR 21492 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'fileController': Unsatisfied dependency expressed through field 'fileService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileServiceImpl' defined in URL [jar:file:/home/ubuntu/echeckinfo-backend/target/seamlesscheque-api-0.0.1-SNAPSHOT.jar!/com/seamlesscheque/app/service/FileServiceImpl.class]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.seamlesscheque.app.service.FileServiceImpl]: Constructor threw exception; nested exception is com.seamlesscheque.app.exception.FileStorageException: Could not create the directory where the uploaded files will be stored.
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at com.seamlesscheque.app.SeamlesschequeApiApplication.main(SeamlesschequeApiApplication.java:37) [seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_312]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_312]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_312]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_312]
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48) [spring-boot-thin-launcher-1.0.23.RELEASE-exec.jar:1.0.23.RELEASE]
at org.springframework.boot.loader.Launcher.launch(Launcher.java:87) [spring-boot-thin-launcher-1.0.23.RELEASE-exec.jar:1.0.23.RELEASE]
at org.springframework.boot.loader.Launcher.launch(Launcher.java:50) [spring-boot-thin-launcher-1.0.23.RELEASE-exec.jar:1.0.23.RELEASE]
at org.springframework.boot.loader.thin.ThinJarLauncher.launch(ThinJarLauncher.java:193) [spring-boot-thin-launcher-1.0.23.RELEASE-exec.jar:1.0.23.RELEASE]
at org.springframework.boot.loader.thin.ThinJarLauncher.main(ThinJarLauncher.java:140) [spring-boot-thin-launcher-1.0.23.RELEASE-exec.jar:1.0.23.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_312]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_312]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_312]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_312]
at org.springframework.boot.loader.wrapper.ThinJarWrapper.launch(ThinJarWrapper.java:140) [seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.boot.loader.wrapper.ThinJarWrapper.main(ThinJarWrapper.java:107) [seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileServiceImpl' defined in URL [jar:file:/home/ubuntu/echeckinfo-backend/target/seamlesscheque-api-0.0.1-SNAPSHOT.jar!/com/seamlesscheque/app/service/FileServiceImpl.class]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.seamlesscheque.app.service.FileServiceImpl]: Constructor threw exception; nested exception is com.seamlesscheque.app.exception.FileStorageException: Could not create the directory where the uploaded files will be stored.
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:304) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:285) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1308) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1154) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:273) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1237) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1164) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
... 34 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.seamlesscheque.app.service.FileServiceImpl]: Constructor threw exception; nested exception is com.seamlesscheque.app.exception.FileStorageException: Could not create the directory where the uploaded files will be stored.
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:184) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:117) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:300) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
... 47 common frames omitted
Caused by: com.seamlesscheque.app.exception.FileStorageException: Could not create the directory where the uploaded files will be stored.
at com.seamlesscheque.app.service.FileServiceImpl.<init>(FileServiceImpl.java:46) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_312]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_312]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_312]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_312]
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:172) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
... 49 common frames omitted
Caused by: java.nio.file.AccessDeniedException: /home/echeckpiiweb
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:84) ~[na:1.8.0_312]
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102) ~[na:1.8.0_312]
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107) ~[na:1.8.0_312]
at sun.nio.fs.UnixFileSystemProvider.createDirectory(UnixFileSystemProvider.java:384) ~[na:1.8.0_312]
at java.nio.file.Files.createDirectory(Files.java:674) ~[na:1.8.0_312]
at java.nio.file.Files.createAndCheckIsDirectory(Files.java:781) ~[na:1.8.0_312]
at java.nio.file.Files.createDirectories(Files.java:767) ~[na:1.8.0_312]
at com.seamlesscheque.app.service.FileServiceImpl.<init>(FileServiceImpl.java:44) ~[seamlesscheque-api-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]
... 54 common frames omitted
I have solve this problem. In order to run this -
First we have to run our project in sudo mode.
sudo java -jar myjarfileName.jar
Note -
Make sure you have java installed
sudo apt-update
sudo apt-get install openjdk-8-jre openjdk-8-jdk)
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/
java -version
Make sure you have maven installed
sudo apt-get install maven
mvn -version
Make sure you can able to build your application
Note - It will take some of the time to start. Once its start, you can ran your application, it will create all the directory, you can remove sudo, and ran it again. by saying -
java -jar myjarfileName.jar

How to mock connection to DB

I have simple rest controller test, and it works when postgresql run. I try run test, but before I stop service postgresql, and then my test failed. How I can mock connectin to database? I don't use DB in my test.
#SpringBootTest
#AutoConfigureMockMvc
public class UserControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private UserService service;
#WithMockUser(username = "TestUser", roles = {"SUPER_ADMIN"})
#Test
public void testGetUserWhenUserIsAuthorized() throws Exception {
UserAllInfo userAllInfo = new UserAllInfo(1L, 1L, "sdfsdf#gmail.com", "USER",
"userenko", Collections.singletonList(1));
doReturn(Optional.of(userAllInfo)).when(service).getUser(1);
mockMvc.perform(get("/api/identity/user/{id}", 1L))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.userId", is(1)))
.andExpect(jsonPath("$.vendingBranchId", is(1)))
.andExpect(jsonPath("$.email", is("sdfsdf#gmail.com")))
.andExpect(jsonPath("$.name", is("USER")))
.andExpect(jsonPath("$.surname", is("userenko")))
.andExpect(jsonPath("$.roles", is(Collections.singletonList(1))));
}
#Test
public void testGetUserWhenUserIsUnauthorized() throws Exception {
mockMvc.perform(get("/api/identity/user/{id}", 1L))
.andDo(print())
.andExpect(status().isUnauthorized());
}
}
And I have list of exceptions. I think it's two solutions first create database in memory, second mock connection to database when i don't use it, but i don't know how I can do it.
18:00:57.542 INFO [ task-1] org.hibernate.Version - HHH000412: Hibernate Core {5.2.17.Final}
18:00:57.544 INFO [ task-1] org.hibernate.cfg.Environment - HHH000206: hibernate.properties not found
18:00:57.609 INFO [ task-1] o.h.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
18:00:57.757 WARN [ main] o.s.b.a.o.j.JpaBaseConfiguration$JpaWebConfiguration - spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
18:00:57.771 INFO [ task-1] com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
18:00:58.739 INFO [ main] c.e.identity.rabbit.FanoutSender - Sending startup notification...
18:00:58.741 INFO [ main] o.s.a.r.c.CachingConnectionFactory - Attempting to connect to: [168.119.176.120:30672]
18:00:58.817 ERROR [ task-1] com.zaxxer.hikari.pool.HikariPool - HikariPool-1 - Exception during pool initialization.
org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:303)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:51)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:225)
at org.postgresql.Driver.makeConnection(Driver.java:465)
at org.postgresql.Driver.connect(Driver.java:264)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:477)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:560)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115)
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:861)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:888)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
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)
Caused by: java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
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.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:607)
at org.postgresql.core.PGStream.createSocket(PGStream.java:231)
at org.postgresql.core.PGStream.<init>(PGStream.java:95)
at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:98)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:213)
... 34 common frames omitted
18:00:58.818 WARN [ task-1] o.h.e.j.e.i.JdbcEnvironmentInitiator - HHH000342: Could not obtain connection to query metadata : Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
18:00:58.836 INFO [ task-1] org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
18:00:58.858 INFO [ task-1] o.h.e.j.e.i.LobCreatorBuilderImpl - HHH000422: Disabling contextual LOB creation as connection was null
18:00:58.861 INFO [ task-1] org.hibernate.type.BasicTypeRegistry - HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType#569533c9
18:00:59.036 INFO [ main] o.s.a.r.c.CachingConnectionFactory - Created new connection: rabbitConnectionFactory#33eb0d4:0/SimpleConnection#19cdc217 [delegate=amqp://rabbit#168.119.176.120:30672/, localPort= 44962]
18:00:59.597 INFO [ task-1] com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
18:01:00.599 ERROR [ task-1] com.zaxxer.hikari.pool.HikariPool - HikariPool-1 - Exception during pool initialization.
org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:303)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:51)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:225)
at org.postgresql.Driver.makeConnection(Driver.java:465)
at org.postgresql.Driver.connect(Driver.java:264)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:477)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:560)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115)
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180)
at org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl.getIsolatedConnection(DdlTransactionIsolatorNonJtaImpl.java:43)
at org.hibernate.tool.schema.internal.exec.ImprovedExtractionContextImpl.getJdbcConnection(ImprovedExtractionContextImpl.java:60)
at org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorLegacyImpl.extractMetadata(SequenceInformationExtractorLegacyImpl.java:40)
at org.hibernate.tool.schema.extract.internal.DatabaseInformationImpl.initializeSequences(DatabaseInformationImpl.java:65)
at org.hibernate.tool.schema.extract.internal.DatabaseInformationImpl.<init>(DatabaseInformationImpl.java:59)
at org.hibernate.tool.schema.internal.Helper.buildDatabaseInformation(Helper.java:132)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:96)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:183)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:312)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:462)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:892)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
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)
Caused by: java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
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.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:607)
at org.postgresql.core.PGStream.createSocket(PGStream.java:231)
at org.postgresql.core.PGStream.<init>(PGStream.java:95)
at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:98)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:213)
... 32 common frames omitted
18:01:00.602 WARN [ task-1] o.h.e.jdbc.spi.SqlExceptionHelper - SQL Error: 0, SQLState: 08001
18:01:00.602 ERROR [ task-1] o.h.e.jdbc.spi.SqlExceptionHelper - Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
18:01:00.609 WARN [ main] o.s.w.c.s.GenericWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'fanoutReceiverFromVendingDeviceService' defined in file [/home/dev/IdeaProjects/dms-identity-service/target/classes/com/ecosoft/identity/rabbit/FanoutReceiverFromVendingDeviceService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fanoutSender': Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository' defined in com.ecosoft.identity.repository.UserRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
18:01:00.826 INFO [ main] o.s.o.j.LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'default'
18:01:00.826 WARN [ main] o.s.b.f.s.DisposableBeanAdapter - Invocation of destroy method failed on bean with name 'entityManagerFactory': javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
Update
#AutoConfigureMockMvc
#WebMvcTest(UserController.class)
#ComponentScan("com.ecosoft.identity")
class UserController1Test {
private String USER_NOT_EXISTS="User not exist";
#Autowired
private MockMvc mockMvc;
#MockBean
private UserService service;
#MockBean
private UserDetailsServiceImpl userDetailsService;
#MockBean
private AuthEntryPointJwt authEntryPointJwt;
#MockBean
private VendingBranchRepository vendingBranchRepository;
#MockBean
private FanoutSender fanoutSender;
#WithMockUser(username = "TestUser", roles = {"SUPER_ADMIN"})
#Test
public void testGetUserWhenUserIsAuthorized() throws Exception {
UserAllInfo userAllInfo = new UserAllInfo(1L, 1L, "sdfsdf#gmail.com", "USER",
"userenko", Collections.singletonList(1));
doReturn(userAllInfo).when(service).getUser(1);
mockMvc.perform(get("/api/identity/user/{id}", 1L))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.userId", is(1)))
.andExpect(jsonPath("$.vendingBranchId", is(1)))
.andExpect(jsonPath("$.email", is("sdfsdf#gmail.com")))
.andExpect(jsonPath("$.name", is("USER")))
.andExpect(jsonPath("$.surname", is("userenko")))
.andExpect(jsonPath("$.roles", is(Collections.singletonList(1))));
}
#Test
public void testGetUserWhenUserIsUnauthorized() throws Exception {
mockMvc.perform(get("/api/identity/user/{id}", 1L))
.andDo(print())
.andExpect(status().isUnauthorized());
}
}
But my test testGetUserWhenUserIsUnauthorized don't work, i get status 200, but I need get 401
The answer provided by #k-wasilewski is great, if you want to do a proper integration test.
If your goal is to simply test the web-layer of your application without the need to configure a database connection, you can limit the scope of the test by using the #WebMvcTest(UserController.class) annotation instead of the #SpringBootTest annotation (see comments underneath the question).
This will only create the beans needed for the specified controller. You might need to mock some services and other dependents with #MockBean.
#RunWith(SpringRunner.class)
#SpringBootTest
#ContextConfiguration(initializers = {MyExample.Initializer.class})
#AutoConfigureMockMvc
public class MyExample {
#BeforeClass
public static void setTest() {
postgreSQLContainer.start();
}
#ClassRule
public static PostgreSQLContainer postgreSQLContainer =
new PostgreSQLContainer("postgres:11.1")
.withDatabaseName("world-db")
.withUsername("world")
.withPassword("world123");
static class Initializer
implements ApplicationContextInitializer<ConfigurableApplicationContext> {
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
// setup (postgreSQLContainer.getJdbcUrl()) as "hibernate.connection.url" here...
}
}
#Test
public void test() {
// should be able to connect to your database here
}
}

Stuckup with - HikariCP : JZ0C0: Connection is already closed (Sybase DB with SpringBoot v2.1.7)

I am getting Connection is already closed issue, for a CommandLineRunner -Spring Boot Application.
Here is the tech stack I am using
SpringBoot v2.1.7
Sybase DB v16.x with jconn4
HikarCP - Configuration info :
DEBUG] 2020-05-22 10:51:58.449 [main] o.s.j.d.DataSourceUtils - Fetching JDBC Connection from DataSource
[DEBUG] 2020-05-22 10:51:58.450 [main] c.z.h.HikariConfig - GBSHikariCP - configuration:
[DEBUG] 2020-05-22 10:51:58.451 [main] c.z.h.HikariConfig - allowPoolSuspension.............false
[DEBUG] 2020-05-22 10:51:58.451 [main] c.z.h.HikariConfig - autoCommit......................true
[DEBUG] 2020-05-22 10:51:58.451 [main] c.z.h.HikariConfig - catalog.........................none
[DEBUG] 2020-05-22 10:51:58.451 [main] c.z.h.HikariConfig - connectionInitSql...............none
[DEBUG] 2020-05-22 10:51:58.451 [main] c.z.h.HikariConfig - connectionTestQuery............."SELECT 1"
[DEBUG] 2020-05-22 10:51:58.451 [main] c.z.h.HikariConfig - connectionTimeout...............30000
[DEBUG] 2020-05-22 10:51:58.451 [main] c.z.h.HikariConfig - dataSource......................none
[DEBUG] 2020-05-22 10:51:58.451 [main] c.z.h.HikariConfig - dataSourceClassName.............none
[DEBUG] 2020-05-22 10:51:58.451 [main] c.z.h.HikariConfig - dataSourceJNDI..................none
[DEBUG] 2020-05-22 10:51:58.452 [main] c.z.h.HikariConfig - dataSourceProperties............{password=<masked>}
[DEBUG] 2020-05-22 10:51:58.452 [main] c.z.h.HikariConfig - driverClassName................."com.sybase.jdbc4.jdbc.SybDriver"
[DEBUG] 2020-05-22 10:51:58.452 [main] c.z.h.HikariConfig - healthCheckProperties...........{}
[DEBUG] 2020-05-22 10:51:58.452 [main] c.z.h.HikariConfig - healthCheckRegistry.............none
[DEBUG] 2020-05-22 10:51:58.452 [main] c.z.h.HikariConfig - idleTimeout.....................30000
[DEBUG] 2020-05-22 10:51:58.452 [main] c.z.h.HikariConfig - initializationFailTimeout.......1
[DEBUG] 2020-05-22 10:51:58.452 [main] c.z.h.HikariConfig - isolateInternalQueries..........false
[DEBUG] 2020-05-22 10:51:58.452 [main] c.z.h.HikariConfig - jdbcUrl.........................jdbc:sybase:Tds:xxxxx.xxx.xx.xx:11111/SOMEDB
[DEBUG] 2020-05-22 10:51:58.452 [main] c.z.h.HikariConfig - leakDetectionThreshold..........2500
[DEBUG] 2020-05-22 10:51:58.452 [main] c.z.h.HikariConfig - maxLifetime.....................90000
[DEBUG] 2020-05-22 10:51:58.452 [main] c.z.h.HikariConfig - maximumPoolSize.................20
[DEBUG] 2020-05-22 10:51:58.452 [main] c.z.h.HikariConfig - metricRegistry..................none
[DEBUG] 2020-05-22 10:51:58.453 [main] c.z.h.HikariConfig - metricsTrackerFactory...........none
[DEBUG] 2020-05-22 10:51:58.453 [main] c.z.h.HikariConfig - minimumIdle.....................5
[DEBUG] 2020-05-22 10:51:58.453 [main] c.z.h.HikariConfig - password........................<masked>
[DEBUG] 2020-05-22 10:51:58.453 [main] c.z.h.HikariConfig - poolName........................"HikariCP"
[DEBUG] 2020-05-22 10:51:58.453 [main] c.z.h.HikariConfig - readOnly........................false
[DEBUG] 2020-05-22 10:51:58.453 [main] c.z.h.HikariConfig - registerMbeans..................false
[DEBUG] 2020-05-22 10:51:58.453 [main] c.z.h.HikariConfig - scheduledExecutor...............none
[DEBUG] 2020-05-22 10:51:58.453 [main] c.z.h.HikariConfig - schema.........................."dbo"
[DEBUG] 2020-05-22 10:51:58.453 [main] c.z.h.HikariConfig - threadFactory...................internal
[DEBUG] 2020-05-22 10:51:58.453 [main] c.z.h.HikariConfig - transactionIsolation............default
[DEBUG] 2020-05-22 10:51:58.453 [main] c.z.h.HikariConfig - username........................"usr111"
[DEBUG] 2020-05-22 10:51:58.453 [main] c.z.h.HikariConfig - validationTimeout...............10000
Here is the stack trace I see on the STS Console
2020-05-22 10:51:58.857 [main] c.z.h.p.PoolBase - HikariCP - Closing connection com.sybase.jdbc4.jdbc.SybConnection#4a183d02: (Failed to create/setup connection)
[DEBUG] 2020-05-22 10:51:58.859 [main] c.z.h.p.PoolBase - GBSHikariCP - Closing connection com.sybase.jdbc4.jdbc.SybConnection#4a183d02 failed
java.sql.SQLException: JZ0C0: Connection is already closed.
at com.sybase.jdbc4.jdbc.ErrorMessage.raiseError(Unknown Source)
at com.sybase.jdbc4.jdbc.SybConnection.checkConnection(Unknown Source)
at com.sybase.jdbc4.jdbc.SybConnection.close(Unknown Source)
at com.zaxxer.hikari.pool.PoolBase.quietlyCloseConnection(PoolBase.java:135)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:380)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:198)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:467)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:541)
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:157)
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:115)
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:78)
at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:319)
at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:356)
at org.springframework.boot.autoconfigure.orm.jpa.DatabaseLookup.getDatabase(DatabaseLookup.java:73)
at org.springframework.boot.autoconfigure.orm.jpa.JpaProperties.determineDatabase(JpaProperties.java:142)
at org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.jpaVendorAdapter(JpaBaseConfiguration.java:113)
at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration$$EnhancerBySpringCGLIB$$9d0516b2.CGLIB$jpaVendorAdapter$7(<generated>)
at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration$$EnhancerBySpringCGLIB$$9d0516b2$$FastClassBySpringCGLIB$$9e5bd134.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration$$EnhancerBySpringCGLIB$$9d0516b2.jpaVendorAdapter(<generated>)
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:497)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1251)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:509)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1251)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:509)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:743)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:390)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:312)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1214)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1203)
at com.xxx.xx.xxx.jrt.JOBRunTP.main(JOBRunTP.java:44)
Caused by: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: JZ0C0: Connection is already closed.
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:81)
at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:319)
... 61 common frames omitted
Caused by: java.sql.SQLException: JZ0C0: Connection is already closed.
at com.sybase.jdbc4.jdbc.SybConnection.getAllExceptions(Unknown Source)
at com.sybase.jdbc4.jdbc.SybConnection.handleSQLE(Unknown Source)
at com.sybase.jdbc4.jdbc.SybConnection.isReadOnly(Unknown Source)
at com.zaxxer.hikari.pool.PoolBase.setupConnection(PoolBase.java:413)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:374)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:198)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:467)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:541)
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:157)
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:115)
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:78)
I also observed that , the same connection config perfectly works with a different Sybase user id . Is the issue specific to DB user ids ? any one help me where am I doing wrong .
At last this issue has been solved by adding the custome data source properties , as mentioned below in the spring boot application.yml file. Hope this helps others.
These properties were validated at sybase db. (its application specific validation) .
spring:
datasource:
hikari:
data-source-properties:
SELECT_OPENS_CURSOR : true
applicationName: GBS«¼Æ¢ó½Ç²îª°»L

MongoSocketOpenException when using spring-boot-starter-parent 2.0.0

I am trying to build spring boot MongoDB project provided at https://spring.io/guides/gs/accessing-data-mongodb/ which is using spring-boot-starter-parent 2.0.0.RELEASE,
and getting
stack trace:
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.connection.SocketStream.open(SocketStream.java:62) ~[mongodb-driver-core-3.6.3.jar:na]
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:126) ~[mongodb-driver-core-3.6.3.jar:na]
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:114) ~[mongodb-driver-core-3.6.3.jar:na]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_151]
Caused by: java.net.SocketException: Socket operation on non-socket (Error setting socket option)
at java.net.PlainSocketImpl.socketSetOption0(Native Method) ~[na:1.8.0_151]
at java.net.PlainSocketImpl.socketSetOption(PlainSocketImpl.java:88) ~[na:1.8.0_151]
at java.net.AbstractPlainSocketImpl.setOption(AbstractPlainSocketImpl.java:275) ~[na:1.8.0_151]
at java.net.Socket.setTcpNoDelay(Socket.java:980) ~[na:1.8.0_151]
at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:36) ~[mongodb-driver-core-3.6.3.jar:na]
at com.mongodb.connection.SocketStream.open(SocketStream.java:57) ~[mongodb-driver-core-3.6.3.jar:na]
... 3 common frames omitted
When I changed spring-boot-starter-parent version to 1.5.9.RELEASE or 1.5.10.RELEASE, the same code is working fine. So is there any problem with version 2.0.0.RELEASE when using spring data mongo.
System details:
mongod version: 3.4.13
openjdk version "1.8.0_151"
I had to install and start mongodb first for spring-boot-starter-parent 2.0.x
assuming you are using MacOS
# to install mongodb
➜ ~ brew install mongodb
# To have launchd start mongodb now and restart at login
➜ ~ brew services start mongodb
after that everything worked as expected:
2018-04-05 22:13:43.189 INFO 26777 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2018-04-05 22:13:43.229 INFO 26777 --- [localhost:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:1}] to localhost:27017
2018-04-05 22:13:43.234 INFO 26777 --- [localhost:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 3]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=3049505}
2018-04-05 22:13:43.352 INFO 26777 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2018-04-05 22:13:43.469 INFO 26777 --- [localhost:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:2}] to localhost:27017
2018-04-05 22:13:43.471 INFO 26777 --- [localhost:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 3]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=1552605}

Categories

Resources