Legacy Spring MVC to Spring Boot - java

I have a legacy application which uses web.xml configuration.
The web.xml looks something like this.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring/common-beans-context.xml
</param-value>
</context-param>
<servlet>
<servlet-name>dispatcherOne</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcherOne-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherOne</servlet-name>
<url-pattern>/test/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>dispatcherTwo</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcherTwo-context.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherTwo</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
To Convert this to Spring Boot Application,
I have done the below changes:
#Bean
public XmlWebApplicationContext xmlWebApplicationContext() {
XmlWebApplicationContext applicationContext = new XmlWebApplicationContext();
applicationContext.setConfigLocations("classpath:spring/common-beans-context.xml");
applicationContext.refresh();
return applicationContext;
}
#Bean
public ServletRegistrationBean<DispatcherServlet> mvcTestServlet(XmlWebApplicationContext applicationContext) {
DispatcherServlet dispatcherServlet = new DispatcherServlet();
// create child application context
XmlWebApplicationContext childApplicationContext = new XmlWebApplicationContext();
childApplicationContext.setConfigLocation("classpath:spring/dispatcherOne-context.xml");
// set parent from the previous method
childApplicationContext.setParent(applicationContext);
dispatcherServlet.setApplicationContext(childApplicationContext);
childApplicationContext.refresh();
ServletRegistrationBean<DispatcherServlet> servletRegistrationBean = new ServletRegistrationBean<DispatcherServlet>(
dispatcherServlet, "/test/*");
servletRegistrationBean.setName("dispatcherOne");
servletRegistrationBean.addUrlMappings("/test/*");
servletRegistrationBean.setLoadOnStartup(1);
return servletRegistrationBean;
}
#Bean
public ServletRegistrationBean<DispatcherServlet> mvcServlet(XmlWebApplicationContext applicationContext) {
DispatcherServlet dispatcherServlet = new DispatcherServlet();
// similar to the previous method..
// 1. create local applicationContext and then set parent.
}
I added childApplicationContext.refresh() to see if the beans were loading properly but what i think is happening is that the two dispatcher servlets are not able to access the beans defined in the parentContext. and are throwing beans not found exception even though they're available in parentContext
Is there a workaround for this?
or is there any other way I can achieve this ?

To create a Spring Boot application and re-using your existing config do the following and don't create a context yourself. You are basically trying to outsmart or work-around Spring Boot with what you are currently doing.
Create a class annotated with #SpringBootApplication and use #ImportResource to let Spring Boot creat the main application context.
#SpringBootApplication
#ImportResource("classpath:spring/common-beans-context.xml")
public YourApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(YourApplication.class);
}
}
Now as you have 2 DispatcherServlets in your original config you need to add 2 ServletRegistrationBean to set the URL etc.
#Bean
public ServletRegistrationBean<DispatcherServlet> dispatcherServletOneRegistration() {
ServletRegistrationBean<DispatcherServlet> registration = new ServletRegistrationBean(new DispatcherServlet(), "/test/*");
registration.setLoadOnStartup(1);
registration.setName("dispatcherOne");
registration.setInitParameters(Collections.singletonMap("contextConfigLocation", "classpath:spring/dispatcherOne-context.xml");
return registration;
}
And more or less the same for the second servlet.
#Bean
public ServletRegistrationBean<DispatcherServlet> dispatcherServletTwoRegistration() {
ServletRegistrationBean<DispatcherServlet> registration = new ServletRegistrationBean(new DispatcherServlet(), "/");
registration.setLoadOnStartup(1);
registration.setName("dispatcherTwo");
registration.setInitParameters(Collections.singletonMap("contextConfigLocation", "classpath:spring/dispatcherTwo-context.xml");
return registration;
}

Related

No bean named 'springSecurityFilterChain' available

I am getting error
No bean named 'springSecurityFilterChain' available
when I don't include spring security configuration my code works fine. This project is created using spring annotation based configuration. When I created project using Maven pom.xml, web.xml, MvcConfiguration automatically gets created. Now I want to implement Spring-security with the same project and configuration. My configuration files are shown below.
MvcConfiguration.java
#Configuration
#ComponentScan(basePackages="com.mywebsite.emusicstore")
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter
{
#Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver resolver=new CommonsMultipartResolver();
Long maxUploadSize = 2048000L;
resolver.setMaxUploadSize(maxUploadSize);
return resolver;
} }
SpringSecurity.java
#Configuration
#EnableWebSecurity
public class SpringSecurity extends WebSecurityConfigurerAdapter{
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/admin**").access("ROLE_USER")
.and().formLogin().loginPage("/login").defaultSuccessUrl("/admin/").failureUrl("/login?error").usernameParameter("username").passwordParameter("password")
.and().logout().logoutSuccessUrl("/login?logout");
//http.csrf().disable();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
HibernateConfig hc = new HibernateConfig();
String authoritiesByUsernameQuery = "SELECT username,authorities FROM authorities WHERE username = ?";
String usersByUsernameQuery = "SELECT username,password,enabled FROM users WHERE username = ?";
auth.jdbcAuthentication().dataSource(hc.dataSource()).authoritiesByUsernameQuery(authoritiesByUsernameQuery).usersByUsernameQuery(usersByUsernameQuery);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 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">
<display-name>emusicstore</display-name>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>SpringDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.mywebsite.emusicstore</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringDispatcher</servlet-name>
<url-pattern>/</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>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
Error
SEVERE: Exception starting filter springSecurityFilterChain
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean
named 'springSecurityFilterChain' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1207)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1086)
at org.springframework.web.filter.DelegatingFilterProxy.initDelegate(DelegatingFilterProxy.java:327)
at org.springframework.web.filter.DelegatingFilterProxy.initFilterBean(DelegatingFilterProxy.java:235)
at org.springframework.web.filter.GenericFilterBean.init(GenericFilterBean.java:236)
at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:279)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:260)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:105)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4598)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5223)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:155)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1404)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1394)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Please add this class as well.
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer{
}

