Getter returning null SessionFactory - java

I am trying to develop Springs-Hibernate login application with springs security. When i am trying to retrieve users from DB with Hibernate. I have proper working Springs-Hibernate Configuration. Everytime getter returning sessionFactory null (I am printing address in getSessionFactory method). I have one method getLoginDetails() which is working perfectly if i am not invoking method at login time (Checked with just simple anchor tag), but when i am logging in its not working. Here is my code:
Springs-security.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:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<!-- This is where we configure Spring-Security -->
<security:http auto-config="true" use-expressions="true" access-denied-page="/auth/denied" >
<security:intercept-url pattern="/auth/login" access="permitAll"/>
<security:intercept-url pattern="/main/admin" access="hasRole('ROLE_ADMIN')"/>
<security:intercept-url pattern="/main/common" access="hasRole('ROLE_USER')"/>
<security:form-login
login-page="/auth/login"
authentication-failure-url="/auth/hi"
authentication-success-handler-ref="myAuthenticationSuccessHandler"/>
<security:logout
invalidate-session="true"
logout-success-url="/loggedout" />
</security:http>
<!-- A custom service where Spring will retrieve users and their corresponding access levels -->
<bean id="customUserDetailsService" class="com.springs.service.CustomUserDetailsService"/>
<!--A service where spring will redirect to proper view after successfull login-->
<bean id="myAuthenticationSuccessHandler" class="com.springs.controller.MySimpleUrlAuthenticationSuccessHandler" />
<!-- Declare an authentication-manager to use a custom userDetailsService -->
<security:authentication-manager>
<security:authentication-provider user-service-ref="customUserDetailsService">
</security:authentication-provider>
</security:authentication-manager>
</beans>
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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:jdbc.properties</value>
</property>
</bean>
<bean id="DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${jdbc.driverClassName}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="acquireIncrement" value="${c3p0.acquireIncrement}" />
<property name="minPoolSize" value="${c3p0.minPoolSize}" />
<property name="maxPoolSize" value="${c3p0.maxPoolSize}" />
<property name="maxIdleTime" value="${c3p0.maxIdleTime}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="DataSource"/>
<property name="packagesToScan" value="com.hibernate.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>
Dispatcher-servlet.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- Scan only for #Controllers -->
<context:component-scan base-package="com.springs">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<mvc:annotation-driven />
<tx:annotation-driven/>
<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
</beans>
CustomerUserDetailsService.java
package com.springs.service;
import com.hibernate.model.DbUser;
import com.springs.dao.UserDAO;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
#Transactional(readOnly = true)
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private UserDAO userDAO ;
#Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
UserDetails user = null;
try {
DbUser dbUser;
userDAO=new UserDAO();
dbUser = userDAO.getLoginDetails(username);
user = new User(
dbUser.getUsername(),
dbUser.getPassword().toLowerCase(),
true,
true,
true,
true,
getAuthorities(dbUser.getAccess()));
} catch (Exception e) {
System.out.println("\n\n\n\n\n");
e.printStackTrace();
throw new UsernameNotFoundException("Error in retrieving user");
}
return user;
}
public Collection<SimpleGrantedAuthority> getAuthorities(Integer access) {
List<SimpleGrantedAuthority> authList = new ArrayList<SimpleGrantedAuthority>(2);
if (access.compareTo(1) == 0) {
authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
} else {
authList.add(new SimpleGrantedAuthority("ROLE_USER"));
}
return authList;
}
}
UserDAO.java
#Repository
public class UserDAO {
#Autowired
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
System.out.println("session factory: "+sessionFactory);
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public int getdata(String username) {
String hql = "select count(*) from Userdetails";
Userdetails u = (Userdetails) getSessionFactory().openSession().get(Userdetails.class, username);
System.out.println(u.getName());
Long l = (Long) getSessionFactory().openSession().createQuery(hql).uniqueResult();
return l.intValue();
}
public DbUser getLoginDetails(String username) {
DbUser user = new DbUser();
Userdetails u = (Userdetails) getSessionFactory().openSession().get(Userdetails.class, username);
user.setUsername(u.getName());
user.setPassword(u.getPassword());
user.getAccess();
Set userroles = u.getUserroles();
Iterator it = userroles.iterator();
while (it.hasNext()) {
Userrole ux=(Userrole) it.next();
user.setAccess(ux.getRollid());
}
System.out.println("accss is: "+user.getAccess());
System.out.println("username is: "+user.getUsername());
System.out.println("pw is "+user.getPassword());
return user;
}
}
message in server log :
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/SpringSecurity] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.springs.dao.UserDAO.getdata(UserDAO.java:42)
at com.springs.controller.testController.getUser(testController.java:31)
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.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
I am not able to figure out sessionFactory is null if i am using it at Login activity otherwise its not null. First I was missing tx annotation in xml which i added later for #Transactional annotation. How can i solve this?

