How to enable logging in Spring Junit test? I think web.xml is not found when I do tests. Need to tell somehow to Junit where is web.xml with log configuration exists so logs will start working and I could bebug springs configuration errors.
My test class:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("test-context.xml")
public class DSLCapacityTest {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
#Autowired private DSLCapacity dc;
private AnnotationMethodHandlerAdapter adapter;
#Before
public void setUp() throws Exception {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
response.setOutputStreamAccessAllowed(true);
adapter = new AnnotationMethodHandlerAdapter();
}
#Test
#Repeat(2)
public void testGetIndex() throws Exception {
request.setRequestURI("/dashboard/dsl-capacity/");
request.setMethod("GET");
ModelAndView mv = adapter.handle(request, response, dc);
assertSame("Incorrect message", "dashboard/dsl-capacity/index", mv.getViewName());
}
And my test-context.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:sec="http://www.springframework.org/schema/security"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:amq="http://activemq.apache.org/schema/core"
xmlns:jms="http://www.springframework.org/schema/jms"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.2.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.8.0.xsd">
<bean id="portalAuthenticator" class="uk.co.powergroup.portal.security.Authenticator">
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:ignoreUnresolvablePlaceholders="false">
<property name="location">
<value>file:/etc/portal-frontend/config.properties</value>
</property>
</bean>
<sec:authentication-manager>
<sec:authentication-provider ref='portalAuthenticator'/>
</sec:authentication-manager>
<sec:http pattern="/favicon.ico" security="none"/>
<sec:http pattern="/static/**" security="none"/>
<sec:http pattern="/logged-out" security="none"/>
<sec:http pattern="/login" security="none"/>
<sec:http pattern="/**/nologin*" security="none"/>
<sec:http auto-config="false" use-expressions="true">
<sec:csrf disabled="true"/>
<sec:intercept-url pattern="/forgot-password" access="isAnonymous()"/>
<sec:intercept-url pattern="/**" access="isAuthenticated()" />
<sec:logout logout-url="/logout" logout-success-url="/logged-out"/>
<sec:form-login login-page="/login" login-processing-url="/login-security-check" authentication-failure-url="/login" />
<sec:custom-filter position="CONCURRENT_SESSION_FILTER" ref="concurrencyFilter" />
<sec:session-management session-authentication-strategy-ref="sas"/>
<sec:custom-filter ref="userValidator" after="FILTER_SECURITY_INTERCEPTOR" />
</sec:http>
<sec:global-method-security pre-post-annotations="enabled" secured-annotations="enabled">
<sec:expression-handler ref="expressionHandler"/>
</sec:global-method-security>
<bean id="userValidator" class="uk.co.powergroup.portal.security.UserValidator">
</bean>
<bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
<property name="permissionEvaluator" ref="myPermissionEvaluator"/>
</bean>
<bean id="myPermissionEvaluator" class="uk.co.powergroup.portal.security.PermissionChecker"/>
<bean id="concurrencyFilter" class="org.springframework.security.web.session.ConcurrentSessionFilter">
<constructor-arg name="sessionRegistry" ref="sessionRegistry" />
<constructor-arg name="expiredUrl" value="/login" />
</bean>
<bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl"/>
<bean id="sas" class="org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy">
<constructor-arg name="sessionRegistry" ref="sessionRegistry" />
<property name="maximumSessions" value="-1"/>
</bean>
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="persistenceUnitName" value="PORTAL2DB"/>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://10.10.10.249:3306/portal"/>
<property name="username" value="portal"/>
<property name="password" value="twink13s"/>
</bean>
<bean id="jmsFactory" class="org.apache.activemq.pool.PooledConnectionFactory"
destroy-method="stop">
<property name="connectionFactory">
<bean class="org.apache.activemq.spring.ActiveMQConnectionFactory">
<property name="brokerURL">
<value>${activemq.uri}</value>
</property>
<property name="password">
<value>${activemq.password}</value>
</property>
<property name="userName">
<value>${activemq.user}</value>
</property>
</bean>
</property>
<!-- Make this 2.5 minutes in case for some reason the JMS tester job stops (sends every minute so default of 30 seconds too short) -->
<property name="idleTimeout" value="150000"/>
</bean>
<!-- Spring JMS Template -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="jmsFactory"/>
<property name="receiveTimeout" value="1000"/>
<property name="sessionTransacted" value="false"/>
</bean>
<bean id="jmsMessageListener" class="uk.co.powergroup.portal.jms.ReplyHandler"/>
<jms:listener-container container-type="default" connection-factory="jmsFactory" acknowledge="auto"
concurrency="2-5">
<jms:listener destination="${activemq.replyQueue}" ref="jmsMessageListener"/>
</jms:listener-container>
<bean id="threadPool" class="uk.co.powergroup.portal.helper.ThreadPool"/>
<bean name="retryTransactionsFilterBean" class="uk.co.powergroup.portal.helper.RetryFilter"/>
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="uk.co.powergroup.portal.converters.PermissionConverter"/>
<bean class="uk.co.powergroup.portal.converters.RoleConverter"/>
<bean class="uk.co.powergroup.portal.converters.SuiteConverter"/>
<bean class="uk.co.powergroup.portal.converters.DataCentreConverter"/>
<bean class="uk.co.powergroup.portal.converters.DataCentreLocationConverter"/>
<bean class="uk.co.powergroup.portal.converters.CompanyConverter"/>
<bean class="uk.co.powergroup.portal.converters.HardwareConverter"/>
<bean class="uk.co.powergroup.portal.converters.RackConverter"/>
<bean class="uk.co.powergroup.portal.converters.EquipmentConverter"/>
<bean class="uk.co.powergroup.portal.converters.PowerDistributionUnitTypeConverter"/>
<bean class="uk.co.powergroup.portal.converters.TimeZoneDOConverter"/>
<bean class="uk.co.powergroup.portal.converters.DslLnsBearerTypeConverter"/>
<bean class="uk.co.powergroup.portal.converters.DslLnsLocationConverter"/>
<bean class="uk.co.powergroup.portal.converters.DslLnsOrganisationConverter"/>
<bean class="uk.co.powergroup.portal.converters.DslLnsConverter"/>
<bean class="uk.co.powergroup.portal.converters.BigDecimalConverter"/>
<bean class="uk.co.powergroup.portal.converters.PstnNumberDDIConverter"/>
</set>
</property>
</bean>
<context:component-scan base-package="uk.co.powergroup.portal.dao.impl"
name-generator="uk.co.powergroup.portal.misc.BeanNameGeneratorImpl"/>
You can do configuration for log4j.properties in your test case file so it will create log for you.
#BeforeClass
public static void init() {
PropertyConfigurator.configure("src/configuration/log4j.properties");
}
Java web containers mainly used web.xml file and also web.xml file not belongs to Spring context configuration.
Related
I am trying to implement token based authentication with spring security.
Planning to use Header based authentication token.
My web.xml file is this
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>api</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/api-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>api</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>0</session-timeout>
</session-config>
</web-app>
my admin servlet is this
<?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"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<context:property-placeholder location="/WEB-INF/database.properties" />
<context:component-scan base-package="com.netphenix.employee.api" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="defaultContentType" value="text/html"/>
<property name="ignoreAcceptHeader" value="true"/>
<property name="favorPathExtension" value="true"/>
<property name="order" value="1"/>
<property name="mediaTypes">
<map>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<!-- Use tiles2 for views -->
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView" />
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<ref bean="jsonView"/>
</list>
</property>
</bean>
<bean id="jsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="contentType" value="application/json;charset=UTF-8"/>
</bean>
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${database.driver}" />
<property name="jdbcUrl" value="${database.url}" />
<property name="user" value="${database.user}" />
<property name="password" value="${database.password}" />
<property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
<property name="minPoolSize" value="${jdbc.minPoolSize}" />
<property name="maxStatements" value="${jdbc.maxStatements}" />
<property name="testConnectionOnCheckout" value="${jdbc.testConnection}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.netphenix.employee.model"/>
<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.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
<bean id="freemarkerConfigFactory" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
<property name="templateLoaderPath" value="classpath:templates/"/>
</bean>
<!--
<bean id="daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userDetailsService"/>
</bean>
<bean id= "authenticationManager" class= "org.springframework.security.authentication.ProviderManager">
<constructor-arg>
<list>
<bean class= "org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userDetailsService"/>
</bean>
</list>
</constructor-arg>
</bean>-->
<sec:http>
<sec:intercept-url pattern="/login.html"/>
<sec:intercept-url pattern="/api/**" access="ROLE_ADMIN" />
<sec:form-login login-page="/login.html"
authentication-failure-url="/login.html?error=failed"
login-processing-url="/login-please.html" />
<sec:logout logout-url="/logoff-please.html"
logout-success-url="/logoff.html" />
</sec:http>
<sec:authentication-manager>
<sec:authentication-provider user-service-ref="userDetailsService">
<sec:password-encoder hash="md5"/>
</sec:authentication-provider>
</sec:authentication-manager>
<sec:http auto-config="true">
<sec:intercept-url pattern="/api/**" access="ROLE_ADMIN" />
<sec:logout logout-success-url="/login" />
</sec:http>
<sec:authentication-manager>
<sec:authentication-provider>
<sec:user-service>
<sec:user name="mkyong" password="password" authorities="ROLE_USER" />
<sec:user name="eclipse" password="password" authorities="ROLE_ADMIN" />
</sec:user-service>
</sec:authentication-provider>
</sec:authentication-manager>
<sec:global-method-security pre-post-annotations="enabled" />
</beans>
EDIT: UserDetailsService
#Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired
private UserDao userDao;
#Autowired
private Assembler assembler;
#Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
UserDetails userDetails = null;
// User userEntity = userDao.getUser(username);
User userEntity = new User();
userEntity.setUsername("admin");
userEntity.setPassword("$2a$10$hbxecwitQQ.dDT4JOFzQAulNySFwEpaFLw38jda6Td.Y/cOiRzDFu");
if (userEntity == null)
throw new UsernameNotFoundException("user not found");
return assembler.buildUserFromUserEntity(userEntity);
}
}
API works okay. but its not getting authenticated. Which means, even for the url which requires ROLE_ADMIN also works without any authentication. Any pointer towards fixing this will be helpful.
I have Spring project which produces 42MB war file. Whenever I deploy it in a server it is taking more than an hour with tomcat 7. Even in development environment it is consuming more than 20 mins in the local environment if we make any changes in it.
I suspect I have a major mistake.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
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:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util" xmlns:cache="http://www.springframework.org/schema/cache"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
<context:component-scan base-package="com.abc.xyz.server.filters" />
<context:component-scan base-package="com.abc.xyz.server.utils" />
<context:component-scan base-package="com.abc.xyz.server.application.Bean" />
<context:component-scan
base-package="com.abc.xyz.server.application.controllers" />
<context:component-scan
base-package="com.abc.xyz.server.application.services" />
<jpa:repositories
base-package="com.abc.xyz.server.application.repositories" />
<mvc:annotation-driven>
<mvc:message-converters>
<!-- Use the HibernateAware mapper instead of the default -->
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean
class="com.abc.xyz.server.utils.HibernateAwareObjectMapper" />
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- <bean id="jdbcEmployeeDAO" class="com.abc.xyz.server.application.model.dao.JDBCEmployeeDAOImpl">
</bean> -->
<bean id="jdbcProperty"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>/WEB-INF/application.properties</value>
</property>
</bean>
<bean id="abstractDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:username="${jdbc.username}" p:password="${jdbc.password}">
<property name="initialSize" value="0" />
<property name="maxIdle" value="1" />
<property name="minIdle" value="0" />
<property name="validationQuery" value="SELECT 1" />
<property name="testOnBorrow" value="true" />
<property name="testWhileIdle" value="true" />
<property name="timeBetweenEvictionRunsMillis" value="180000" />
<property name="numTestsPerEvictionRun" value="100" />
<property name="minEvictableIdleTimeMillis" value="120000" />
<property name="removeAbandonedTimeout" value="60" />
<property name="logAbandoned" value="true" />
<property name="maxActive" value="30" />
<property name="maxWait" value="3000" />
<property name="removeAbandoned" value="true" />
</bean>
<bean id="concreteDataSourceOne" parent="abstractDataSource"
p:url="${jdbc.databaseurlOne}" />
<bean id="concreteDataSourceTwo" parent="abstractDataSource"
p:url="${jdbc.databaseurlTwo}" />
<bean id="concreteDataSourceDev" parent="abstractDataSource"
p:url="${jdbc.databaseurlDev}" />
<bean id="concreteDataSourceGlace" parent="abstractDataSource"
p:url="${jdbc.databaseurlGlace}" />
<bean id="dataSource"
class="com.abc.xyz.server.datasource.TennantAwareDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="database2" value-ref="concreteDataSourceTwo" />
<entry key="database1" value-ref="concreteDataSourceOne" />
<entry key="dev" value-ref="concreteDataSourceDev" />
<entry key="glace" value-ref="concreteDataSourceGlace" />
</map>
</property>
<property name="defaultTargetDataSource" ref="concreteDataSourceGlace" />
</bean>
<bean id="objectmapper" class="com.fasterxml.jackson.databind.ObjectMapper"></bean>
<bean id="EntityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:persistenceUnitName="PersistenceUnit" p:dataSource-ref="dataSource">
<!-- THIS IS WHERE THE MODELS ARE -->
<property name="packagesToScan"
value="com.abc.xyz.server.application.models" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:showSql="${hibernate.show_sql}" p:generateDdl="false"
p:databasePlatform="${hibernate.dialect}" />
</property>
</bean>
<!-- Ecache related stuff -->
<!-- <cache:annotation-driven /> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cache-manager-ref="ehcache"/> <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:config-location="classpath:ehcache.xml" p:shared="true"/> -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="EntityManagerFactory" />
</bean>
<tx:annotation-driven />
<bean id="sessionMap" class="com.abc.xyz.server.utils.SessionMap"
scope="session">
<!-- this next element effects the proxying of the surrounding bean -->
<aop:scoped-proxy />
</bean>
<!-- Configuration Bean -->
<mvc:default-servlet-handler />
<mvc:interceptors>
<bean class="com.abc.xyz.server.utils.EMRRequestInterceptor" />
</mvc:interceptors>
<!-- Swagger --><!--
<context:property-placeholder location="classpath:/swagger.properties" />
<bean id="springSwaggerConfig"
class="com.mangofactory.swagger.configuration.SpringSwaggerConfig" /> -->
<!-- File Upload --> <!--
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /> -->
I also get GC messages like this in the console.
[GC [PSYoungGen: 605920K->128K(660480K)] 1237105K->631313K(2058752K),
0.0141920 secs] [Times: user=0.03 sys=0.00, real=0.02 secs]
I am using Spring framework with Security in my web application. I have a Guest user and its privileges in my db but I can't implement AnonymousAuthenticationFilter and AnonymousAuthenticationProvider to use that user. Here is my appSecurity configuration:
<?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" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
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/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<bean id="loginUrlAuthenticationEntryPoint"
class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"
p:loginFormUrl="/login" p:useForward="false" p:forceHttps="false" />
<bean id="successHandler"
class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler"
p:defaultTargetUrl="/" />
<bean id="failureHandler"
class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"
p:defaultFailureUrl="/login?error=true" p:useForward="false" />
<bean id="accessDeniedHandler"
class="com.asosyalbebe.springtest.gui.user.security.CustomAccessDeniedHandler">
<property name="accessDeniedUrl" value="/accessDenied" />
</bean>
<bean id="userDetailsService"
class="com.asosyalbebe.springtest.gui.user.service.UserServiceImpl" />
<bean id="tokenBasedRememberMeServices"
class="com.asosyalbebe.springtest.gui.user.security.CustomRememberMeServices">
<property name="alwaysRemember" value="true" />
<property name="key" value="abcdef123456" />
<property name="parameter" value="remember" />
<property name="cookieName" value="_ab_memo" />
<property name="userDetailsService" ref="userDetailsService" />
</bean>
<bean id="authenticationProcessingFilter"
class="com.asosyalbebe.springtest.gui.user.security.AuthenticationProcessingFilter">
<property name="filterProcessesUrl" value="/j_spring_security_check" />
<property name="authenticationManager" ref="authenticationManager" />
<property name="postOnly" value="true" />
<property name="authenticationSuccessHandler" ref="successHandler" />
<property name="authenticationFailureHandler" ref="failureHandler" />
<property name="rememberMeServices" ref="tokenBasedRememberMeServices" />
</bean>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider
ref="anonymousAuthProvider" />
<security:authentication-provider
ref="rememberMeAuthProvider" />
<security:authentication-provider
ref="customAuthenticationProvider" />
</security:authentication-manager>
<bean id="anonymousAuthProvider" class="com.asosyalbebe.springtest.gui.user.security.CustomAnonymousAuthProvider">
<property name="userDetailsService" ref="userDetailsService" />
<property name="key" value="foobar" />
</bean>
<bean name="rememberMeAuthProvider"
class="org.springframework.security.authentication.RememberMeAuthenticationProvider">
<property name="key" value="xy1245aazpo98qwe" />
</bean>
<bean id="customAuthenticationProvider"
class="com.asosyalbebe.springtest.gui.user.security.UserAuthenticationProvider">
<property name="userDetailsService" ref="userDetailsService" />
</bean>
<bean id="securityContextPersistenceFilter"
class="org.springframework.security.web.context.SecurityContextPersistenceFilter">
<property name='securityContextRepository'>
<bean
class='org.springframework.security.web.context.HttpSessionSecurityContextRepository'>
<property name='allowSessionCreation' value='false' />
</bean>
</property>
</bean>
<bean id="customLogoutSuccessHandler" class="com.asosyalbebe.springtest.gui.user.security.CustomLogoutSuccessHandler" />
<bean id="logoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
<constructor-arg ref="customLogoutSuccessHandler" />
<constructor-arg>
<list>
<bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler" />
<ref bean="tokenBasedRememberMeServices"/>
</list>
</constructor-arg>
</bean>
<bean name="rememberMeAuthenticationFilter" class="org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter">
<property name="authenticationManager" ref="authenticationManager" />
<property name="rememberMeServices" ref="tokenBasedRememberMeServices" />
</bean>
<bean id="anonymousProcessingFilter" class="org.springframework.security.web.authentication.AnonymousAuthenticationFilter">
<property name="key" value="foobar" />
<property name="userAttribute" value="anonymousUser,PRIV_ANONYMOUS" />
</bean>
<bean id="exceptionTranslationFilter" class="org.springframework.security.web.access.ExceptionTranslationFilter">
<property name="authenticationEntryPoint" ref="loginUrlAuthenticationEntryPoint" />
<property name="accessDeniedHandler" ref="accessDeniedHandler"/>
</bean>
<bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter">
<property name="rolePrefix" value="PRIV_"/>
</bean>
<bean id="accessDecisionManager" class="com.asosyalbebe.springtest.gui.user.security.CustomAccessDecisionManager">
<property name="allowIfAllAbstainDecisions" value="false" />
<property name="decisionVoters">
<list>
<ref bean="roleVoter" />
</list>
</property>
</bean>
<bean id="securityMetadataSource" class="com.asosyalbebe.springtest.gui.user.security.CustomFilterInvocationDefinitionSource"/>
<bean id="filterInvocationInterceptor" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
<property name="authenticationManager" ref="authenticationManager" />
<property name="accessDecisionManager" ref="accessDecisionManager" />
<property name="securityMetadataSource" ref="securityMetadataSource" />
<property name="rejectPublicInvocations" value="false"/>
</bean>
<bean id="filterChainProxy" class="org.springframework.security.web.FilterChainProxy">
<security:filter-chain-map path-type="ant">
<security:filter-chain pattern="/**"
filters="securityContextPersistenceFilter,
logoutFilter,
authenticationProcessingFilter,
rememberMeAuthenticationFilter,
anonymousProcessingFilter,
exceptionTranslationFilter,
filterInvocationInterceptor" />
</security:filter-chain-map>
</bean>
</beans>
And here is my Custom Anonymous Authentication Provider:
package com.asosyalbebe.springtest.gui.user.security;
import org.springframework.security.authentication.AnonymousAuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import com.asosyalbebe.springtest.gui.user.model.GuiUser;
import com.asosyalbebe.springtest.gui.user.service.UserService;
#SuppressWarnings("deprecation")
public class CustomAnonymousAuthProvider extends AnonymousAuthenticationProvider {
private UserService userDetailsService;
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
GuiUser user = userDetailsService.getGuestUser();
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(user, "pwd", user.getAuthorities());
result.setDetails(user);
return result;
}
#Override
public boolean supports(Class<?> class1) {
return true;
}
public void setUserDetailsService(UserService userDetailsService) {
this.userDetailsService = userDetailsService;
}
}
I think the authenticate method in CustomAnonymousAuthProvider is never executed. What else can I do?
From the AuthenticationManager's perspective, the AnonymousAuthenticationToken which is created by then filter is already authenticated (the isAuthenticated property is true), so it doesn't try to authenticate it. Hence your provider is not called.
The simplest option would be to customize the AnonymousAuthenticationFilter to use the authorities from your database directly.
I am trying to access a property file containing db configurations in a Maven + Spring project.
I get following error:
Cannot load JDBC driver class '${db_driver}'
My Property file is placed in src/resources folder.
Below is the tag to load property files:
<bean id="dbPropertyReader"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="1" />
<property name="locations">
<value>classpath:${appenv.deployment}.properties</value>
</property>
</bean>
Following tag uses properties loaded:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="url" value="${db_url}" />
<property name="driverClassName" value="${db_driver}" />
<property name="username" value="${db_username}" />
<property name="password" value="${db_password}" />
</bean>
Below are contents of properties file:
#JDBC Properties
db_driver=com.mysql.jdbc.Driver
db_url=jdbc\:mysql\://hostname\:3306/xxx_dbxxx?useUnicode\=true
db_username=abcdefgh
db_password=ijklmnopq
db_removeabadoned=true
db_initialsize=1
db_maxactive=2
${appenv.deployment} is a VMArgument set as follows:
-Dappenv.deployment=development
I have checked, this value is getting populated properly.
I am getting following line in logs:
Found key 'appenv.deployment' in [systemProperties] with type [String] and value 'development'
Then after this I am also getting following:
Loading properties file from class path resource [development.properties]
But some how, the values are not getting loaded.
Spring-Datasource.xml
<beans xmlns="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-2.5.xsd">
<bean id="dbPropertyReader"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="1" />
<property name="locations">
<value>classpath:${appenv.deployment}.properties</value>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="url" value="${db_url}" />
<property name="driverClassName" value="${db_driver}" />
<property name="username" value="${db_username}" />
<property name="password" value="${db_password}" />
<property name="initialSize" value="${db_initialsize}" />
<property name="maxActive" value="${db_maxactive}" />
</bean>
<bean id="firstConfigDataFromDB" class="org.apache.commons.configuration.DatabaseConfiguration">
<constructor-arg type="javax.sql.DataSource" ref="dataSource" />
<constructor-arg index="1" value="tablename1" />
<constructor-arg index="2" value="propertyname2" />
<constructor-arg index="3" value="propertyvalue2" />
</bean>
<bean id="firstConfigDataFromDBFactory"
class="org.springmodules.commons.configuration.CommonsConfigurationFactoryBean">
<constructor-arg ref="firstConfigDataFromDB" />
</bean>
<!-- DB Properties Initialization -->
<bean id="firstConfigurationPlaceHolder"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="2" />
<property name="ignoreUnresolvablePlaceholders" value="false"/>
<property name="properties" ref="firstConfigDataFromDBFactory" />
</bean>
<bean id="secondConfigurationFromDB"
class="org.apache.commons.configuration.DatabaseConfiguration">
<constructor-arg type="javax.sql.DataSource" ref="dataSource" />
<constructor-arg index="1" value="tablename2" />
<constructor-arg index="2" value="propertyname2" />
<constructor-arg index="3" value="propertyvalue2" />
</bean>
<bean id="secondConfigurationFromDBFactory"
class="org.springmodules.commons.configuration.CommonsConfigurationFactoryBean">
<constructor-arg ref="secondConfigurationFromDB" />
</bean>
<!--
Error Map Initialization
Subtype of org.springframework.beans.factory.config.PropertyPlaceholderConfigurer
-->
<bean id="secondConfigurationPlaceHolder"
class="com.application.SecondConfigurationPlaceHolder">
<property name="order" value="3" />
<property name="ignoreUnresolvablePlaceholders" value="false"/>
<property name="properties" ref="secondConfigurationFromDBFactory" />
</bean>
</beans>
Generic.xml
<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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"
>
<!-- Enable annotation scanning -->
<context:annotation-config/>
<!-- Initialise connection to Database -->
<import resource="Spring-Datasource.xml"/>
<!-- Initialize mail connection -->
<import resource="Spring-Mail.xml"/>
<!-- Inject database connection to DAO -->
<import resource="Spring-DAO.xml"/>
<!-- Other Beans Below -->
</beans>
applicationContext.xml
<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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"
>
<import resource="generic.xml" />
<bean id="applicationBean" class="com.application.ApplicationBean" scope="singleton" >
<property .. />
<property .. />
</bean>
</beans>
I am loading applicationContext.xml with following statement in code:
`appContext = new ClassPathXmlApplicationContext("applicationContext.xml");`
applicationContext.xml imports generic.xml.
generic.xml imports Spring-DataSource.xml.
have you added this to your application context file
<context:property-placeholder location="Path for .properties file"/>
add this line before the beans
I have following code:
//preparing DAO objects
FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("test-context.xml");
surveyDao = (SurveyDao)context.getBean("surveyDao");
recordDao = (RecordDao)context.getBean("recordDao");
//creating GUI
createWindow();
The problem is that it runs perfectly in Eclipse, but when I export it to executable jar it crashes with following
org.springframework.beans.factory.parsing.BeanDefinitionParsingException
unable to locate Spring NameSpaceHandler for XML schema namespace
[http://www.springframework.org/schema/tx]
Offending resource: file test-context.xml
test-context.xml file:
<?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"
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:util="http://www.springframework.org/schema/util"
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://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"
default-lazy-init="true"
default-autowire="byName">
<context:annotation-config/>
<!-- <bean id="applicationContextProvider" class="org.openforis.collect.context.ApplicationContextAwareImpl" /> -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="file:${user.dir}/dev.properties"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="${collect.devdb.url}"/>
<property name="username" value="${collect.devdb.username}" />
<property name="password" value="${collect.devdb.password}" />
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="surveyDao" class="org.openforis.collect.persistence.SurveyDao" init-method="init">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="logoDao" class="org.openforis.collect.persistence.LogoDao">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="recordDao" class="org.openforis.collect.persistence.RecordDao">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="taxonomyDao" class="org.openforis.collect.persistence.TaxonomyDao">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="taxonDao" class="org.openforis.collect.persistence.TaxonDao">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dynamicTableDao" class="org.openforis.collect.persistence.DynamicTableDao">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="myTest" class="com.arbonaut.collcomm.main.MyTest" init-method="init" />
<!-- Managers -->
<bean id="recordManager" class="org.openforis.collect.manager.RecordManager" init-method="init" />
<bean id="surveyManager" class="org.openforis.collect.manager.SurveyManager" init-method="init" />
<!-- Expression Factory -->
<bean id="expressionFactory" class="org.openforis.idm.model.expression.ExpressionFactory" />
<bean id="validator" class="org.openforis.idm.metamodel.validation.Validator" />
<bean id="externalCodeListProvider" class="org.openforis.collect.persistence.DatabaseExternalCodeListProvider" />
<bean id="taxonVernacularNameDao" class="org.openforis.collect.persistence.TaxonVernacularNameDao">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- enables interpretation of the #Transactional annotations for declarative transaction management-->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
</beans>
Have you got the spring-tx jar on the classpath / rebundled into your executable jar?
spring-tx-3.1.0-RELEASE.jar contains the xsd http://www.springframework.org/schema/tx/spring-tx-3.1.xsd:
/org/springframework/transaction/config/spring-tx-3.1.xsd