java.lang.IllegalArgumentException: Could not resolve placeholder 'crossOrigin' in value "${crossOrigin}" - spring-data-jpa

I am writing test case for controller class. When I am adding cross origin on top of every methods like this #CrossOrigin(origins = "http://localhost:4200")
at that time Test cases running properly without error.
But I don't want to hard code that cross origin on top of every methods. For that I added one variable in application.property file and accessing that variable in controller on top of class.When I added cross origin like this I am able to access my services from other machine. But my test cases getting failed.
when I am comment this #CrossOrigin(origins = "${crossOrigin}") from controller class test cases are running properly.
Can any one tell me why it's happening?
AccountController.java
package com.spacestudy.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.querydsl.core.Tuple;
import com.spacestudy.model.Account;
import com.spacestudy.model.*;
import com.spacestudy.services.*;
#RestController
#CrossOrigin(origins = "${crossOrigin}")
#RequestMapping("/api.spacestudy.com/spacestudy/rockefeller/admin/account")
public class AccountController {
#Autowired
AccountService accService;
#GetMapping("/loadAcctLocationList")
public ResponseEntity<List<Account>> findLocation() {
return ResponseEntity.ok(accService.findLocation());
}
Application.property
crossOrigin=http://localhost:4200
server.port=8088
spring.datasource.url=jdbc:postgresql://localhost/TestDB_002
spring.datasource.username=postgres
spring.datasource.password=postgres
TestAccountController
#RunWith(SpringRunner.class)
public class TestAccountController {
private MockMvc mockMvc;
#Mock
private AccountService accountService;
#InjectMocks
private AccountController accountController;
#Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
}
#Test
public void findLocationTest() throws Exception {
Account account = new Account();
account.setsLocation("US");
account.setsLocation("pune");
List<Account> accountObj = new ArrayList<Account>();
accountObj.add(account);
Mockito.when(accountService.findLocation()).thenReturn(accountObj);
mockMvc.perform(get("/api.spacestudy.com/spacestudy/rockefeller/admin/account/loadAcctLocationList"))
.andExpect(status().isOk()).andExpect(jsonPath("$[0].sLocation", is("pune")));
}
Stack Trace
java.lang.IllegalArgumentException: Could not resolve placeholder 'crossOrigin' in value "${crossOrigin}"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
at org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticStringValueResolver.resolveStringValue(StandaloneMockMvcBuilder.java:517)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.resolveCorsAnnotationValue(RequestMappingHandlerMapping.java:349)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.updateCorsConfig(RequestMappingHandlerMapping.java:319)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.initCorsConfiguration(RequestMappingHandlerMapping.java:303)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.initCorsConfiguration(RequestMappingHandlerMapping.java:55)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry.register(AbstractHandlerMethodMapping.java:558)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.registerHandlerMethod(AbstractHandlerMethodMapping.java:264)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.detectHandlerMethods(AbstractHandlerMethodMapping.java:250)
at org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping.registerHandlers(StandaloneMockMvcBuilder.java:490)
at org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder.registerMvcSingletons(StandaloneMockMvcBuilder.java:356)
at org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder.initWebAppContext(StandaloneMockMvcBuilder.java:341)
at org.springframework.test.web.servlet.setup.AbstractMockMvcBuilder.build(AbstractMockMvcBuilder.java:139)
at com.spacestudy.controller.TestAccountController.setup(TestAccountController.java:46)
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.RunBefores.evaluate(RunBefores.java:24)
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:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
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:191)
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)

I realize this question is over a year old, however I too ran into this issue.
The solution is one needs to provide the MockMvc with the place holder value.
So the following :
mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
Should be :
mockMvc = MockMvcBuilders.standaloneSetup(accountController).addPlaceholderValue("crossOrigin","https://some.url.com").build();

Related

Quarkus: Cannot #Inject MongoClient using Kotlin

