Trouble configuring spring caffeine cache manager - spring

I have a spring boot project which serves as a library (packaged jar file) to some other project. I am trying yo configure caffeine cache that will refresh asynchronously after request is made to the service.
pom.xml (includes) :
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
My configuration class :
#EnableCaching
#Configuration
public class CaffeineCacheConfig {
#Bean
public CacheManager cacheManager(){
CaffeineCacheManager cacheManager = new CaffeineCacheManager("userStories", "features");
cacheManager.setCaffeine(caffeineCacheBuilder());
cacheManager.setAllowNullValues(false);
return cacheManager;
}
Caffeine<Object, Object> caffeineCacheBuilder() {
return Caffeine.newBuilder()
.initialCapacity(100)
.maximumSize(500)
.refreshAfterWrite(1, TimeUnit.MINUTES)
.weakKeys()
.recordStats();
}
}
DAO layer (needs caching here) :
#Component
#EnableCaching
#CacheConfig(cacheNames = {"userStories"})
public class UserStoryDaoImpl implements IUserStoryDao {
#Override
#Cacheable
public List<UserStory> getUserStoriesForProjectAndRelease(UserDto userDto, Set<Integer> reportProjectId, int releaseId) {
return new ArrayList(); //slow and low performing method that returns a list
}
DAO layer (needs caching here as well) :
#Component
#EnableCaching
#CacheConfig(cacheNames = {"features"})
public class FeatureDaoImpl implements IFeatureDao {
#Override
#Cacheable
public List<Features> geFeaturesForProjectAndRelease(UserDto userDto, Set<Integer> reportProjectId, int releaseId) {
return new ArrayList(); //slow and low performing method that returns a list
}
}
I am getting below error stack while running this setup:
2020-03-31 16:55:46,020 ERROR web.context.ContextLoader - Context initialization failed [localhost-startStop-1] {}
java.lang.NullPointerException
at org.springframework.context.annotation.AutoProxyRegistrar.registerBeanDefinitions(AutoProxyRegistrar.java:62)
at org.springframework.context.annotation.ConfigurationClassParser.processImport(ConfigurationClassParser.java:385)
at org.springframework.context.annotation.ConfigurationClassParser.processImport(ConfigurationClassParser.java:377)
at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:205)
at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:164)
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:130)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:287)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:225)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:632)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:410)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at com.intland.codebeamer.context.CodeBeamerContextListener.lambda$contextInitialized$1(CodeBeamerContextListener.java:117)
at com.intland.codebeamer.context.CodeBeamerContextListener.logExecutionTime(CodeBeamerContextListener.java:148)
at com.intland.codebeamer.context.CodeBeamerContextListener.contextInitialized(CodeBeamerContextListener.java:117)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4699)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5165)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:743)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:719)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:714)
at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1125)
at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1859)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
2020-03-31 16:55:46,070 INFO codebeamer.context.CodeBeamerContextListener - Context - Destroyed [localhost-startStop-1] {}
2020-03-31 16:55:46,132 WARN context.support.XmlWebApplicationContext - Exception thrown from ApplicationListener handling ContextClosedEvent [localhost-startStop-1] {}
java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: Root WebApplicationContext: startup date [Tue Mar 31 16:55:35 IST 2020]; root of context hierarchy
at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:347)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:334)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1051)
at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:1012)
at org.springframework.web.context.ContextLoader.closeWebApplicationContext(ContextLoader.java:586)
at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:143)
at com.intland.codebeamer.context.CodeBeamerContextListener.contextDestroyed(CodeBeamerContextListener.java:128)
at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4746)
at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5403)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:226)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:743)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:719)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:714)
at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1125)
at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1859)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
2020-03-31 16:55:46,132 WARN context.support.XmlWebApplicationContext - Exception thrown from LifecycleProcessor on context close [localhost-startStop-1] {}
java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: Root WebApplicationContext: startup date [Tue Mar 31 16:55:35 IST 2020]; root of context hierarchy
at org.springframework.context.support.AbstractApplicationContext.getLifecycleProcessor(AbstractApplicationContext.java:360)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1059)
at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:1012)
at org.springframework.web.context.ContextLoader.closeWebApplicationContext(ContextLoader.java:586)
at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:143)
at com.intland.codebeamer.context.CodeBeamerContextListener.contextDestroyed(CodeBeamerContextListener.java:128)
at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4746)
at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5403)
at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:226)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:743)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:719)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:714)
at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1125)
at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1859)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Not sure what is missing in the setup?

