Test RestController Delete Crud method return 404 expected 400 - rest

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");

Related

Why my unit test is giving me an AssertionFailedError when I try to render another page

I am learning unit testing and trying to check if the login is valid on the HomePage and if so that the SuccessPage is rendered but it is giving me an AssertionFailedError
.java:
#Test
public void validLogin(){
tester.startPage(HomePage.class);
FormTester form = tester.newFormTester("userForm");
form.setValue("username", "emile");
form.setValue("password", "123");
form.submit();
//onsubmit the Successpage is rendered in response
tester.assertRenderedPage(SuccessPage.class);
}
the error:
[main] INFO org.apache.wicket.Application - [WicketTesterApplication-768a67f4-8bf1-45d0-bdcb-3a9be18172e1] init: Wicket core library initializer
[main] INFO org.apache.wicket.Application - [WicketTesterApplication-768a67f4-8bf1-45d0-bdcb-3a9be18172e1] init: Wicket extensions initializer
[main] INFO org.apache.wicket.Application - [WicketTesterApplication-768a67f4-8bf1-45d0-bdcb-3a9be18172e1] init: Wicket jQuery UI initializer
[main] INFO org.apache.wicket.Application - [WicketTesterApplication-768a67f4-8bf1-45d0-bdcb-3a9be18172e1] init: Wicket jQuery UI initializer (theme-uilightness)
ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
junit.framework.AssertionFailedError: classes not the same, expected 'class com.mycompany.SuccessPage', current 'class com.mycompany.HomePage'
at org.apache.wicket.util.tester.WicketTester.assertResult(WicketTester.java:798)
at org.apache.wicket.util.tester.WicketTester.assertRenderedPage(WicketTester.java:697)
at com.mycompany.TestHomePage.validLogin(TestHomePage.java:48)
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.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
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.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
I got the answer, so I didn't reference the form.submit(); to the onSubmit() function so I basically did this:
#Test
public void validLogin() throws Exception {
tester.startPage(HomePage.class);
// tester.startComponentInPage(HomePage.class);
FormTester form = tester.newFormTester("userForm");
form.setValue("username", "emile");
form.setValue("password", "123");
form.submit("error"); // new code that was edited
//onsubmit the Successpage is rendered in response
tester.assertRenderedPage(SuccessPage.class);
}
the form.submit("error"); now references to the wicket:id="error" and passed the test :D

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

Controller Test fails with MethodArgumentConversionNotSupportedException but not in the running application