I created a simple Kotlin Quarkus application that connects to my local MongoDB instance following the official guide.
The connection works, however it seems that it fails to inject the MongoClient/ReactiveMongoClient like so:
...
import com.mongodb.client.MongoClient
...
#ApplicationScoped
open class KotlinService #Inject constructor(private val mongoClient: MongoClient) {
fun getCollection(): MongoCollection<Document> = mongoClient.getDatabase("test").getCollection("hello")
}
Calling getCollection() results in:
org.jboss.resteasy.spi.UnhandledException: java.lang.NullPointerException
at org.jboss.resteasy.core.ExceptionHandler.handleApplicationException(ExceptionHandler.java:106)
at org.jboss.resteasy.core.ExceptionHandler.handleException(ExceptionHandler.java:372)
at org.jboss.resteasy.core.SynchronousDispatcher.writeException(SynchronousDispatcher.java:209)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:496)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:252)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:153)
at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:363)
at org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:156)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:238)
at io.quarkus.resteasy.runtime.standalone.RequestDispatcher.service(RequestDispatcher.java:73)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.dispatch(VertxRequestHandler.java:118)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.lambda$handle$0(VertxRequestHandler.java:74)
at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$2(ContextImpl.java:316)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.lang.NullPointerException
at ...service.KotlinService.getCollection(KotlinService.kt:12)
at ...resource.ReceiptResource.getAll(ReceiptResource.kt:19)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
.....
If I rewrite the class in Java instead it works fine:
...
import com.mongodb.client.MongoClient;
...
#ApplicationScoped
public class JavaService {
private MongoClient mongoClient;
#Inject
public JavaService(MongoClient mongoClient) {
this.mongoClient = mongoClient;
}
public MongoCollection<Document> getCollection() {
return mongoClient.getDatabase("test").getCollection("hello");
}
}
A bug or am I missing something here?
Update
Reported as a bug on github.

java.lang.IllegalStateException: Failed to load ApplicationContext error in Spring Boot