Sorry, I do not see the problem. But I'd like to attache similar files from myy sample project regarding to security. I hope it helps you:
applicationContext-security.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
">
<!-- HTTP security configurations -->
<http auto-config="true" use-expressions="true">
<form-login login-processing-url="/resources/j_spring_security_check" login-page="/login" authentication-failure-url="/login?login_error=t" />
<logout logout-url="/resources/j_spring_security_logout" />
<!-- Configure these elements to secure URIs in your application -->
<intercept-url pattern="/login-user/**" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/choices/**" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/member/**" access="isAuthenticated()" />
<intercept-url pattern="/resources/**" access="permitAll" />
<intercept-url pattern="/login/**" access="permitAll" />
<intercept-url pattern="/**" access="isAuthenticated()" />
</http>
<!-- Configure Authentication mechanism -->
<authentication-manager alias="authenticationManager">
<!-- SHA-256 values can be produced using 'echo -n your_desired_password | sha256sum' (using normal *nix environments) -->
<authentication-provider>
<password-encoder hash="sha-256" />
<user-service>
<user name="admin" password="8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918" authorities="ROLE_ADMIN" />
<user name="user" password="04f8996da763b7a969b1028ee3007569eaf3a635486ddab211d512c85b9df8fb" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
">
<context:property-placeholder location="classpath*:META-INF/spring/*.properties"/>
<context:spring-configured/>
<context:component-scan base-package="org.sample.login">
<context:exclude-filter expression=".*_Roo_.*" type="regex"/>
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource">
<property name="driverClassName" value="${database.driverClassName}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
<property name="testOnBorrow" value="true"/>
<property name="testOnReturn" value="true"/>
<property name="testWhileIdle" value="true"/>
<property name="timeBetweenEvictionRunsMillis" value="1800000"/>
<property name="numTestsPerEvictionRun" value="3"/>
<property name="minEvictableIdleTimeMillis" value="1800000"/>
<property name="validationQuery" value="SELECT version();"/>
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager"/>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="persistenceUnitName" value="persistenceUnit"/>
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
MyUser.java:
package org.sample.login.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Version;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
#Table(name = "my_user")
#Entity
public class MyUser {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Version
#Column(name = "version")
private Integer version;
/**
*/
#NotNull
#Size(min = 6)
private String name;
/**
*/
#NotNull
#Size(min = 6)
private String password;
#Override
public String toString() {
return "MyUser [name=" + name + ", password=" + password + "]";
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getVersion() {
return this.version;
}
public void setVersion(Integer version) {
this.version = version;
}
}

Related

Data entered in product java class is giving exception

Hi I am getting the following Exception in the springMVC application code.. I read some previous question but didn't find any help.
I have two entities in the application i.e.
user
products
Data entered in product java class is giving exception:-
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.MappingException: Unknown entity: com.onlineshopping.model.Product
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:659)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:563)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
Product.java class is :
package com.onlineshopping.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Product")
public class Product implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="productid")
private Integer proid;
#Column(name="productname")
private String proname;
#Column(name="price")
private Integer price;
#Column(name="details")
private String details;
public Integer getProid() {
return proid;
}
public void setProid(Integer proid) {
this.proid = proid;
}
public String getProname() {
return proname;
}
public void setProname(String proname) {
this.proname = proname;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
}
Configuration File:
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:property-placeholder location="classpath:resources/database.properties" />
<context:component-scan base-package="com.onlineshopping" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.onlineshopping.model.Customer</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Can someone tell me why this exception occur.the other user entity is working correctly.
thanks
so after comment #dhs found answer
session factory needs to setPackagesToScan so do try this adding into annotatedClasses
com.onlineshopping.model.Product
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:property-placeholder location="classpath:resources/database.properties" />
<context:component-scan base-package="com.onlineshopping" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.onlineshopping.model.Customer</value>
<value>com.onlineshopping.model.Product</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>

