I have a working Spring application compiled with maven and deployed on tomcat 7.
I'm trying to implements some test cases using JUnit 4. I successfully make some test for a part of the application but I get compilation problem when I want to test two parts which used external framework: Shiro and OIOSAML. Since there is no OIOSAML community here, I'll focus on shiro but I believe that the cause of the problem is the same.
When I try to load the application-context in the JUnit test, I obtains loading errors (see next). It looks like some dependencies can't be loaded/found in the frameworks part. Here is some helpful information:
Shiro exception:
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'authorization' defined in class path resource [test-context.xml]:
Instantiation of bean failed;
nested exception is org.springframework.beans.BeanInstantiationException:
Could not instantiate bean class [myPackage.ShiroAuthorization]:
Constructor threw exception; nested exception is org.apache.shiro.config.ConfigurationException:
Unable to instantiate class [com.mysql.jdbc.jdbc2.optional.MysqlDataSource] for object named 'ds'.
Please ensure you've specified the fully qualified class name correctly.
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1035)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:939)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at myPackage.Test.init(Test.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [myPackage.ShiroAuthorization]: Constructor threw exception; nested exception is org.apache.shiro.config.ConfigurationException: Unable to instantiate class [com.mysql.jdbc.jdbc2.optional.MysqlDataSource] for object named 'ds'. Please ensure you've specified the fully qualified class name correctly.
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:162)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:110)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:280)
... 29 more
Caused by: org.apache.shiro.config.ConfigurationException: Unable to instantiate class [com.mysql.jdbc.jdbc2.optional.MysqlDataSource] for object named 'ds'. Please ensure you've specified the fully qualified class name correctly.
at org.apache.shiro.config.ReflectionBuilder.createNewInstance(ReflectionBuilder.java:151)
at org.apache.shiro.config.ReflectionBuilder.buildObjects(ReflectionBuilder.java:119)
at org.apache.shiro.config.IniSecurityManagerFactory.buildInstances(IniSecurityManagerFactory.java:161)
at org.apache.shiro.config.IniSecurityManagerFactory.createSecurityManager(IniSecurityManagerFactory.java:124)
at org.apache.shiro.config.IniSecurityManagerFactory.createSecurityManager(IniSecurityManagerFactory.java:102)
at org.apache.shiro.config.IniSecurityManagerFactory.createInstance(IniSecurityManagerFactory.java:88)
at org.apache.shiro.config.IniSecurityManagerFactory.createInstance(IniSecurityManagerFactory.java:46)
at org.apache.shiro.config.IniFactorySupport.createInstance(IniFactorySupport.java:123)
at org.apache.shiro.util.AbstractFactory.getInstance(AbstractFactory.java:47)
at myPackage.ShiroAuthorization.<init>(ShiroAuthorization.java:31)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
... 31 more
Caused by: org.apache.shiro.util.UnknownClassException: Unable to load class named [com.mysql.jdbc.jdbc2.optional.MysqlDataSource] from the thread context, current, or system/application ClassLoaders. All heuristics have been exhausted. Class could not be found.
at org.apache.shiro.util.ClassUtils.forName(ClassUtils.java:148)
at org.apache.shiro.util.ClassUtils.newInstance(ClassUtils.java:164)
at org.apache.shiro.config.ReflectionBuilder.createNewInstance(ReflectionBuilder.java:144)
... 45 more
Shiro.ini
...
ds = com.mysql.jdbc.jdbc2.optional.MysqlDataSource
ds.url = jdbc:mysql://*******
...
jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled=true
jdbcRealm.dataSource = $ds
...
securityManager.realms = $jdbcRealm,
...
OIOSAML exception:
...Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/opensaml/xml/ConfigurationException...
Test Case
...
public static ApplicationContext context;
#BeforeClass
public static void init() throws Exception {
context = new ClassPathXmlApplicationContext("test-context.xml");
}
I tried to play with the context file but nothing helps. Which is strange is I can successfully test the connection pool of tomcat 7 which shows that dependencies are correctly loaded.
I remind you that everything works except when I want to test it with JUnit.
Do you have mySql driver in your classpath? Probably that's the problem.
Try to annotate your JUnit test class using:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {
"classpath:/test-context.xml"
})
This loads your applicationContext when running your JUnit tests.
Make sure your applicationContext xml is on your classpath.
Related
I have a Soap Web Service developed using Spring WS. I want to create Junit test cases that test the service before it moves to other environments ( from dev to sit to uat to prod).
I am trying to use Spring test's MockWebServiceClient like this
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:WEB-INF/spring-ws-servlet.xml" })
public class AccountSearchEndpointTests {
#Autowired
private ApplicationContext applicationContext;
private MockWebServiceClient mockClient;
#Before
public void createClient() {
mockClient = MockWebServiceClient.createClient(applicationContext);
}
#Test
public void testWsEndPointTest() throws Exception {
StringSource requestPayload = new StringSource(
""); //omitted actual request
StringSource responsePayload = new StringSource(""); //omitted actual response
mockClient.sendRequest(withPayload(requestPayload)).andExpect(payload(responsePayload));
}
However the error i get is
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:308)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:220)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:301)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:303)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bean' defined in class path resource [WEB-INF/spring-ws-servlet.xml]: Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:84)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:1)
at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:280)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:304)
... 24 more
Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:350)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at com.bean.initialize(bean.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1581)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1522)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
... 37 more
This is the bean in spring-ws-servlet
<bean id="bean" init-method="initialize" destroy-method="terminate"
class="com.bean" />
and in the initialize of bean this happens
ctx = new InitialContext();
ds = (DataSource) ctx.lookup(DS_NAME);
I understand that the webservice should be running in a container like tomcat, but then i want to know how can i mock it/ configure something in spring test for it. Essentially i want to know how can i go about testing the webservice using junit!
This is essentially a duplicate of https://stackoverflow.com/a/5947016/388980.
So check out the solutions discussed there.
In summary, you should not be performing JDNI look-ups directly within your code. Instead, you should externalize the JDNI lookup in your Spring configuration and then only have Spring inject the DataSource into your components.
You can then use an embedded database (e.g., H2, HSQL, Derby -- Spring supports all three of those) while testing and inject the DataSource for the embedded database into your components.
As an alternative, you could move the data access code to a dedicated Repository or DAO implementation and inject a mock for that into your Web Service endpoints -- for example, using Mockito.
If you're not familiar with bean definition profiles in Spring, you should read the corresponding sections of the Spring Reference Manual. The Testing chapter demonstrates how to use profiles prod for production and dev in your tests.
I have a Spring Boot application that I would like to add Spring Security too. So I've added the following configuration, which starts and runs just fine:
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Resource
private Environment environment;
#Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
if(environment.acceptsProfiles("live")) {
http.requiresChannel().anyRequest().requiresSecure();
}
http.csrf().disable();
}
}
The problem is that my functional tests fail to load the application context. All functional tests extend from the following configuration:
#ContextConfiguration(loader = SpringApplicationContextLoader.class, classes = MyConfiguration.class)
#WebAppConfiguration
#IntegrationTest
class ContextInitializer extends GebReportingSpec {
}
When the tests attempts to load the application, it throws the following stack trace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:835)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:117)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:689)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:321)
at org.springframework.boot.test.SpringApplicationContextLoader.loadContext(SpringApplicationContextLoader.java:103)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)
at org.spockframework.spring.SpringTestContextManager.prepareTestInstance(SpringTestContextManager.java:49)
at org.spockframework.spring.SpringInterceptor.interceptSetupMethod(SpringInterceptor.java:42)
at org.spockframework.runtime.extension.AbstractMethodInterceptor.intercept(AbstractMethodInterceptor.java:28)
at org.spockframework.runtime.extension.MethodInvocation.proceed(MethodInvocation.java:87)
at org.spockframework.runtime.BaseSpecRunner.invoke(BaseSpecRunner.java:471)
at org.spockframework.runtime.BaseSpecRunner.runSetup(BaseSpecRunner.java:375)
at org.spockframework.runtime.BaseSpecRunner.runSetup(BaseSpecRunner.java:370)
at org.spockframework.runtime.BaseSpecRunner.doRunIteration(BaseSpecRunner.java:323)
at org.spockframework.runtime.BaseSpecRunner$6.invoke(BaseSpecRunner.java:309)
at org.spockframework.runtime.extension.MethodInvocation.proceed(MethodInvocation.java:88)
at org.spockframework.runtime.extension.builtin.AbstractRuleInterceptor$1.evaluate(AbstractRuleInterceptor.java:37)
at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
at org.spockframework.runtime.extension.builtin.TestRuleInterceptor.intercept(TestRuleInterceptor.java:38)
at org.spockframework.runtime.extension.MethodInvocation.proceed(MethodInvocation.java:87)
at org.spockframework.runtime.BaseSpecRunner.invoke(BaseSpecRunner.java:471)
at org.spockframework.runtime.BaseSpecRunner.runIteration(BaseSpecRunner.java:288)
at org.spockframework.runtime.BaseSpecRunner.initializeAndRunIteration(BaseSpecRunner.java:278)
at org.spockframework.runtime.BaseSpecRunner.runSimpleFeature(BaseSpecRunner.java:269)
at org.spockframework.runtime.BaseSpecRunner.doRunFeature(BaseSpecRunner.java:263)
at org.spockframework.runtime.BaseSpecRunner$5.invoke(BaseSpecRunner.java:246)
at org.spockframework.runtime.BaseSpecRunner.invokeRaw(BaseSpecRunner.java:480)
at org.spockframework.runtime.BaseSpecRunner.invoke(BaseSpecRunner.java:463)
at org.spockframework.runtime.BaseSpecRunner.runFeature(BaseSpecRunner.java:238)
at org.spockframework.runtime.BaseSpecRunner.runFeatures(BaseSpecRunner.java:188)
at org.spockframework.runtime.BaseSpecRunner.doRunSpec(BaseSpecRunner.java:98)
at org.spockframework.runtime.BaseSpecRunner$1.invoke(BaseSpecRunner.java:84)
at org.spockframework.runtime.BaseSpecRunner.invokeRaw(BaseSpecRunner.java:480)
at org.spockframework.runtime.BaseSpecRunner.invoke(BaseSpecRunner.java:463)
at org.spockframework.runtime.BaseSpecRunner.runSpec(BaseSpecRunner.java:76)
at org.spockframework.runtime.BaseSpecRunner.run(BaseSpecRunner.java:67)
at org.spockframework.runtime.Sputnik.run(Sputnik.java:63)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:105)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:56)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:64)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:50)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:106)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:360)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 78 common frames omitted
Caused by: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.util.Assert.notNull(Assert.java:115)
at org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer.<init>(DefaultServletHandlerConfigurer.java:53)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping(WebMvcConfigurationSupport.java:426)
at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$4bbac173.CGLIB$defaultServletHandlerMapping$25(<generated>)
at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$4bbac173$$FastClassBySpringCGLIB$$59db630c.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:318)
at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$4bbac173.defaultServletHandlerMapping(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 79 common frames omitted
Seems like I need to let the Integration test context loader know about the spring security somehow.
EDIT:
I've narrowed the problem down to a converter that pulls in a PasswordEncoder. Removing the converter and using the PasswordEncoder directly in the controller causes the problem to go away. Also, removing the Security Configuration will allow me to use the Converter just fine.
Here is a link to a repository I made that replicates the issue:
https://github.com/StephenTurley/SpringBootSecurityTest.git
The last commit causes the error. Not sure why I can't use spring converters and Spring security. Any ideas?
I suspect this is an initialization issue that is fixed by adding DelegatingFilterProxy support in Boot 1.3. I sent you a pull request that resolves the issue by updating to Spring Boot 1.3.2.RELEASE. It also resolves a few other dependency issues I was having.
Came across the same problem sometime back and fixed it adding javax.servlet-api and jsp-api in test scope, can you try adding same dependencies, below for reference:
For Maven:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
For Gradle:
testCompile "javax.servlet:javax.servlet-api:3.0.1"
testCompile "javax.servlet:jsp-api:2.0"
Also make sure you have spring-test dependency in test scope in your classpath.
I think in you application context shoul include the security context, so try to add that in you application context:
#Configuration
#Import({
SecurityConfiguration.class
})
#ComponentScan(basePackages = {
})
public class ApplicationContext {
}
Anothing, I think SecurityConfiguration should be called as SecurityContext.
I may be lacking some context information here but have you tried:
#EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class,WebMvcAutoConfiguration.class })
Maybe one of your #Configuration classes is annotated with #EnableWebMvc??
We are trying to substitute commons-logging + log4j by jcl-over-slf4j and logback (OK, at first we will try jcl-over-slf4j and log4j). Our application runs under WAS 8.0. Once the commons-logging jar has been erased and substituted by jcl-over-slf4j, slf4j and slf4j-log4j, we get this error message:
[21/11/14 16:12:08:430 CET] 0000006a webapp E com.ibm.ws.webcontainer.webapp.WebApp commonInitializationFinally SRVE0266E: Se ha producido un error al inicializar los servlets: {0}
javax.servlet.ServletException: SRVE0207E: No se ha detectado la excepción de inicialización creada por el servlet
at com.ibm.ws.webcontainer.servlet.ServletWrapper.init(ServletWrapper.java:404)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.init(ServletWrapperImpl.java:168)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.loadOnStartupCheck(ServletWrapper.java:1366)
at com.ibm.ws.webcontainer.webapp.WebApp.doLoadOnStartupActions(WebApp.java:615)
at com.ibm.ws.webcontainer.webapp.WebApp.commonInitializationFinally(WebApp.java:584)
at com.ibm.ws.webcontainer.webapp.WebAppImpl.initialize(WebAppImpl.java:421)
at com.ibm.ws.webcontainer.webapp.WebGroupImpl.addWebApplication(WebGroupImpl.java:88)
at com.ibm.ws.webcontainer.VirtualHostImpl.addWebApplication(VirtualHostImpl.java:169)
at com.ibm.ws.webcontainer.WSWebContainer.addWebApp(WSWebContainer.java:749)
at com.ibm.ws.webcontainer.WSWebContainer.addWebApplication(WSWebContainer.java:634)
at com.ibm.ws.webcontainer.component.WebContainerImpl.install(WebContainerImpl.java:422)
at com.ibm.ws.webcontainer.component.WebContainerImpl.start(WebContainerImpl.java:714)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:1164)
at com.ibm.ws.runtime.component.DeployedApplicationImpl.fireDeployedObjectStart(DeployedApplicationImpl.java:1369)
at com.ibm.ws.runtime.component.DeployedModuleImpl.start(DeployedModuleImpl.java:639)
at com.ibm.ws.runtime.component.DeployedApplicationImpl.start(DeployedApplicationImpl.java:967)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplication(ApplicationMgrImpl.java:770)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplicationDynamically(ApplicationMgrImpl.java:1361)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:2162)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:446)
at com.ibm.ws.runtime.component.CompositionUnitImpl.start(CompositionUnitImpl.java:123)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:389)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.access$500(CompositionUnitMgrImpl.java:117)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl$1.run(CompositionUnitMgrImpl.java:664)
at com.ibm.ws.security.auth.ContextManagerImpl.runAs(ContextManagerImpl.java:5468)
at com.ibm.ws.security.auth.ContextManagerImpl.runAsSystem(ContextManagerImpl.java:5594)
at com.ibm.ws.security.core.SecurityContext.runAsSystem(SecurityContext.java:255)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.startCompositionUnit(CompositionUnitMgrImpl.java:678)
at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.startCompositionUnit(CompositionUnitMgrImpl.java:622)
at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplication(ApplicationMgrImpl.java:1251)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:57)
at sun.reflect.GeneratedMethodAccessor71.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:260)
at javax.management.modelmbean.RequiredModelMBean$4.run(RequiredModelMBean.java:1141)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:86)
at javax.management.modelmbean.RequiredModelMBean.invokeMethod(RequiredModelMBean.java:1135)
at javax.management.modelmbean.RequiredModelMBean.invoke(RequiredModelMBean.java:988)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:835)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:771)
at com.ibm.ws.management.AdminServiceImpl$1.run(AdminServiceImpl.java:1335)
at com.ibm.ws.security.util.AccessController.doPrivileged(AccessController.java:118)
at com.ibm.ws.management.AdminServiceImpl.invoke(AdminServiceImpl.java:1228)
at com.ibm.ws.management.connector.AdminServiceDelegator.invoke(AdminServiceDelegator.java:181)
at com.ibm.ws.management.connector.ipc.CallRouter.route(CallRouter.java:247)
at com.ibm.ws.management.connector.ipc.IPCConnectorInboundLink.doWork(IPCConnectorInboundLink.java:360)
at com.ibm.ws.management.connector.ipc.IPCConnectorInboundLink$IPCConnectorReadCallback.complete(IPCConnectorInboundLink.java:602)
at com.ibm.ws.ssl.channel.impl.SSLReadServiceContext$SSLReadCompletedCallback.complete(SSLReadServiceContext.java:1819)
at com.ibm.ws.tcp.channel.impl.WorkQueueManager.requestComplete(WorkQueueManager.java:558)
at com.ibm.ws.tcp.channel.impl.WorkQueueManager.attemptIO(WorkQueueManager.java:608)
at com.ibm.ws.tcp.channel.impl.WorkQueueManager.workerRun(WorkQueueManager.java:985)
at com.ibm.ws.tcp.channel.impl.WorkQueueManager$Worker.run(WorkQueueManager.java:1074)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1702)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tareaIntegrationLectSolicitNuevasFacturas': Autowiring of fields failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private es.nexus.facturaelectronica.service.interfaces.integrations.IIntegracionPersistirNuevasFacturas es.nexus.facturaelectronica.service.impl.integrations.IntegrationLectSolicitNuevasFacturas.integracionPersistirNuevasFacturas; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tareaIntegrationPersistirNuevasFacturas' defined in ServletContext resource [/WEB-INF/classes/bean-application-config.xml]: Initialization of bean failed; nested exception is java.lang.ExceptionInInitializerError
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation(AutowiredAnnotationBeanPostProcessor.java:243)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:959)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:729)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:381)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
at com.ibm.ws.webcontainer.webapp.WebApp.notifyServletContextCreated(WebApp.java:1686)
at com.ibm.ws.webcontainer.webapp.WebAppImpl.initialize(WebAppImpl.java:410)
... 53 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private es.nexus.facturaelectronica.service.interfaces.integrations.IIntegracionPersistirNuevasFacturas es.nexus.facturaelectronica.service.impl.integrations.IntegrationLectSolicitNuevasFacturas.integracionPersistirNuevasFacturas; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tareaIntegrationPersistirNuevasFacturas' defined in ServletContext resource [/WEB-INF/classes/bean-application-config.xml]: Initialization of bean failed; nested exception is java.lang.ExceptionInInitializerError
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:435)
at org.springframework.beans.factory.annotation.InjectionMetadata.injectFields(InjectionMetadata.java:105)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation(AutowiredAnnotationBeanPostProcessor.java:240)
... 71 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tareaIntegrationPersistirNuevasFacturas' defined in ServletContext resource [/WEB-INF/classes/bean-application-config.xml]: Initialization of bean failed; nested exception is java.lang.ExceptionInInitializerError
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:671)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:610)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:412)
... 73 more
Caused by: java.lang.ExceptionInInitializerError
at org.apache.axis.description.TypeDesc.<clinit>(TypeDesc.java:61)
at es.gob.face.webservice.SRCFFactura.<clinit>(SRCFFactura.java:196)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:171)
at com.sun.proxy.$Proxy450.<clinit>(Unknown Source)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at java.lang.reflect.Proxy.newInstance(Proxy.java:715)
at java.lang.reflect.Proxy.newProxyInstance(Proxy.java:706)
at org.springframework.aop.framework.JdkDynamicAopProxy.getProxy(JdkDynamicAopProxy.java:117)
at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:110)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:488)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:363)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:324)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:361)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1343)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473)
... 84 more
Caused by: org.apache.commons.discovery.DiscoveryException: Class org.apache.commons.logging.impl.LogFactoryImpl does not implement org.apache.commons.logging.LogFactory
at org.apache.commons.discovery.tools.ClassUtils.verifyAncestory(ClassUtils.java:180)
at org.apache.commons.discovery.tools.SPInterface.verifyAncestory(SPInterface.java:201)
at org.apache.commons.discovery.tools.SPInterface.newInstance(SPInterface.java:195)
at org.apache.commons.discovery.tools.DiscoverClass.newInstance(DiscoverClass.java:579)
at org.apache.commons.discovery.tools.DiscoverSingleton.find(DiscoverSingleton.java:418)
at org.apache.commons.discovery.tools.DiscoverSingleton.find(DiscoverSingleton.java:378)
at org.apache.axis.components.logger.LogFactory$1.run(LogFactory.java:45)
at java.security.AccessController.doPrivileged(Native Method)
at org.apache.axis.components.logger.LogFactory.getLogFactory(LogFactory.java:41)
at org.apache.axis.components.logger.LogFactory.<clinit>(LogFactory.java:33)
... 103 more
It all end with the org.apache.commons.discovery.DiscoveryException: Class org.apache.commons.logging.impl.LogFactoryImpl does not implement org.apache.commons.logging.LogFactory
error message.
Is there some kind of incompatibility between commons-logging and its jcl-over-slf4j substitute?
We've checked some other projects, and it seems a common pattern: axis 1.4 + jcl-over-slf4j = exception.
[Note 1]
Classloader policy: tests.
In order to get commons-logging working with log4j at application level, we have assigned those libraries to the application (first we declare them both as "shared libraries", and we do the same with commons-logging.properties and log4j.properties files, then We assign them all to the application, and then we set the application's classloader policy to "Parent Last". This way, we force the application to load and use it's own copy of commons-logging, with its own configuration file, thus overcoming the commons-logging.properties included within WAS. This said, we have tried some "stupid" configurations, like make all the application use a single application classloader, or setting the web modules classloader policy to Parent Last. Such changes made no difference, as expected.
This far, we have found some nasty scenarios:
Axis + WAS logging facility (write all to SystemOut): OK, it works,
but we do not want everything written down to SystemOut!
Axis + commons-logging + log4j + their configuration files assigned
to the application at application classloader level,policy=Parent
Last. Some applications work, some others don't (theyshow messages
like the one quoted before).
jcl-over-slf4j + log4j + configuration file for log4j: Same result
as in point 2 of this list.
The last application we are dealing with right now, the application that fails with the excetions in the code block quoted previously: we have discovered that it only fails when we use configuration 3 (in this list), but it does not fail with configuration 2, which is very surprising and unexpected: in previous test with other applications, if the configuration fails with configuration 2, then it also fails with configuration 3.
[End of Note 1]
Any help will be welcome.
We have exactly the same Setup here:
WAS 8.0.0.9
log4j for logging
EAR containing jcl-over-slf4j, slf4j and slf4j-log4j
Axis 1.4
Classloader policy Parent Last and WAR policy Single class loader for application
As soon as axis-classes are loaded, some static-initializer-block gets executed and we get this Exception:
DiscoveryException: Class org.apache.commons.logging.impl.LogFactoryImpl does not implement org.apache.commons.logging.LogFactory
It seems like org.apache.commons.logging.LogFactory is loaded from jcl-over-slf4j and org.apache.commons.logging.impl.LogFactoryImpl is provided by WebSphere.
The only way it works for us, is to remove jcl-over-slf4j.jar from our EAR. Of course this way we might lose some Logs or find them in WebSphere SystemOut.log but at least 'it works'...
We encountered the same issues. Our solution is to tell commons-logging to use the slf4j factory implementation in our classloading context (in our case an ejb.jar).
To achieve this we simply added a commons-logging.properties file to our ejb.jar root folder with following content:
priority=1
org.apache.commons.logging.LogFactory=org.apache.commons.logging.impl.SLF4JLogFactory
This resolved the issue in our application.
Maybe this can help you. I was with a similar problem, and discovered a solution in SLF4J documentation.
http://slf4j.org/faq.html#excludingJCL
alternative 2) provided scope Commons-logging can be rather simply and
conveniently excluded as a dependency by declaring it in the provided
scope within the pom.xml file of your project. The actual
commons-logging classes would be provided by jcl-over-slf4j. This
translates into the following pom file snippet:
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.21</version>
</dependency>
The first dependency declaration essentially states that
commons-logging will be "somehow" provided by your environment. The
second declaration includes jcl-over-slf4j into your project. As
jcl-over-slf4j is a perfect binary-compatible replacement for
commons-logging, the first assertion becomes true. Unfortunately,
while declaring commons-logging in the provided scope gets the job
done, your IDE, e.g. Eclipse, will still place commons-logging.jar on
your project's class path as seen by your IDE. You would need to make
sure that jcl-over-slf4j.jar is visible before commons-logging.jar by
your IDE.
SLF4J documentation gives more alternatives, this worked for me.
I am using spring-integration in my project. When I deploy my app in the jetty container, I am getting the following exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'integrationRequestMappingHandlerMapping': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'inboundhttpJobRequestGateway': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.integration.http.inbound.HttpRequestHandlingMessagingGateway]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/http/converter/json/MappingJackson2HttpMessageConverter
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at com.dsths.spring.web.DsthsContextLoaderListener.configureAndRefreshWebApplicationContext(DsthsContextLoaderListener.java:97)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:284)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:771)
at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:411)
at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:763)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:247)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1238)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:706)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:480)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at com.dsths.common.container.core.deploy.DeploymentManager.deploy(DeploymentManager.java:54)
at com.dsths.common.container.core.deploy.DeploymentManager$$FastClassByCGLIB$$f5bc43eb.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.aop.interceptor.AsyncExecutionInterceptor$1.call(AsyncExecutionInterceptor.java:95)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'inboundhttpJobRequestGateway': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.integration.http.inbound.HttpRequestHandlingMessagingGateway]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/http/converter/json/MappingJackson2HttpMessageConverter
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1035)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:939)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1093)
at org.springframework.integration.http.inbound.IntegrationRequestMappingHandlerMapping.detectHandlerMethods(IntegrationRequestMappingHandlerMapping.java:103)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.initHandlerMethods(AbstractHandlerMethodMapping.java:109)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.initApplicationContext(AbstractHandlerMethodMapping.java:89)
at org.springframework.context.support.ApplicationObjectSupport.initApplicationContext(ApplicationObjectSupport.java:119)
at org.springframework.web.context.support.WebApplicationObjectSupport.initApplicationContext(WebApplicationObjectSupport.java:72)
at org.springframework.context.support.ApplicationObjectSupport.setApplicationContext(ApplicationObjectSupport.java:73)
at org.springframework.context.support.ApplicationContextAwareProcessor.invokeAwareInterfaces(ApplicationContextAwareProcessor.java:117)
at org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:92)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:394)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1448)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
... 29 more
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.integration.http.inbound.HttpRequestHandlingMessagingGateway]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/http/converter/json/MappingJackson2HttpMessageConverter
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:162)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:110)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:280)
... 49 more
Caused by: java.lang.NoClassDefFoundError: org/springframework/http/converter/json/MappingJackson2HttpMessageConverter
at org.springframework.integration.http.inbound.HttpRequestHandlingEndpointSupport.<init>(HttpRequestHandlingEndpointSupport.java:166)
at org.springframework.integration.http.inbound.HttpRequestHandlingMessagingGateway.<init>(HttpRequestHandlingMessagingGateway.java:72)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
... 51 more
Caused by: java.lang.ClassNotFoundException: org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at com.dsths.common.container.ContainerClassLoader.loadClass(ContainerClassLoader.java:136)
at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:429)
at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:382)
... 58 more
I have both the jars jackson-core-asl-1.8.3 and jackson-core-2.3.1 in the class path. Still I am getting the error. How to resolve the problem?
Normally, the class MappingJackson2HttpMessageConverter exists in spring-web.jar (or spring-web-x.y.z-RELEASE.jar), you should add it to your classpath, or if using maven add following dependency :
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>x.y.z.RELEASE</version>
</dependency>
Edit per Artem Bilan comment :
Normally, if you use maven, it should be present as a dependency of spring-integration-http, provided you have this one.
I had this weird error, too. I did a search in my jars in the web server's (tomcat) webapps/myapp/WEB-INF/lib and the class was there -- and only once.
It went away when I looked at another project at my job and used the same jackson jars.
Originally, I had the following:
jackson-core-2.4.3.jar
jackson-databind-2.4.3.jar
I removed these and added the following (packaged into my WEB-INF/lib):
jackson-mapper-asl-1.9.13.jar
jackson-datatype-jsr310-2.5.0.jar
jackson-datatype-joda-2.5.0.jar
jackson-databind-2.5.0.jar
jackson-core-2.5.0.jar
jackson-annotations-2.5.0.jar
I'm running this on Tomcat 7 on windows; using Java 1.6 (for compiling and runtime in Tomcat)
servlet.xml:
<beans:bean id="jacksonMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" >
</beans:bean>
<beans:bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<beans:property name="messageConverters">
<beans:list>
<beans:ref bean="jacksonMessageConverter" />
</beans:list>
</beans:property>
</beans:bean>
In case it helps, I run the following shell from cygwin for searching for jats
JAR="C:/java/Java/jdk1.7.0_71/bin/jar.exe"
srchdir="c:/appservers/apache-tomcat-7.0.57/webapps/my-web/WEB-INF/lib"
echo "SEARCH FOLDER: $srchdir"
find $srchdir -print | grep '\.jar$' | while read f
do
$JAR tf $f | grep 'MappingJackson2HttpMessageConverter\.class' >/dev/null 2>&1
[ $? -eq 0 ] && echo "==> $f" && $JAR tf $f | grep MappingJackson2HttpMessageConverter\.class
done
It's interesting what is com.dsths.common.container.ContainerClassLoader...
Looks like spring-integration-http is loaded by this ClassLoader, but MappingJackson2HttpMessageConverter and all others spring-web classes with another ClassLoader.
Would be great, if you place all spring jars within the same class loader.
The app is not able to find MappingJackson2HttpMessageConverter in the class path. The problem is one class loader is picking one version and another class loader is picking another version.
Basically, it's a jar package problem. You can't find this method in the jar package you imported. You should replace it with another jar package
I have a webapp running on Tomcat 6, one class checks for existence of directory and creates it if doesn't exist -
// make sure path exists
File f = new File(value);
if (!f.exists()) {
if (!f.mkdirs()) {
throw new RuntimeException("Failed creating directory " + value);
}
}
Now, it all works just fine when running on my local machine, but when executed on EC2 instance, I see the following at catalina.out -
2012-05-30 06:57:28 main ConfigService [INFO] Directory path not exists, creating /usr/share/tomcat6/webapps/ROOT/WEB-INF/data/temp/currency
2012-05-30 06:57:28 main DefaultListableBeanFactory [INFO] Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#1b4c1d7: defining beans [fetchAppRankingJob,fetchCurrencyRatesJob,fetchReviewsJob,sendDailyReportJob,importSalesReportJob,fetchSalesReportJob,processSalesReportsJob,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,org.springframework.scheduling.support.ScheduledMethodRunnable#0,org.springframework.scheduling.support.ScheduledMethodRunnable#1,org.springframework.scheduling.support.ScheduledMethodRunnable#2,org.springframework.scheduling.support.ScheduledMethodRunnable#3,org.springframework.scheduling.support.ScheduledMethodRunnable#4,org.springframework.scheduling.config.ScheduledTaskRegistrar#0,appsales-scheduler,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
2012-05-30 06:57:28 main ContextLoader [ERROR] Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fetchCurrencyRatesJob' defined in file [/var/lib/tomcat6/webapps/ROOT/WEB-INF/classes/com/appround/collect/currency/FetchCurrencyRatesJob.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.appround.collect.currency.FetchCurrencyRatesJob]: Constructor threw exception; nested exception is java.lang.RuntimeException: Failed creating directory /usr/share/tomcat6/webapps/ROOT/WEB-INF/data/temp/currency
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:997)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:943)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:385)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:284)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4206)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:799)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:779)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:601)
at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1079)
at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:1002)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:506)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1317)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:324)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1065)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
at org.apache.catalina.core.StandardService.start(StandardService.java:525)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.appround.collect.currency.FetchCurrencyRatesJob]: Constructor threw exception; nested exception is java.lang.RuntimeException: Failed creating directory /usr/share/tomcat6/webapps/ROOT/WEB-INF/data/temp/currency
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:162)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:76)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:990)
... 37 more
Caused by: java.lang.RuntimeException: Failed creating directory /usr/share/tomcat6/webapps/ROOT/WEB-INF/data/temp/currency
at com.appround.collect.ConfigService.getPathProperty(ConfigService.java:109)
at com.appround.collect.currency.FetchCurrencyRatesJob.<init>(FetchCurrencyRatesJob.java:18)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
... 39 more
I prefer writing to /home/ec2-user/collect/data, tried writing to my webapp's directory because it should have writing privilege to WEB-INF folder.
I've tried granting file permission write/read to that folder at /usr/share/tomcat6/conf/catalina.policy -
grant {
permission java.io.FilePermission "/home/ec2-user/collect/data", "read, write";
permission java.io.FilePermission "/home/ec2-user/collect/data/*", "read, write";
}
Still, no luck.
Any clue?
Thanks!
I am assuming you are using Amazon Linux since you mention the ec2-user.
What permissions are set on the parent folder /usr/share/tomcat6/webapps/ where you try to create the new one? Usually the user running Tomcat (should also be called tomcat) does not have write permission there unless you set it explicitly using chmod u+w.
In adddition the tomcat user is not allowed to write to a different user's home (/home/ec2-user/ in your case), unless you give the user permissions for this directory. Your example is a little confusing there since you mention trying to write to the webapps folder but specify the ec2-user's home directory in the policy file.
Generally, if you want to create temporary data files, I would suggest using File.createTempFile(..) to create them, they will automatically be placed in the standard temporary folder. If you would like to create a dedicated folder for data files yourself, /var/tmp/ may be better suited since it is the standard unix location for temporary files (/tmp/ may be cleared upon reboot, so please do not put any persistent files there).