I am new to unit testing and I have to test my methods in spring boot.
I created application with Spring Security JWT Authentication + PostgreSQL – RestAPIs SpringBoot + Spring MVC + Spring JPA from this link
then I created controller for users to edit update ect.
My users controller looks like this
#RestController
#RequestMapping("/users")
public class Users {
#Autowired
private UserService userService;
#GetMapping(value = "/*")//can access with this root
#PreAuthorize("hasRole('ADMIN')") //Only admin can view all users' details
public List<User> AllUsers(){
return this.userService.getAllUsers();
}
#GetMapping(value = "/{username}")//can access with this root
public User GetOneUser(#PathVariable(value = "username") String username){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String auth_name = auth.getName(); //get logged in username
if(auth_name.equals(username)||this.userService.isAdmin(auth_name)){//admin and user can see the details
return this.userService.getUser(username);
}
else{
return null;
}
}
#DeleteMapping(value = "/{id}")//can access with this root
#PreAuthorize("hasRole('ADMIN')") //Only admin can delete user
public void DeleteUser(#PathVariable(value = "id") Long id){
this.userService.deleteUser(id);
}
#PostMapping(value = "/{username}")//can access with this root
public User EditUser(#PathVariable(value = "username") String username,#RequestBody SignUpForm user) {//only user can edit
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String auth_name = auth.getName(); //get logged in username
User upUser=null;
if(auth_name.equals(username)){
upUser=this.userService.updateUser(username,user);
}
return upUser;
}
}
then I created UserService like this:
#Service
public class UserService {
#Autowired
private UserRepository userRepository;
#Autowired
private RoleRepository roleRepository;
#Autowired
PasswordEncoder encoder;
public List<User> getAllUsers(){
// return topics;
List<User> users=new ArrayList<>();
userRepository.findAll().forEach(users::add);
return users;
}
public boolean isAdmin(String username){
boolean flag=false;
if(this.userRepository.existsByUsername(username)){
User user=this.userRepository.findByUsername(username).get();
Role adminRole = roleRepository.findByName(RoleName.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException("Fail! -> Cause: User Role not find."));
if(user.getId().equals(adminRole.getId())){
flag=true;
}
}
return flag;
}
public User getUser(String username){
return userRepository.findByUsername(username).orElse(null);
}
public User updateUser(String username, SignUpForm user) {
if(userRepository.existsByUsername(username)) {
User ExistingUser=userRepository.findByUsername(username).get();
if(ExistingUser.getName()!=user.getName()){
ExistingUser.setName(user.getName());
}
if(ExistingUser.getUsername()!=user.getUsername()){
ExistingUser.setUsername(user.getUsername());
}
if(ExistingUser.getPassword()!=user.getPassword()){
ExistingUser.setPassword(encoder.encode(user.getPassword()));
}
if(ExistingUser.getEmail()!=user.getEmail()){
ExistingUser.setEmail(user.getEmail());
}
Set<String> Roles =user.getRole();
Set<Role> roles = new HashSet<>();
Roles.forEach(role -> {
switch(role) {
case "admin":
Role adminRole = roleRepository.findByName(RoleName.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException("Fail! -> Cause: User Role not find."));
roles.add(adminRole);
break;
case "pm":
Role pmRole = roleRepository.findByName(RoleName.ROLE_PM)
.orElseThrow(() -> new RuntimeException("Fail! -> Cause: User Role not find."));
roles.add(pmRole);
break;
default:
Role userRole = roleRepository.findByName(RoleName.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Fail! -> Cause: User Role not find."));
roles.add(userRole);
}
});
if(ExistingUser.getRoles()!=roles){
ExistingUser.setRoles(roles);
}
userRepository.save(ExistingUser);
}
return userRepository.findByUsername(user.getUsername()).get();
}
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
}
it works.
But then I created class for testing that tests getUser() method from UserService
#WebMvcTest
#RunWith(SpringRunner.class)
public class UserServiceTest {
#MockBean
UserRepository repository;
#Autowired
UserService userService;
#Test
public void getUserTest(){
User user=this.userService.getUser("arife");
assertThat(user).isNotNull();
}
}
But it gives me error that looks like this:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.postProcessFields(MockitoTestExecutionListener.java:95)
at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.injectFields(MockitoTestExecutionListener.java:79)
at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.prepareTestInstance(MockitoTestExecutionListener.java:54)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
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)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authRestAPIs': Unsatisfied dependency expressed through field 'authenticationManager'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webSecurityConfig': Unsatisfied dependency expressed through field 'userDetailsService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'springbootjwtauthenticationpostgresql.springbootjwtauthenticationpostgresql.security.services.UserDetailsServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:598)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:376)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:847)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:744)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:391)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:312)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
... 25 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webSecurityConfig': Unsatisfied dependency expressed through field 'userDetailsService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'springbootjwtauthenticationpostgresql.springbootjwtauthenticationpostgresql.security.services.UserDetailsServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:598)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:376)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:392)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1255)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1175)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:595)
... 43 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'springbootjwtauthenticationpostgresql.springbootjwtauthenticationpostgresql.security.services.UserDetailsServiceImpl' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1662)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1221)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1175)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:595)
... 65 more
Please can someone help me?
Is pretty hard to follow up your problem if you don't add more details (log trace, code snapshots...)
But maybe you can find this pet project done by me (https://github.com/geeksusma/jwt-rest-controller)
Basically is a RestController which works with JWT.
I hope it could help
Now I wrote like this
#DataJpaTest
#RunWith(SpringRunner.class)
public class UserServiceTest {
#MockBean
UserService userService;
#Test
public void getUserTest(){
assertThat(this.userService.getUser("arife")).isNotNull();
}
}
and then I added new File application-test.properties
#ActiveProfiles("test")
#PostgreSQL
spring.datasource.url=jdbc:postgresql:
spring.datasource.username=
spring.datasource.password=
spring.jpa.generate-ddl=true
now it gives me error
java.lang.AssertionError:
Expecting actual not to be null
at springbootjwtauthenticationpostgresql.springbootjwtauthenticationpostgresql.model.UserServiceTest.getUserTest(UserServiceTest.java:59)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
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:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
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)
I think that is not connected to database

multiple datasource with spring boot jpa