JavaConfig No bean named 'springSecurityFilterChain' is defined

I followed tutorial on http://shazsterblog.blogspot.com.es/2014/07/spring-security-custom-filterchainproxy.html to create a security filter using Java configuration instead of XML.
The bean is not being created and the application fails to load:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:575)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1111)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:276)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1123)
at org.springframework.web.filter.DelegatingFilterProxy.initDelegate(DelegatingFilterProxy.java:323)
at org.springframework.web.filter.DelegatingFilterProxy.initFilterBean(DelegatingFilterProxy.java:235)
at org.springframework.web.filter.GenericFilterBean.init(GenericFilterBean.java:194)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:234)
at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:332)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:90)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:3783)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4409)
at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeployInternal(TomcatDeployment.java:313)
at org.jboss.web.tomcat.service.deployers.TomcatDeployment.performDeploy(TomcatDeployment.java:145)
at org.jboss.web.deployers.AbstractWarDeployment.start(AbstractWarDeployment.java:461)
at org.jboss.web.deployers.WebModule.startModule(WebModule.java:122)
at org.jboss.web.deployers.WebModule.start(WebModule.java:97)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:157)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96)
This is the 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>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.config.SecurityConfig</param-value>
</context-param>
<servlet>
<servlet-name>Dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>dispatchOptionsRequest</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Dispatcher</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/application-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>test</realm-name>
</login-config>
<security-role>
<role-name>ADMIN</role-name>
</security-role>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<security-constraint>
<web-resource-collection>
<web-resource-name>COMUN</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>ADMIN</role-name>
</auth-constraint>
</security-constraint>
</web-app>
This is the SecurityConfig class:
#Configuration
#EnableWebMvc
public class SecurityConfig extends WebMvcConfigurerAdapter implements ResourceLoaderAware{
private ResourceLoader resourceLoader;
#Bean
public FilterChainProxy springSecurityFilterChain() throws Exception {
AuthenticationManager am = authenticationManager();
SecurityContextPersistenceFilter sif = getSecurityContextPersistenceFilter();
J2eePreAuthenticatedProcessingFilter j2eePreAuthFilter = getJ2eePreAuthenticatedProcessingFilter(am);
LogoutFilter logoutFilter = getLogoutFilter();
ExceptionTranslationFilter etf = getExceptionTranslationFilter();
FilterSecurityInterceptor fsi = getFilterSecurityInterceptor(am);
FilterChainProxy fcp = new FilterChainProxy(new DefaultSecurityFilterChain(
new AntPathRequestMatcher("/**"),
sif, j2eePreAuthFilter, logoutFilter, etf, fsi
));
return fcp;
}
private FilterSecurityInterceptor getFilterSecurityInterceptor(AuthenticationManager am) {
AccessDecisionVoter<Object> roleVoter = new RoleVoter();
List<AccessDecisionVoter> decisionVoters = new LinkedList<AccessDecisionVoter>();
decisionVoters.add(roleVoter);
AffirmativeBased httpRequestAccessDecisionManager = new AffirmativeBased(decisionVoters);
httpRequestAccessDecisionManager.setAllowIfAllAbstainDecisions(false);
FilterSecurityInterceptor filterSecurityInterceptor = new FilterSecurityInterceptor();
filterSecurityInterceptor.setAuthenticationManager(am);
filterSecurityInterceptor.setAccessDecisionManager(httpRequestAccessDecisionManager);
LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();
List<ConfigAttribute> configs = new ArrayList<ConfigAttribute>();
configs.add(new org.springframework.security.access.SecurityConfig("hasRole(ADMIN)"));
requestMap.put(new AntPathRequestMatcher("/**"), configs);
FilterInvocationSecurityMetadataSource filterInvocationSecurityMetadataSource = new ExpressionBasedFilterInvocationSecurityMetadataSource(
requestMap, new DefaultWebSecurityExpressionHandler());
filterSecurityInterceptor
.setSecurityMetadataSource(filterInvocationSecurityMetadataSource);
return filterSecurityInterceptor;
}
private LogoutFilter getLogoutFilter() {
org.springframework.security.web.authentication.logout.LogoutFilter logoutFilter = new LogoutFilter("/", new SecurityContextLogoutHandler());
return logoutFilter;
}
private ExceptionTranslationFilter getExceptionTranslationFilter() {
ExceptionTranslationFilter exceptionTranslationFilter = new ExceptionTranslationFilter(
new Http403ForbiddenEntryPoint());
return exceptionTranslationFilter;
}
private SecurityContextPersistenceFilter getSecurityContextPersistenceFilter() {
return new org.springframework.security.web.context.SecurityContextPersistenceFilter();
}
private J2eePreAuthenticatedProcessingFilter getJ2eePreAuthenticatedProcessingFilter(AuthenticationManager am) throws Exception {
WebXmlMappableAttributesRetriever mappableRolesRetriever = new WebXmlMappableAttributesRetriever();
mappableRolesRetriever.setResourceLoader(this.resourceLoader);
mappableRolesRetriever.afterPropertiesSet();
SimpleAttributes2GrantedAuthoritiesMapper userRoles2GrantedAuthoritiesMapper = new SimpleAttributes2GrantedAuthoritiesMapper();
userRoles2GrantedAuthoritiesMapper.setConvertAttributeToUpperCase(true);
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource j2eeBasedPreAuthenticatedWebAuthenticationDetailsSource
= new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
j2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.setMappableRolesRetriever(mappableRolesRetriever);
j2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.setUserRoles2GrantedAuthoritiesMapper(userRoles2GrantedAuthoritiesMapper);
J2eePreAuthenticatedProcessingFilter j2eePreAuthenticatedProcessingFilter = new J2eePreAuthenticatedProcessingFilter();
j2eePreAuthenticatedProcessingFilter.setAuthenticationManager(am);
j2eePreAuthenticatedProcessingFilter.setAuthenticationDetailsSource(j2eeBasedPreAuthenticatedWebAuthenticationDetailsSource);
return j2eePreAuthenticatedProcessingFilter;
}
#Bean
public AuthenticationManager authenticationManager() throws Exception {
PreAuthenticatedGrantedAuthoritiesUserDetailsService preAuthenticatedGrantedAuthoritiesUserDetailsService = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();;
PreAuthenticatedAuthenticationProvider preAuthenticatedAuthenticationProvider = new PreAuthenticatedAuthenticationProvider();
preAuthenticatedAuthenticationProvider.setPreAuthenticatedUserDetailsService(preAuthenticatedGrantedAuthoritiesUserDetailsService);
List<AuthenticationProvider> lProviders = new LinkedList<AuthenticationProvider>();
lProviders.add(preAuthenticatedAuthenticationProvider);
AuthenticationManager am = new ProviderManager(lProviders);
return am;
}
#Override
public void setResourceLoader(ResourceLoader arg0) {
this.resourceLoader = arg0;
}
}
Any help please?
Bit different from the example and simplified for this case, the filter class is created if its package is set on component-scan
The following part of the web.xml is not needed:
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.config.SecurityConfig</param-value>
</context-param>
The web.xml defines the application context which will scan the class and create an instance of the filter. Later the instance is used in the web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/application-context-${environment}.xml</param-value>
</context-param>
If the ${environment} variable is "DEV", it uses an application context that has the security defined in XML, if the ${environment} variable is "PRO", it uses the following application context which has the logic defined in Java:
<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:jee="http://www.springframework.org/schema/jee"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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/security
http://www.springframework.org/schema/security/spring-security.xsd>
<context:component-scan base-package="com.config" />
</beans>
The filter only needs created in PRO so it needs the component-scan only for its package from within the application-context used in PRO.

