Spring: Illegally attempted to associate a proxy with two open Sessions - spring

I have a page to create taxis which consist on a simple form to fill my database. This class and the dao were autogenerated by hibernate tools. When I post my code and it's called the persist method then I get a PersistException The code:
Controller.java
#Controller
#RequestMapping(value="/session/taxi")
public class TaxiController {
private final Log log = LogFactory.getLog(getClass());
#Autowired
private UserManager userManager;
#Autowired
private TaxiManager taxiManager;
/**
* Returns the create taxi page.
* #param model the model on which to map.
* #return A String reference to jsp.
*/
#RequestMapping(value="/create", method=RequestMethod.GET)
public String createTaxi(ModelMap model){
//Add the current business and city to this taxi. It can not be modified
Taxi taxi = taxiManager.createDefaultTaxi();
TaxiPassword taxiPass = new TaxiPassword();
taxiPass.setTaxi(taxi);
model.addAttribute("newTaxi", taxiPass);
return "taxi/createtaxi";
}
/**
* Add a new taxi to the database.
* #param taxiPassword the taxi to be added.
* #param result the result of binding taxi from the model.
* #param redirectAttributes attributes to show messages when redirect.
* #return a string that refers to jsp page.
*/
#RequestMapping(value="/create", method=RequestMethod.POST)
public String addNewTaxi(#ModelAttribute("newTaxi") #Valid TaxiPassword taxiPassword, BindingResult result,
final RedirectAttributes redirectAttributes){
String newPage = "";
Taxi taxi = taxiPassword.getTaxi();
//Check password is correct
if (!result.hasErrors()){
//Set the password as md5
taxi.setPassword(SecurityUtils.getMD5Password(taxi.getPassword()));
//Persist it
taxiManager.persistTaxi(taxiPassword.getTaxi());
newPage = "redirect:/session/taxi/viewtaxi";
}else{
newPage = "taxi/createtaxi";
}
return newPage;
}
}
Taxi.java
#Entity
#Table(name = "taxi", catalog = "takeme", uniqueConstraints = #UniqueConstraint(columnNames = "username"))
public class Taxi implements java.io.Serializable {
#NotNull
#Size(min=1, max=20)
#Digits(integer = 15, fraction = 0)
private String idLicense;
#Valid
private City city;
#Valid
private Business business;
#NotNull
#Nif
private String dni;
#NotNull
#Size(min=3, max=50)
private String username;
#Size(min=5, max=50)
private String password;
#NotNull
#Size(min=1, max=50)
private String name;
#NotNull
#Size(min=1, max=45)
private String surname;
#NotNull
#Size(min=1, max=30)
private String phone;
#NotNull
private boolean creditCardAvailability;
#NotNull
private boolean taxiAdapted;
#NotNull
private boolean bigTaxi;
#NotNull
private boolean availability;
private Double latitude;
private Double longitude;
private byte[] photo;
#NotNull
private boolean state;
private Set<Booking> bookings = new HashSet<Booking>(0);
private Set<MobileClientRateTaxi> mobileClientRateTaxis = new HashSet<MobileClientRateTaxi>(
0);
public Taxi() {
}
public Taxi(String idLicense, City city, Business business, String dni,
String username, String password, String name, String surname,
String phone, boolean creditCardAvailability, boolean taxiAdapted,
boolean bigTaxi, boolean availability, boolean state) {
this.idLicense = idLicense;
this.city = city;
this.business = business;
this.dni = dni;
this.username = username;
this.password = password;
this.name = name;
this.surname = surname;
this.phone = phone;
this.creditCardAvailability = creditCardAvailability;
this.taxiAdapted = taxiAdapted;
this.bigTaxi = bigTaxi;
this.availability = availability;
this.state = state;
}
public Taxi(String idLicense, City city, Business business, String dni,
String username, String password, String name, String surname,
String phone, boolean creditCardAvailability, boolean taxiAdapted,
boolean bigTaxi, boolean availability, Double latitude,
Double longitude, byte[] photo, boolean state,
Set<Booking> bookings,
Set<MobileClientRateTaxi> mobileClientRateTaxis) {
this.idLicense = idLicense;
this.city = city;
this.business = business;
this.dni = dni;
this.username = username;
this.password = password;
this.name = name;
this.surname = surname;
this.phone = phone;
this.creditCardAvailability = creditCardAvailability;
this.taxiAdapted = taxiAdapted;
this.bigTaxi = bigTaxi;
this.availability = availability;
this.latitude = latitude;
this.longitude = longitude;
this.photo = photo;
this.state = state;
this.bookings = bookings;
this.mobileClientRateTaxis = mobileClientRateTaxis;
}
#Id
#Column(name = "id_license", unique = true, nullable = false, length = 20)
public String getIdLicense() {
return this.idLicense;
}
public void setIdLicense(String idLicense) {
this.idLicense = idLicense;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_city", nullable = false)
public City getCity() {
return this.city;
}
public void setCity(City city) {
this.city = city;
}
// More autogenerated setters and getters...
}
TaxiDao.java
#Repository(value = "taxiDAO")
public class TaxiDAOImpl implements TaxiDAO{
private final Log log = LogFactory.getLog(getClass());
#PersistenceContext(unitName = "takemePU", type = PersistenceContextType.EXTENDED)
private EntityManager entityManager;
#Transactional(readOnly = false)
public void persist(Taxi transientInstance) {
log.debug("Persisting taxi instance: " + transientInstance.getIdLicense());
try {
entityManager.persist(transientInstance);
log.debug("Persist successful");
} catch (RuntimeException re) {
log.error("Persist failed: ", re);
throw re;
}
}
#Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW)
public void remove(Taxi persistentInstance) {
log.debug("Removing taxi instance: " + persistentInstance.getIdLicense());
try {
entityManager.remove(persistentInstance);
log.debug("Remove successful");
} catch (RuntimeException re) {
log.error("Remove failed: ", re);
throw re;
}
}
#Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW)
public Taxi merge(Taxi detachedInstance) {
log.debug("Merging taxi instance: " + detachedInstance.getIdLicense());
try {
Taxi result = entityManager.merge(detachedInstance);
log.debug("Merge successful");
return result;
} catch (RuntimeException re) {
log.error("Merge failed: ", re);
throw re;
}
}
#Transactional(readOnly = true)
public Taxi findById(String id) {
log.debug("Getting taxi instance with id: " + id);
try {
Taxi instance = entityManager.find(Taxi.class, id);
log.debug("Get successful");
return instance;
} catch (RuntimeException re) {
log.error("Get failed: ", re);
throw re;
}
}
#Transactional(readOnly = true)
public Taxi findByUsername(String username) {
log.debug("Getting taxi instance with id: " + username);
try {
Taxi instance = entityManager.find(Taxi.class, username);
log.debug("Get successful");
return instance;
} catch (RuntimeException re) {
log.error("Get failed: ", re);
throw re;
}
}
#SuppressWarnings("unchecked")
#Transactional(readOnly = true)
public List<Taxi> getTaxiList() {
return entityManager.createQuery("select taxi from Taxi taxi").getResultList();
}
#SuppressWarnings("unchecked")
#Transactional(readOnly = true)
public List<Taxi> getTaxisByBusiness(String idBusiness) {
return entityManager.createQuery("select taxi from Taxi taxi where taxi.business.idBusiness='"+ idBusiness+"'").getResultList();
}
}
Here is the stacktrace:
javax.persistence.PersistenceException: org.hibernate.HibernateException: illegally attempted to associate a proxy with two open Sessions
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1235)
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1168)
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1174)
org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:674)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:366)
com.sun.proxy.$Proxy90.persist(Unknown Source)
com.hp.unileon.takeme.dao.TaxiDAOImpl.persist(TaxiDAOImpl.java:36)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
com.sun.proxy.$Proxy100.persist(Unknown Source)
com.hp.unileon.takeme.service.SimpleTaxiManager.persistTaxi(SimpleTaxiManager.java:19)
com.hp.unileon.takeme.controller.TaxiController.addNewTaxi(TaxiController.java:112)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
If you need any configuration files to know what I am doing wrong tell me, I think it's huge amount of code for now (it has been simplified). Thanks.
UPDATE: my application context is:
<!-- Bean used by the daos to connect and make transactions with the database -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory"/>
<!-- Activate the annotation driven configurations making useful #Transaction annotations -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="com.hp.unileon.takeme.service" />
<context:component-scan base-package="com.hp.unileon.takeme.dao" />
<!-- Holding properties for database connectivity -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- Enabling annotation driven configuration like #Component-->
<context:annotation-config/>
<!-- Selects the database data source giving username password and nedded parameters
to connect on it. You can change those parameters easily on /classes/messages.properties -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- Element that loads tables on the database into object entities and so on -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource"
p:jpaVendorAdapter-ref="jpaAdapter">
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
<!-- This persistence unit can be found on /main/resources/META-INF/persistence.xml -->
<property name="persistenceUnitName" value="takemePU"></property>
</bean>
<!-- Enable hibernate to perform the database operations -->
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="${jpa.database}"
p:showSql="${jpa.showSql}"/>