Trying to setup dual datasource with spring boot, but it would seem alot harder then first thought,
tried to follow tons of tutorials and guides, but keep getting error with my repos.
application properties
# Primary DataSource
datasource.primary.url=url
datasource.primary.username=user
datasource.primary.password=pw
datasource.primary.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
# Secondary DataSource
datasource.secondary.url=url
datasource.secondary.username=user
datasource.secondary.password=pw
datasource.secondary.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
# hibernate strategy (create/update)
spring.jpa.hibernate.ddl-auto=update
# name strategy
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
first db config
package com.anders.cphbusiness.db;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
basePackages = {"com.anders.cphbusiness.repositories"},
entityManagerFactoryRef = "primaryEM")
public class LoadDataSourceConfig {
#Bean(name = "primaryDS")
#Primary
#ConfigurationProperties(prefix = "datasource.primary")
public DataSource loadingDataSource() {
return DataSourceBuilder.create().build();
}
#PersistenceContext(unitName = "primaryPU")
#Primary
#Bean(name = "primaryEM")
public LocalContainerEntityManagerFactoryBean loadingEntityManagerFactory(
EntityManagerFactoryBuilder builder, #Qualifier("primaryDS") DataSource primaryDS) {
return builder
.dataSource(primaryDS)
.persistenceUnit("primaryPU")
.packages("com.anders.cphbusiness.entitiesModel")
.build();
}
#Primary
#Bean(name = "primaryTM")
public PlatformTransactionManager transactionManager(
#Qualifier("primaryEM") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
second db config
package com.anders.cphbusiness.db;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
basePackages = "com.anders.cphbusiness.secondRepo",
entityManagerFactoryRef = "secondaryEM",
transactionManagerRef = "secondaryTransactionManager")
public class StoreDataSourceConfig {
#Bean(name = "secondaryDS")
#ConfigurationProperties(prefix = "datasource.secondary")
public DataSource storingDataSource() {
return DataSourceBuilder.create().build();
}
#PersistenceContext(unitName = "secondaryPU")
#Bean(name = "secondaryEM")
public LocalContainerEntityManagerFactoryBean storingEntityManagerFactory(
EntityManagerFactoryBuilder builder, #Qualifier("secondaryDS") DataSource secondaryDS) {
return builder
.dataSource(secondaryDS)
.packages("com.anders.cphbusiness.storingModel")
.persistenceUnit("secondaryPU")
.build();
}
#Bean(name = "secondaryTM")
public PlatformTransactionManager secondaryTransactionManager(
#Qualifier("secondaryEM") EntityManagerFactory secondaryEM) {
return new JpaTransactionManager(secondaryEM);
}
}
repo examples
package com.anders.cphbusiness.repositories;
import com.anders.cphbusiness.entitiesModel.WagerBoard;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import javax.persistence.PersistenceContext;
#Repository
#PersistenceContext(name = "primaryEM")
public interface WagerBoardRepo extends JpaRepository<WagerBoard, String> {
}
storeDbEntRepo:
package com.anders.cphbusiness.secondRepo;
import com.anders.cphbusiness.entitiesModel.WagerBoard;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import javax.persistence.PersistenceContext;
#Repository
#PersistenceContext(name = "secondaryEM")
public interface StoreDbEntRepo extends JpaRepository<WagerBoard, String> {
}
the error
2017-02-07 10:57:54.222 ERROR 7176 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'storeDbEntRepo': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.anders.cphbusiness.entitiesModel.WagerBoard
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:742) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) ~[spring-context-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at com.anders.cphbusiness.DsRngCheckerApplication.main(DsRngCheckerApplication.java:18) [main/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_111]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_111]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_111]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_111]
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) [idea_rt.jar:na]
Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.anders.cphbusiness.entitiesModel.WagerBoard
at org.hibernate.jpa.internal.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:210) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:70) ~[spring-data-jpa-1.11.0.RELEASE.jar:na]
at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:67) ~[spring-data-jpa-1.11.0.RELEASE.jar:na]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:152) ~[spring-data-jpa-1.11.0.RELEASE.jar:na]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:99) ~[spring-data-jpa-1.11.0.RELEASE.jar:na]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:81) ~[spring-data-jpa-1.11.0.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:199) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:277) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:263) ~[spring-data-commons-1.13.0.RELEASE.jar:na]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:101) ~[spring-data-jpa-1.11.0.RELEASE.jar:na]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
... 21 common frames omitted
Your main problem is: not a managed type: class com.anders.cphbusiness.entitiesModel.WagerBoard
Your StoreDbEntRepo is using "secondaryEM", but is using WagerBoard entity to create the repo.
WagerBoard entity belongs to entitiesModel package. If you want to use that entity into your StoreDbEntRepo, your need to scan the proper package in your EntityManager, doing an update from
.packages("com.anders.cphbusiness.storingModel")
to
.packages("com.anders.cphbusiness.storingModel","com.anders.cphbusiness.entitiesModel").
But if your don't, use an entity that belongs to storingModel package to create the StoreDbEntRepo.

WELD-001408 Unsatisfied dependencies

