Spring Security UserDetailsService Not Validating Password - spring

I'm implementing spring security 3.0.5 and in my form based login im extending the spring UserDetailsService. Currently my login form is only validating user name and not password. Where does spring security validate the password being posted to /j_spring_security_check?
security config:
<?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:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
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/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="dc" />
<global-method-security />
<http access-denied-page="/auth/denied.html">
<intercept-url filters="none" pattern="/javax.faces.resource/**" />
<intercept-url filters="none" pattern="/services/rest-api/1.0/**" />
<intercept-url filters="none" pattern="/preregistered/*"/>
<intercept-url
pattern="/**/*.xhtml"
access="ROLE_NONE_GETS_ACCESS" />
<intercept-url
pattern="/auth/**"
access="ROLE_ANONYMOUS,ROLE_USER" />
<intercept-url
pattern="/auth/*"
access="ROLE_ANONYMOUS" />
<intercept-url
pattern="/registered/*"
access="ROLE_USER" />
<intercept-url
pattern="/*"
access="ROLE_ANONYMOUS" />
<form-login
login-processing-url="/j_spring_security_check.html"
login-page="/auth/login.html"
default-target-url="/home.html"
authentication-failure-url="/login.html" />
<logout invalidate-session="true"
logout-url="logout.html"
success-handler-ref="SuccessHandler"/>
<anonymous username="guest" granted-authority="ROLE_ANONYMOUS"/>
<remember-me user-service-ref="userManager" key="dfdfdfdff"/>
<custom-filter after="FORM_LOGIN_FILTER" ref="xmlAuthenticationFilter"/>
</http>
<!-- Configure the authentication provider -->
<authentication-manager alias="am">
<authentication-provider user-service-ref="userManager">
<password-encoder ref="passwordEncoder" />
</authentication-provider>
<authentication-provider ref="xmlAuthenticationProvider" />
</authentication-manager>
</beans:beans>
beans:
<?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:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
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.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.dc"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="springContextHolder" class="SpringContextHolder" factory-method="getInstance" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL" />
<property name="showSql" value="true" />
</bean>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/webapp" />
<property name="username" value="userid" />
<property name="password" value="password" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="false"/>
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="localhost"/>
<property name="port" value="25"/>
</bean>
<bean id="utilities" class="UtilitiesImpl"/>
<bean id="xmlAuthenticationFilter" class="com.dc.api.service.impl.XMLAuthenticationFilter">
<property name="authenticationManager" ref="am" />
<property name="utilities" ref="utilities"/>
</bean>
<bean id="xmlAuthenticationProvider" class="com.dc.api.service.impl.XMLAuthenticationProvider">
<property name="userManager" ref="userManager"/>
</bean>
<bean id="DCLogoutSuccessHandler" class="LogoutSuccessHandler"/>
</beans>
UserDetails Implementation:
import javax.inject.Inject;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.dc.api.dao.AuthorityDAO;
import com.dc.api.dao.UserDAO;
import com.dc.api.exception.ApiDataException;
import com.dc.api.exception.EmailNotFoundException;
import com.dc.api.helper.MailContentHelper;
import com.dc.api.model.Users;
import com.dc.api.model.vo.APIResponse;
import com.dc.api.service.UserManager;
import com.dc.api.service.Utilities;
#Service("userManager")
public class UserManagerImpl extends UserDetailsService {
#Inject
UserDAO userDAO;
#Inject
AuthorityDAO authorityDAO;
#Inject
PasswordEncoder passwordEncoder;
#Inject
Utilities utilities;
private void encodePassword(Users user) {
if (user.getPassword() == null && user.getRawPassword() != null) {
user.setPassword(passwordEncoder.encodePassword(user.getRawPassword(), null));
user.setRawPassword(null);
}
}
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
Users user = null;
try {
user = userDAO.findByUsername(username);
if (user != null) {
}
} catch (DataAccessException ex) {
throw new UsernameNotFoundException("Invalid login", ex);
}
if (user == null) {
throw new UsernameNotFoundException("User not found.");
}
return user;
}
public Users getUser(String username) {
try {
return userDAO.findByUsername(username);
} catch (DataAccessException ex) {
// ignore
log.warn("Duplicate username: " + username);
}
return null;
}
public boolean isUsernameTaken(String username) {
try {
if (userDAO.findByUsername(username) == null) {
return false;
} else {
return true;
}
} catch (DataAccessException ex) {
// ignore
log.warn("Duplicate username: " + username);
}
return true;
}
public boolean isLoginValid(String username, String password) throws ApiDataException {
Users user = null;
try {
user = userDAO.findByUsername(username);
} catch (DataAccessException ex) {
throw new ApiDataException("Data Access Exception while verifying login");
}
if (user == null) {
return false;
}
if (passwordEncoder.isPasswordValid(user.getPassword(), password, null)) {
return true;
}
return false;
}
#Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public void saveUser(Users user) {
encodePassword(user);
userDAO.save(user);
}
#Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public void updateUser(Users user) {
encodePassword(user);
userDAO.update(user);
}
#Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public void resetPassword(String username, MailContentHelper mailContentHelper) {
String newPassword = utilities.generateSecret(8);
this.changePassword(username, newPassword, mailContentHelper);
}
#Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public void changePassword(String username, String password, MailContentHelper mailContentHelper) {
Users user = userDAO.findByUsername(username);
user.setPassword(null);
user.setRawPassword(password);
encodePassword(user);
userDAO.update(user);
String firstName = user.getFirstName();
firstName = (firstName == null) ? user.getUsername() : firstName;
//SimpleMailMessage message = mailContentHelper.retrieveContent(new Object[]{firstName, password, user.getEmail()});
//utilities.sendMail(message);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<context-param>
<param-name>javax.faces.FACELETS_LIBRARIES</param-name>
<param-value>/WEB-INF/facelet/dc.taglib.xml</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
WEB-INF/dc-context-api.xml
WEB-INF/dc-context-security.xml
</param-value>
</context-param>
<context-param>
<param-name>resteasy.resource.method-interceptors</param-name>
<param-value>org.jboss.resteasy.core.ResourceMethodSecurityInterceptor</param-value>
</context-param>
<context-param>
<param-name>resteasy.resources</param-name>
<param-value>
com.dc.web.actions.GlobalWebService</param-value>
</context-param>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/services/rest-api</param-value>
</context-param>
<context-param>
<param-name>resteasy.media.type.mappings</param-name>
<param-value>json : application/json, xml : application/xml</param-value>
</context-param>
<context-param>
<param-name>resteasy.resources</param-name>
<param-value>
com.WebService
</param-value>
</context-param>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>none</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>1000</param-value>
</context-param>
<context-param>
<param-name>primefaces.PRIVATE_CAPTCHA_KEY</param-name>
<param-value>6LeL-MISAAAAAG6k07ch22oy-mxXBUi1MXKmrWiD</param-value>
</context-param>
<context-param>
<param-name>primefaces.PUBLIC_CAPTCHA_KEY</param-name>
<param-value>6LeL-MISAAAAAPTK5lYI9tK0SWWY2BqC2Hun7sH3</param-value>
</context-param>
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter </filter-class>
<init-param>
<param-name>thresholdSize</param-name> <param-value>51200</param-value>
</init-param>
<init-param>
<param-name>uploadDirectory</param-name>
<param-value>url/upload</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-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>*.html</url-pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>*.xhtml</url-pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/dc_security_check</url-pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<listener>
<listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<listener>
<listener-class>org.jboss.resteasy.plugins.spring.SpringContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<servlet>
<servlet-name>Resteasy</servlet-name>
<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
</servlet>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Resteasy</servlet-name>
<url-pattern>api/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
</web-app>