Start with removing #EnableCaching from #Component classes - keep
it only on #Configuration.
Not sure about #CacheConfig, normally
you can configure cache name in #Cacheable.
I have previous experience with your idea. The problem here is that refreshing cache needs a method to do the refresh - a method which would produce an up-to-date value based on the key. It's tricky to implement such method when key is based on multiple parameters from the method signature. Also this means that value loading mechanism should be implemented twice: in the annotated method and in the reloader.

I have fixed it to add the next line to the application properties:
cache.ttl=60

Related

Quarkus #Inject settings from application.properties in #WebFilter

I'm trying to #Inject some settings from application.properties in #WebFilter, but it doesn't seem to work:
Caused by: javax.servlet.ServletException: UT010013: Could not instantiate com.foo.www.PageFilter
at io.undertow.servlet.core.ManagedFilter.createFilter(ManagedFilter.java:77)
at io.undertow.servlet.core.DeploymentManagerImpl$2.call(DeploymentManagerImpl.java:591)
at io.undertow.servlet.core.DeploymentManagerImpl$2.call(DeploymentManagerImpl.java:556)
at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:42)
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at io.quarkus.undertow.runtime.UndertowDeploymentRecorder$9$1.call(UndertowDeploymentRecorder.java:566)
at io.undertow.servlet.core.DeploymentManagerImpl.start(DeploymentManagerImpl.java:598)
at io.quarkus.undertow.runtime.UndertowDeploymentRecorder.bootServletContainer(UndertowDeploymentRecorder.java:517)
... 18 more
Caused by: java.lang.RuntimeException: Error injecting com.foo.config.GlobalConfig com.foo.www.PageFilter.globalConfig
at com.foo.www.PageFilter_Bean.create(Unknown Source)
at com.foo.www.PageFilter_Bean.get(Unknown Source)
at com.foo.www.PageFilter_Bean.get(Unknown Source)
The config itself is as follows:
#ConfigMapping(prefix = "global")
public interface GlobalConfig {
List<String> domains();
}
Any workaround?

Exception when deploying .war file on tomcat9.0.2 LifecycleExecption: Failed to start component [duplicate]

I am not able to deploy my war file into tomcat server. I am ending up with the below exception.
SEVERE: ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/BatchApp-1.0.0.M1]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:977)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1655)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at com.sun.faces.config.InitFacesContext.cleanupInitMaps(InitFacesContext.java:281)
at com.sun.faces.config.InitFacesContext.<init>(InitFacesContext.java:107)
at com.sun.faces.config.FacesInitializer.onStartup(FacesInitializer.java:115)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5280)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 11 more
May 11, 2013 5:28:05 PM org.apache.catalina.startup.HostConfig deployWAR
SEVERE: Error deploying web application archive C:\AppDev\Tomcat7.0\webapps\BatchApp-1.0.0.M1.war
java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/BatchApp-1.0.0.M1]]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:904)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:977)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1655)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I further debugged it and looks like at the below code #getInitContextServletContextMap() method in com.sun.faces.config.InitFacesContext I am ending up with null pointer being returned.
static Map getInitContextServletContextMap() {
ConcurrentHashMap initContextServletContext = null;
try {
Field initContextMap = FacesContext.class.getDeclaredField("initContextServletContext");
initContextMap.setAccessible(true);
initContextServletContext = (ConcurrentHashMap)initContextMap.get(null);
} catch (Exception e) {
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.log(Level.FINEST, "Unable to get (init context, servlet context) map", e);
}
}
return initContextServletContext;
}
It is cleared that the server is looking for "initContextServletContext", but where to set this?
Please let me know how can I resolve this issue.
Had the exact same error. It was a dependency issue: I was using Oracle's implementation of JSF (2.2.1), but one of my Maven dependencies was pulling in Apache MyFaces.
What happened is that the code snippet that you show, which is from the Oracle impelementation, tries to access a static private field of FacesContext. But the classloader has loaded the MyFaces implementation of FacesContext, which doesn't have that field. Therefore barf.
Check your dependencies. I bet you will find that you've got two different versions or two different implementations of JSF.