Spring 4 #Scheduled Task is executing task twice

I'm trying to execute some task every X second but the task runs twise. I'm Using Spring 4.2.5 - the latest version.(I tryed it with 4.05 the same result)
#Service
#Transactional
#EnableScheduling
public class PaymentServices {
#Autowired
private MMTransactionDAO mmTransactionDAO;
#Scheduled(fixedDelay=230000)
public void getListOfPenddingTransactions() throws MambuApiException {
System.out.println("JOB Started");
List<MMPayTransaction> listOfPenddingTransaction = mmTransactionDAO.getListOfPenddingTransaction();
for(MMPayTransaction transaction : listOfPenddingTransaction){
if (transaction.getErrorcode().equals("-6")){
cancelTransactionInMambu(transaction.getMambuClientID(),transaction.getPaymentAmount(),transaction.getFeeAmount());
transaction.setFinalStatus(TansactionStatus.FAILED);
}else if(transaction.getErrorcode().equals("-21")){
cancelTransactionInMambu(transaction.getMambuClientID(),transaction.getPaymentAmount(),transaction.getFeeAmount());
transaction.setFinalStatus(TansactionStatus.FAILED);
}else if(transaction.getErrorcode().equals("-18")){
cancelTransactionInMambu(transaction.getMambuClientID(),transaction.getPaymentAmount(),transaction.getFeeAmount());
transaction.setFinalStatus(TansactionStatus.FAILED);
}else if (transaction.getErrorcode().equals("-37")){
cancelTransactionInMambu(transaction.getMambuClientID(),transaction.getPaymentAmount(),transaction.getFeeAmount());
transaction.setFinalStatus(TansactionStatus.FAILED);
}
else{
check(transaction.getOperationID());
}
}
}
}
here is my web.xml
<web-app version="2.4"
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">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
UPDATED
here is my application configuration calss:
#EnableWebMvc
#Configuration
#ComponentScan({"ge.kapi.*"})
#EnableTransactionManagement
public class AppConfig extends WebMvcConfigurerAdapter {
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory()
{
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(Boolean.TRUE);
vendorAdapter.setShowSql(Boolean.TRUE);
factory.setDataSource(dataSource());
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("ge.kapi");
Properties jpaProperties = getHibernateProperties();
factory.setJpaProperties(jpaProperties);
factory.afterPropertiesSet();
factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
return factory;
}
private Properties getHibernateProperties() {
Properties prop = new Properties();
prop.put("hibernate.show_sql", "true");
prop.put("hibernate.dialect","ge.kapi.config.SQLServerUnicodeDialect");
return prop;
}
#Bean(name = "dataSource")
public BasicDataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
ds.setUrl("jdbc:sqlserver://host;useUnicode=true;characterEncoding=UTF-8;DatabaseName=Base");
ds.setUsername("user");
ds.setPassword("pass");
return ds;
}
#Bean
public StringHttpMessageConverter stringHttpMessageConverter() {
return new StringHttpMessageConverter(Charset.forName("UTF-8"));
}
#Bean
public PlatformTransactionManager transactionManager()
{
EntityManagerFactory factory = entityManagerFactory().getObject();
return new JpaTransactionManager(factory);
}
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver
= new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setContentType("text/html; charset=UTF-8");
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
Why is it running TWICE each time?
Thanks in advance
-- Found Solution --
I have removed #ComponentScan({"ge.kapi.*"}) from AppConfig.java because this scan was also initiated from mvc-dispatcher-servlet.xml like this:
<context:component-scan base-package="ge.kapi"/>
Now Job starts only ones.
Thank you all for your time helping me!!!
I suggest you check if the bean is being created twice. It can happen if you have 2 app contexts (root and dispatcher).
Check if you have declared bean in xml and by annotation too.
And if you have spring security configuration in your application then keep mvc-dispatcher.xml declaration in of DispatcherServlet and spring-security.xml in of context loader listener .
Otherwise if you keep both xml with DispatcherServlet in that case two object will be created and that is why your scheduler will get call twice.

