JHipster MongoDB connection authorization - mongodb

I have problem with connection of the JHipster generated application to the secured mongodb instance. I have created mongodb user for database and granted readWrite role to it.
> show users
{
"_id" : "jhipster.jhipster",
"user" : "jhipster",
"db" : "jhipster",
"roles" : [
{
"role" : "readWrite",
"db" : "jhipster"
}
]
}
In the generated application I have added in application-dev.yml file configuration preferences for mongodb like so:
server:
port: 8080
spring:
profiles:
active: dev
data:
mongodb:
host: localhost
port: 27017
database: jhipster
authenticationDatabase: jhipster
username: jhipster
password: jhipster
mail:
baseUrl: http://localhost:8080
thymeleaf:
mode: XHTML
cache: false
metrics:
jmx.enabled: true
spark:
enabled: false
host: localhost
port: 9999
graphite:
enabled: false
host: localhost
port: 2003
prefix: jhipster
After launching the application with command mvn spring-boot:run I get the following stack trace:
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building jhipster 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> spring-boot-maven-plugin:1.2.1.RELEASE:run (default-cli) > test-compile # jhipster >>>
[INFO]
[INFO] --- maven-enforcer-plugin:1.3.1:enforce (enforce-versions) # jhipster ---
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) # jhipster ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 4 resources
[INFO] Copying 8 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) # jhipster ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 82 source files to /Users/grega/Development/sandbox/jhipster/target/classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) # jhipster ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 2 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) # jhipster ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] <<< spring-boot-maven-plugin:1.2.1.RELEASE:run (default-cli) < test-compile # jhipster <<<
[INFO]
[INFO] --- spring-boot-maven-plugin:1.2.1.RELEASE:run (default-cli) # jhipster ---
[INFO] Attaching agents: []
Listening for transport dt_socket at address: 5005
[INFO] com.mycompany.myapp.Application - Starting Application on Gregas-MacBook-Pro.local with PID 20096 (/Users/grega/Development/sandbox/jhipster/target/classes started by grega in /Users/grega/Development/sandbox/jhipster)
[DEBUG] com.mycompany.myapp.Application - Running with Spring Boot v1.2.1.RELEASE, Spring v4.1.4.RELEASE
[DEBUG] org.jboss.logging - Logging Provider: org.jboss.logging.Slf4jLoggerProvider
[DEBUG] com.mycompany.myapp.config.AsyncConfiguration - Creating Async Task Executor
[DEBUG] com.mycompany.myapp.config.MetricsConfiguration - Registering JVM gauges
[INFO] com.mycompany.myapp.config.MetricsConfiguration - Initializing Metrics JMX reporting
[DEBUG] com.mycompany.myapp.config.MailConfiguration - Configuring mail server
[INFO] com.mycompany.myapp.config.WebConfigurer - Web application configuration, using profiles: [dev]
[DEBUG] com.mycompany.myapp.config.WebConfigurer - Initializing Metrics registries
[DEBUG] com.mycompany.myapp.config.WebConfigurer - Registering Metrics Filter
[DEBUG] com.mycompany.myapp.config.WebConfigurer - Registering Metrics Servlet
[INFO] com.mycompany.myapp.config.WebConfigurer - Web application fully configured
[INFO] com.mycompany.myapp.Application - Running with Spring profile(s) : [dev]
[INFO] com.mycompany.myapp.config.ThymeleafConfiguration - loading non-reloadable mail messages resources
[DEBUG] com.mycompany.myapp.config.apidoc.SwaggerConfiguration - Starting Swagger
[DEBUG] com.mycompany.myapp.config.apidoc.SwaggerConfiguration - Started Swagger in 34 ms
[DEBUG] com.mycompany.myapp.config.CacheConfiguration - No cache
[DEBUG] com.mycompany.myapp.config.DatabaseConfiguration - Configuring Mongeez
[INFO] org.mongeez.reader.FilesetXMLReader - Num of changefiles 2
[WARN] org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongeez' defined in class path resource [com/mycompany/myapp/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.mongeez.Mongeez]: Factory method 'mongeez' threw exception; nested exception is com.mongodb.CommandFailureException: { "serverUsed" : "localhost:27017" , "ok" : 0.0 , "errmsg" : "not authorized on jhipster to execute command { $eval: \"db.T_AUTHORITY.insert({\"_id\" : \"ROLE_ADMIN\"});\n db.T_AUTHORITY.insert({\"_id\" : \"ROLE_USER\"});\", args: [] }" , "code" : 13}
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1111) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1006) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:762) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) ~[spring-context-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) ~[spring-context-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) [spring-boot-1.2.1.RELEASE.jar:1.2.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691) [spring-boot-1.2.1.RELEASE.jar:1.2.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:321) [spring-boot-1.2.1.RELEASE.jar:1.2.1.RELEASE]
at com.mycompany.myapp.Application.main(Application.java:55) [classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.mongeez.Mongeez]: Factory method 'mongeez' threw exception; nested exception is com.mongodb.CommandFailureException: { "serverUsed" : "localhost:27017" , "ok" : 0.0 , "errmsg" : "not authorized on jhipster to execute command { $eval: \"db.T_AUTHORITY.insert({\"_id\" : \"ROLE_ADMIN\"});\n db.T_AUTHORITY.insert({\"_id\" : \"ROLE_USER\"});\", args: [] }" , "code" : 13}
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
... 15 common frames omitted
Caused by: com.mongodb.CommandFailureException: { "serverUsed" : "localhost:27017" , "ok" : 0.0 , "errmsg" : "not authorized on jhipster to execute command { $eval: \"db.T_AUTHORITY.insert({\"_id\" : \"ROLE_ADMIN\"});\n db.T_AUTHORITY.insert({\"_id\" : \"ROLE_USER\"});\", args: [] }" , "code" : 13}
at com.mongodb.CommandResult.getException(CommandResult.java:76) ~[mongo-java-driver-2.12.4.jar:na]
at com.mongodb.CommandResult.throwOnError(CommandResult.java:131) ~[mongo-java-driver-2.12.4.jar:na]
at com.mongodb.DB.eval(DB.java:461) ~[mongo-java-driver-2.12.4.jar:na]
at org.mongeez.dao.MongeezDao.runScript(MongeezDao.java:124) ~[mongeez-0.9.4.jar:na]
at org.mongeez.commands.Script.run(Script.java:32) ~[mongeez-0.9.4.jar:na]
at org.mongeez.ChangeSetExecutor.execute(ChangeSetExecutor.java:53) ~[mongeez-0.9.4.jar:na]
at org.mongeez.ChangeSetExecutor.execute(ChangeSetExecutor.java:42) ~[mongeez-0.9.4.jar:na]
at org.mongeez.Mongeez.process(Mongeez.java:40) ~[mongeez-0.9.4.jar:na]
at com.mycompany.myapp.config.DatabaseConfiguration.mongeez(DatabaseConfiguration.java:65) ~[classes/:na]
at com.mycompany.myapp.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$5c5942c3.CGLIB$mongeez$4(<generated>) ~[spring-core-4.1.4.RELEASE.jar:na]
at com.mycompany.myapp.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$5c5942c3$$FastClassBySpringCGLIB$$e5d33dc7.invoke(<generated>) ~[spring-core-4.1.4.RELEASE.jar:na]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:309) ~[spring-context-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at com.mycompany.myapp.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$5c5942c3.mongeez(<generated>) ~[spring-core-4.1.4.RELEASE.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_65]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_65]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_65]
at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_65]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
... 16 common frames omitted
[INFO] com.mycompany.myapp.config.CacheConfiguration - Closing Cache Manager
[ERROR] org.springframework.boot.SpringApplication - Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongeez' defined in class path resource [com/mycompany/myapp/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.mongeez.Mongeez]: Factory method 'mongeez' threw exception; nested exception is com.mongodb.CommandFailureException: { "serverUsed" : "localhost:27017" , "ok" : 0.0 , "errmsg" : "not authorized on jhipster to execute command { $eval: \"db.T_AUTHORITY.insert({\"_id\" : \"ROLE_ADMIN\"});\n db.T_AUTHORITY.insert({\"_id\" : \"ROLE_USER\"});\", args: [] }" , "code" : 13}
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1111) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1006) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:762) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) ~[spring-context-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) ~[spring-context-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.2.1.RELEASE.jar:1.2.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691) ~[spring-boot-1.2.1.RELEASE.jar:1.2.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:321) ~[spring-boot-1.2.1.RELEASE.jar:1.2.1.RELEASE]
at com.mycompany.myapp.Application.main(Application.java:55) [classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.mongeez.Mongeez]: Factory method 'mongeez' threw exception; nested exception is com.mongodb.CommandFailureException: { "serverUsed" : "localhost:27017" , "ok" : 0.0 , "errmsg" : "not authorized on jhipster to execute command { $eval: \"db.T_AUTHORITY.insert({\"_id\" : \"ROLE_ADMIN\"});\n db.T_AUTHORITY.insert({\"_id\" : \"ROLE_USER\"});\", args: [] }" , "code" : 13}
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
... 15 common frames omitted
Caused by: com.mongodb.CommandFailureException: { "serverUsed" : "localhost:27017" , "ok" : 0.0 , "errmsg" : "not authorized on jhipster to execute command { $eval: \"db.T_AUTHORITY.insert({\"_id\" : \"ROLE_ADMIN\"});\n db.T_AUTHORITY.insert({\"_id\" : \"ROLE_USER\"});\", args: [] }" , "code" : 13}
at com.mongodb.CommandResult.getException(CommandResult.java:76) ~[mongo-java-driver-2.12.4.jar:na]
at com.mongodb.CommandResult.throwOnError(CommandResult.java:131) ~[mongo-java-driver-2.12.4.jar:na]
at com.mongodb.DB.eval(DB.java:461) ~[mongo-java-driver-2.12.4.jar:na]
at org.mongeez.dao.MongeezDao.runScript(MongeezDao.java:124) ~[mongeez-0.9.4.jar:na]
at org.mongeez.commands.Script.run(Script.java:32) ~[mongeez-0.9.4.jar:na]
at org.mongeez.ChangeSetExecutor.execute(ChangeSetExecutor.java:53) ~[mongeez-0.9.4.jar:na]
at org.mongeez.ChangeSetExecutor.execute(ChangeSetExecutor.java:42) ~[mongeez-0.9.4.jar:na]
at org.mongeez.Mongeez.process(Mongeez.java:40) ~[mongeez-0.9.4.jar:na]
at com.mycompany.myapp.config.DatabaseConfiguration.mongeez(DatabaseConfiguration.java:65) ~[classes/:na]
at com.mycompany.myapp.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$5c5942c3.CGLIB$mongeez$4(<generated>) ~[spring-core-4.1.4.RELEASE.jar:na]
at com.mycompany.myapp.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$5c5942c3$$FastClassBySpringCGLIB$$e5d33dc7.invoke(<generated>) ~[spring-core-4.1.4.RELEASE.jar:na]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:309) ~[spring-context-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at com.mycompany.myapp.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$5c5942c3.mongeez(<generated>) ~[spring-core-4.1.4.RELEASE.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_65]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_65]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_65]
at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_65]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.1.4.RELEASE.jar:4.1.4.RELEASE]
... 16 common frames omitted
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongeez' defined in class path resource [com/mycompany/myapp/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.mongeez.Mongeez]: Factory method 'mongeez' threw exception; nested exception is com.mongodb.CommandFailureException: { "serverUsed" : "localhost:27017" , "ok" : 0.0 , "errmsg" : "not authorized on jhipster to execute command { $eval: \"db.T_AUTHORITY.insert({\"_id\" : \"ROLE_ADMIN\"});\n db.T_AUTHORITY.insert({\"_id\" : \"ROLE_USER\"});\", args: [] }" , "code" : 13}
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1111)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1006)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:762)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:321)
at com.mycompany.myapp.Application.main(Application.java:55)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.mongeez.Mongeez]: Factory method 'mongeez' threw exception; nested exception is com.mongodb.CommandFailureException: { "serverUsed" : "localhost:27017" , "ok" : 0.0 , "errmsg" : "not authorized on jhipster to execute command { $eval: \"db.T_AUTHORITY.insert({\"_id\" : \"ROLE_ADMIN\"});\n db.T_AUTHORITY.insert({\"_id\" : \"ROLE_USER\"});\", args: [] }" , "code" : 13}
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 15 more
Caused by: com.mongodb.CommandFailureException: { "serverUsed" : "localhost:27017" , "ok" : 0.0 , "errmsg" : "not authorized on jhipster to execute command { $eval: \"db.T_AUTHORITY.insert({\"_id\" : \"ROLE_ADMIN\"});\n db.T_AUTHORITY.insert({\"_id\" : \"ROLE_USER\"});\", args: [] }" , "code" : 13}
at com.mongodb.CommandResult.getException(CommandResult.java:76)
at com.mongodb.CommandResult.throwOnError(CommandResult.java:131)
at com.mongodb.DB.eval(DB.java:461)
at org.mongeez.dao.MongeezDao.runScript(MongeezDao.java:124)
at org.mongeez.commands.Script.run(Script.java:32)
at org.mongeez.ChangeSetExecutor.execute(ChangeSetExecutor.java:53)
at org.mongeez.ChangeSetExecutor.execute(ChangeSetExecutor.java:42)
at org.mongeez.Mongeez.process(Mongeez.java:40)
at com.mycompany.myapp.config.DatabaseConfiguration.mongeez(DatabaseConfiguration.java:65)
at com.mycompany.myapp.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$5c5942c3.CGLIB$mongeez$4(<generated>)
at com.mycompany.myapp.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$5c5942c3$$FastClassBySpringCGLIB$$e5d33dc7.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:309)
at com.mycompany.myapp.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$5c5942c3.mongeez(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 16 more
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 19.800 s
[INFO] Finished at: 2015-02-13T18:56:39+01:00
[INFO] Final Memory: 28M/228M
[INFO] ------------------------------------------------------------------------
Does anyone know what am I doing wrong?

I had the same problem for a day.
I still don't know the real reason of my problem (I had the same error stack), but I disabled SELinux and it worked.
(I did not have any notifications from SELinux though)
You should look that way !
Good luck

I am not sure why this is not working as I am still facing the same issue, but using the below properties work
spring.data.mongodb.uri=mongodb://username:password#localhost:27017/database_name

I had the same problem yesterday. The problem is that MongoDB 3.0 changed the default authentication mechanism from MONGODB-CR to SCRAM-SHA-1.
Try this (it worked for me):
1) Update to the latest version of Spring Data Mongodb
Add in the pom.xml in properties this:
<spring-data-releasetrain.version>Fowler-SR2</spring-data-releasetrain.version>
2) Add the latest version of the mongo-java-driver
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.0.4</version>
</dependency>
3) Set MongoClient specific options for setting credentials
Override
#Bean
public Mongo mongo() throws Exception {
return new MongoClient(singletonList(new ServerAddress(host, port)),
singletonList(MongoCredential.createCredential(username,database, password.toCharArray())));
}
If you would like more information I have written a detailed post about it:
http://ignaciosuay.com/how-to-connect-to-mongodb-3-0-using-spring-boot/