org.apache.http.client.HttpResponseException: No authentication header supplied

I am configuring neo4j database with Spring Boot. I am able to setup Spring Boot and it is working fine. But When I configure neo4j it is throwing exception org.apache.http.client.HttpResponseException: No authentication header supplied.
Log stash is below:
2016-11-08 15:20:54.962 INFO 4932 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 23 ms
2016-11-08 15:24:29.062 INFO 4932 --- [nio-8080-exec-2] o.n.o.drivers.http.request.HttpRequest : Thread: 27, url: http://localhost:7474/db/data/transaction/commit, request: {"statements":[{"statement":"MATCH (user:User) WHERE user.id = {id} RETURN user","parameters":{"id":"10"},"resultDataContents":["graph"],"includeStats":false}]}
2016-11-08 15:24:29.285 WARN 4932 --- [nio-8080-exec-2] o.n.o.drivers.http.request.HttpRequest : Thread: 27, response: No authentication header supplied.
2016-11-08 15:24:29.288 INFO 4932 --- [nio-8080-exec-2] o.s.d.neo4j.config.Neo4jConfiguration : Intercepted exception
2016-11-08 15:24:29.299 ERROR 4932 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.neo4j.ogm.drivers.http.request.HttpRequestException: http://localhost:7474/db/data/transaction/commit: No authentication header supplied.] with root cause
org.apache.http.client.HttpResponseException: No authentication header supplied.
at org.neo4j.ogm.drivers.http.request.HttpRequest.execute(HttpRequest.java:203) ~[neo4j-ogm-http-driver-2.0.5.jar:na]
at org.neo4j.ogm.drivers.http.request.HttpRequest.executeRequest(HttpRequest.java:168) ~[neo4j-ogm-http-driver-2.0.5.jar:na]
at org.neo4j.ogm.drivers.http.request.HttpRequest.execute(HttpRequest.java:87) ~[neo4j-ogm-http-driver-2.0.5.jar:na]
at org.neo4j.ogm.session.delegates.ExecuteQueriesDelegate.executeAndMap(ExecuteQueriesDelegate.java:114) ~[neo4j-ogm-core-2.0.5.jar:na]
at org.neo4j.ogm.session.delegates.ExecuteQueriesDelegate.query(ExecuteQueriesDelegate.java:87) ~[neo4j-ogm-core-2.0.5.jar:na]
at org.neo4j.ogm.session.delegates.ExecuteQueriesDelegate.queryForObject(ExecuteQueriesDelegate.java:61) ~[neo4j-ogm-core-2.0.5.jar:na]
at org.neo4j.ogm.session.Neo4jSession.queryForObject(Neo4jSession.java:363) ~[neo4j-ogm-core-2.0.5.jar:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_31]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_31]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_31]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_31]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:133) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:121) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at com.sun.proxy.$Proxy60.queryForObject(Unknown Source) ~[na:na]
Configuration Class:
public class ApplicationConfiguration extends Neo4jConfiguration{
#Bean
public Configuration getConfiguration(){
Configuration config = new Configuration();
config.driverConfiguration()
.setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver")
.setURI("http://neo4j:welcome*123#localhost:7474");
return config;
}
#Bean
public SessionFactory getSessionFactory(){
return new SessionFactory(getConfiguration(), "com.ent.entity");
}
#Bean
#Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Session getSession() throws Exception{
return super.getSession();
}
}
Spring Boot has the list of the configuration properties, which can be set in the "application.properties" file.
Setting these might solve the problem:
spring.data.neo4j.username=neo4j (default user)
spring.data.neo4j.password=neo4j (default password)
This requires an authentication in the header or you can disable authentication try to edit the neo4j.conf install dir bin/neo4j.conf
and uncomment this line
# Whether requests to Neo4j are authenticated.
# To disable authentication, uncomment this line
dbms.security.auth_enabled=false
OR enable neo DBMS connector
# HTTP Connector. There must be exactly one HTTP connector.
dbms.connector.http.enabled=true
#dbms.connector.http.listen_address=:7474