It compares the password you submit to the password returned by the UserDetails object returned by your UserDetailsService. Please post your config and your UserDetailsService if you need more help.
EDIT: Thanks for the info. It does exactly what you're guessing. The ProviderManager (which is used by default) has the following in its JavaDoc:
If a subsequent provider successfully
authenticates the request, the earlier
authentication exception is
disregarded and the successful
authentication will be used.
So your problem is the latter provider "overruling" the decision of the first one.

Related

spring security and mvc

I am using spring security and some mvc controllers. I am not able to make it work. Below is the error I get.
org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/auth/ping] in DispatcherServlet with name 'application'
It would be great if anyone can figure out what's wrong with my code
below are my files
web.xml
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Out of school network backend</display-name>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/application-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- CORS Filter -->
<filter>
<filter-name>corsFilter</filter-name>
<filter-class>com.myproj.filters.SimpleCORSFilter</filter-class>
</filter>
<!-- Spring Security Filter -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>corsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>application</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>application</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Below is my application context:
<?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:sec="http://www.springframework.org/schema/security"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
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/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.5.xsd">
<context:annotation-config />
<context:component-scan base-package="com.myproj.controllers" />
<mvc:annotation-driven />
<!-- mongodb -->
<mongo:db-factory id="mongoDbFactory"
host="<ip address>"
port="27017"
dbname="mongotest"
username="username"
password="password"/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongoDbFactory" />
</bean>
<mongo:repositories base-package="com.myproj.repositories" />
<!-- Global Security Settings -->
<sec:global-method-security pre-post-annotations="enabled" />
<sec:http use-expressions="true" disable-url-rewriting="true" auto-config="true"
entry-point-ref="authenticationEntryPoint"
authentication-manager-ref="authenticationManager">
<sec:intercept-url pattern="/auth/*" access="isAnonymous()" />
<sec:intercept-url method="POST" pattern="/be/user" access="isAnonymous()" />
<sec:intercept-url pattern="/home" access="isAnonymous()" />
<sec:intercept-url pattern="/api/*" access="hasRole('ROLE_USER')" />
<sec:form-login login-processing-url="/auth/login"
default-target-url="/account"
username-parameter="username"
password-parameter="password"
authentication-failure-url="/login?loginError"/>
<sec:logout logout-success-url="/login?logout" />
</sec:http>
<bean id="authenticationEntryPoint" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint" />
<bean id="userDetailsService" class="com.myproj.security.UserDetailsServiceImpl" />
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider user-service-ref="userDetailsService" />
</sec:authentication-manager>
Below is the controller:
package com.myproj.controllers;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;
public class PingController {
#RequestMapping(value = "auth/ping", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public #ResponseBody String login() {
return "unprotected";
}
#RequestMapping(value = "api/protected", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public #ResponseBody String getpro() {
return "protected";
}
}
You forgot #Controller on your PingController class.