The problem is related to PersistenceContextType.EXTENDED. When I get nested objects from database that use extended persistence context, they open a new session and then are returned by the entityManager. So, if I use them in the same request and try to add to the Taxi entity those nested objects, City and Business belongs to a non clossed session (because scope is EXTENDED) and Taxi belongs to the new session. Persist method does not allow the use of this kind of behabiour because proxy lazy evaluation objects belong to different sessions.
The solution I've finally found is using OpenEntityManagerInViewFilter, that joins all the transactions in the same session. To do it you only have to add this pieze of code in your web.xml.
<filter>
<filter-name>openEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
<init-param>
<param-name>entityManagerFactoryBeanName</param-name>
<param-value>entityManagerFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Related

How to inject Values into a Null Object Using #Autowired in Spring IOC?

I just started working on a Spring Rest Application, currently I am managing the authentication operations, what I want to do is to Simply check if the typed email address is already used, the problem is that when It doesn't exist I can't autowire the bean User I get a NullPointerException.
I found similar questions in SOF but my code seems to be correct, please Help.
Here is My Code :
Project Architecture
User.java:
#Component
#Entity
#JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="idUser", scope = User.class)
public class User implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idUser;
#Column(name = "login", unique = true)
private String login;
private String password;
private String nom;
private String prenom;
private String email;
private long telephone;
private String statut;
private int isDeleted;
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#ManyToOne(fetch = FetchType.LAZY)
private Role userRole;
public User(Long idUser, String login, String password, String nom, String prenom, String email,
long telephone, String statut, int isDeleted, Role userRole) {
super();
this.idUser = idUser;
this.login = login;
this.password = password;
this.nom = nom;
this.prenom = prenom;
this.email = email;
this.telephone = telephone;
this.statut = statut;
this.isDeleted = isDeleted;
this.userRole = userRole;
}
public User() {
super();
}
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getTelephone() {
return telephone;
}
public void setTelephone(long telephone) {
this.telephone = telephone;
}
public String getStatut() {
return statut;
}
public void setStatut(String statut) {
this.statut = statut;
}
public int getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(int isDeleted) {
this.isDeleted = isDeleted;
}
public Role getUserRole() {
return userRole;
}
public void setUserRole(Role userRole) {
this.userRole = userRole;
}}
UserRepository.java:
#Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByLoginLikeAndPasswordLikeAndIsDeletedEquals(String login, String password, int i);
User findByLoginLike(String login);
}
UserDTO.java
#Component
public class UserDTO {
private Long idUser;
private String login;
private String password;
private String role ;
public UserDTO(Long idUser, String login, String password, String role) {
super();
this.idUser = idUser;
this.login = login;
this.password = password;
this.role = role;
}
public UserDTO() {
super();
}
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
UserService.java :
#Service
public class UserService {
#Autowired
private UserDTO userDto;
#Autowired
private User user;
#Autowired
private UserRepository userRep;
#Autowired
private RoleRepository roleRep;
public boolean addUser(String login, String password, String role) {
boolean state = false;
try {
System.out.println(user.toString());
user = userRep.findByLoginLike(login);
if (user == null) {
user.setPassword(password);
user.setLogin(login);
user.setUserRole(roleRep.findByNomRoleLike(role));
userRep.save(user);
state = true;
} else {
System.out.println("user already exists");
state = false;
}
} catch (Exception e) {
e.printStackTrace();
state = false;
}
return state;
}
UserController.java
#RestController
public class UserControler {
#Autowired
private User user;
#Autowired
private UserRepository userRep;
#Autowired
private List<User> allUsers;
#Autowired
private UserService userService;
#Autowired
private UserDTO userDTO;
#RequestMapping( value = "/addUser", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public Boolean addUser(#RequestBody UserDTO u){
boolean state = false;
try {
state = userService.addUser(u.getLogin(), u.getPassword(), "Administrateur");
} catch (Exception e) {
e.printStackTrace();
}
return state;
}
StackTrace :
Hibernate: select users0_.user_role_id_role as user_ro10_1_0_,
users0_.id_user as id_user1_1_0_, users0_.id_user as id_user1_1_1_,
users0_.email as email2_1_1_, users0_.is_deleted as is_delet3_1_1_,
users0_.login as login4_1_1_, users0_.nom as nom5_1_1_,
users0_.password as password6_1_1_, users0_.prenom as prenom7_1_1_,
users0_.statut as statut8_1_1_, users0_.telephone as telephon9_1_1_,
users0_.user_role_id_role as user_ro10_1_1_ from user users0_ where
users0_.user_role_id_role=? 2018-12-20 14:25:58.061 TRACE 6192 ---
[nio-8080-exec-5] o.h.type.descriptor.sql.BasicBinder : binding
parameter 1 as [BIGINT] - [3] 2018-12-20 14:26:36.015 WARN 6192 ---
[nio-8080-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved
exception caused by handler execution:
org.springframework.web.HttpRequestMethodNotSupportedException:
Request method 'POST' not supported
java.lang.NullPointerException at
com.akkaprofil.service.UserService.addUser(UserService.java:63) at
com.akkaprofil.controller.UserControler.addUser(UserControler.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:849)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:760)
at
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
at
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) at
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109)
at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800)
at
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
at
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
When I call the AddUser Request method, this Exception is triggered, I can't find the reason why values are not set to the user Object when the email adress is not found, All the classes are annotated woth their Stereotypes, the user
Bean is autowired, I haven't declared a new Operator.
Would you clarify the cause behind this Exception.
Thank you