How can i take email and password from database? I can't validate users in Spring security

Stacktrace
Why i have java.lang.NullPointerException in UserDetailsServiceImplementation when i try call method loadUserByUsername in line AdminUser user = (AdminUser) jpaUserDao.findUserByEmail(username);
`2016-02-13 15:08:52 ERROR UsernamePasswordAuthenticationFilter:226 - An internal error occurred while trying to authenticate the user.
Caused by: java.lang.NullPointerException
at com.softserveinc.ita.redplatform.business.service.UserDetailsServiceImplementation.loadUserByUsername(UserDetailsServiceImplementation.java:39)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114)
... 41 more`
spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/adm/**" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/red/**" access="hasAnyRole('ROLE_ADMIN', 'ROLE_REDADMIN')" />
<intercept-url pattern="/**" access="permitAll" />
<!-- access denied page -->
<access-denied-handler error-page="/index" />
<form-login login-page="/login" default-target-url="/index"
login-processing-url="/j_spring_security_check"
authentication-failure-url="/login?error"
username-parameter="email"
password-parameter="password" />
<logout logout-success-url="/login?logout" />
</http>
<beans:bean id="UserDetailsServiceImplementation"
class="com.softserveinc.ita.redplatform.business.service.UserDetailsServiceImplementation">
</beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="UserDetailsServiceImplementation">
</authentication-provider>
</authentication-manager>
</beans:beans>
persistance.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
<context:component-scan base- package="com.softserveinc.ita.redplatform.persistence.dao.impl" />
<bean id="entityManagerFactoryBean"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="JPAUnit" />
<property name="packagesToScan">
<list>
<value>com.softserveinc.ita.redplatform.common.entity</value>
</list>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
</bean>
<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>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryBean" />
</bean>
<tx:annotation-driven />
</beans>
JPAAdminUserDao find user by email
#Repository
#Transactional
public class JPAAdminUserDao extends JPAGenericDao<AdminUser, Long>
implements AdminUserDao {
#PersistenceContext
private EntityManager entityManagerFactoryBean;
public final AdminUser findUserByEmail(final String email) {
List<AdminUser> users = new ArrayList<AdminUser>();
users = (List<AdminUser>) entityManagerFactoryBean
.createQuery("from " + AdminUser.class.getName()
+ " as user where user.email=:email")
.setParameter("email", email).getResultList();
if (users.size() > 0) {
return users.get(0);
} else {
return null;
}
}
public static void main(String[] args) {
JPAAdminUserDao dao = new JPAAdminUserDao();
dao.findUserByEmail("rom23");
}
}
UserDetailsServiceImplementation
public class UserDetailsServiceImplementation implements UserDetailsService {
private AdminUserDao jpaUserDao;
#Override
public final UserDetails loadUserByUsername(final String username)
throws UsernameNotFoundException {
HashSet<String> set = new HashSet<String>();
AdminUser user = (AdminUser) jpaUserDao.findUserByEmail(username);
if (user instanceof AdminUser) {
set.add(new String("ROLE_USER"));
set.add(new String("ROLE_ADMIN"));
set.add(new String("ROLE_REDADMIN"));
} else {
set.add(new String("ROLE_USER"));
}
List<GrantedAuthority> authorities = buildUserAuthority(set);
return buildUserForAuthentication(user, authorities);
}
private User buildUserForAuthentication(final AdminUser user,
final List<GrantedAuthority> authorities) {
return new User(user.getEmail(), user.getPassword(), true,
true, true, true, authorities);
}
private List<GrantedAuthority> buildUserAuthority(final
Set<String> userRoles) {
Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
// Build user's authorities
for (String userRole : userRoles) {
setAuths.add(new SimpleGrantedAuthority(userRole));
}
List<GrantedAuthority> result = new
ArrayList<GrantedAuthority>(setAuths);
return result;
}
public final AdminUserDao getJpaUserDao() {
return jpaUserDao;
}
public final void setAdminUserDao(final AdminUserDao newJpaUserDao) {
this.jpaUserDao = newJpaUserDao;
}
}
the issue is with this line of code:
AdminUser user = (AdminUser) jpaUserDao.findUserByEmail(username);
Simply jpaUserDao is not injected.
you have to set jpaUserDao in bean declaration, like:
<beans:bean id="UserDetailsServiceImplementation"
class="com.softserveinc.ita.redplatform.business.service.UserDetailsServiceImplementation">
<property name="adminUserDao" ref="jpaUserDao" />
</beans:bean>
and make sure that jpaUserDao is also declared

Spring Memcached annotations not Caching

I'm trying to get Memcache working in Spring.
I've setup a local Memcached server using Docker and Kitematic:
I can access the Memcached server using telnet: telnet 192.168.99.100 32780 and then run stats or stats items (which only prints out END if the cache is empty);
My pom.xml:
<dependency>
<groupId>com.google.code.simple-spring-memcached</groupId>
<artifactId>simple-spring-memcached</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>com.google.code.simple-spring-memcached</groupId>
<artifactId>spring-cache</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>com.google.code.simple-spring-memcached</groupId>
<artifactId>xmemcached-provider</artifactId>
<version>3.6.0</version>
</dependency>
In my applicationContext.xml I have the following:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:property-placeholder location="classpath*:META-INF/spring/*.properties"/>
...
<import resource="cacheContext.xml" />
...
In cacheContext.xml my config is as follow:
<?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:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<aop:aspectj-autoproxy/>
<cache:annotation-driven/>
<context:component-scan base-package="com.google.code.ssm"/>
<context:component-scan base-package="com.mycee.application"/>
<bean id="cacheBase" class="com.google.code.ssm.aop.CacheBase"/>
<bean id="readThroughSingleCache" class="com.google.code.ssm.aop.ReadThroughSingleCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="readThroughMultiCache" class="com.google.code.ssm.aop.ReadThroughMultiCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="readThroughAssignCache" class="com.google.code.ssm.aop.ReadThroughAssignCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="updateSingleCache" class="com.google.code.ssm.aop.UpdateSingleCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="updateMultiCache" class="com.google.code.ssm.aop.UpdateMultiCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="updateAssignCache" class="com.google.code.ssm.aop.UpdateAssignCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="invalidateSingleCache" class="com.google.code.ssm.aop.InvalidateSingleCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="invalidateMultiCache" class="com.google.code.ssm.aop.InvalidateMultiCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="invalidateAssignCache" class="com.google.code.ssm.aop.InvalidateAssignCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="incrementCounterInCache" class="com.google.code.ssm.aop.counter.IncrementCounterInCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="decrementCounterInCache" class="com.google.code.ssm.aop.counter.DecrementCounterInCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="readCounterFromCache" class="com.google.code.ssm.aop.counter.ReadCounterFromCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="updateCounterInCache" class="com.google.code.ssm.aop.counter.UpdateCounterInCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean name="cacheManager" class="com.google.code.ssm.spring.SSMCacheManager">
<property name="caches">
<set>
<bean class="com.google.code.ssm.spring.SSMCache">
<constructor-arg name="cache" index="0" ref="defaultCache"/>
<constructor-arg name="expiration" index="1" value="300"/>
<constructor-arg name="allowClear" index="2" value="false"/>
</bean>
</set>
</property>
</bean>
<bean name="defaultCache" class="com.google.code.ssm.CacheFactory" depends-on="cacheBase">
<property name="cacheName" value="defaultCache"/>
<property name="cacheClientFactory">
<bean class="com.google.code.ssm.providers.xmemcached.MemcacheClientFactoryImpl"/>
</property>
<property name="addressProvider">
<bean class="com.google.code.ssm.config.DefaultAddressProvider">
<property name="address" value="localhost:11211"/>
</bean>
</property>
<property name="configuration">
<bean class="com.google.code.ssm.providers.CacheConfiguration">
<property name="consistentHashing" value="true"/>
</bean>
</property>
</bean>
</beans>
I've created three different methods, each using different caching mechanisms:
#Component("cacheEndpoint")
public class CacheClass {
#Autowired
SSMCacheManager cache;
public String getDateTime1(String anything) {
SSMCache c = cache.getCache("defaultCache");
String s = c.get(anything, String.class);
if (s != null) {
return s;
}
Date d = new Date();
String response = d.toString() + " - " + d.getTime();
c.put(anything, response);
return response;
}
#Cacheable("defaultCache")
public String getDateTime2(String anything) {
Date d = new Date();
String response = d.toString() + " - " + d.getTime();
return response;
}
#ReadThroughSingleCache(namespace = "defaultCache", expiration = 15000)
public String getDateTime3(String anything) {
Date d = new Date();
String response = d.toString() + " - " + d.getTime();
return response;
}
}
To access it I do:
#Autowired
CacheClass c;
...
// caches perfectly
c.getDateTime1("test");
// doesn't do any caching
c.getDateTime2("test");
// doesn't do any caching
c.getDateTime3("test");
After placing runtime exceptions in getDateTime2 and getDateTime3, it was established that the interceptors aren't being invoked.
Any idea what could be the cause of #Cachable and #ReadThroughSingleCache not doing their interception magic?
Update based on Matjaž Pečan's response:
CacheClass Interface:
public interface CacheClass {
public String getDateTime1(String anything);
public String getDateTime2(String anything);
public String getDateTime3(String anything);
}
CacheClass Implementation:
#Component("cacheEndpoint")
public class CacheClassImpl implements CacheClass {
#Autowired
SSMCacheManager cache;
public String getDateTime1(String anything) {
SSMCache c = cache.getCache("defaultCache");
String s = c.get(anything, String.class);
if (s != null) {
return s;
}
Date d = new Date();
String response = d.toString() + " - " + d.getTime();
c.put(anything, response);
return response;
}
#Cacheable("defaultCache")
public String getDateTime2(String anything) {
Date d = new Date();
String response = d.toString() + " - " + d.getTime();
return response;
}
#ReadThroughSingleCache(namespace = "defaultCache", expiration = 15000)
public String getDateTime3(String anything) {
Date d = new Date();
String response = d.toString() + " - " + d.getTime();
return response;
}
}
SOAP Endpoint where I'm testing the cache:
#Endpoint
public class PingEndpoint {
#Autowired
CacheClass c;
#ResponsePayload
#PayloadRoot(localPart = "PingRequest", namespace = "http://www.mycee.com/Application")
public PingResponse doPing(#RequestPayload PingRequest request) {
// caches perfectly
System.out.println(c.getDateTime1("test"));
// doesn't do any caching
System.out.println(c.getDateTime2("test"));
// doesn't do any caching
System.out.println(c.getDateTime3("test"));
}
}
cacheContext.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:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<aop:aspectj-autoproxy proxy-target-class="true"/>
<cache:annotation-driven/>
...
There is an error in SSM 3.6.0, please downgrade to 3.5.0 to solve the issue or try to add
depends-on="cacheBase"
to defaultCache bean definition.
Update 1
Self invocations don't work. A call won't be intercepted and result won't be cached if a invocation is through this object. Make sure that method defined in a bean is invoked from another Spring bean.
Update 2
For SSM method has to be annotated as below:
#ReadThroughSingleCache(namespace = "defaultCache", expiration = 15000)
public String getDateTime3(#ParameterValueKeyProvider String anything) {
...
}
Still interceptors for some reasons aren't triggered.
Spring proxying mechanisms differ depending on which implementation is used.
The default is AspectJ which requires interfaces (proxy-by-interface) and those interfaces will then be implemented by the actual proxy wrapped around your bean. Since your bean is only a class and does not have an interface, it is not proxied with AspectJ.
There are two possible solutions:
Implement an interface for CacheClass and use that interface in wiring to other beans
Use CGLib proxying (you will need to add a runtime dependency on CGLib) and add proxy-target-class in your aspectj-proxy element:
<aop:aspectj-autoproxy proxy-target-class="true"/>

Rollback not working in jdbc spring programatic transaction

Im unable to get a rollback working in my spring (3.0.5) jdbc application, running on Oracle 11.2
When I throw NoClassesException in the Controller below the row inserted by updatedB() remains in the dB.
I think this is because autoCommit is on (by default) in my dataSource so the commit has already happened and the rollback obviously doesn't work,
but I thought the Spring DataSourceTransactionManager handled all this and enforced the rollback?
Interestingly, when i turn autoCommit off in my dataSource ie comment in the :
"defaultAutoCommit" value="false"
and call the commit explicity myself ie comment in:
this.jdbcTemplate.getDataSource().getConnection().commit();
nothing happens ie the row is not commited at all,so it looks like i've done something stupid.
If someone could please point out this mistake I would be very gratefull
My code is :
public static void main(String[] args) {
String [] configList ={"database.xml","spring.xml"};
ApplicationContext ctx = new ClassPathXmlApplicationContext(configList);
cont = (Controller)ctx.getBean("controller");
cont.transactionTest();
}
// Controller , called from Main()
public class Controller {
private JdbcTemplate jdbcTemplate;
public void transactionTest()
{
int retCode=0;
try {
retCode = updatedB("param1","param2");
//this.jdbcTemplate.getDataSource().getConnection().commit();
throw new NoClassesException();
}catch (NoClassesException e){
System.out.println(e.getMessage() + "2 patents ");
}
}
public int updatedB(String param1,String param2 )
{
int stat = 0;
stat = this.jdbcTemplate.update("INSERT INTO myTable"
+ "(param1,param2)"
+ " VALUES(?,?)" ,
new Object[] { param1,param2});
return stat;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
public class NoClassesException extends RuntimeException {
public NoClassesException() {
super("Rolled back ");
}
}
and my spring.xml file is:
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<bean id="controller" class="Controller">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="transaction*" propagation="REQUIRED" rollback-for="NoClassesException" />
<tx:method name="update*" propagation="SUPPORTS" />
<tx:method name="*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="myMethods" expression="execution(* *..Controller.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="myMethods" />
</aop:config>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
and my database.xml file is:
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<bean id="dataConfigPropertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="searchSystemEnvironment" value="true" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="initialSize" value="2" />
<property name="maxActive" value="2" />
<property name="url" value="my connection details" />
<property name="username" value="xxx" />
<property name="password" value="xxx" />
<!-- <property name="defaultAutoCommit" value="false" /> -->
</bean>
</beans>
Your code should be updated such as
public void transactionTest()
{
int retCode=0;
retCode = updatedB("param1","param2");
//this.jdbcTemplate.getDataSource().getConnection().commit();
throw new NoClassesException();
}
public int updatedB(String param1,String param2 )
{
int stat = 0;
stat = this.jdbcTemplate.update("INSERT INTO myTable"
+ "(param1,param2)"
+ " VALUES(?,?)" ,
new Object[] { param1,param2});
return stat;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}

Problems with Autowired and Spring Injection [duplicate]

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 8 years ago.
SOLVED
Lately I've been having problems with an Spring MVC application which I'm trying to develop.
The main problem is that I don't know exactly why the #Autowired annotation is not working properly and that's probably because I have something wrong. I'm going to post here my code so you can help me with my issue! Thanks a lot guys:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>HelloWorld Application</display-name>
<description>
This is a simple web application with a source code organization
based on the recommendations of the Application Developer's Guide.
</description>
<servlet>
<servlet-name>webDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>webDispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:annotation-config />
<context:spring-configured />
<context:component-scan base-package="com.agrichem.server" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="WEB-INF/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="securityDao"
class="com.agrichem.server.model.repositories.impl.SecurityDaoImpl">
</bean>
</beans>
webDispatcher-servlet.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:annotation-config />
<context:spring-configured />
<context:component-scan base-package="com.agrichem.server" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- <import resource="spring-security-web.xml"/> -->
</beans>
SecurityDao.java
public interface SecurityDao {
public boolean validateUser(User user);
public User authenticateUser(User user);
public User getUser (User user);
}
SecurityDaoImpl.java
#Repository("securityDao")
public class SecurityDaoImpl extends HibernateDao implements SecurityDao {
public SecurityDaoImpl() {
super();
}
#Override
public boolean validateUser(User user) {
Query query = openSession()
.createQuery(
"from User u where u.login = :login and u.password = :password");
query.setParameter("login", user.getLogin());
query.setParameter("password", user.getPassword());
return (query.list().size() > 0) ? true : false;
}
#Override
public User authenticateUser(User user) {
Query query = openSession()
.createQuery(
"from User u where u.login = :login and u.password = :password");
query.setParameter("login", user.getLogin());
query.setParameter("password", user.getPassword());
return (User) query.uniqueResult();
}
#Override
public User getUser(User user) {
Query query = openSession().createQuery(
"from User u where u.login = :login");
query.setParameter("login", user.getLogin());
return (User) query.uniqueResult();
}
}
WebSecurityConfig.java
#Configuration
#EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(new CustomUserDetailsService());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers("/home/logout.do").permitAll()
.anyRequest().authenticated().and().formLogin()
.loginPage("/home/login.do").permitAll()
.failureUrl("/home/accessdenied.do").permitAll();
}
}
CustomUserDetailsService.java
#Configurable
#Transactional
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
#Qualifier("securityDao")
private SecurityDao securityDAO;
#Override
public UserDetails loadUserByUsername(String arg0)
throws UsernameNotFoundException {
com.agrichem.server.model.security.User user = securityDAO
.getUser(new com.agrichem.server.model.security.User(arg0, ""));
User userDetails = new User(user.getLogin(), user.getPassword(),
getGrantedAuthorities(user.getRoles()));
return userDetails;
}
public static List<GrantedAuthority> getGrantedAuthorities(Set<Role> roles) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (Role role : roles) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
return authorities;
}
public SecurityDao getSecurityDAO() {
return securityDAO;
}
public void setSecurityDAO(SecurityDao securityDAO) {
this.securityDAO = securityDAO;
}
}
In this point when I try to login to the application and I'm gonna check the Dao to access to the database I'm getting the 'securityDao' property null. Exactly in CustomUserDetailsService in the following line : com.agrichem.server.model.security.User user = securityDAO.getUser(new com.agrichem.server.model.security.User(arg0, "")); and obvisously I'm getting a NullPointerException.
org.springframework.security.authentication.InternalAuthenticationServiceException
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:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at com.agrichem.server.services.security.CustomUserDetailsService.loadUserByUsername(CustomUserDetailsService.java:35)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:102)
... 36 more
Solution:
Found it! The problem was that in WebSecurityConfig I was doing the following:
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(**new CustomUserDetailsService()**);
}
and then the new instance of CustemUserDetailsService was out of the Spring Control.
To solve it I added in CustomUserDetailsService a constructor:
private SecurityDao securityDAO;
public CustomUserDetailsService(SecurityDao securityDAO) {
super();
this.securityDAO = securityDAO;
}
and I modified WebSecurityConfig in this way:
#Autowired
private SecurityDao securityDao;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(new CustomUserDetailsService(securityDao));
}
Thanks anyway for your help!
Eventhough you have solved this issue, the solution is ugly in terms of Spring Dependency Injection and Inversion of Control theories.
Basically you should never use the new keyword to instantiate objects if you are using Spring. Because all objects must be instantiated and injected only by the Spring Container.
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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:annotation-config />
<context:spring-configured />
<context:component-scan base-package="com.agrichem.server" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="WEB-INF/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="securityDao"
class="com.agrichem.server.model.repositories.impl.SecurityDaoImpl">
</bean>
<bean id="customerService"
class="com.agrichem.server.path.to.service.CustomUserDetailsService">
</bean>
</beans>
WebSecurityConfig.java
#Configuration
#EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService customUserDetailsService
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(customUserDetailsService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers("/home/logout.do").permitAll()
.anyRequest().authenticated().and().formLogin()
.loginPage("/home/login.do").permitAll()
.failureUrl("/home/accessdenied.do").permitAll();
}
}
And you should have a Default Constructor for CustomUserDetailsService which doesn't take in any arguments. All your #Autowired properties should be inject by the spring container.
Furthermore you are intermixing Spring Java Configuration and Spring XML Configuration which is fine, but it is better if you decide on one particular method to define your beans.

Categories

Resources