Jboss error on deployment bean

I'm trying to deploy a bean that uses #Interceptros annotation in Jboss.
According to documentation I've created beanRefContext.xml and here is Bean code
#Stateless
#LocalBean
#Interceptors(SpringBeanAutowiringInterceptor.class)
public class ClienteBean implements ClienteBeanLocal {
public ClienteBean() {
// TODO Auto-generated constructor stub
}
#Autowired
private IClienteDAO cliente;
#Override
public List<ClienteDTO> selectALL() throws Exception {
return cliente.selectALL();
}
}
I am deploying it inside an EAR. When I try to deploy in Jboss 6 I get the following error:
Caused by: java.lang.ArrayStoreException: sun.reflect.annotation.TypeNotPresentExceptionProxy
at sun.reflect.annotation.AnnotationParser.parseClassArray(Unknown Source) [:1.7.0_09]
at sun.reflect.annotation.AnnotationParser.parseArray(Unknown Source) [:1.7.0_09]
at sun.reflect.annotation.AnnotationParser.parseMemberValue(Unknown Source) [:1.7.0_09]
at sun.reflect.annotation.AnnotationParser.parseAnnotation(Unknown Source) [:1.7.0_09]
at sun.reflect.annotation.AnnotationParser.parseAnnotations2(Unknown Source) [:1.7.0_09]
at sun.reflect.annotation.AnnotationParser.parseAnnotations(Unknown Source) [:1.7.0_09]
at java.lang.Class.initAnnotationsIfNecessary(Unknown Source) [:1.7.0_09]
at java.lang.Class.getAnnotations(Unknown Source) [:1.7.0_09]
at org.jboss.reflect.plugins.introspection.IntrospectionTypeInfoFactoryImpl.readAnnotations(IntrospectionTypeInfoFactoryImpl.java:610) [jboss-reflect.jar:2.2.0.GA]
at org.jboss.reflect.plugins.introspection.IntrospectionTypeInfoFactoryImpl.getAnnotations(IntrospectionTypeInfoFactoryImpl.java:126) [jboss-reflect.jar:2.2.0.GA]
at org.jboss.reflect.plugins.InheritableAnnotationHolder.getDeclaredAnnotations(InheritableAnnotationHolder.java:96) [jboss-reflect.jar:2.2.0.GA]
at org.jboss.reflect.plugins.ClassInfoImpl.getAnnotations(ClassInfoImpl.java:181) [jboss-reflect.jar:2.2.0.GA]
at org.jboss.reflect.plugins.AbstractAnnotatedInfo.getUnderlyingAnnotations(AbstractAnnotatedInfo.java:63) [jboss-reflect.jar:2.2.0.GA]
at org.jboss.scanning.plugins.visitor.ClassHierarchyResourceVisitor.handleClass(ClassHierarchyResourceVisitor.java:76) [:1.0.0.GA]
at org.jboss.scanning.plugins.visitor.ReflectResourceVisitor.doVisit(ReflectResourceVisitor.java:108) [:1.0.0.GA]
at org.jboss.scanning.plugins.visitor.ReflectResourceVisitor.visit(ReflectResourceVisitor.java:86) [:1.0.0.GA]
... 53 more
How can I solve it?
Seems JBoss is not seeing SpringBeanAutowiringInterceptor.class. In your EAR file put your spring jars on the lib directory. See if that works.
If you are using maven to assemble your EAR file you can do something like this:
http://maven.apache.org/plugins/maven-ear-plugin/examples/customizing-module-location.html