unable to query findOne - SpringMVC MongoDB

I am trying to login but unable to login because findOne query fails in DAOimplementation. I put series of system.out.println to see where does things go wrong.
and I get this
email: abcdef Password : 123123
email2: abcdef Password2: 123123
check 1
check 2
for some reason program wont reach to check 3, check 4 and inside if condition where user != null.
I tried mongoTemplate, mongoOperations, using addCriteria without criteria but no luck.
Code: UserDaoImplementation
import com.mthree.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.UUID;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;
#Repository
#Service(value = "userDao")
public class UserDaoImpl implements UserDao {
#Autowired
MongoTemplate mongoTemplate;
private static final String COLLECTION_NAME = "user";
public List<User> listUser() {
return mongoTemplate.findAll(User.class, COLLECTION_NAME);
}
public void add(User user) {
if(!mongoTemplate.collectionExists(User.class)){
mongoTemplate.createCollection(User.class);
}
user.setId(UUID.randomUUID().toString());
mongoTemplate.insert(user, COLLECTION_NAME);
}
public void update(User user) {
mongoTemplate.save(user);
}
public void delete(User user) {
mongoTemplate.remove(user, COLLECTION_NAME);
}
public User findUserById(String id) {
return mongoTemplate.findById(id, User.class);
}
#Override
public User login(String Email, String Password) {
System.out.println("email2: "+ Email + " Password2: "+ Password);
try {
System.out.println("check 1");
Query query = new Query();
System.out.println("check 2");
// User user = mongoTemplate
// .findOne(query.addCriteria(Criteria.where("Email").is(Email)), User.class, COLLECTION_NAME);
User user = mongoTemplate.findOne(query(where("Email").is(Email)), User.class,COLLECTION_NAME);
System.out.println("check 3");
if(user != null){
//return user;
System.out.println("check 4");
System.out.println("password3: "+ Password + " Password4: "+ user.getPassword());
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//{} t y
if(bCryptPasswordEncoder.matches(Password, user.getPassword())) {
return user;
}
}
return null;
}catch (Exception e){
return null;
}
}
#Override
public void register(User user) {
mongoTemplate.insert(user);
}
#Override
public void changeProfile(User user) {
mongoTemplate.save(user);
}
}
Controller
#RequestMapping(value="/login", method= RequestMethod.POST)
public String login(#ModelAttribute("user") User user, HttpSession session, ModelMap modelMap){
//simply checking the values my password is not yet encrypted
System.out.println("email: "+ user.getEmail() + " Password : "+ user.getPassword());
User user2 = userService.login(user.getEmail(), user.getPassword());
if(user2 == null){
modelMap.put("error", "Invalid User");
return "account/login";
}else{
session.setAttribute("username", user.getFirstname());
return "account/welcome";
}
//BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
// userService.register(user);
//return "redirect:../login";
}
User - model
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document
public class User {
#Id
private String id;
private long UserId;
private String Firstname;
private String Lastname;
private String Email;
private String Password;
private String Role;
private long CountryCode;
private long MobileNumber;
private String City;
private String Address;
public User(){
super();
}
public User(String id, long userId, String firstname, String lastname, String email, String password, String role, long countryCode, long mobileNumber, String city, String address) {
super();
this.id = id;
this.UserId = userId;
this.Firstname = firstname;
this.Lastname = lastname;
this.Email = email;
this.Password = password;
this.Role = role;
this.CountryCode = countryCode;
this.MobileNumber = mobileNumber;
this.City = city;
this.Address = address;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public long getUserId() {
return UserId;
}
public void setUserId(long userId) {
this.UserId = userId;
}
public String getFirstname() {
return Firstname;
}
public void setFirstname(String firstname) {
this.Firstname = firstname;
}
public String getLastname() {
return Lastname;
}
public void setLastname(String lastname) {
this.Lastname = lastname;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
this.Email = email;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
this.Password = password;
}
public String getRole() {
return Role;
}
public void setRole(String role) {
this.Role = role;
}
public long getCountryCode() {
return CountryCode;
}
public void setCountryCode(long countryCode) {
this.CountryCode = countryCode;
}
public long getMobileNumber() {
return MobileNumber;
}
public void setMobileNumber(long mobileNumber) {
this.MobileNumber = mobileNumber;
}
public String getCity() {
return City;
}
public void setCity(String city) {
this.City = city;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
this.Address = address;
}
}
Stack Trace
e: org.springframework.data.mapping.context.InvalidPersistentPropertyPath: No property email found on com.mthree.model.User!
org.springframework.data.mapping.context.InvalidPersistentPropertyPath: No property email found on com.mthree.model.User!
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentPropertyPath(AbstractMappingContext.java:257)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentPropertyPath(AbstractMappingContext.java:230)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentPropertyPath(AbstractMappingContext.java:205)
at org.springframework.data.mongodb.core.convert.QueryMapper$MetadataBackedField.getPath(QueryMapper.java:867)
at org.springframework.data.mongodb.core.convert.QueryMapper$MetadataBackedField.<init>(QueryMapper.java:758)
at org.springframework.data.mongodb.core.convert.QueryMapper$MetadataBackedField.<init>(QueryMapper.java:735)
at org.springframework.data.mongodb.core.convert.QueryMapper.createPropertyField(QueryMapper.java:231)
at org.springframework.data.mongodb.core.convert.QueryMapper.getMappedObject(QueryMapper.java:129)
at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1760)
at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1750)
at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:624)
at org.springframework.data.mongodb.core.MongoTemplate.findOne(MongoTemplate.java:589)
at org.springframework.data.mongodb.core.MongoTemplate.findOne(MongoTemplate.java:581)
at com.mthree.dao.UserDaoImpl.login(UserDaoImpl.java:67)
at com.mthree.service.UserServiceImpl.login(UserServiceImpl.java:38)
at com.mthree.controller.HomeController.login(HomeController.java:76)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2549)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2538)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Use proper Java (Beans) naming conventions:
CamelCase with first letter lowercase:
public User(String id, long userId, String firstname, String lastname, String email, String password, String role, long countryCode, long mobileNumber, String city, String address)
{
super();
this.id = id;
this.userId = userId;
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
this.password = password;
this.role = role;
this.countryCode = countryCode;
this.mobileNumber = mobileNumber;
this.city = city;
this.address = address;
}
Getter and Setter should be the field name with the first letter upper case and prefixed with get or set if present.
Properties referenced in queries/Strings are the same as the field name.
Note: There are some defiations from the actual Java Beans specification, e.g. the option to not have a default constructor.

