Grails 3.1.16 - Call method of session scope service from scheduled service - spring

I created a test basic application on Grails 3.1.16 that has two services, a first async and scheduled service (ex. FirstService) calling a second session scoped service (ex. SessionScopeService), as below:
"FirstService.groovy":
import org.springframework.scheduling.annotation.Async
import org.springframework.scheduling.annotation.Scheduled
class FirstService {
def sessionScopeService
boolean lazyInit = false
#Async
#Scheduled(cron="*/10 * * * * MON-FRI")
void firstServiceMethod() {
sessionScopeService.serviceMethod()
}
}
"SessionScopeService.groovy":
class SessionScopeService {
static scope = "session"
static proxy = "true"
def serviceMethod() {
log.info("test OK")
}
}
The application fails to start, reporting scope session error:
ERROR org.springframework.boot.SpringApplication - Application startup
failed
org.springframework.beans.factory.BeanCreationException: Error creating bean
with name 'firstService': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionScopeService ': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:778)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:760)
at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:360)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:306)
at grails.boot.GrailsApp.run(GrailsApp.groovy:55)
at grails.boot.GrailsApp.run(GrailsApp.groovy:375)
at grails.boot.GrailsApp.run(GrailsApp.groovy:364)
at grails.boot.GrailsApp$run.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
at testservice.Application.main(Application.groovy:8)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionScopeService': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:355)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByName(AbstractAutowireCapableBeanFactory.java:1248)
at org.grails.spring.beans.factory.OptimizedAutowireCapableBeanFactory.autowireByName(OptimizedAutowireCapableBeanFactory.java:160)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1198)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
... 20 common frames omitted
Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
at org.springframework.web.context.request.SessionScope.get(SessionScope.java:91)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:340)
... 25 common frames omitted
I also tried to create manually scoped proxy on 'resources.groovy' :
beans = {
sessionScopeServiceProxy(ScopedProxyFactoryBean) {
targetBeanName = 'sessionScopeService'
proxyTargetClass = true
}
}
and then in the FirstService injected this proxy:
def sessionScopeServiceProxy
but without success (the method of "sessionScopeServiceProxy" is not even recognized by the "FirstService").
How can I solve this?
Thanks for your time

I guess you want to use a new SessionScopeService instance each time your 'job' runs, so you should be using 'prototype' as the scope and manually get the bean in the firstServiceMethod execution : grailsApplication.mainContext.getBean(SessionScopeService). This way, each time your 'job' kicks in, a new 'SessionScopeService' will be created for that execution.

Related

Spring tries to initialize AutoConfiguration beans using default constructor

We are having issues starting up our Spring Boot Web application. The main problem to properly diagnose the startup is that it only seems to happen in 1% of the startups. In 99% of the startup procedures all works fine and we end up having a properly working spring boot application. However in those 1% of those cases we see issues like this:
WARN o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'errorPageFilterRegistration' defined in org.springframework.boot.web.servlet.support.Error
PageFilterConfiguration: Unsatisfied dependency expressed through method 'errorPageFilterRegistration' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'errorPageFilter' defined in org.springframework.boot.web.servlet.support.ErrorPageFilterConfiguration: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.spring
framework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.autoconfigu
re.web.servlet.error.ErrorMvcAutoConfiguration]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration.<init>() []
For some reason it tries to initialize AutoConfiguration beans by using a default constructor which obviously is not present. There is a constructor present which should be autowired.
Also the AutoConfiguration that is in the stacktrace can be different. Sometimes it is another one like e.g. org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration
Any help or ideas on why this could be happening is appreciated. As this happens very occasionally this is hard to debug as we cannot relyably reproduce. Note that the stacktrace does not contain any custom code. Our application is quite big and we rely mostly on #Configuration classes to do configure the Beans.
Why would spring attempt to initialize an AutoConfiguration bean with a default constructor ?
The errorPageFilterConfiguration source of spring looks like this:
#Configuration(proxyBeanMethods = false)
class ErrorPageFilterConfiguration {
#Bean
ErrorPageFilter errorPageFilter() {
return new ErrorPageFilter();
}
#Bean
FilterRegistrationBean<ErrorPageFilter> errorPageFilterRegistration(ErrorPageFilter filter) {
FilterRegistrationBean<ErrorPageFilter> registration = new FilterRegistrationBean<>(filter);
registration.setOrder(filter.getOrder());
registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC);
return registration;
}
}
According to the stack on creation of the errorPageFilter it is initializing the ErrorMvcAutoConfiguration as a prerequisite ? Why ?
We are not initializing these beans manually. The only relevant code for error page handling that we have is this following:
#Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> webServerFactoryCustomizer() {
return webServerFactory -> {
ErrorPage errorPage = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error");
webServerFactory.addErrorPages(errorPage);
};
}
This is a bug in Spring framework, introduced in version 5.3 in AbstractBeanFactory.
BeanPostProcessorCacheAwareList and accesses to the beanPostProcessors instance are not Thread safe. If multiple Threads are running during initialization and a Thread calls getBeanPostProcessorCache() while another Thread is calling addBeanPostProcessors, you can create a cache which does not contain all BeanPostProcessor instances and thus doesn't find the appropriate constructor.
I will submit a bug for this to spring-framework.
https://github.com/spring-projects/spring-framework/blob/16ea4692bab551800b9ba994ac08099e8acfd6cd/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java#L964
Issue created : https://github.com/spring-projects/spring-framework/issues/29299