how to convert site minder xml configuration using Spring4 Java config

I am converting an old version based Spring application to annotation based Spring4 application. As a first step I converted all xmls to java configuration based annotations. The application is working fine, but the only issue is with the site minder xml configuration. I don't know how to convert the below siteminder configuration which is there in the web.xml into java based.
<login-config>
<auth-method>CLIENT-CERT</auth-method>
<realm-name>SiteMinderRealm</realm-name>
</login-config>
The above siteminder configuration is in web.xml,
Can anyone please tell me how to write the java based configuration for the above xml in AppInitializer.java
my web.xml and its corresponding substituted AppInitializer.java code is as shown below
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_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>SpringWebMVCApp</display-name>
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.helloworld.config.AppConfig</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/rest/</url-pattern>
</servlet-mapping>
<login-config>
<auth-method>CLIENT-CERT</auth-method>
<realm-name>SiteMinderRealm</realm-name>
</login-config>
</web-app>
AppInitializer.java
public class AppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/rest/");
}
private AnnotationConfigWebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(AppConfig.class);
return context;
}
}
Update 1
public class AppInitializer extends WebSecurityConfigurerAdapter implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/rest/");
}
private AnnotationConfigWebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(AppConfig.class);
return context;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().realmName("SiteMinderRealm").and().x509();
}
}
Did you try configuring this on the WebSecurityConfigurerAdapter? Something like this:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().realmName("SiteMinderRealm").and().x509();
}
}