Accessing Userdata within Custom PermissionEvaluator

I am having some problems with my custom permissionevaluator.
I get a nullpointer exception when trying to acces userdata in hasPermission()
My Permission Evaluator:
#Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
if (authentication == null) {
System.out.println("Auth is NULL");
return false;
}
User currentUser = (User) authentication.getPrincipal();
if (targetDomainObject instanceof Asset) {
Asset currentAsset = (Asset) targetDomainObject;
for (Role r : currentUser.getRoleList()) {
if ("admin".equals(r.getRole())) {
return true;
}
}
//Check if owner of asset
for (Asset a : currentUser.getAssets()) {
if (null!=a && a.equals(currentAsset)) {
return true;
}
}
The for (Role r : currentUser.getRoleList()) { works as expected but the line for (Asset a : currentUser.getAssets()) { creates a nullpointer eception
My CustomUserDetailsService:
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
com.redast.model.User domainUser = getUserDAO().findByLogin(login);
if(domainUser == null){
throw new UsernameNotFoundException("could not find user"+login);
}
return new UserDAOUserDetails(domainUser);
}
private final static class UserDAOUserDetails extends com.redast.model.User implements UserDetails {
private UserDAOUserDetails(com.redast.model.User user){
super(user);
}
....
}
The com.redast.model.User is a Entity Class whrere i am using Hibernate.
The Login:
public String login() {
try {
Authentication request = new UsernamePasswordAuthenticationToken(this.getUserName(), this.getPassword());
Authentication result = authenticationManager.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(result);
} catch (AuthenticationException e) {
return "/pages/unsecure/login";
}
return "/pages/unsecure/welcomePage?faces-redirect=true";
}
My guess is that the UserDAOUserDetails is not constructed correctly. I hope what I am trying to do makes sense and you can give me some insight in to fixing this issue thanks!
EDIT:
Thought my security-context.xml might be helpful:
<!-- Set customUserDetailsService class as the authentication Manager for Spring Security-->
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider user-service-ref="customUserDetailsService">
<sec:password-encoder hash="bcrypt"></sec:password-encoder>
</sec:authentication-provider>
</sec:authentication-manager>
<beans:bean id="customUserDetailsService"
class="com.redast.service.CustomUserDetailsService">
</beans:bean>
<beans:bean id="expressionHandler"
class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
<beans:property name="permissionEvaluator" ref="myPermissionEvaluator"/>
</beans:bean>
<beans:bean id="myPermissionEvaluator" name="myPermissionEvaluator" class="com.redast.security.CustomPermissionEvaluator">
</beans:bean>
Stack:
Information: 09:14:14.326 [http-listener-1(4)] DEBUG o.s.orm.jpa.JpaTransactionManager - Initiating transaction rollback
Information: 09:14:14.326 [http-listener-1(4)] DEBUG o.s.orm.jpa.JpaTransactionManager - Rolling back JPA transaction on EntityManager [org.hibernate.jpa.internal.EntityManagerImpl#3dbdb407]
Schwerwiegend: Error Rendering View[/pages/secure/asset.xhtml]
javax.el.ELException: /pages/secure/asset.xhtml #13,75 value="# {assets.currentAsset.assetTitle}": java.lang.NullPointerException
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:114)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
at javax.faces.component.UIOutput.getValue(UIOutput.java:174)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:205)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:355)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:164)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:919)
at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:83)
at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:66)
at org.primefaces.component.panel.PanelRenderer.encodeContent(PanelRenderer.java:206)
at org.primefaces.component.panel.PanelRenderer.encodeMarkup(PanelRenderer.java:123)
at org.primefaces.component.panel.PanelRenderer.encodeEnd(PanelRenderer.java:58)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:919)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:456)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:133)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:176)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.el.ELException: java.lang.NullPointerException
at javax.el.BeanELResolver.getValue(BeanELResolver.java:368)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at com.sun.el.parser.AstValue.getValue(AstValue.java:140)
at com.sun.el.parser.AstValue.getValue(AstValue.java:204)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:226)
at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
... 92 more
Caused by: java.lang.NullPointerException
at com.redast.security.CustomPermissionEvaluator.hasPermission(CustomPermissionEvaluator.java:56)
at org.springframework.security.access.expression.SecurityExpressionRoot.hasPermission(SecurityExpressionRoot.java:136)
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:483)
at org.springframework.expression.spel.support.ReflectiveMethodExecutor.execute(ReflectiveMethodExecutor.java:112)
at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:129)
at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:85)
at org.springframework.expression.spel.ast.SpelNodeImpl.getTypedValue(SpelNodeImpl.java:131)
at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:299)
at org.springframework.security.access.expression.ExpressionUtils.evaluateAsBoolean(ExpressionUtils.java:11)
at org.springframework.security.access.expression.method.ExpressionBasedPostInvocationAdvice.after(ExpressionBasedPostInvocationAdvice.java:51)
at org.springframework.security.access.prepost.PostInvocationAdviceProvider.decide(PostInvocationAdviceProvider.java:38)
at org.springframework.security.access.intercept.AfterInvocationProviderManager.decide(AfterInvocationProviderManager.java:73)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.afterInvocation(AbstractSecurityInterceptor.java:282)
at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:68)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at com.redast.service.AssetService$$EnhancerBySpringCGLIB$$32adb660.getById(<generated>)
at com.redast.managedController.AssetBean.getCurrentAsset(AssetBean.java:68)
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:483)
at javax.el.BeanELResolver.getValue(BeanELResolver.java:363)
... 99 more
I am using
Spring-security: 3.2.6.RELEASE
spring: 4.1.4.RELEASE
spring-data.jpa: 1.7.2.RELEASE
hibernate 4.3.8.FINAL
EDIT:
User Class:
#Entity
#Table(name = "users")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "login")
private String login;
#Column(name = "password")
private String password;
// #Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
#Column(name = "email")
private String email;
#Column(name = "firstName")
private String firstName;
#Column(name = "lastName")
private String lastName;
#Column(name = "enabled")
private Boolean enabled;
#JoinTable(name = "user_roles", joinColumns = {
#JoinColumn(name = "user_id", referencedColumnName = "id")}, inverseJoinColumns = {
#JoinColumn(name = "role_id", referencedColumnName = "id")})
#ManyToMany(fetch = FetchType.LAZY)
private List<Role> roleList;
#JoinTable(name = "user_assets", joinColumns = {
#JoinColumn(name = "users_id", referencedColumnName = "id")}, inverseJoinColumns = {
#JoinColumn(name = "assets_id", referencedColumnName = "id")})
#ManyToMany(fetch = FetchType.LAZY)
private List<Asset> assets;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userOuPK.user", fetch = FetchType.LAZY)
private List<UsersOu> usersOU;
public User(User user) {
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(user.password);
this.id = user.id;
this.email = user.email;
this.enabled = user.enabled;
this.firstName = user.firstName;
this.lastName = user.lastName;
this.login = user.login;
this.roleList = user.roleList;
this.password = user.password;
}
public User() {
}
public User(Integer id) {
this.id = id;
}
public User(Integer id, String login, String password) {
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(password);
this.id = id;
this.login = login;
this.password = password;
}
...getter and setter
}
UserDAO:
Public interface UserDAO extends JpaRepository<User, Integer>{
User findByLogin(String login);
}
Everything looks good to me your CustomPermissionEvaluator is configured properly and hasPermission is getting invoked as well, only quetion here who is raising the null pionter and from code it looks like null value returning from .getAssets() is throwing that.
Edited:
Missing
this.assets = user.assets;
this.usersOU = user.usersOU;
In the copy Constructor