Mongeez uses the mongodb eval command to bootstrap the database. In some scenarios this command is not permitted / disabled. Therefore Mongeez will not work.
Instead of Mongeez you can use mongobee to provide the migration logic for your app.
This is my default mongobee migration code for jhipster that has the same effect as the mongeez one.
package your.package.name.config.dbmigrations;
import com.github.mongobee.changeset.ChangeLog;
import com.github.mongobee.changeset.ChangeSet;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* Creates the initial database setup
*/
#ChangeLog(order = "001")
public class InitialSetupMigration {
private Map<String, String>[] authoritiesUser = new Map[]{new HashMap<>()};
private Map<String, String>[] authoritiesAdminAndUser = new Map[]{new HashMap<>(), new HashMap<>()};
{
authoritiesUser[0].put("_id", "ROLE_USER");
authoritiesAdminAndUser[0].put("_id", "ROLE_USER");
authoritiesAdminAndUser[1].put("_id", "ROLE_ADMIN");
}
#ChangeSet(order = "01", author = "initiator", id = "01-addAuthorities")
public void addAuthorities(DB db) {
DBCollection authorityCollection = db.getCollection("jhi_authority");
authorityCollection.insert(
BasicDBObjectBuilder.start()
.add("_id", "ROLE_ADMIN")
.get());
authorityCollection.insert(
BasicDBObjectBuilder.start()
.add("_id", "ROLE_USER")
.get());
}
#ChangeSet(order = "02", author = "initiator", id = "02-addUsers")
public void addUsers(DB db) {
DBCollection usersCollection = db.getCollection("jhi_user");
usersCollection.createIndex("login");
usersCollection.createIndex("email");
usersCollection.insert(BasicDBObjectBuilder.start()
.add("_id", "user-0")
.add("login", "system")
.add("password", "$2a$10$mE.qmcV0mFU5NcKh73TZx.z4ueI/.bDWbj0T1BYyqP481kGGarKLG")
.add("first_name", "")
.add("last_name", "System")
.add("email", "system#localhost")
.add("activated", "true")
.add("lang_key", "en")
.add("created_by", "system")
.add("created_date", new Date())
.add("authorities", authoritiesAdminAndUser)
.get()
);
usersCollection.insert(BasicDBObjectBuilder.start()
.add("_id", "user-1")
.add("login", "anonymousUser")
.add("password", "$2a$10$j8S5d7Sr7.8VTOYNviDPOeWX8KcYILUVJBsYV83Y5NtECayypx9lO")
.add("first_name", "Anonymous")
.add("last_name", "User")
.add("email", "anonymous#localhost")
.add("activated", "true")
.add("lang_key", "en")
.add("created_by", "system")
.add("created_date", new Date())
.add("authorities", new Map[]{})
.get()
);
usersCollection.insert(BasicDBObjectBuilder.start()
.add("_id", "user-2")
.add("login", "admin")
.add("password", "$2a$10$gSAhZrxMllrbgj/kkK9UceBPpChGWJA7SYIb1Mqo.n5aNLq1/oRrC")
.add("first_name", "admin")
.add("last_name", "Administrator")
.add("email", "admin#localhost")
.add("activated", "true")
.add("lang_key", "en")
.add("created_by", "system")
.add("created_date", new Date())
.add("authorities", authoritiesAdminAndUser)
.get()
);
usersCollection.insert(BasicDBObjectBuilder.start()
.add("_id", "user-3")
.add("login", "user")
.add("password", "$2a$10$VEjxo0jq2YG9Rbk2HmX9S.k1uZBGYUHdUcid3g/vfiEl7lwWgOH/K")
.add("first_name", "")
.add("last_name", "User")
.add("email", "user#localhost")
.add("activated", "true")
.add("lang_key", "en")
.add("created_by", "system")
.add("created_date", new Date())
.add("authorities", authoritiesUser)
.get()
);
}
#ChangeSet(author = "initiator", id = "03-addSocialUserConnection", order = "03")
public void addSocialUserConnection(DB db) {
DBCollection socialUserConnectionCollection = db.getCollection("jhi_social_user_connection");
socialUserConnectionCollection.createIndex(BasicDBObjectBuilder
.start("user_id", 1)
.add("provider_id", 1)
.add("provider_user_id", 1)
.get(),
"user-prov-provusr-idx", true);
}
}
In the DatabaseConfiguration.java file remove mongeez and add
#Bean
public Mongobee mongobee() {
log.debug("Configuring Mongobee");
Mongobee mongobee = new Mongobee(mongo);
mongobee.setDbName(mongoProperties.getDatabase());
mongobee.setChangeLogsScanPackage(
"de.shaere.sharecore.config.dbmigrations"); // package to scan for changesets
mongobee.setEnabled(true);
return mongobee;
}
And finally update your gradle file removing the mongeez dependency and adding:
compile group: 'com.github.mongobee', name: 'mongobee', version: mongobee_version
I've also opened a pull request to update the JHipster generator. Now we wait to see if the guys agree :)