Transaction control in a JSF Spring 3 project

i got a problem in my project using JSF 2.0 with Primefaces, Spring 3 and Hibernate.
I was able to configure the whole project correctly and been able to use springĀ“s dependency injection and transaction control just fine along with JSF views, service(interface and impl), DAO(interface and impl).
But whenever I try to list or delete objects of a certain model it duplicates the current objects that is in the model table.
Anyone had this problem before?
PS: Im annotating my controller class with #Component("myBeanName"), so my jsf view can understand the bean name to call methods and use objects.
Here is the 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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
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:component-scan base-package="br.com.dentrio" />
<context:annotation-config />
<context:spring-configured />
<!-- Data Source Declaration -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/dentriodb" />
<property name="user" value="root" />
<property name="password" value="root" />
<property name="maxPoolSize" value="10" />
<property name="maxStatements" value="0" />
<property name="minPoolSize" value="5" />
</bean>
<!-- Session Factory Declaration -->
<bean id="SessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- <property name="packagesToScan"> <list> <value>net.javabeat.spring.model</value>
</list> </property> -->
<property name="packagesToScan" value="br.com.dentrio.model"></property>
<!-- <property name="annotatedClasses"> -->
<!-- <list> -->
<!-- <value>net.javabeat.spring.model.*</value> -->
<!-- </list> -->
<!-- </property> -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<!-- Enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="txManager" />
<!-- Transaction Manager is defined -->
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
My faces-config.xml file
<?xml version="1.0" encoding="utf-8"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
<application>
<locale-config>
<default-locale>pt_BR</default-locale>
</locale-config>
</application>
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
<application>
<message-bundle>
messages
</message-bundle>
</application>
My web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>PrimeFaces Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener- class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
<!-- Change to "Production" when you are ready to deploy -->
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<!-- Welcome page -->
<welcome-file-list>
<welcome-file>home.xhtml</welcome-file>
</welcome-file-list>
<!-- JSF mapping -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map these files with JSF -->
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
</web-app>
My Bean controller
package br.com.managedController;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.view.ViewScoped;
import org.springframework.dao.DataAccessException;
import br.com.dentrio.comum.BaseBean;
import br.com.dentrio.model.Dentista;
import br.com.dentrio.service.DentistaServiceImpl;
#Component("dentistaBean")
public class DentistaBean extends BaseBean implements Serializable {
private static final long serialVersionUID = 1L;
#Autowired
DentistaService dentistaService;
private Date data;
private Dentista dentista = new Dentista();
private Dentista dentistaSelecionado;
List<Dentista> listaDentistas = new ArrayList<Dentista>();
public void prepararPedidos() {
carregarListaDentistas();
}
#PostConstruct
private void carregarListaDentistas() {
listaDentistas = new ArrayList<Dentista>();
listaDentistas.addAll(dentistaService.listDentistas());
}
public String adicionarDentista() {
try {
dentistaService.addDentista(dentista);
carregarListaDentistas();
addMessage("Sucesso", "Dentista adicionado com Sucesso!");
return "listarDentistas?faces-redirect=true";
} catch (DataAccessException e) {
e.printStackTrace();
}
return ERROR;
}
public void deletarDentista(Integer dentistaId) {
try {
Dentista dentista = dentistaService.getDentista(dentistaId);
dentistaService.deletarDentista(dentista);
addMessage("Sucesso", "Dentista deletado com Sucesso!");
carregarListaDentistas();
} catch (Exception e) {
e.printStackTrace();
}
}
public void resetForm() {
dentista = new Dentista();
}
public Dentista getDentista() {
return dentista;
}
public void setDentista(Dentista dentista) {
this.dentista = dentista;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
public List<Dentista> getListaDentistas() {
return listaDentistas;
}
public void setListaDentistas(List<Dentista> listaDentistas) {
this.listaDentistas = listaDentistas;
}
public Dentista getDentistaSelecionado() {
return dentistaSelecionado;
}
public void setDentistaSelecionado(Dentista dentistaSelecionado) {
this.dentistaSelecionado = dentistaSelecionado;
}
public DentistaService getDentistaService() {
return dentistaService;
}
public void setDentistaService(DentistaService dentistaService) {
this.dentistaService = dentistaService;
}
}
What i do is inject the Spring service as a managed property in JSF bean. You can use #ViewScoped without problems.
#ViewScoped
public class bean{
#ManagedProperty(value="#{springService}")
private SpringService springService;
//getter and setter

spring autowired classes are null in jersey rest

I'm new to Spring and Jersey. I have web application which consists of spring servlet and jersey rest servlet. When I try use spring's autowire annotation in jersey rest servlet, I get nullpointerexception on those object. Others jersey based methods works fine.
This is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>My Application</display-name>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/dispatcher-servlet.xml
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<!-- Spring Security -->
<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>
<servlet>
<servlet-name>JerseyServlet1</servlet-name>
<servlet-class>
com.sun.jersey.spi.spring.container.servlet.SpringServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/JerseyServlet1-servlet.xml</param-value>
</init-param>
<init-param>
<param-name>
com.sun.jersey.config.property.packages
</param-name>
<param-value>pl.mypack.rest</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JerseyServlet1</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
And JerseyServlet1-servlet.xml 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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config />
<context:component-scan base-package="pl.mypack" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages"></property>
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties"></bean>
<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>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="contactDAO" class="pl.mypack.dao.ContactDAOImpl"></bean>
<bean id="contactService" class="pl.mypack.service.ContactServiceImpl"></bean>
<bean id="userDetailsService" class="pl.mypack.service.UserDetailsServiceImpl"></bean>
<bean id="RestService" class="pl.mypack.rest.RestServiceImpl"></bean>
<bean id="userDAO" class="pl.mypack.dao.UserEntityDAOImpl"></bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
And Java class:
package pl.mypack.rest;
import com.google.gson.Gson;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.springframework.beans.factory.annotation.Autowired;
import pl.mypack.dao.ContactDAO;
import pl.mypack.dao.UserEntityDAO;
import pl.mypack.domain.UserEntity;
#Path("/json/metallica")
public class JSONService {
#Autowired
private ContactDAO contactDAO;
#Autowired
private UserEntityDAO userDAO;
#GET
#Path("/get")
#Produces(MediaType.APPLICATION_JSON)
public Track getTrackInJSON() {
Track track = new Track();
track.setTitle("Enter Sandman");
track.setSinger("Metallica");
return track;
}
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
public Response createTrackInJSON(Track track) {
String result = "Track saved : " + track;
return Response.status(201).entity(result).build();
}
#GET
#Path("/getcontacts")
#Produces(MediaType.APPLICATION_JSON)
public String getAllContactList(#QueryParam("login") String login, #QueryParam("pass") String password) {
UserEntity usr = userDAO.findByLoginData(login, password);
if(usr != null)
{
Gson gson = new Gson();
return gson.toJson(contactDAO.getLoggedUserContacts(usr.getId()));
}
return null;
}
}
Any help will be much appreciated!
Thank you
You are loading dispatcher-servlet context 2 times.
There are two possibilities for why beans are not being autowired:
1) If your service and data access beans(like you mentioned ContactDAO, UserEntityDAO etc.,) are in separate config xml, say config.xml, then mention in web.xml as:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config.xml</param-value>
</context-param>
Remove the reference of >/WEB-INF/dispatcher-servlet.xml from this contextConfigLocation.
2) If your service and data access beans(like you mentioned ContactDAO, UserEntityDAO etc.,) for some reason are in dispatcher-servlet.xml, then you mentioned it in two places
a) <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml
/WEB-INF/spring-security.xml
</param-value>
</context-param>
This is fine.
b) In dispatcher servlet:
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</init-param>
This becomes the sibling of JerseyServlet1 which will not have any visibility into it and its beans. So remove this from dispatcher-servlet <init-param>