Own SpringSecurity UserDetailsService dont load User - Could not obtain transaction-synchronized Session for current thread

I wrote my own SpringSecurity UserDetailsService. I used this tutorial for it.
The only differents between my configuration and that tutorial is, that I have a xml file for spring framework. But my application didn't work:
The problem is, that userDao.load(email); (watch UserDetailsService below) returns null and not an userObject. But if I switch the configuration of SpringSecurity to an inMemoryAuthentication and use userDao.load(email); in another context, the service returns the right user.
Stacktrace:
SCHWERWIEGEND: An internal error occurred while trying to authenticate the user.
org.springframework.security.authentication.InternalAuthenticationServiceException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:110)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:132)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:177)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:211)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014)
at de.nak.cars.dao.UserDAO.load(UserDAO.java:61)
at de.nak.cars.service.impl.UserDetailsServiceImpl.loadUserByUsername(UserDetailsServiceImpl.java:34)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:102)
... 39 more
UserDetailsService:
#Component
#Qualifier("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired
private UserDAO userDao;
#Transactional(readOnly=true)
#Override
public UserDetails loadUserByUsername(final String email)
throws UsernameNotFoundException {
de.name.cars.model.User user = userDao.load(email); //load returns null, saw in debug mode
List<GrantedAuthority> authorities = buildUserAuthority(user.getRoles());
return buildUserForAuthentication(user, authorities);
}
private UserDetails buildUserForAuthentication(de.name.cars.model.User user,
List<GrantedAuthority> authorities) {
return new User(user.getEmail(), user.getPassword(), true, true, true, true, authorities);
}
private List<GrantedAuthority> buildUserAuthority(Set<UserRole> roles) {
Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
for (UserRole role : roles){
setAuths.add(new SimpleGrantedAuthority(role.getRoleName()));
}
List<GrantedAuthority> result = new ArrayList<GrantedAuthority>(setAuths);
return result;
}
}
spring-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="de.nak.cars" />
<!-- The data source -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.h2.Driver"/>
<property name="url"
value="jdbc:h2:Y:/db/nak"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<!-- The session factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="de.nak.cars.model"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.hbm2ddl.import_files">initial-sql.sql</prop>
</props>
</property>
</bean>
<!-- The transaction manager -->
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- The advice -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- The pointcut definition -->
<aop:config>
<aop:pointcut id="serviceMethods" expression="execution(* de.nak.cars.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods"/>
</aop:config>
</beans>
User.java
#Entity
public class User implements Serializable {
/** Generated version id. */
private static final long serialVersionUID = -5464675373969471720L;
/** The identifier. */
private Long id;
/** The user's firstname. */
private String firstName;
/** The user's lastname. */
private String lastName;
/** The user's student identification number. */
private String email;
/** The user's roles. */
private Set<UserRole> roles;
/** The user's password. */
private String password;
/** Set of user-exam combinations. */
private Set<ExamKey> examKeys = new HashSet<ExamKey>(0);
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "FIRST_NAME", length = 100, nullable = false)
public String getFirstname() {
return firstName;
}
public void setFirstname(String firstName) {
this.firstName = firstName;
}
#Column(name = "LAST_NAME", length = 100, nullable = false)
public String getlastName() {
return lastName;
}
public void setlastName(String lastName) {
this.lastName = lastName;
}
#ManyToMany(fetch = FetchType.LAZY, cascade= CascadeType.ALL)
#JoinTable(name="USER_USERROLE", joinColumns = {
#JoinColumn(name="USER_ID", nullable = false, updatable = false)},
inverseJoinColumns = { #JoinColumn(name="ROLE_ID", nullable = false, updatable = false)})
public Set<UserRole> getRoles() {
return roles;
}
public void setRoles(Set<UserRole> roles) {
this.roles = roles;
}
#Column(name = "EMAIL", nullable = false, unique = true)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name="PASSWORD", nullable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "examKeyId.user")
public Set<ExamKey> getExamKeys() {
return examKeys;
}
public void setExamKeys(Set<ExamKey> examKeys) {
this.examKeys = examKeys;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result
+ ((lastName == null) ? 0 : lastName.hashCode());
result = prime * result + ((lastName == null) ? 0 : email.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
if (!email.equals(other.email))
return false;
return true;
}
#Override
public String toString() {
return "User [id=" + id + ", firstName=" + firstName + ", lastName="
+ lastName + ", email=" + email + ", password=" + password + ", examKeys=" + examKeys
+ "]";
}
}
you need to enable transaction management support. In the guide you followed it was done with #EnableTransactionManagement annotation over AppConfig class. In your case you use xml configuration, so you should add <tx:annotation-driven transaction-manager="txManager" /> inside your spring-config.xml

Spring JPA Repository Autowire Issue

I followed a youtube video tutorial for setting up a Spring JPA project but im still having issues with my Spring JPA project and was hoping someone could help.
http://www.youtube.com/watch?v=kM7Gr3XTzIg
The main problem seems to be Autowiring my JPARepository. I have tested that my entityManager / persistence unit works via the following test code (it pulls back the expected record).
public class CheckEntityManagerWorksTest {
private static Logger logger = Logger.getLogger(CheckEntityManagerWorksTest.class.getName());
private static EntityManagerFactory emFactory;
private static EntityManager em;
#BeforeClass
public static void setUp() throws Exception {
try {
logger.info("Building JPA EntityManager for unit tests");
emFactory = Persistence.createEntityManagerFactory("pu");
em = emFactory.createEntityManager();
} catch (Exception ex) {
ex.printStackTrace();
fail("Exception during JPA EntityManager instanciation.");
}
}
#AfterClass
public static void tearDown() throws Exception {
logger.info("Shuting down Hibernate JPA layer.");
if (em != null) {
em.close();
}
if (emFactory != null) {
emFactory.close();
}
}
#Test
public void testPersistence() {
try {
em.getTransaction().begin();
Integer id = 51;
Accounts account = em.find(Accounts.class, id);
assertNotNull(account);
System.out.println("Account username: " + account.getUsername());
em.getTransaction().commit();
} catch (Exception ex) {
em.getTransaction().rollback();
ex.printStackTrace();
fail("Exception during testPersistence");
}
}
}
As i said that test works for connecting to the database, etc. but the test below fails with a autowire exception (stack trace at very bottom of page):
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("**/applicationContext.xml")
public class AccountsRepositoryTest {
#Autowired
AccountsRepository repo;
#Test
public void testAccountsRepository() {
assertNotNull(repo.findOne(51));
}
}
Below is my setup.
Persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="pu">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.url" value="jdbc:derby://localhost:1527/craigtest"/>
<property name="hibernate.connection.password" value="craigtest"/>
<property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="hibernate.connection.username" value="craigtest"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<bean id="myEmf" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="pu"/>
</bean>
<bean id="myTxManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf"/>
</bean>
<jpa:repositories base-package="com.mycompany.jpaspring.repositories" />
</beans>
My Repository:
package com.mycompany.jpaspring.repositories;
import com.mycompany.jpaspring.entity.Accounts;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AccountsRepository extends JpaRepository<Accounts, Integer>{
}
My Entity:
package com.mycompany.jpaspring.entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "ACCOUNTS")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Accounts.findAll", query = "SELECT a FROM Accounts a"),
#NamedQuery(name = "Accounts.findById", query = "SELECT a FROM Accounts a WHERE a.id = :id"),
#NamedQuery(name = "Accounts.findByUsername", query = "SELECT a FROM Accounts a WHERE a.username = :username"),
#NamedQuery(name = "Accounts.findByFirstname", query = "SELECT a FROM Accounts a WHERE a.firstname = :firstname"),
#NamedQuery(name = "Accounts.findByLastname", query = "SELECT a FROM Accounts a WHERE a.lastname = :lastname")})
public class Accounts implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "ID")
private Integer id;
#Basic(optional = false)
#Column(name = "USERNAME")
private String username;
#Column(name = "FIRSTNAME")
private String firstname;
#Column(name = "LASTNAME")
private String lastname;
public Accounts() {
}
public Accounts(Integer id) {
this.id = id;
}
public Accounts(Integer id, String username) {
this.id = id;
this.username = username;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Accounts)) {
return false;
}
Accounts other = (Accounts) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.mycompany.jpaspring.entity.Accounts[ id=" + id + " ]";
}
}
Stack trace:
-------------------------------------------------------------------------------
Test set: com.mycompany.jpaspring.AccountsRepositoryTest
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.797 sec <<< FAILURE!
testAccountsRepository(com.mycompany.jpaspring.AccountsRepositoryTest) Time elapsed: 0.507 sec <<< ERROR!
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.mycompany.jpaspring.AccountsRepositoryTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.mycompany.jpaspring.repositories.AccountsRepository com.mycompany.jpaspring.AccountsRepositoryTest.repo; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.mycompany.jpaspring.repositories.AccountsRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
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:601)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.mycompany.jpaspring.repositories.AccountsRepository com.mycompany.jpaspring.AccountsRepositoryTest.repo; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.mycompany.jpaspring.repositories.AccountsRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:513)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:92)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
... 32 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.mycompany.jpaspring.repositories.AccountsRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:947)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:816)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:730)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:485)
... 34 more
Everything seems to be fine to me, except for this line:
#ContextConfiguration("**/applicationContext.xml")
Do you really need to import multiple xml files?
In which folder is the applicationContext.xml exactly?
Could you try replacing the above with a full path reference? Something like this:
#ContextConfiguration("classpath:/com/.../application-context.xml")

Resources