I have a very famous error, but I can't solve it.
I'm trying to run arqullian test for my application.
I've done everything according to the official documentation.
The long search for solution to the problem given nothing.
16:49:42,713 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-4) MSC00001: Failed to start service jboss.deployment.unit."test.war".WeldService: org.jboss.msc.service.StartException in service jboss.deployment.unit."test.war".WeldService: org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [Sender] with qualifiers [#Default] at injection point [[field] #Inject com.test.test2.ejb.AppManagerBean.sender]
at org.jboss.as.weld.services.WeldService.start(WeldService.java:83)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_13]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_13]
at java.lang.Thread.run(Thread.java:722) [rt.jar:1.7.0_13]
Caused by: org.jboss.weld.exceptions.DeploymentException:
WELD-001408 Unsatisfied dependencies for type [Sender] with qualifiers [#Default]
at injection point [[field] #Inject com.test.test2.ejb.AppManagerBean.sender]
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:275)
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:244)
at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:107)
at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:127)
at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:346)
at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:331)
at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:366)
at org.jboss.as.weld.WeldContainer.start(WeldContainer.java:83)
at org.jboss.as.weld.services.WeldService.start(WeldService.java:76)
... 5 more
My test class:
package com.highstreetlabs.wlcome.rest;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import com.test.test2.ejb.AppManager;
import com.test.test2.ejb.Storage;
import com.test.test2model.Customer;
import com.test.test2.rest.model.ProximityModel;
import com.test.test2.util.EntityManagerProducer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.json.simple.parser.ParseException;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.ejb.EJB;
import javax.inject.Inject;
#RunWith(Arquillian.class)
public class CustomerCollectionResourceTest {
#Deployment
public static WebArchive createTestArchive() {
return ShrinkWrap.create(WebArchive.class, "test.war")
.addClasses(CustomerCollectionResource.class, EntityManagerProducer.class,
AppManager.class, Storage.class,
ParseException.class, Sender.class)
.addPackage(Customer.class.getPackage())
.addPackage(Result.class.getPackage())
.addPackage(NotFoundException.class.getPackage())
.addPackage(CustomerPhotoResource.class.getPackage())
.addPackage(ProximityModel.class.getPackage())
.addAsResource("import.sql")
.addAsManifestResource(EmptyAsset.INSTANCE, "META-INF/beans.xml")
.addAsManifestResource("test-ds.xml", "test-ds.xml");
}
#Inject
CustomerCollectionResource resource;
#EJB
AppManager manager;
#Test
public void testList() throws Exception {
resource = new CustomerCollectionResource();
resource.list(null);
}
}
AppManagerBean.java
import com.google.android.gcm.server.Constants;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import com.google.common.base.Strings;
import com.test.test2.json.JacksonObjectMapperProvider;
import com.test.test2.model.*;
import com.test.test2.rest.HttpStatusException;
import com.test.test2.rest.NotFoundException;
import com.test.test2.rest.model.ProximityModel;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ejb.Asynchronous;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.*;
import javax.persistence.criteria.*;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.List;
/**
* Stateless EJB bean containing entire business logic implementation
*/
#Local(AppManager.class)
#Stateless
public class AppManagerBean implements AppManager {
public static final String
GCM_ENTER_ACTION = "enter",
GCM_EXIT_ACTION = "exit",
PARAM_DATA_JSON = "proximityModel",
PARAM_CUSTOMER_ID = "customerId",
PARAM_ACTION = "action";
#Inject
EntityManager em;
#Inject
Sender sender;
....
}
And finally class for test CustomerCollectionResource
#Path("customer/")
#RequestScoped
public class CustomerCollectionResource {
final static int CACHEABLE_SECONDS = 0;
#EJB
private AppManager manager;
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response list(#QueryParam("email") String email) {
final List<Customer> entities = manager.listCustomers(email);
if(entities.size() == 0)
throw new NotFoundException("There is no any customer");
ListModel<ListItem> result = new ListModel<ListItem>(entities.size());
result.itemType = ListItem.MEDIA_TYPE;
final UriBuilder itemLink = UriBuilder.fromResource(CustomerResource.class);
for (Customer entity : entities) {
result.add(new ListItem(entity.getName(), itemLink.build(entity.getId())));
}
CacheControl cc = new CacheControl();
cc.setMaxAge(CACHEABLE_SECONDS);
cc.setPrivate(true);
return Response.ok(result).cacheControl(cc).build();
}
}
Sender Producer
public class GcmSenderProducer {
#Resource String senderId;
#Produces public Sender getSender() {
return new Sender(senderId);
}
}
Yes, I also think the GcmSenderProducer is missing so the Sender class cannot be injected propperly since it looks like it has no no-arg constructor and I guess the constructor.