Spring Boot App using 2.0.3.RELEASE of Spring Boot.
So I have REST API controller written like this:
#RestController
#RequestMapping("/root/{id}")
#Slf4j
public class RootController {
#GetMapping
public ResponseEntity<?> getXXX(
#PathVariable String id,
#RequestParam(value = "status") Status status,
#RequestParam(value = "comment") String comment,
#RequestParam(value = "other") Optional<String> other) {
log.info("Requested getXXX id={} status={} other={} comment={}", id, status, other, comment);
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
}
So the interesting part is the Optional<String> other on the above definition. I have tested the above manually via calling curl:
curl -v -X GET 'http://localhost:8080/root/ID?status=OK&comment=Comment'
which results in logging output on console like this:
...Requested getXXX id=ID status=OK other=Optional.empty comment=Comment
and using curl like this:
curl -v -X GET 'http://localhost:8080/root/ID?status=OK&comment=Comment&other=MoreOther'
which results in the following output:
Requested getXXX id=ID status=OK other=Optional[MoreOther] comment=Comment
So far so good.
But of course I would like to check this via unit tests and not manually...So I wrote a REST controller test which looks like this:
#RunWith(SpringRunner.class)
#SpringBootTest(classes = RootController.class)
#AutoConfigureMockMvc
public class RootControllerTest {
#Autowired
private MockMvc mvc;
#Test
public void shouldReturnNotImplemented() throws Exception {
//#formatter:off
mvc.perform(
get("/root/xyz?status={status}&comment={comment}&other={other}", Status.NOTOK, "COMMENT", Optional.<String>of("Other"))
.characterEncoding("UTF-8")
.accept(MediaType.ALL)
)
.andExpect(
status().isNotImplemented()
);
//#formatter:on
}
But unfortunately the above test fails with:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /root/xyz
Parameters = {status=[OK], comment=[Comment], other=[Optional[Other]]}
Headers = {Accept=[*/*]}
Body = null
Session Attrs = {}
Handler:
Type = ...RootController
Method = public org.springframework.http.ResponseEntity<?> .getRoot(java.lang.String,Status,java.lang.String,java.util.Optional<java.lang.String>)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.web.method.annotation.MethodArgumentConversionNotSupportedException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 500
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
Where the exception: org.springframework.web.method.annotation.MethodArgumentConversionNotSupportedException is the thing I don't understand.
The final question is: Why does the test fail but the running application does not? Does someone has a hint / idea for me?
Update 1:
I have tested also the following:
get("/root/xyz?status={status}&comment={comment}&other={other}", Status.NOTOK, "COMMENT", "Other")
and furthermore which means using only strings.
get("/root/xyz?status={status}&comment={comment}&other={other}", "NOTOK", "COMMENT", "Other")
The point that the running application works perfectly but unfortunately the test do not.
Update 2:
So after turning on debugging mode in test I got the following output: This brings me more and more into the direction that there is a bug within it..cause the parameters are always converted into String instead of Optional...and based on the parameters of get(..., Object... uriVars)
it looks like there is some problem in the code...
2018-07-16 15:50:21.029 DEBUG 16022 --- [main] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /root/xyz
2018-07-16 15:50:21.031 DEBUG 16022 --- [main] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.http.ResponseEntity<?> de....RootController.getXXX(java.lang.String,de....Status,java.lang.String,java.util.Optional<java.lang.String>)]
2018-07-16 15:50:21.057 DEBUG 16022 --- [main] .w.s.m.m.a.ServletInvocableHandlerMethod : Failed to resolve argument 3 of type 'java.util.Optional'
org.springframework.web.method.annotation.MethodArgumentConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Optional'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.util.Optional': no matching editors or conversion strategy found
at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:127)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:124)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:161)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:131)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:165)
at de...RootControllerTest.shouldReturnNotImplemented(RootControllerTest.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Caused by: java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.util.Optional': no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:299)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:99)
at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:73)
at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:52)
at org.springframework.validation.DataBinder.convertIfNecessary(DataBinder.java:692)
at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:123)
... 50 common frames omitted
This is an issue with how you are loading the test up.
When you specify #SpringBootTest(classes = RootController.class) a class with SpringBootTest it will only load that class into the context i.e. it allows you to specify certain configurations etc. that you would want to test for some integration tests rather than using ContextConfiguration.
You can either remove the RootController and load a full test application context, effectively loading your entire application.
or just specify,
#RunWith(SpringRunner.class)
#WebMvcTest
public class RootControllerTest {
To load a slice test, which will only load the required beans to completely test the WebMVC.
working tests,
https://github.com/Flaw101/mockmvctests
Edit,
I've updated my example and introduced a second controller but only load the RootController in the RootControllerMock via #WebMvcTest(controllers = RootController.class). You can see in the logged output that it only load this controller.
2018-07-16 15:34:28.264 INFO 6176 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/root/{id}],methods=[GET]}" onto public org.springframework.http.ResponseEntity<?> com.darrenforsythe.mockmvc.RootController.getXXX(java.lang.String,java.lang.String,java.lang.String,java.util.Optional<java.lang.String>)
references,
https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTest.html
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests

org.springframework.kafka.listener.ListenerExecutionFailedException: Listener method threw java.lang.NullPointerException

I am getting the below error within my Consumer class InventoryEventReceiver in the listener method.
Not sure of why the NullPointerException is appearing. I am just POSTing two InventoryEvent objects.
Any quick help will be appreciated.
My Consumer class with listener method
public class InventoryEventReceiver {
private static final Logger log = LoggerFactory.getLogger(InventoryEventReceiver.class);
private CountDownLatch latch = new CountDownLatch(1);
public CountDownLatch getLatch() {
return latch;
}
#KafkaListener(topics="inventory", containerFactory="kafkaListenerContainerFactory")
public void listenWithHeaders(
InventoryEvent event) {
System.out.println("EVENT HAS BEEN RECEIVED by listenWithHeaders(InventoryEvent)");
System.out.println(event.toString());
log.info(System.currentTimeMillis() + "-- Received Event :\"" + event + " for topic : inventory");
System.out.println("Sending event to webhook triggers ... ");
KafkaWebhookServiceImpl webhookService = new KafkaWebhookServiceImpl();
List<WebhookRequestBody> listWebhooks = webhookService.getAllWebhooksForTopic("inventory");
System.out.println("Number of registered webhooks for topic \"inventory\" : " + listWebhooks.size());
CountDownLatch countLatch = new CountDownLatch(listWebhooks.size());
for(WebhookRequestBody w : listWebhooks) {
Executors.newSingleThreadExecutor().execute(new InventoryEventProcessor(countLatch, event, w));
}
try {
countLatch.await(); // wait until countLatch counted down to 0
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Events SENT to all listening webhook triggers. ");
latch.countDown();
}
}
KafkaWebhookServiceImpl class
#Service("webhookService")
#Transactional
public class KafkaWebhookServiceImpl implements KafkaWebhookService {
#Autowired
private KafkaWebhookRepository webhookRepository;
#Override
public List<WebhookRequestBody> getAllWebhooksForTopic(String topic) {
return webhookRepository.findByTopic(topic); <-- ERROR: line 45
}
}
I am POSTing the below two records through Kafka REST Proxy
curl -i -X POST -H "Content-Type: application/vnd.kafka.json.v1+json" --data '{"value_schema": "{\"type\": \"record\", \"name\": \"InventoryEvent\", \"fields\": [{\"name\": \"id\", \"type\": \"int\"},{\"name\": \"eventType\", \"type\": \"string\"},{\"name\": \"qtyReq\", \"type\": \"int\"},{\"name\": \"qtyLevel\", \"type\": \"int\"}]}", "records": [{"value": {"id": 6122,"eventType":"inventory.transaction","qtyReq": 34,"qtyLevel": 129}},{"value": {"id": 7798,"eventType":"inventory.transaction","qtyReq": 5,"qtyLevel": 27}}]}' http://localhost:8082/topics/inventory
Error Log
EVENT HAS BEEN RECEIVED by listenWithHeaders(InventoryEvent)
InventoryEvent [id=7798, eventType='inventory.transaction', qtyReq='5', qtyLevel='27']
2017-12-29 10:51:22.375 INFO 12418 --- [ntainer#0-0-C-1] c.p.kafka.spring.InventoryEventReceiver : 1514544682375-- Received Event :"InventoryEvent [id=7798, eventType='inventory.transaction', qtyReq='5', qtyLevel='27'] for topic : inventory
Sending event to webhook triggers ...
2017-12-29 10:51:22.376 ERROR 12418 --- [ntainer#0-0-C-1] o.s.kafka.listener.LoggingErrorHandler : Error while processing: ConsumerRecord(topic = inventory, partition = 0, offset = 23, CreateTime = 1514544682080, checksum = 1801448922, serialized key size = -1, serialized value size = 72, key = null, value = InventoryEvent [id=7798, eventType='inventory.transaction', qtyReq='5', qtyLevel='27'])
org.springframework.kafka.listener.ListenerExecutionFailedException: Listener method 'public void com.psl.kafka.spring.InventoryEventReceiver.listenWithHeaders(com.psl.kafka.spring.InventoryEvent)' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.kafka.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:188) ~[spring-kafka-1.1.7.RELEASE.jar:na]
at org.springframework.kafka.listener.adapter.RecordMessagingMessageListenerAdapter.onMessage(RecordMessagingMessageListenerAdapter.java:72) ~[spring-kafka-1.1.7.RELEASE.jar:na]
at org.springframework.kafka.listener.adapter.RecordMessagingMessageListenerAdapter.onMessage(RecordMessagingMessageListenerAdapter.java:47) ~[spring-kafka-1.1.7.RELEASE.jar:na]
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeRecordListener(KafkaMessageListenerContainer.java:792) [spring-kafka-1.1.7.RELEASE.jar:na]
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeListener(KafkaMessageListenerContainer.java:736) [spring-kafka-1.1.7.RELEASE.jar:na]
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.run(KafkaMessageListenerContainer.java:568) [spring-kafka-1.1.7.RELEASE.jar:na]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_151]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_151]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_151]
Caused by: java.lang.NullPointerException: null
at com.psl.kafka.rest.KafkaWebhookServiceImpl.getAllWebhooksForTopic(KafkaWebhookServiceImpl.java:45) ~[classes/:0.0.1-SNAPSHOT]
at com.psl.kafka.spring.InventoryEventReceiver.listenWithHeaders(InventoryEventReceiver.java:126) ~[classes/:0.0.1-SNAPSHOT]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_151]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_151]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_151]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_151]
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:180) ~[spring-messaging-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:112) ~[spring-messaging-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.kafka.listener.adapter.HandlerAdapter.invoke(HandlerAdapter.java:48) ~[spring-kafka-1.1.7.RELEASE.jar:na]
at org.springframework.kafka.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:174) ~[spring-kafka-1.1.7.RELEASE.jar:na]
... 8 common frames omitted
the problem is in KafkaWebhookServiceImpl webhookService = new KafkaWebhookServiceImpl(); in InventoryEventReceiver class.
if you want spring to manage dependencies (process autowired) you shouldn't create beans on your own.
right now in this code
#Override
public List<WebhookRequestBody> getAllWebhooksForTopic(String topic) {
return webhookRepository.findByTopic(topic); <-- ERROR: line 45
}
you got NPE as webhookRepository is null and never was set.
You need to rewrite InventoryEventReceiver class to have instance of webhookRepository and not to create it.

JHipster MongoDB connection authorization

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