Placement css, img and js of files after deploy spring mvc application

I'm new in spring mvc, and I have some questions:
1) Can I get access to img, css and js inside WEB-INF directory from jsp page?
Folder structure is:
webapp
- WEB-INF
- css
- js
- img
2) I have the class WebMvcConfig, extending WebMvcConfigurerAdapter:
#Configuration
#EnableWebMvc
#Import({BeanConfig.class, CacheConfig.class})
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("/resources/css/").setCachePeriod(31556926);
registry.addResourceHandler("/img/**").addResourceLocations("/resources/img/").setCachePeriod(31556926);
registry.addResourceHandler("/js/**").addResourceLocations("/resources/js/").setCachePeriod(31556926);
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ControllerInterceptor());
}
#Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Bean
public ContentNegotiatingViewResolver getContentNegotiatingViewResolver() {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
ArrayList<View> defaultViews = new ArrayList<View>();
MappingJacksonJsonView jsonView = new MappingJacksonJsonView();
jsonView.setPrefixJson(true);
defaultViews.add(new MappingJacksonJsonView());
resolver.setDefaultViews(defaultViews);
resolver.setOrder(1);
return resolver;
}
#Bean
public ControllerInterceptor getLoggingInterceptor() {
return new ControllerInterceptor();
}
}
I want to get access to folders: /resources/css, /resources/img and /resources/js,
Part of web.xml file:
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
config.WebMvcConfig
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Folder structure is:
webapp
- WEB-INF
- resources
- css
- js
- img
But it does not worked
Yes, you can do this.
registry.addResourceHandler("/css/**").addResourceLocations("/resources/css/").setCachePeriod(31556926);
And you have this structure
webapp
- WEB-INF
- resources
- css
- somefile.css
- js
- img
You would access your resources at
localhost:8080/context/css/somefile.css
will get the resource from /resources/css/somefile.css. Do the same for all the other resources.

Categories

Resources