Create a spring session in amqp rpc client

I developped spring remoting amqp rpc applications.
That's works well for methods that don't use bean with Scope SESSION.
For the other methods, the client can't use spring session, and I get this exception
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.userSession': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:362) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35) ~[spring-aop-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673) ~[spring-aop-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at io.kzreactive.akwtype.akwtypeback.common.service.UserSession$$EnhancerBySpringCGLIB$$55d53e95.setUser(<generated>) ~[classes/:na]
at io.kzreactive.akwtype.akwtypeback.engine.service.AppService.login(AppService.kt:30) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
at org.springframework.remoting.support.RemoteInvocation.invoke(RemoteInvocation.java:215) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.remoting.support.DefaultRemoteInvocationExecutor.invoke(DefaultRemoteInvocationExecutor.java:39) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at io.kzreactive.akwtype.akwtypeback.gateway.rabbitmq.SessionDefaultRemoteInvocationExecutor.invoke(RabbitMQSession.kt:48) ~[classes/:na]
at org.springframework.remoting.support.RemoteInvocationBasedExporter.invoke(RemoteInvocationBasedExporter.java:78) [spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.remoting.support.RemoteInvocationBasedExporter.invokeAndCreateResult(RemoteInvocationBasedExporter.java:114) [spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.amqp.remoting.service.AmqpInvokerServiceExporter.onMessage(AmqpInvokerServiceExporter.java:80) [spring-amqp-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:1457) [spring-rabbit-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.actualInvokeListener(AbstractMessageListenerContainer.java:1348) [spring-rabbit-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:1324) [spring-rabbit-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:1303) [spring-rabbit-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doReceiveAndExecute(SimpleMessageListenerContainer.java:785) ~[spring-rabbit-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.receiveAndExecute(SimpleMessageListenerContainer.java:769) ~[spring-rabbit-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$700(SimpleMessageListenerContainer.java:77) ~[spring-rabbit-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1010) ~[spring-rabbit-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at java.base/java.lang.Thread.run(Thread.java:844) ~[na:na]
Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131) ~[spring-web-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.web.context.request.SessionScope.get(SessionScope.java:55) ~[spring-web-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:350) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
... 24 common frames omitted
So I would create and use a spring session over rabbit mq
First, I managed to pass the sessionId in RPC call
on the server I add an attribute
class SessionDefaultRemoteInvocationFactory : DefaultRemoteInvocationFactory() {
override fun createRemoteInvocation(methodInvocation: MethodInvocation?): RemoteInvocation {
return super.createRemoteInvocation(methodInvocation)
.apply { addAttribute("sessionId", RequestContextHolder.currentRequestAttributes().sessionId) }
}
}
on the client I can read it
class SessionDefaultRemoteInvocationExecutor : DefaultRemoteInvocationExecutor() {
override fun invoke(invocation: RemoteInvocation?, targetObject: Any?): Any {
if (invocation is RemoteInvocation) {
invocation.getAttribute("sessionId")?.let {
val sessionId = it.toString()
SecurityContextHolder.getContext().authentication = AnonymousAuthenticationToken(sessionId,
"anonymousUser", listOf(SimpleGrantedAuthority("ROLE_ANONYMOUS")))
val attr = RequestContextHolder.currentRequestAttributes() as ServletRequestAttributes // <= ERROR here
attr.request.getSession(true)
}
}
return super.invoke(invocation, targetObject)
}
}
but I don't manage to use it to create a spring session
How can I create a spring session in this NON http context
I tried to create a request context listener
#Configuration
#WebListener
class MyRequestContextListener : RequestContextListener()
but same error
For the moment I bypass the spring session and I inject a bean with the same behavior
#Component
#Scope("singleton")
class EngineThread(var engineSession: ThreadLocal<EngineSession> = ThreadLocal()) : IEngineSession by engineSession.getOrSet( { EngineSession() })
#Component
#Profile("engine & !test")
class SessionDefaultRemoteInvocationExecutor(val engineThread: EngineThread) : DefaultRemoteInvocationExecutor() {
val engineSessionStore : MutableMap<String, EngineSession> = mutableMapOf()
override fun invoke(invocation: RemoteInvocation?, targetObject: Any?): Any {
if (invocation is RemoteInvocation) {
invocation.getAttribute(SESSION_ID)?.let {
val sessionId = it.toString()
SecurityContextHolder.getContext().authentication = AnonymousAuthenticationToken(sessionId,
"anonymousUser", listOf(SimpleGrantedAuthority("ROLE_ANONYMOUS")))
if (! engineSessionStore.contains(sessionId)) {
engineSessionStore.put(sessionId, EngineSession())
}
engineThread.engineSession.set(engineSessionStore.getValue(sessionId))
}
}
return super.invoke(invocation, targetObject)
}
}
The job is done but I'm not very well with this solution
(I will add clean by softreference… but all this work is reinvent session instead of use spring session)

Spring Boot startup throws Exception: No thread-bound request found for request scoped bean

I'm trying to build a Proof-of-Concept using Spring Boot (1.3.5) with Jersey. My pom has the spring-boot-starter-jersey artifact listed as a dependency.
With only singleton beans defined, it works fine. However, I've now tried to inject request-scoped beans into a singleton bean and am running into the following exception:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.jndi': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:355) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35) ~[spring-aop-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.getTarget(CglibAopProxy.java:687) ~[spring-aop-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:637) ~[spring-aop-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at $java.util.Properties$$EnhancerBySpringCGLIB$$1a020092.size(<generated>) ~[na:na]
at org.springframework.jndi.JndiTemplate.createInitialContext(JndiTemplate.java:133) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.jndi.JndiTemplate.getContext(JndiTemplate.java:103) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:85) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:152) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:179) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:95) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:106) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.ejb.access.AbstractRemoteSlsbInvokerInterceptor.lookup(AbstractRemoteSlsbInvokerInterceptor.java:99) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.ejb.access.AbstractSlsbInvokerInterceptor.refreshHome(AbstractSlsbInvokerInterceptor.java:121) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.ejb.access.SimpleRemoteSlsbInvokerInterceptor.refreshHome(SimpleRemoteSlsbInvokerInterceptor.java:162) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.ejb.access.AbstractSlsbInvokerInterceptor.afterPropertiesSet(AbstractSlsbInvokerInterceptor.java:108) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.ejb.access.SimpleRemoteStatelessSessionProxyFactoryBean.afterPropertiesSet(SimpleRemoteStatelessSessionProxyFactoryBean.java:101) ~[spring-context-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
... 21 common frames omitted
Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131) ~[spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.web.context.request.AbstractRequestAttributesScope.get(AbstractRequestAttributesScope.java:41) ~[spring-web-4.2.6.RELEASE.jar:4.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:340) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
... 40 common frames omitted
According to what I read, I need to enable the RequestContextListener, which I have done, but it hasn't made any difference:
#Configuration
public class AppConfig {
#Bean(name="jndi")
#Scope(scopeName=WebApplicationContext.SCOPE_REQUEST, proxyMode=ScopedProxyMode.TARGET_CLASS)
public Properties getJNDIContext(){
Properties p = new Properties();
p.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces" );
p.setProperty("java.naming.provider.url", "jnp://localhost:1099");
p.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.security.jndi.JndiLoginInitialContextFactory");
p.setProperty(Context.SECURITY_PRINCIPAL,"test" );
p.setProperty(Context.SECURITY_CREDENTIALS,"12345678" );
return p;
}
#Bean
public FactoryBean<?> getAthleteManagerFactory(#Qualifier("jndi") Properties p){
SimpleRemoteStatelessSessionProxyFactoryBean factory = new SimpleRemoteStatelessSessionProxyFactoryBean();
String beanName = "zone.jndi.ejb3.RemoteAthleteManager";
factory.setJndiName(beanName);
factory.setBusinessInterface(AthleteManager.class);
factory.setJndiEnvironment(p);
return factory;
}
#Bean
public RequestContextListener requestContextListener(){
return new RequestContextListener();
}
}
And my controller is fairly simple:
#Component
#Path("/athlete")
public class AthleteController {
#Autowired
private AthleteManager athleteManager;
....
....
}
I suspect the error is that the factory is trying to instantiate the object using a proxied request-scoped bean to inject into my Controller, and the request scope doesn't yet exist.
Is there a way to resolve this problem? I would have expected the proxyMode to handle the issue, but it doesn't seem to make any difference. I get similar (albeit slightly different) exception stack traces with or without the proxyMode enabled.
If I mark my factory as Lazy, it still doesn't make a difference as Spring needs to instantiate it (and its object) in order to autowire my controller class.
Is there any way to do this? My need is for a filter to override the credentials in the getJNDIContext() properties object at each call.
I finally found a solution to my issue, although I don't particularly like it. For starters, I need to delay the JNDI bean lookup/initialization from startup so that the container doesn't try to populate the JNDI properties until they are actually available (only at the Request time). I also noticed that I am unable to scope the JNDI to the request scope, and consequently have to look it up every time (or the authentication credentials may be incorrect).
#Bean(name="jndi")
#Scope(scopeName=WebApplicationContext.SCOPE_REQUEST, proxyMode=ScopedProxyMode.TARGET_CLASS)
public Properties getJNDIContext(){
Properties p = new Properties();
p.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces" );
p.setProperty("java.naming.provider.url", "jnp://localhost:1099");
p.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.security.jndi.JndiLoginInitialContextFactory");
return p;
}
#Bean
public FactoryBean<?> getLoginManagerFactory(#Qualifier("jndi") Properties p){
return getEjbFactoryBean(LoginManager.class, p );
}
/**
* Helper method to setup the factory
* #param clazz
* #param jndi
* #return
*/
private SimpleRemoteStatelessSessionProxyFactoryBean getEjbFactoryBean(Class clazz, Properties jndi){
SimpleRemoteStatelessSessionProxyFactoryBean factory = new SimpleRemoteStatelessSessionProxyFactoryBean();
// need to delay lookup since security params are only available in a request thread
factory.setLookupHomeOnStartup(false);
// refresh home in case EJB server is restarted
factory.setRefreshHomeOnConnectFailure(true);
// do not cache - need to lookup every time due to changing security params. They are only set upon initial bean lookup
factory.setCacheHome(false);
// set the JNDI properties
factory.setJndiEnvironment(jndi);
String beanName = REMOTE_EJB_PREFIX + clazz.getSimpleName();
factory.setJndiName(beanName);
factory.setBusinessInterface(clazz);
return factory;
}
Finally, I set up a filter to specify my credentials on every request:
#Provider
public class SecurityFilter implements ContainerRequestFilter {
#Autowired #Qualifier("jndi")
private Properties userCreds;
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// extract username/password from basic auth
String[] auth = decode( requestContext.getHeaderString(HttpHeaders.AUTHORIZATION) );
userCreds.setProperty(Context.SECURITY_PRINCIPAL, auth[0] );
userCreds.setProperty(Context.SECURITY_CREDENTIALS, auth[1] );
}
}
Conceptually, this works, but it is very inefficient. I would like to find a solution that allows me to do the same, but at least scope my bean at the request level, so that it isn't retrieved every time.

why Mixing Spring AOP proxy mechanisms (CGLIB and JDKDynmic) for dependent beans does not work

I have two public classes configured as follows in Spring application context:
public class LoadErrorData{
private ExceptionData exceptionData;
public LoadErrorData() { }
// reminder
}
public class ExceptionData implements Serializable{
private Resource exceptionDataResource;
public ExceptionData() { }
// reminder
}
Spring applicationContext.xml :
<beans:bean id="loadErrorData" class="com.startup.LoadErrorData" init-method="startup">
<beans:property name="exceptionData" ref="exceptionData"/>
</beans:bean>
<beans:bean id="exceptionData" class="com.server.ExceptionData" init-method="startup">
<beans:property name="exceptionDataResource" value="classpath:${exception.datafile.path}"/>
</beans:bean>
It gives following Exception while initializing :
Oct 07, 2013 1:45:21 PM org.apache.catalina.core.StandardContext
listenerStart SEVERE: Exception sending context initialized event to
listener instance of class
org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'loadErrorData' defined in class path resource
[spring/startup-config.xml]: Initialization of bean failed; nested
exception is
org.springframework.beans.ConversionNotSupportedException: Failed to
convert property value of type 'com.sun.proxy.$Proxy12 implementing
java.io.Serializable,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised'
to required type 'com.server.IICExceptionData' for property
'exceptionData'; nested exception is java.lang.IllegalStateException:
Cannot convert value of type [com.sun.proxy.$Proxy12 implementing
java.io.Serializable,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised]
to required type [com.server.IICExceptionData] for property
'exceptionData': no matching editors or conversion strategy found 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:609)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:469)
at
org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383)
at
org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
at
org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at
org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4723)
at
org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5226)
at
org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5221)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166) 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.ConversionNotSupportedException: Failed to
convert property value of type 'com.sun.proxy.$Proxy12 implementing
java.io.Serializable,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised'
to required type 'com.server.IICExceptionData' for property
'exceptionData'; nested exception is java.lang.IllegalStateException:
Cannot convert value of type [com.sun.proxy.$Proxy12 implementing
java.io.Serializable,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised]
to required type [com.server.IICExceptionData] for property
'exceptionData': no matching editors or conversion strategy found at
org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:485)
at
org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:516)
at
org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:510)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1406)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1365)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1118)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
... 19 more Caused by: java.lang.IllegalStateException: Cannot convert
value of type [com.sun.proxy.$Proxy12 implementing
java.io.Serializable,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised]
to required type [com.server.IICExceptionData] for property
'exceptionData': no matching editors or conversion strategy found at
org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:241)
at
org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:470)
... 25 more
but when i put
<aop:scoped-proxy proxy-target-class="true"/>
in ExceptionData bean configuration OR if i remove
implements Serializable
from ExceptionData
exception goes away. My AOP pointcut is as follows:
expression="execution(* com..*(..))"
It seems that Spring is trying to create CGLIB proxy for bean LoadErrorData (as it does not implement any interface) and JDKdynamicProxy for its dependency ExceptionData (as it does implement interface Serializable). And it is not able to do so. Because when i tell spring to create CGLIB proxy explicitly for ExceptionData it works fine. Why is this so? Why it is not able to create JDKDynamic Proxy for a bean(ExceptionData) who is a dependency of bean (LoadErrorData) for which it is trying to Create CGLIB proxy? According to documentation it says that Spring will detect it automatically.
Actually the situation you describe is exactly what is happening.
LoadErrorData is going to be a CgLIB proxy (due to no interfaces.
ExceptionData is going to be a JDK Dynamic Proxy.
However your LoadErrorData expects a bean of type ExceptionData, the JDK Dynamic proxy is only a Serializable (as it will only proxy interfaces and not classes). It will never be possible to cast this to an instance of ExceptionData and hence the loading of the context will fail. (This is also what the stacktrace tells you from the error message).
It will work if you are forcing class based proxies for everything or by removing the Serializable interface. Either way will lead to a classbased proxy.

Calling session Bean deployed on jboss 5.x from client side

I'm running JBoss 5.1 GA with JDK 1.6 on Linux and trying to call session bean(jar containing this session bean is deployed on jboss server), Now i want to call this session bean from client, but didnt work.
Java Code at client Side
public class CallingJbossSessionBeanFromClient {
/**
* #param args
* #throws Exception
*/
public static void main(String[] args) throws Exception
{
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
p.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
p.put(Context.PROVIDER_URL, "jnp://182.158.93.41:8080");
Context context = new InitialContext(p);
System.out.println("Successfully Lookup and going to call SessionBean Function deployed on JBoss-5.1.0 Server");
SlsSessiongRemote remote=(SlsSessionRemote) context.lookup("SlsSessionBean/remote");
//SlsSessionBean/remote is RemoteBinding of session Bean
System.out.println("Called");
}
}
where 'SlsSessionBean/remote' is remote binding of session bean deployed on jboss server.
#Stateless
#RemoteBinding(jndiBinding="SlsSessionBean/remote")
but end up with following error
Exception in thread "main" javax.naming.NoInitialContextException: Cannot instantiate class: org.jnp.interfaces.NamingContextFactory [Root exception is java.lang.ClassNotFoundException: org.jnp.interfaces.NamingContextFactory]
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:657)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.init(InitialContext.java:223)
at javax.naming.InitialContext.<init>(InitialContext.java:197)
at CallingJbossSessionBeanFromClient.main(CallingJbossSessionBeanFromClient.java:20)
Caused by: java.lang.ClassNotFoundException: org.jnp.interfaces.NamingContextFactory
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:303)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:316)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at com.sun.naming.internal.VersionHelper12.loadClass(VersionHelper12.java:46)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:654)
... 4 more
After seeing above error i added jbossjmx-ant.jar in the classpath of 'CallingJbossSessionBeanFromClient' class and got following error
Exception in thread "main" java.lang.NoClassDefFoundError: org/jboss/logging/Logger
at org.jnp.interfaces.NamingContext.<clinit>(NamingContext.java:181)
at org.jnp.interfaces.NamingContextFactory.getInitialContext(NamingContextFactory.java:55)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.init(InitialContext.java:223)
at javax.naming.InitialContext.<init>(InitialContext.java:197)
at CallingJbossSessionBeanFromClient.main(CallingJbossSessionBeanFromClient.java:20)
Caused by: java.lang.ClassNotFoundException: org.jboss.logging.Logger
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:303)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:316)
... 7 more
After seeing above error i added jboss-logging-spi.jar in the classpath of 'CallingJbossSessionBeanFromClient' class and got following error
Exception in thread "main" javax.naming.CommunicationException: Could not obtain connection to any of these urls: 182.158.93.41:8080 and discovery failed with error: javax.naming.CommunicationException: Receive timed out [Root exception is java.net.SocketTimeoutException: Receive timed out] [Root exception is javax.naming.CommunicationException: Failed to retrieve stub from server /182.158.93.41:8080 [Root exception is java.io.EOFException]]
at org.jnp.interfaces.NamingContext.checkRef(NamingContext.java:1763)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:693)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:686)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at CallingJbossSessionBeanFromClient.main(CallingJbossSessionBeanFromClient.java:22)
Caused by: javax.naming.CommunicationException: Failed to retrieve stub from server /182.158.93.41:8080 [Root exception is java.io.EOFException]
at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:327)
at org.jnp.interfaces.NamingContext.checkRef(NamingContext.java:1734)
... 4 more
Caused by: java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2281)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2750)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:780)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:280)
at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:312)
... 5 more
Plz tell me, am i on the right way to call sesion bean from client java class?
I have spent hours looking for solution on Google. However I cannot seem to find anything that holds the hand..try to be more clear, i'm in lack of ideas in this problem, even it sounds like a classic
Plz suggest solution
The solution to this problem is to open the JMX-Console and click on the service=Naming to view the MBean view of the Naming service. Check if the port used is still 1099.....
Changed the URL to jnp://182.158.93.41:1299, the client could communicate with the EJB.
If you are running over JBoss AS 5.x
Here is RMI based JNDI description.
RMI-Port: default -1099 / If dynamic port changed to ports-01 Then Port is 1199
Now, Remaining Things are OK, Modify code ass below
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
p.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
p.put(Context.PROVIDER_URL, "jnp://182.158.93.41:1199");
Another Point is case of accessing
SlsSessiongRemote remote=(SlsSessionRemote) context.lookup("SlsSessionBean/remote");
if - #Stateless(name="SlsSessionBean")
Then Remote JNDI- [SlsSessionBean/remote] and Local JNDI - [SlsSessionBean/local]
if - #Stateless(name="SlsSessionBean", mappedName="SlsSessionBeanGlobal")
Then Remote JNDI- [SlsSessionBeanGlobal] and Local JNDI - [SlsSessionBean/local]

Resources