unable to integrate spring security in existing application

I am not able to find out my problem in spring security integration. I have spent 2-3 days already.So, please help me.
below is my web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>cdl</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>startUpServlet</servlet-name>
<servlet-class>com.qait.cdl.commons.startup.StartUpServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>startUpServlet</servlet-name>
<url-pattern>/startUpServlet.htm</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>CDL_ENV</param-name>
<param-value>staging</param-value>
</context-param>
<listener>
<listener-class>com.qait.cdl.commons.startup.CdlContextListner</listener-class>
</listener>
<!-- Session timeout -->
<session-config>
<session-timeout>600</session-timeout>
</session-config>
<!-- <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
WEB-INF/dispatcher-servlet.xml
</param-value>
</context-param>
</web-app>
Below is my applicationContext.xml 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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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">
<import resource="classapth*:spring/SpringSecurityConfig.xml" />
<!-- <bean name="springSecurityFilterChain" class="org.springframework.web.filter.OncePerRequestFilter"/> -->
</beans>
Below is my SpringSecurityConfig.xml
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">
<security:http auto-config="true" use-expressions="true">
<security:intercept-url pattern="/displayAdminPage.htm" access="hasRole('ROLE_ADMIN')" />
<security:form-login login-page="/login.htm" authentication-failure-url="/login.htm"/>
<security:logout logout-url="/logout.htm" logout-success-url="/login.htm"/>
<security:access-denied-handler error-page="/login.htm" />
</security:http>
<security:authentication-manager>
<security:authentication-provider user-service-ref="userService" >
</security:authentication-provider>
</security:authentication-manager>
below is my 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:context="http://www.springframework.org/schema/context"
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">
<!-- Message resource -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>messages</value>
<value>error</value>
</list>
</property>
</bean>
<!-- Imports all configuration files -->
<import resource="classpath*:spring/*.xml" />
<import resource="classpath*:spring/*/*.xml" />
<!-- Interceptor mapping -->
<bean id="handlerMapping"
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
<!-- <property name="interceptors" ref="cdlInterceptor" /> -->
<property name="interceptors" ref="cdlSessionInterceptor"></property>
</bean>
<!-- Tiles view resolver and configuration -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.tiles2.TilesView" />
<property name="order" value="1" />
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles-defs.xml</value>
</list>
</property>
</bean>
<!-- XmlView Resolver -->
<bean class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="location" value="/WEB-INF/spring-Xmlviews.xml" />
<property name="order" value="0" />
</bean>
<!-- MultipartResolver for file upload -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<bean id="rssViewer" class="com.qait.cdl.rssfeed.view.CustomRssViewer" />
<!-- Default view resolver mapping <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <property
name="suffix"> <value>.jsp</value> </property> <property name="order" value="1"
/> </bean> -->
</beans>
I have following queries.
Is it necessary to give "filter" tag in web.xml, if yes than why?
In my application, I have two application context(one for spring security and other for dispatcher-servlet), is it possible for springSecurityConfig.xml to access bean definition which is defined in dispatcher-servlet.xml?
what is the flow of spring-security configuration.Upto my knowledge, i have understood that intercept-url tag intercept the request and check appropriate role using expression language.I am not able to understand how it looks appropriate role in DB via authentication-manager i've provided.
below is my userService bean definition in service.xml
<bean name="userService" class="com.qait.cdl.services.impl.UserServiceImpl">
<property name="userDao" ref="userDao" />
</bean>
below is userService interface
public interface UserService extends UserDetailsService{
}
this UserDetailsService is from springframework
below is UserServiceimpl class
public class UserServiceImpl implements UserService {
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
UserDetails userDetails = null;
if(username != null && !"".equals(username)){
User user = userDao.get(username);
if(user != null){
UserGroupAuthority groupAuthority = userDao.getUserAuthority(user);
if(groupAuthority != null){
Collection<GrantedAuthority> grantedAuthorities = getGrantedAuthorities(groupAuthority.getAuthority());
userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
true, true, true, true, grantedAuthorities);
}
}
}
return userDetails;
}
#Override
public Collection<GrantedAuthority> getGrantedAuthorities(String authority) {
List<GrantedAuthority> grantedAuthorities = new LinkedList<GrantedAuthority>();
grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_USER"));
return grantedAuthorities;
}
#Override
public UserGroupAuthority getUserAuthority(User user) {
return userDao.getUserAuthority(user);
}
}
Simply the problem is , it is not validating the given intercept-url. Where I am doing mistake?
Activate springSecurityFilterChain in your web.xml. It's an entry point of Spring Security. If springSecurityFilterChain is deactivated then Spring Security will never work.