Morphia-MongoDB - "Please override this method for user marked Id field entity"

I am following a tutorial mention on code.google, but my example fails giving the following trace :
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at com.google.code.morphia.mapping.MappedClass.callLifecycleMethods(MappedClass.java:323)
at com.google.code.morphia.mapping.Mapper.toDBObject(Mapper.java:371)
at com.google.code.morphia.DatastoreImpl.entityToDBObj(DatastoreImpl.java:674)
at com.google.code.morphia.DatastoreImpl.save(DatastoreImpl.java:722)
at com.google.code.morphia.DatastoreImpl.save(DatastoreImpl.java:802)
at com.google.code.morphia.DatastoreImpl.save(DatastoreImpl.java:796)
at models.com.vlist.activity.classes.TestMongoData.testUserData(TestMongoData.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.google.code.morphia.mapping.MappedClass.callLifecycleMethods(MappedClass.java:304)
... 28 more
Caused by: java.lang.UnsupportedOperationException: Please override this method for user marked Id field entity: models.com.vlist.activity.classes.User
at play.modules.morphia.Model.setId_(Model.java:284)
at play.modules.morphia.Model.generateId_(Model.java:299)
... 33 more
My example is as following:
import javax.persistence.Entity;
import org.bson.types.ObjectId;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.annotations.Id;
import play.modules.morphia.Model;
#Entity
public class User extends Model {
#Id ObjectId id;
private String firstName;
private String lastName;
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName(){
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
}
and
import static org.junit.Assert.*;
import org.junit.Test;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
public class TestMongoData {
#Test
public void testUserData() {
User user = new User();
user.setFirstName("first");
user.setLastName("last");
Morphia morphia = new Morphia();
Datastore ds = morphia.createDatastore("testData");
ds.save(user);
}
}
What could be wrong?
Update:
When I use play test, i see the following:
08:01:55,783 ERROR ~
#66h1bm10d
Internal Server Error (500) for request GET /#tests
Compilation error (In {module:morphia}/app/morphia/Filter.java around line 8)
The file {module:morphia}/app/morphia/Filter.java could not be compiled. Error raised is : The type Filter is already defined
play.exceptions.CompilationException: The type Filter is already defined
at play.classloading.ApplicationCompiler$2.acceptResult(ApplicationCompiler.java:246)
at org.eclipse.jdt.internal.compiler.Compiler.handleInternalException(Compiler.java:672)
at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:516)
at play.classloading.ApplicationCompiler.compile(ApplicationCompiler.java:278)
at play.classloading.ApplicationClassloader.getAllClasses(ApplicationClassloader.java:406)
at play.Play.start(Play.java:453)
at play.Play.detectChanges(Play.java:574)
at play.Invoker$Invocation.init(Invoker.java:186)
at Invocation.HTTP Request(Play!)
The problem comes from your #Entity definition. You're using JPA annotation while you should use the Morphia ones.
On startup, the Morphia plugin will retrieve all classes marked with the morphia Entity annotation and enhance them with various injected model methods. You're receiving this exception because your model class hasn't been enhanced.
If you annotate #Id then play morphia won't enhance your model by providing right implementation for void setId_(Object id) method. Try defining one yourself like this.
#Entity
class User extends Model {
#Id String email;
protected void setId_(Object id) {
}
}
Try removing the #Id ObjectId id; from your model. The Morphia Module for Play Framework will add the id for you.
Then make the fields public and remove the getter/setter methods.
public String firstName;
public String lastName;
Also, your Entity import is incorrect. Try this
import com.google.code.morphia.annotations.Entity;
Try this for a test case:
import static org.junit.Assert.*;
import org.junit.Test;
import play.test.UnitTest;
public class TestMongoData extends UnitTest {
#Test
public void testUserData() {
User user = new User();
user.setFirstName("first");
user.setLastName("last");
user.save();
}
}
It's seems that you have defined the morphia module in the dependency file and in the application conf file.
In the dependencies file : - play -> morphia [1.2.1beta6,)
In the application conf file : module.morphia=${play.path}/modules/morphia
You must removed one of this declaration otherwise the morphia module is loaded twice ...