The default encrypted password mentioned in the class InitialSetupMigration is wrong.
Changed credentials would be
username: admin
password: user

Related

Deploying Spring Boot App to Google App Engine - issues with connecting to SQL instance (PostgreSQL)

I have a Gradle based Spring Boot app that I'm trying to deploy to the App Engine via the App Engine gradle plugin. The SQL instance (PostgreSQL) is up and running fine, I can connect to it locally through DataGrip and it works fine. Here's my application.properties file:
spring.datasource.username=username
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
#################### GOOGLE CLOUD SETTINGS
spring.cloud.gcp.sql.enabled=true
spring.cloud.gcp.sql.database-name=db-name
spring.cloud.gcp.sql.instance-connection-name=app-name:europe-west2:db-name
When I try to deploy the app, I'm getting the following error (seems that it can't connect to the SQL instance):
A 2020-05-27T16:12:26.340839Z 2020-05-27 16:12:26.340 INFO 10 --- [ main] o.s.c.g.a.s.GcpCloudSqlAutoConfiguration : Default POSTGRESQL JdbcUrl provider. Connecting to jdbc:postgresql://google/db-name?socketFactory=com.google.cloud.sql.postgres.SocketFactory&cloudSqlInstance=instance-name:europe-west2:db-name with driver org.postgresql.Driver
A 2020-05-27T16:12:26.773138Z 2020-05-27 16:12:26.772 INFO 10 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
A 2020-05-27T16:12:26.977687Z 2020-05-27 16:12:26.977 INFO 10 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.15.Final
A 2020-05-27T16:12:27.413333Z 2020-05-27 16:12:27.413 INFO 10 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
A 2020-05-27T16:12:27.683594Z 2020-05-27 16:12:27.683 INFO 10 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
A 2020-05-27T16:12:27.760810Z 2020-05-27 16:12:27.760 INFO 10 --- [ main] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [app-name:europe-west2:db-name] via unix socket.
A 2020-05-27T16:12:27.966435Z 2020-05-27 16:12:27.966 WARN 10 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IncompatibleClassChangeError: Found interface org.objectweb.asm.ClassVisitor, but class was expected
2020-05-27 17:12:27.970 BST
2020-05-27 16:12:27.970 INFO 10 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
I've researched this issue and it seems that this happens when the runtime classpath is different the compile class path. Problem is that I can't reproduce it locally and I can't figure out if it's a dependency that's causing this.
Full stack trace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IncompatibleClassChangeError: Found interface org.objectweb.asm.ClassVisitor, but class was expected
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean (AbstractAutowireCapableBeanFactory.java:1796)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean (AbstractAutowireCapableBeanFactory.java:595)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean (AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0 (AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton (DefaultSingletonBeanRegistry.java:226)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean (AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean (AbstractBeanFactory.java:202)
at org.springframework.context.support.AbstractApplicationContext.getBean (AbstractApplicationContext.java:1108)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization (AbstractApplicationContext.java:868)
at org.springframework.context.support.AbstractApplicationContext.refresh (AbstractApplicationContext.java:550)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh (ServletWebServerApplicationContext.java:141)
at org.springframework.boot.SpringApplication.refresh (SpringApplication.java:747)
at org.springframework.boot.SpringApplication.refreshContext (SpringApplication.java:397)
at org.springframework.boot.SpringApplication.run (SpringApplication.java:315)
at org.springframework.boot.SpringApplication.run (SpringApplication.java:1226)
at org.springframework.boot.SpringApplication.run (SpringApplication.java:1215)
at com.turbochargedapps.basketballappinternalrest.BasketballAppInternalRestApplication.main (BasketballAppInternalRestApplication.java:21)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:566)
at org.springframework.boot.loader.MainMethodRunner.run (MainMethodRunner.java:48)
at org.springframework.boot.loader.Launcher.launch (Launcher.java:87)
at org.springframework.boot.loader.Launcher.launch (Launcher.java:51)
at org.springframework.boot.loader.JarLauncher.main (JarLauncher.java:52)
Caused by: java.lang.IncompatibleClassChangeError: Found interface org.objectweb.asm.ClassVisitor, but class was expected
at jnr.ffi.provider.jffi.AsmLibraryLoader.generateInterfaceImpl (AsmLibraryLoader.java:104)
at jnr.ffi.provider.jffi.AsmLibraryLoader.loadLibrary (AsmLibraryLoader.java:89)
at jnr.ffi.provider.jffi.NativeLibraryLoader.loadLibrary (NativeLibraryLoader.java:44)
at jnr.ffi.LibraryLoader.load (LibraryLoader.java:325)
at jnr.unixsocket.Native.<clinit> (Native.java:80)
at jnr.unixsocket.UnixSocketChannel.<init> (UnixSocketChannel.java:101)
at jnr.unixsocket.UnixSocketChannel.open (UnixSocketChannel.java:65)
at com.google.cloud.sql.core.CoreSocketFactory.connect (CoreSocketFactory.java:180)
at com.google.cloud.sql.postgres.SocketFactory.createSocket (SocketFactory.java:71)
at org.postgresql.core.PGStream.<init> (PGStream.java:73)
at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect (ConnectionFactoryImpl.java:93)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl (ConnectionFactoryImpl.java:197)
at org.postgresql.core.ConnectionFactory.openConnection (ConnectionFactory.java:49)
at org.postgresql.jdbc.PgConnection.<init> (PgConnection.java:211)
at org.postgresql.Driver.makeConnection (Driver.java:459)
at org.postgresql.Driver.connect (Driver.java:261)
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:101)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService (AbstractServiceRegistryImpl.java:263)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService (AbstractServiceRegistryImpl.java:237)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService (AbstractServiceRegistryImpl.java:214)
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices (DefaultIdentifierGeneratorFactory.java:152)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies (AbstractServiceRegistryImpl.java:286)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService (AbstractServiceRegistryImpl.java:243)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService (AbstractServiceRegistryImpl.java:214)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init> (InFlightMetadataCollectorImpl.java:176)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete (MetadataBuildingProcess.java:118)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata (EntityManagerFactoryBuilderImpl.java:1214)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build (EntityManagerFactoryBuilderImpl.java:1245)
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 org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet (AbstractEntityManagerFactoryBean.java:378)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet (LocalContainerEntityManagerFactoryBean.java:341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods (AbstractAutowireCapableBeanFactory.java:1855)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean (AbstractAutowireCapableBeanFactory.java:1792)
build.gradle file:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.google.cloud.tools:appengine-gradle-plugin:2.2.0'
}
}
plugins {
id 'org.springframework.boot' version '2.2.7.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
id 'org.asciidoctor.convert' version '1.5.8'
id 'java'
}
apply plugin: 'com.google.cloud.tools.appengine'
appengine {
deploy {
appengine.deploy.version = "GCLOUD_CONFIG"
appengine.deploy.projectId = "GCLOUD_CONFIG"
}
}
group = 'com.group'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
ext {
set('snippetsDir', file("build/generated-snippets"))
set('springCloudVersion', "Hoxton.SR4")
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
compile project(':project-core-submodule')
compile group: 'com.jayway.jsonpath', name: 'json-path', version: '2.0.0'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'
testImplementation 'org.springframework.security:spring-security-test'
testCompile group: 'com.h2database', name: 'h2', version: '1.4.200'
compile 'io.jsonwebtoken:jjwt-api:0.11.1'
runtime 'io.jsonwebtoken:jjwt-impl:0.11.1',
// Uncomment the next line if you want to use RSASSA-PSS (PS256, PS384, PS512) algorithms:
//'org.bouncycastle:bcprov-jdk15on:1.60',
'io.jsonwebtoken:jjwt-jackson:0.11.1' // or 'io.jsonwebtoken:jjwt-gson:0.11.1' for gson
// https://mvnrepository.com/artifact/com.google.guava/guava
compile group: 'com.google.guava', name: 'guava', version: '29.0-jre'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
compile group: 'org.springframework.cloud', name: 'spring-cloud-gcp-starter-sql-postgresql'
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
test {
outputs.dir snippetsDir
useJUnitPlatform()
}
asciidoctor {
inputs.dir snippetsDir
dependsOn test
}
Any ideas?
Turns out it was Google Guava that was causing this issue - I simply removed the dependency from my build.gradle file, did gradle clean build and then redeployed!

Spring Cloud config client not picking values from Config server

My Config client is not picking the property values from config
server.
http://localhost:8888/customer_service/default
Above Config server endpoint is returning proper values for Config client,
{
"name": "customer_service",
"profiles": [
"default"
],
"label": null,
"version": "c7648db5662dc65aeaad9c91abbf58b41010be7c",
"state": null,
"propertySources": [
{
"name": "https://github.com/prasadrpm/MicroService_config.git/customer_service.properties",
"source": {
"customer.config.location": "XXXX",
"customer.config.name": "YYYY"
}
}
]
}
Config client bootstrap.properties
server.port=8080
spring.application.name=customer_service
spring.cloud.config.enabled=true
spring.cloud.config.name=config_server
spring.cloud.config.uri=http://localhost:8888
Config client Log
2020-04-10 16:47:00.725 INFO 14976 --- [ main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8888
2020-04-10 16:47:03.267 INFO 14976 --- [ main] c.c.c.ConfigServicePropertySourceLocator : Located environment: name=config_server, profiles=[default], label=null, version=c7648db5662dc65aeaad9c91abbf58b41010be7c, state=null
2020-04-10 16:47:03.269 INFO 14976 --- [ main] b.c.PropertySourceBootstrapConfiguration : Located property source: [BootstrapPropertySource {name='bootstrapProperties-configClient'}]
2020-04-10 16:47:03.280 INFO 14976 --- [ main] com.customer.CustomerServiceApplication : No active profile set, falling back to default profiles: default
...
2020-04-10 16:47:05.164 INFO 14976 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1860 ms
2020-04-10 16:47:05.549 WARN 14976 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'customer.config.location' in value "${customer.config.location}"
2020-04-10 16:47:05.552 INFO 14976 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-04-10 16:47:05.577 INFO 14976 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-04-10 16:47:05.595 ERROR 14976 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'customer.config.location' in value "${customer.config.location}"
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:405) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
The URL that returns you correct properties/configuration is: localhost:8888/customer_service/default
Client application is querying for properties based on following data:
c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8888
c.c.c.ConfigServicePropertySourceLocator : Located environment: name=config_server, profiles=[default], label=null, version=c7648db5662dc65aeaad9c91abbf58b41010be7c, state=null
b.c.PropertySourceBootstrapConfiguration : Located property source: [BootstrapPropertySource {name='bootstrapProperties-configClient'}]
com.customer.CustomerServiceApplication : No active profile set, falling back to default profiles: default
...
So, effectively, client application is calling:
localhost:8888/config_server/default
So, there are two solutions:
delete spring.cloud.config.name=config_server property in bootstrap.properties, and your application should be able to fetch properties.
update value of spring.cloud.config.name to customer_service service. But if you do not provide spring.cloud.config.name explicitly, then client will use spring.application.name as the default value for spring.cloud.config.name.
What annotation you had used here?
It can be easily retrieved like this.
#Value("${customer.config.location}")
private String someOtherProperty;
and it is not needed
spring.cloud.config.name=config_server

SpringData JPA Transaction management

please help me about Spring JPA Transaction Management
I have two methods: usersService.addUser and authoritiesService.addNew
#Service
#Transactional(propagation = PROPAGATION.SUPPORTS, readOnly=true)
public class UsersService {
#Autowired
UsersRepository usersRepository;
#Autowired
AuthotitiesRepository authoritiesReposotory;
#Transaction
public addUser(...){
usersRespository.addUser...
authoritiesRepository.addNew...
}
...
public interface UsersRepository extends JpaRepository<Users, String> {
#Transactional
#Modifying
#Query(value = "insert into users..."
}
public interface AuthoritiesRepository extends JpaRepository<Users, String> {
#Transactional
#Modifying
#Query(value = "insert into abc ...."
}
The problem is when authoritiesRepository.addNew throws Exception(by some SQL syntax) I want to automatically rollback user info.
How can I configure in repository, service ?
Here is the exception trace:
2019-05-22 08:33:16.185 WARN 2276 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 42102, SQLState: 42S02
2019-05-22 08:33:16.185 ERROR 2276 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : Table "AUTHORITIESS" not found; SQL statement:
insert into authoritiess(username, authority) values(?, ?) [42102-199]
2019-05-22 08:33:16.220 ERROR 2276 --- [nio-8080-exec-4] o.s.t.i.TransactionInterceptor : Application exception overridden by commit exception
com.springboot.example.exception.DbCRUDException: Error on add user
at com.springboot.example.security.service.UsersService.addUser(UsersService.java:141) ~[classes/:na]
at com.springboot.example.security.service.UsersService$$FastClassBySpringCGLIB$$3d37fb4e.invoke() ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) [spring-core-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749) [spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) [spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.17.jar:9.0.17]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_162]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_162]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.17.jar:9.0.17]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_162]
Caused by: com.springboot.example.exception.DbCRUDException: Error on add authority
at com.springboot.example.security.service.AuthoritiesService.addNew(AuthoritiesService.java:58) ~[classes/:na]
at com.springboot.example.security.service.UsersService.addUser(UsersService.java:139) ~[classes/:na]
... 114 common frames omitted
Caused by: org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [insert into authoritiess(username, authority) values(?, ?)]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:279) ~[spring-orm-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:253) ~[spring-orm-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryExecution$ModifyingExecution.doExecute(JpaQueryExecution.java:256) ~[spring-data-jpa-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:91) ~[spring-data-jpa-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:136) ~[spring-data-jpa-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:125) ~[spring-data-jpa-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:605) ~[spring-data-commons-2.1.6.RELEASE.jar:2.1.6.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595) ~[sprin
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) [spring-tx-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) [spring-aop-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.1.6.RELEASE.jar:5.1.6.RELEASE]
... 134 common frames omitted
Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "AUTHORITIESS" not found; SQL statement:
insert into authoritiess(username, authority) values(?, ?) [42102-199]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:451) ~[h2-1.4.199.jar:1.4.199]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:427) ~[h2-1.4.199.jar:1.4.199]
at org.h2.message.DbException.get(DbException.java:205) ~[h2-1.4.199.jar:1.4.199]
2019-05-22 08:33:16.226 ERROR 2276 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.transaction.UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only] with root cause
org.springframework.transaction.UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:755) ~[spring-tx-5.1.6.RELEASE.jar:
As #thanhngo alread mentioned. This is how to do it.
You already have the correct annotation on the addUser method and any RuntimeException will cause the transaction to be rolled back.
Make sure that usersRespository.addUser... and authoritiesReposotory.addNew... also have the #Transactional annotation

Test RestController Delete Crud method return 404 expected 400

I have problem with test method. I want to test delete method ( shouldNotDeletePersonByGivenId) but test doesn't work.
This is My test:
#Test
public void shouldNotDeletePersonByGivenId() throws Exception {
Mockito.doThrow(new PersonService.NoEntityFoundException()).when(personService).deleteById(1L);
mockMvc.perform(delete("/persons/{id}", 1))
.andExpect(status().isBadRequest());
}
In service I have this method:
public static class NoEntityFoundException extends RuntimeException {
public NoEntityFoundException() {
super("There is no Entity in database with given id.");
}
}
When I start test I have request:
java.lang.AssertionError: Status
Expected :400
Actual :404
In restController my delete method look's like this:
#DeleteMapping("/persons/{id}")
public ResponseEntity<?> deleteById(#PathVariable Long id) {
try {
personService.deleteById(id);
return ResponseEntity.ok().body("{Deleted}");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Cant delete! Entity not exist");
}
}
In restController is my path (#PathVariable Long id)
logs:
java.lang.AssertionError: Status
Expected :400
Actual :404
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:617)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:178)
at com.softwaremind.crew.people.controller.PersonRestControllerTest.shouldNotDeletePersonByGivenId(PersonRestControllerTest.java:90)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
2018-05-07 12:25:02.218 INFO 11348 --- [ Thread-4] o.s.w.c.s.GenericWebApplicationContext : Closing org.springframework.web.context.support.GenericWebApplicationContext#6b6776cb: startup date [Mon May 07 12:24:57 CEST 2018]; root of context hierarchy
2018-05-07 12:25:02.223 INFO 11348 --- [ Thread-4] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2018-05-07 12:25:02.235 WARN 11348 --- [ Thread-4] o.s.b.f.support.DisposableBeanAdapter : Invocation of destroy method failed on bean with name 'inMemoryDatabaseShutdownExecutor': org.h2.jdbc.JdbcSQLException: Baza danych jest już zamknięta (aby zablokować samoczynne zamykanie podczas zamknięcia VM dodaj ";DB_CLOSE_ON_EXIT=FALSE" do URL bazy danych)
Database is already closed (to disable automatic closing at VM shutdown, add ";DB_CLOSE_ON_EXIT=FALSE" to the db URL) [90121-197]
2018-05-07 12:25:02.235 INFO 11348 --- [ Thread-4] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2018-05-07 12:25:02.237 INFO 11348 --- [ Thread-4] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
Check your mockito rule
=> Mockito.doThrow(new PersonService.NoEntityFoundException()).when(personService).deleteById(1L);
And in your code you are calling that function => personService.deleteById(id); => this throws an exception => your catch blocks catches it and =>
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Cant delete! Entity not exist"); => sends NOT_FOUND status which is 404 !!
From above I am expecting that /persons i syour base path . right ?
Can you see the body "Cant delete! Entity not exist" in error logs ?
404 may be coming from wrong path !
Replace HttpStatus.NOT_FOUND with HttpStatus.BAD_REQUEST .....in..........=>
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Cant delete! Entity not exist");