scheduled method invoked twice in spring 3.0.2

I am using spring 3.0.2
My scheduled method is invoked twice..
am i making some mistake..?
please help me to figure it out..
#Component("happySundayGreetTask")
public class HappySundayGreetTask {
#Autowired
private JavaMailSender mailSender;
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
#Value("${mail.sender}")
private String fromAddress;
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
#Autowired
private VelocityEngine velocityEngine;
public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
#Autowired
private SpitterDAO spitterDAO;
public void setSpitterDAO(SpitterDAO spitterDAO) {
this.spitterDAO = spitterDAO;
}
#Scheduled(cron="0 58 18 ? * SUN")
public void greetSundayToSpitters(){
try {
System.out.println("task started..");
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper mimeHelper = new MimeMessageHelper(message, true);
List<String> spittersEmail = spitterDAO.getSpittersEmail(true);
String toAddress[] = spittersEmail.toArray(new String[spittersEmail.size()]);
String templateLoc = "com/spitter/task/sundayGreetEmailTemplate.vm";
String emailText = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateLoc, null);
mimeHelper.setFrom(fromAddress);
mimeHelper.setTo(toAddress);
mimeHelper.setSubject("Sunday Greeting from Spitter");
mimeHelper.setText(emailText, true);
mailSender.send(message);
}
catch (MessagingException ex) {
Logger.getLogger(HappySundayGreetTask.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
// spitter-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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:jms="http://www.springframework.org/schema/jms"
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.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
">
<!-- Defining a PropertyPlaceholderConfigurer -->
<context:property-placeholder
location="classpath:/com/spitter/dao/db.properties,
classpath:/com/spitter/service/alerts/mailserver.properties"/>
<!-- Declaring security aspects to those beans annotated with #PreAutorize -->
<security:global-method-security pre-post-annotations="enabled" />
<!-- Support for annotation driven validation, message conversion -->
<mvc:annotation-driven/>
<!-- Automatically registering controllers & service objects as beans -->
<context:component-scan base-package="com.spitter"/>
<!-- Autowiring enabled using annotations -->
<context:annotation-config/>
<!-- Using annotation driven transaction facility -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- Configuring a mail sender -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<!-- Configuring mail server properties -->
<property name="host" value="${mailserver.host}"/>
<property name="port" value="${mailserver.port}"/>
<property name="username" value="${mailserver.username}"/>
<property name="password" value="${mailserver.password}"/>
<!-- Other mail properties -->
<property name="javaMailProperties">
<props>
<prop key="mail.transport.protocol">${mail.transport.protocol}</prop>
<prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
<prop key="mail.smtp.starttls.enable">${mail.smtp.starttls.enable}</prop>
<prop key="mail.debug">${mail.debug}</prop>
</props>
</property>
</bean>
<!-- Velocity email template used for sending email alerts -->
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="velocityProperties">
<props>
<prop key="resource.loader">class</prop>
<prop key="class.resource.loader.class">org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader</prop>
</props>
</property>
</bean>
<!-- support for scheduled and asynchronous backgorund jobs -->
<task:annotation-driven/>
</beans>
//spitter-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
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-3.0.xsd
">
<import resource="spitter-servlet.xml"/>
<security:http auto-config="true" use-expressions="true">
<security:remember-me key="spitterKey" token-validity-seconds="86400"/>
<security:form-login login-page="/login" authentication-failure-url="/login?login_error=t"
login-processing-url="/static/j_spring_security_check"
default-target-url="/home"/>
<security:logout logout-url="/logout" logout-success-url="/login?logout=success"/>
<security:intercept-url pattern="/login" access="isAnonymous()"/>
<security:intercept-url pattern="/spitters" access="isAnonymous()"/>
<security:intercept-url pattern="/logout" access="isAuhenticated()"/>
<security:intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')"/>
</security:http>
<security:authentication-manager>
<security:authentication-provider user-service-ref="spitterServiceImpl">
<security:password-encoder hash="md5"/>
</security:authentication-provider>
</security:authentication-manager>
</beans>
//web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spitter-security.xml
</param-value>
</context-param>
<filter>
<description>Filter used to identify requests for PUT & DELETE requests as the case with RESTFul verbs</description>
<filter-name>httpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>httpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<description>Spring security servlet filter delegates to spring managed security filter(Spring security filter)</description>
<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>
<listener>
<listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class>
</listener>
<servlet>
<servlet-name>spitter</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet>
<description>Handles static content</description>
<servlet-name>staticHandler</servlet-name>
<servlet-class>com.spitter.servlet.StaticServlet</servlet-class>
<load-on-startup>5</load-on-startup>
</servlet>
<servlet>
<servlet-name>SpitterServiceEndPoint</servlet-name>
<servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spitter</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>staticHandler</servlet-name>
<url-pattern>/resources/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>SpitterServiceEndPoint</servlet-name>
<url-pattern>/SpitterServiceEndPoint</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
I am using spring 3.0.2
My scheduled method is invoked twice..
am i making some mistake..?
please help me to figure it out..
Found in the documentation of spring :
Make sure that you are not initializing multiple instances of the same #Scheduled annotation class at runtime, unless you do want to schedule callbacks to each such instance. Related to this, make sure that you do not use #Configurable on bean classes which are annotated with #Scheduled and registered as regular Spring beans with the container: You would get double initialization otherwise, once through the container and once through the #Configurable aspect, with the consequence of each #Scheduled method being invoked twice.
Maybe this is the reason
It looks like your cron syntax is wrong - My guess is that you have typed in ? and * accidentally. You should change it to:
#Scheduled(cron="0 58 18 * SUN")
If you specify 6 parameters (like you had in your original syntax), cron expects the 6th element to be the year. SUN is a 'day of the week' parameter, and should be specified in 5th position, so cron is getting confused.

Resources