Testing spring mvc controller having the view with tiles configuration

I dont know how to test a controller that has view with tiles configuration.
Below is the unit test case written
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/servlet-context.xml", "file:src/main/webapp/WEB-INF/tiles-definitions.xml"})
#TestExecutionListeners(DependencyInjectionTestExecutionListener.class)
public class BankControllerTest {
#Inject
private ApplicationContext applicationContext;
private HandlerAdapter handlerAdapter;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private BankController controller;
private ModelAndView handle(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
final HandlerMapping handlerMapping = applicationContext.getBean(HandlerMapping.class);
final HandlerExecutionChain handler = handlerMapping.getHandler(request);
Assert.assertNotNull("No handler found for request, check you request mapping", handler);
final Object controller = handler.getHandler();
for (final HandlerInterceptor interceptor : handlerMapping.getHandler(request).getInterceptors()) {
if (!interceptor.preHandle(request, response, controller)) {
return null;
}
}
return handlerAdapter.handle(request, response, controller);
}
#Before
public void setUp() throws Exception {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
this.handlerAdapter = applicationContext.getBean(HandlerAdapter.class);
}
#Test
public void banksList() throws Exception {
request.setRequestURI("/banksList.do");
request.setMethod("GET");
final ModelAndView mav = handle(request, response);
// assertViewName(mav, "banksList");
// assertAndReturnModelAttributeOfType(mav, "banksList",
// BankList.class);
}
}
I get the following error
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from URL [file:src/main/webapp/WEB-INF/sach-context.xml]
INFO : org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
INFO : org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from URL [file:src/main/webapp/WEB-INF/tiles-definitions.xml]
ERROR: org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#2c1e6b] to prepare test instance [com.myapp.simulator.controller.BankControllerTest#811c88]
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:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
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:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
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.BeanDefinitionStoreException: IOException parsing XML document from URL [file:src/main/webapp/WEB-INF/tiles-definitions.xml]; nested exception is java.net.UnknownHostException: tiles.apache.org
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:408)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:212)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:81)
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: java.net.UnknownHostException: tiles.apache.org
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startEntity(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startDTDEntity(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDTDScannerImpl.setInputSource(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.dispatch(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:75)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:388)
... 34 more
How to overcome this error. What is the testing approach for controller. do i need to use any other framework in order to write testcases for my controllers
Put the lazy-init="true" for tiles bean configuration as below.
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer" lazy-init="true"
It depends on what you want to test. If you are just making sure that the tile view names are correct, then it is correct you don't have to use Spring Configuration. However if you want to see if a view is resolved or check model attributes, responses, etc then Spring has a MVC testing framework. It was a standalone, but it is now part of 3.2. So if you are using Spring 3 you might want to look at the tests in SpringMVC Showcase. I haven't tested it yet with Tiles, but it does have the ability to set a view resolver so it should be possible.
The problem is that you can not load a spring context with beans that requires an web container.
If you only want to test the controllers, then I recommend real Unit test, without Spring Context. That mean you need to create mocks for the classes that are required by your controller.
I am using the following to load test cases in spring boot with tiles as an example
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = {MyApplication.class, TestConfigurtaion.class})
#WebAppConfiguration
public class UserRepositoryTest {
#Autowired
UserRepository userRepository;
#Test
public void testCase{
}
}
Then another class for tiles configuration
#Configuration
public class TestConfigurtaion {
#Bean
public TilesConfigurer tilesConfigurer() {
TilesConfigurer configurer = new TilesConfigurer();
configurer.setDefinitions(new String[] { "file:src/main/webapp/WEB-INF/views/tiles.xml" });
configurer.setCheckRefresh(true);
return configurer;
}
}

Resources