With in-mem database for testing, entity manager not releasing locks 'unable to obtain lock'

I have a Spring Boot app with some integration tests inspecting the results from front-end operations on data in the database.
The app uses DataNucleus JPA underneath spring-data-jpa and spring-data-rest, with an in-memory database, e.g. Derby, set up automatically via Spring Boot testing.
I used to use Hibernate, but I swopped it for DataNucleus. The tests all passed with Hibernate, but now my test JdbcTemplate queries are hanging, as though JPA isn't releasing its locks.
I've tried it with H2 (fails silently), Derby (hangs until time-out) and HSQLDB (hangs forever).
I have tried various work-arounds, e.g. without transactions #Transactional(Transactional.TxType.NEVER) or with/without commits #Rollback(true/false)
Spring Boot instantiates the datasource automatically and injects it into the EntityManagerFactory and the JdbcTemplate.
This is the test:
#ExtendWith(SpringExtension.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK,
classes = { TestDataSourceConfig.class })
#EnableAutoConfiguration
#AutoConfigureMockMvc
#AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.DERBY)
#Transactional
public class SymbolRestTests {
#Autowired
private MockMvc mockMvc;
#Autowired
private JdbcTemplate jdbcTemplate;
#Autowired
private SymbolRepository symbolRepository;
#PersistenceContext
private EntityManager entityManager;
#Before
public void setUp() throws Exception {
symbolRepository.deleteAll();
entityManager.flush();
entityManager.clear();
}
#Test
public void shouldCreateEntity() throws Exception {
String testTitle = "TEST.CODE.1";
String testExtra = "Test for SymbolRestTests.java";
String json = createJsonExample(testTitle, testExtra, true);
MockHttpServletRequestBuilder requestBuilder =
post("/symbols").content(json);
mockMvc.perform(requestBuilder)
.andExpect(status().isCreated())
.andExpect(header().string("Location",
containsString("symbols/")));
entityManager.flush();
entityManager.close(); // this didn't help
String sql = "SELECT count(*) FROM symbol WHERE title = ?";
// exception thrown on this next line
int count = jdbcTemplate.queryForObject(
sql, new Object[] { testTitle }, Integer.class);
Assert.assertThat(count, is(1));
}
}
and this is the error from HSQLDB (seems to be the most informative):
org.springframework.dao.CannotAcquireLockException: PreparedStatementCallback;
SQL [SELECT count(*) FROM symbol WHERE title = ?];
A lock could not be obtained within the time requested;
nested exception is java.sql.SQLTransactionRollbackException:
A lock could not be obtained within the time requested
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:259)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:649)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:684)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:716)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:726)
at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:794)
at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:813)
at com.gis.integration.SymbolRestTests.shouldCreateEntity(SymbolRestTests.java:127)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:316)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:114)
at org.junit.jupiter.engine.descriptor.MethodTestDescriptor.lambda$invokeTestMethod$6(MethodTestDescriptor.java:171)
at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
at org.junit.jupiter.engine.descriptor.MethodTestDescriptor.invokeTestMethod(MethodTestDescriptor.java:168)
at org.junit.jupiter.engine.descriptor.MethodTestDescriptor.execute(MethodTestDescriptor.java:115)
at org.junit.jupiter.engine.descriptor.MethodTestDescriptor.execute(MethodTestDescriptor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.lambda$execute$1(HierarchicalTestExecutor.java:81)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:76)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.lambda$execute$1(HierarchicalTestExecutor.java:91)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:76)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.lambda$execute$1(HierarchicalTestExecutor.java:91)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:76)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:51)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:87)
at org.junit.platform.launcher.Launcher.execute(Launcher.java:93)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:61)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.sql.SQLTransactionRollbackException: A lock could not be obtained within the time requested
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedResultSet.closeOnTransactionError(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedResultSet.movePosition(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedResultSet.next(Unknown Source)
at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:92)
at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:60)
at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:697)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:633)
... 35 more
Caused by: ERROR 40XL1: A lock could not be obtained within the time requested
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.services.locks.ConcurrentLockSet.lockObject(Unknown Source)
at org.apache.derby.impl.services.locks.ConcurrentLockSet.zeroDurationLockObject(Unknown Source)
at org.apache.derby.impl.services.locks.AbstractPool.zeroDurationlockObject(Unknown Source)
at org.apache.derby.impl.services.locks.ConcurrentPool.zeroDurationlockObject(Unknown Source)
at org.apache.derby.impl.store.raw.xact.RowLocking2nohold.lockRecordForRead(Unknown Source)
at org.apache.derby.impl.store.access.heap.HeapController.lockRow(Unknown Source)
at org.apache.derby.impl.store.access.heap.HeapController.lockRow(Unknown Source)
at org.apache.derby.impl.store.access.btree.index.B2IRowLocking3.lockRowOnPage(Unknown Source)
at org.apache.derby.impl.store.access.btree.index.B2IRowLocking3._lockScanRow(Unknown Source)
at org.apache.derby.impl.store.access.btree.index.B2IRowLockingRR.lockScanRow(Unknown Source)
at org.apache.derby.impl.store.access.btree.BTreeForwardScan.fetchRows(Unknown Source)
at org.apache.derby.impl.store.access.btree.BTreeScan.fetchNextGroup(Unknown Source)
at org.apache.derby.impl.sql.execute.BulkTableScanResultSet.reloadArray(Unknown Source)
at org.apache.derby.impl.sql.execute.BulkTableScanResultSet.getNextRowCore(Unknown Source)
at org.apache.derby.impl.sql.execute.ProjectRestrictResultSet.getNextRowCore(Unknown Source)
at org.apache.derby.impl.sql.execute.ScalarAggregateResultSet.getRowFromResultSet(Unknown Source)
at org.apache.derby.impl.sql.execute.ScalarAggregateResultSet.getNextRowCore(Unknown Source)
at org.apache.derby.impl.sql.execute.ProjectRestrictResultSet.getNextRowCore(Unknown Source)
at org.apache.derby.impl.sql.execute.BasicNoPutResultSetImpl.getNextRow(Unknown Source)
... 41 more
Update using DataNucleus transaction documentation I have added some DataNucleus-specific properties to the persistence.xml (without result):
<?xml version="1.0" encoding="UTF-8" ?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
persistence_2_1.xsd">
<persistence-unit name="test">
<provider>org.datanucleus.api.jpa.PersistenceProviderImpl</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="datanucleus.schema.autoCreateAll" value="true"/>
<property name="datanucleus.transactionIsolation" value="read-uncommitted"/>
<property name="datanucleus.NontransactionalRead" value="true"/>
<property name="datanucleus.NontransactionalWrite" value="true"/>
</properties>
</persistence-unit>
</persistence>
UPDATE #2
The log output at DEBUG level showing the DataNucleus-JPA/JdbcTemplate log statements (first the JPA INSERT, then the JdbcTemplate SELECT COUNT(*)):
2017-06-09 14:56:18.055 DEBUG 9492 --- [ main] DataNucleus.Connection : ManagedConnection(non-enlisted) "org.datanucleus.store.rdbms.ConnectionFactoryImpl$ManagedConnectionImpl#5621a671 [conn=org.apache.derby.impl.jdbc.EmbedConnection#2006fdaa, commitOnRelease=true, closeOnRelease=true, closeOnTxnEnd=true]" is being committed.
2017-06-09 14:56:18.055 DEBUG 9492 --- [ main] DataNucleus.Connection : ManagedConnection(non-enlisted) "org.datanucleus.store.rdbms.ConnectionFactoryImpl$ManagedConnectionImpl#5621a671 [conn=org.apache.derby.impl.jdbc.EmbedConnection#2006fdaa, commitOnRelease=true, closeOnRelease=true, closeOnTxnEnd=true]" closed
2017-06-09 14:56:18.068 DEBUG 9492 --- [ main] DataNucleus.Persistence : Object "com.bp.gis.tardis.entity.SymbolEntity#59c08cf1" being inserted into table "SYMBOL"
2017-06-09 14:56:18.071 DEBUG 9492 --- [ main] DataNucleus.Connection : ManagedConnection(non-enlisted) "org.datanucleus.store.rdbms.ConnectionFactoryImpl$ManagedConnectionImpl#63a7af06 [conn=null, commitOnRelease=false, closeOnRelease=false, closeOnTxnEnd=true]" opened with isolation level "read-uncommitted" and auto-commit=false
2017-06-09 14:56:18.074 DEBUG 9492 --- [ main] DataNucleus.Transaction : Running enlist operation on resource: org.datanucleus.store.rdbms.ConnectionFactoryImpl$EmulatedXAResource#3d4b45b, error code TMNOFLAGS and transaction: [DataNucleus Transaction, ID=Xid= , enlisted resources=[]]
2017-06-09 14:56:18.076 DEBUG 9492 --- [ main] DataNucleus.Connection : ManagedConnection(enlisted) "org.datanucleus.store.rdbms.ConnectionFactoryImpl$ManagedConnectionImpl#63a7af06 [conn=org.apache.derby.impl.jdbc.EmbedConnection#19d76106, commitOnRelease=false, closeOnRelease=false, closeOnTxnEnd=true]" starting for transaction "Xid= " with flags "0"
2017-06-09 14:56:18.078 DEBUG 9492 --- [ main] DataNucleus.Connection : ManagedConnection added to the pool : "org.datanucleus.store.rdbms.ConnectionFactoryImpl$ManagedConnectionImpl#63a7af06 [conn=org.apache.derby.impl.jdbc.EmbedConnection#19d76106, commitOnRelease=false, closeOnRelease=false, closeOnTxnEnd=true]" for key="org.datanucleus.ExecutionContextImpl#2c47a053" in factory="ConnectionFactory:tx[org.datanucleus.store.rdbms.ConnectionFactoryImpl#204c5ddf]"
2017-06-09 14:56:18.125 DEBUG 9492 --- [ main] DataNucleus.Datastore : Using PreparedStatement "org.datanucleus.store.rdbms.ParamLoggingPreparedStatement#37753b69" for connection "org.apache.derby.impl.jdbc.EmbedConnection#19d76106"
2017-06-09 14:56:18.134 DEBUG 9492 --- [ main] DataNucleus.Datastore.Native : INSERT INTO SYMBOL (ACTIVE,CREATED,EXTRA,GLOBAL_READ,GLOBAL_WRITE,LAST_MODIFIED,TITLE) VALUES (<'Y'>,<2017-06-09>,<null>,<'N'>,<'N'>,<2017-06-09>,<'TEST.CODE.1'>)
2017-06-09 14:56:18.169 DEBUG 9492 --- [ main] DataNucleus.Datastore.Persist : Execution Time = 36 ms (number of rows = 1) on PreparedStatement "org.datanucleus.store.rdbms.ParamLoggingPreparedStatement#37753b69"
2017-06-09 14:56:18.172 DEBUG 9492 --- [ main] DataNucleus.Datastore.Persist : Object "com.bp.gis.tardis.entity.SymbolEntity#59c08cf1" was inserted in the datastore and was given strategy value of "1"
2017-06-09 14:56:18.179 DEBUG 9492 --- [ main] DataNucleus.Cache : Object "com.bp.gis.tardis.entity.SymbolEntity#59c08cf1" (id="org.datanucleus.identity.IdentityReference#93fb44") being changed to be referenced by id="com.bp.gis.tardis.entity.SymbolEntity:1" in Level 1 cache
2017-06-09 14:56:18.180 DEBUG 9492 --- [ main] DataNucleus.Cache : Object "com.bp.gis.tardis.entity.SymbolEntity#59c08cf1" (id="com.bp.gis.tardis.entity.SymbolEntity:1") added to Level 1 cache (loadedFlags="[YYYYYYYYY]")
2017-06-09 14:56:18.180 DEBUG 9492 --- [ main] DataNucleus.Transaction : Object "com.bp.gis.tardis.entity.SymbolEntity#59c08cf1" (id="org.datanucleus.identity.IdentityReference#93fb44") enlisted in transactional cache is now enlisted using id="com.bp.gis.tardis.entity.SymbolEntity:1"
2017-06-09 14:56:18.181 DEBUG 9492 --- [ main] DataNucleus.Persistence : Insert of object "com.bp.gis.tardis.entity.SymbolEntity#59c08cf1" is calling insertPostProcessing for field "com.bp.gis.tardis.entity.SymbolEntity.timeSeriesList"
2017-06-09 14:56:18.181 DEBUG 9492 --- [ main] DataNucleus.Datastore : Closing PreparedStatement "org.datanucleus.store.rdbms.ParamLoggingPreparedStatement#37753b69"
2017-06-09 14:56:18.181 DEBUG 9492 --- [ main] DataNucleus.Persistence : Insert of object "com.bp.gis.tardis.entity.SymbolEntity#59c08cf1" is calling postInsert for field "com.bp.gis.tardis.entity.SymbolEntity.timeSeriesList"
2017-06-09 14:56:18.205 DEBUG 9492 --- [ main] DataNucleus.Persistence : Object "com.bp.gis.tardis.entity.SymbolEntity#59c08cf1" field "timeSeriesList" is replaced by a SCO wrapper of type "org.datanucleus.store.types.wrappers.backed.List" [cache-values=true, lazy-loading=true, allow-nulls=true]
2017-06-09 14:56:18.207 DEBUG 9492 --- [ main] DataNucleus.Persistence : ExecutionContext.internalFlush() process finished
2017-06-09 14:56:18.218 DEBUG 9492 --- [ main] o.s.jdbc.core.JdbcTemplate : Executing prepared SQL query
2017-06-09 14:56:18.220 DEBUG 9492 --- [ main] o.s.jdbc.core.JdbcTemplate : Executing prepared SQL statement [SELECT count(*) FROM symbol WHERE title = ?]
2017-06-09 14:56:18.250 TRACE 9492 --- [ main] o.s.jdbc.core.StatementCreatorUtils : Setting SQL statement parameter value: column index 1, parameter value [TEST.CODE.1], value class [java.lang.String], SQL type unknown
2017-06-09 14:57:18.298 INFO 9492 --- [ main] o.s.b.f.xml.XmlBeanDefinitionReader : Loading XML bean definitions from class path resource [org/springframework/jdbc/support/sql-error-codes.xml]
2017-06-09 14:57:18.390 INFO 9492 --- [ main] o.s.jdbc.support.SQLErrorCodesFactory : SQLErrorCodes loaded: [DB2, Derby, H2, HSQL, Informix, MS-SQL, MySQL, Oracle, PostgreSQL, Sybase, Hana]
MockHttpServletRequest:
HTTP Method = POST
Request URI = /symbols
Parameters = {}
Headers = {}
Handler:
Type = org.springframework.data.rest.webmvc.RepositoryEntityController
Method = public org.springframework.http.ResponseEntity<org.springframework.hateoas.ResourceSupport> org.springframework.data.rest.webmvc.RepositoryEntityController.postCollectionResource(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.PersistentEntityResource,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler,java.lang.String) throws org.springframework.web.HttpRequestMethodNotSupportedException
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 201
Error message = null
Headers = {X-Application-Context=[application:-1], Location=[http://localhost/symbols/0]}
Content type = null
Body =
Forwarded URL = null
Redirected URL = http://localhost/symbols/0
Cookies = []
2017-06-09 14:57:18.424 DEBUG 9492 --- [ main] DataNucleus.Transaction : Transaction rolling back for ExecutionContext org.datanucleus.ExecutionContextImpl#2c47a053
2017-06-09 14:57:18.429 DEBUG 9492 --- [ main] DataNucleus.Lifecycle : Object "com.bp.gis.tardis.entity.SymbolEntity#59c08cf1" (id="com.bp.gis.tardis.entity.SymbolEntity:1") has a lifecycle change : "P_NEW"->""
2017-06-09 14:57:18.447 DEBUG 9492 --- [ main] DataNucleus.Transaction : Object "com.bp.gis.tardis.entity.SymbolEntity#59c08cf1" (id="com.bp.gis.tardis.entity.SymbolEntity:1") was evicted from transactional cache
2017-06-09 14:57:18.448 DEBUG 9492 --- [ main] DataNucleus.Persistence : Disconnecting com.bp.gis.tardis.entity.SymbolEntity#59c08cf1 from StateManager[pc=com.bp.gis.tardis.entity.SymbolEntity#59c08cf1, lifecycle=P_NEW]
2017-06-09 14:57:18.451 DEBUG 9492 --- [ main] DataNucleus.Cache : Object with id="com.bp.gis.tardis.entity.SymbolEntity:1" being removed from Level 1 cache [current cache size = 1]
2017-06-09 14:57:18.451 DEBUG 9492 --- [ main] DataNucleus.Transaction : Rolling back [DataNucleus Transaction, ID=Xid= , enlisted resources=[org.datanucleus.store.rdbms.ConnectionFactoryImpl$EmulatedXAResource#3d4b45b]]
2017-06-09 14:57:18.452 DEBUG 9492 --- [ main] DataNucleus.Connection : ManagedConnection(enlisted) "org.datanucleus.store.rdbms.ConnectionFactoryImpl$ManagedConnectionImpl#63a7af06 [conn=org.apache.derby.impl.jdbc.EmbedConnection#19d76106, commitOnRelease=false, closeOnRelease=false, closeOnTxnEnd=true]" rolling back for transaction "Xid= "
2017-06-09 14:57:18.461 DEBUG 9492 --- [ main] DataNucleus.Connection : ManagedConnection(non-enlisted) "org.datanucleus.store.rdbms.ConnectionFactoryImpl$ManagedConnectionImpl#63a7af06 [conn=org.apache.derby.impl.jdbc.EmbedConnection#19d76106, commitOnRelease=false, closeOnRelease=false, closeOnTxnEnd=true]" closed
2017-06-09 14:57:18.461 DEBUG 9492 --- [ main] DataNucleus.Connection : ManagedConnection removed from the pool : "org.datanucleus.store.rdbms.ConnectionFactoryImpl$ManagedConnectionImpl#63a7af06 [conn=org.apache.derby.impl.jdbc.EmbedConnection#19d76106, commitOnRelease=false, closeOnRelease=false, closeOnTxnEnd=true]" for key="org.datanucleus.ExecutionContextImpl#2c47a053" in factory="ConnectionFactory:tx[org.datanucleus.store.rdbms.ConnectionFactoryImpl#204c5ddf]"
2017-06-09 14:57:18.462 DEBUG 9492 --- [ main] DataNucleus.Transaction : Transaction rolled back in 38 ms
2017-06-09 14:57:18.462 DEBUG 9492 --- [ main] DataNucleus.Persistence : ExecutionContext "org.datanucleus.ExecutionContextImpl#2c47a053" closed
2017-06-09 14:57:18.463 INFO 9492 --- [ main] o.s.t.c.transaction.TransactionContext : Rolled back transaction for test context [DefaultTestContext#1f6f0fe2 testClass = SymbolRestTests, testInstance = com.bp.gis.tardis.integration.SymbolRestTests#22604c7e, testMethod = shouldCreateEntity#SymbolRestTests, testException = org.springframework.dao.CannotAcquireLockException: PreparedStatementCallback; SQL [SELECT count(*) FROM symbol WHERE title = ?]; A lock could not be obtained within the time requested; nested exception is java.sql.SQLTransactionRollbackException: A lock could not be obtained within the time requested, mergedContextConfiguration = [WebMergedContextConfiguration#3a48c398 testClass = SymbolRestTests, locations = '{}', classes = '{class com.bp.gis.tardis.config.TestDataSourceConfig, class com.bp.gis.tardis.config.TestDataSourceConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{logging.level.DataNucleus=DEBUG, logging.level.com.bp.gis.tardis=TRACE, logging.level.org.springframework.jdbc.core=TRACE, security.basic.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer#1b4ba615 key = [#org.springframework.boot.autoconfigure.AutoConfigurationPackage(), #org.junit.FixMethodOrder(value=NAME_ASCENDING), #org.springframework.context.annotation.Import(value=[class org.springframework.boot.autoconfigure.AutoConfigurationPackages$Registrar]), #org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase(replace=ANY, connection=DERBY), #org.springframework.boot.autoconfigure.EnableAutoConfiguration(exclude=[], excludeName=[]), #org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.context.SpringBootTestContextBootstrapper), #org.junit.jupiter.api.extension.ExtendWith(value=[class org.springframework.test.context.junit.jupiter.SpringExtension]), #org.springframework.transaction.annotation.Transactional(propagation=REQUIRED, rollbackForClassName=[], readOnly=false, isolation=DEFAULT, transactionManager=, noRollbackFor=[], noRollbackForClassName=[], value=, timeout=-1, rollbackFor=[]), #org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc(webDriverEnabled=true, print=DEFAULT, webClientEnabled=true, secure=true, addFilters=true, printOnlyOnFailure=true), #org.springframework.boot.autoconfigure.ImportAutoConfiguration(value=[], exclude=[], classes=[]), #org.junit.platform.commons.meta.API(value=Experimental), #org.springframework.context.annotation.Import(value=[class org.springframework.boot.autoconfigure.ImportAutoConfigurationImportSelector]), #org.springframework.boot.test.autoconfigure.properties.PropertyMapping(value=spring.test.mockmvc, skip=NO), #org.springframework.boot.test.context.SpringBootTest(webEnvironment=MOCK, value=[], properties=[logging.level.DataNucleus=DEBUG, logging.level.com.bp.gis.tardis=TRACE, logging.level.org.springframework.jdbc.core=TRACE, security.basic.enabled=false], classes=[class com.bp.gis.tardis.config.TestDataSourceConfig]), #org.springframework.boot.test.autoconfigure.properties.PropertyMapping(value=spring.test.database, skip=NO), #org.springframework.context.annotation.Import(value=[class org.springframework.boot.autoconfigure.EnableAutoConfigurationImportSelector])]], org.springframework.boot.test.context.SpringBootTestContextCustomizer#702657cc, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#6025e1b6, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#e30f6a3a, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#1ff4931d], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]].
UPDATE #3
The logging shows the INSERT by DataNucleus, followed several log statements that all look kosher about entity objects, and then comes
ExecutionContext.internalFlush() process finished
which sounds like the DataNucleus EntityManager flushing. Then comes the logging statement from Spring's JdbcTemplate which wants to read what JPA insert, and it all goes wrong.
Spring does in fact totally wrap the EntityManager for its testing framework and the wrapper just swallows the call to entityManager.close() so that call won't cause transactions to complete.
Spring also throws an error on calls to entityManager.getTransaction().
Typically in my experience of Spring, what just worked with the conventional Spring approach, e.g. Spring Data JPA with fully integrated Hibernate, does not work with DataNucleus.
Thanks go to this SO Q: How to manually force a commit in a #Transactional method?
I took out the #Transactional annotation from the class declaration, and put nothing on the test method, and called a seperate method with REQUIRES_NEW to do the REST-to-database functionality I want to test. Then in the original test method after that call, it was all committed and not locked so I could use Spring's JdbcTemplate to examine the result.
#Test
public void shouldCreateEntity() throws Exception {
String testTitle = "TEST.CODE.1";
String testExtra = "Test for SymbolRestTests.java";
String json = createJsonExample(testTitle, testExtra, true);
log.debug(String.format("JSON==%s", json));
doInNewTransaction(json);
String sql = "SELECT count(*) FROM symbol WHERE title = ?";
int count = jdbcTemplate.queryForObject(
sql, new Object[] { testTitle }, Integer.class);
Assert.assertThat(count, is(1));
}
#Transactional(propagation = Propagation.REQUIRES_NEW)
private void doInNewTransaction(String json) throws Exception {
MockHttpServletRequestBuilder requestBuilder =
post("/symbols").content(json);
mockMvc.perform(requestBuilder)
.andExpect(status().isCreated())
.andExpect(header().string("Location",
containsString("symbols/")));
}