Access session bean member variable from EJB asynchronous method - asynchronous

I have a #SessionScoped bean (CDI) that I would like to access and update from a EJB #Asynchronous method. If I pass a reference to a member variable in the bean via the #Asynchronous method's parameters and work with it, assuming the object being passed in is made thread safe, is there any other issues I should be aware of?
Is there any different to be aware if a #ViewScoped bean is used instead?
The only one I could think of would be if the CDI Session Bean timed out however that shouldn't be an issue because the object would be retained as the #Asynchronous method still has a reference to it.
I'm trying to pass off a long running task so as not to hold up the user clicking on a button but still update the session model with the result of the job so the user can see the outcome in a "job viewer" type interface.

Never access frontend classes from backend classes.
Just pass a callback to the EJB method.
#Asynchronous
public void asyncDoSomething(SomeInput input, Consumer<SomeResult> callback) {
SomeResult result = doSomethingWith(input);
callback.accept(result);
}
public void yourSessionScopedBeanMethod() {
yourEjb.asyncDoSomething(input, this::setResult);
}
public void setResult(SomeResult result) {
this.result = result;
}

Related

Keep #RequestScoped context when receiving an async CDI event

I want to switch from firing CDI beans synchronous to asynchronous to be able to work stuff parallel.
event.fire(myObject) -> event.fireAsync(myObject)
As I currently use the request context to know what tenant the current process is about, I am confronted with the problem, that the #RequestScoped context is lost in a #ObservesAsync method. Therefor I don't know anymore to what db to persist etc. I could provide the necessary information in the cdi event object and recreate the requestcontext manually after recieving, but this would bloat my object and clutter my code.
Is there a way to simply keep the request context for a async cdi event?
Request scoped objects are not required to be thread-safe and usually are not. For that reason, request context is never automatically propagated across threads. For asynchronous events, indeed you should put all the necessary data into the event object.
You are of course not the first person to ask about this. There's been attempts to define an API/SPI for context propagation (MicroProfile Context Propagation, Jakarta Concurrency), including CDI request context, but they only work correctly in case of sequential processing with thread jumps (common in non-blocking/reactive programming). If you try to [ab]use context propagation for concurrent processing, you're signing up for troubles. For the latest discussion about this, see https://github.com/jakartaee/cdi/issues/474
I actually switched to using interfaces. This gives me more control and makes the code more understandable:
abstract class Publisher<T>{
#All
#Inject
private List<EventConsumer<T>> eventConsumers;
#Inject
private ContextInfo contextInfo;
#Inject
private MutableContextInfo mutableContextInfo;
...
public void publishEvent(T event){
String myContextInfo= contextInfo.getMyContextInfo();
eventConsumers.forEach(consumer -> notifyAsync(consumer, receivedObject, myContextInfo))
}
private void notifyAsync(EventConsumer<T> consumer, T object, String myContextInfo) {
Uni.createFrom()
.voidItem()
.subscribeAsCompletionStage()
.thenAccept(voidItem -> notifyConsumer(consumer, object, myContextInfo));
}
/**
* Method needs to be public to be able to activate request context on self invocation
*/
#ActivateRequestContext
public void notifyConsumer(EventConsumer<T> consumer, T object, String myContextInfo) {
mutableContextInfo.setMyContextInfo(myContextInfo);
try {
consumer.onEvent(object);
} catch (RuntimeException ex) {
log.error("Error while promoting object to eventconsumer", ex);
}
}
}

.net transient database context being disposed prematurely

I am moving an asp.net mvc5 application using EF6 to asp.net core MVC 3.0 using EF Core.
In my mvc5 application I have some administrative operation that modify the database and take a long time, so I use a pattern when I create a new DBContext that is not the one that is associated with the request context and then run the task in the background using Task.Run. This has been working fine for years.
In converting to .net core it was unclear how to create a new DBContext in the way that I was doing it in my old codebase. It seems like I should be able to create a Transient DBContext in these cases and all should be fine.
So I created a subclass of MyDbContext called MyTransientDbContex and in my Configure class I added this service:
services.AddDbContext<MyTransientDbContex>(options =>
options.UseSqlServer(
context.Configuration.GetConnectionString("MyContextConnection")),
ServiceLifetime.Transient, ServiceLifetime.Transient);
In my controller I inject the context in the action that needs the transient service and spawn a thread to do something with it:
public ActionResult Update([FromServices] MyTransientContext context) {
Task.Run(() =>
{
try {
// Do some long running operation with context
}
Catch (Exception e) {
// Report Exception
}
finally {
context.Dispose();
}
}
return RedirectToAction("Status");
}
I would not expect my transient context to be disposed until the finally block. But I am getting this exception when attempting to access the context on the background thread:
Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'MyTransientContext'.'
And indeed the _disposed flag is set to true on the context object.
I put a breakpoint on the constructer for MyTransientContext and "Made an Object ID" of the this pointer so that I could track the object. This transient object is being created and is the same one that is inject into my controller action. It's also the same object that I'm trying to reference when the exception is thrown.
I tried setting a data breakpoint on the _disposed member in order to get a callstack on when disposed is being set to true, but the breakpoint won't bind.
I also tried overriding the Dispose method on MyTransientContext, and it isn't called until my explicit dispose in the finally block, which is after the exception is thrown and caught.
I feel like I'm missing something fundamental here. Isn't this what the transient services are for? What would dispose a Transient service?
One last detail - MyTransientContext is derived from MyContext, which is in turn derived from IdentityDbContext (Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityDbContex)
Edit: The reason that I went down the path of using a Transient was because of this ef core document page: https://learn.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext. It states that "...any code that explicitly executes multiple threads in parallel should ensure that DbContext instances aren't ever accessed concurrently. Using dependency injection, this can be achieved by either registering the context as scoped and creating scopes (using IServiceScopeFactory) for each thread, or by registering the DbContext as transient (using the overload of AddDbContext which takes a ServiceLifetime parameter)."
As xabikos pointed out, this seems to be overriden by the scoping of the asp.net DI system, where it looks like anything created by that system is scoped to the request context, including Transient objects. Can someone point out where that's documented so that I can better understand how to work with the limitations?
f you want manage the lifetime of service, you can instantiate it manually (or use a factory) :
public ActionResult Update()
{
Task.Run(() =>
{
using(var context = new MyTransientContext(...))
{
try
{
// Do some long running operation with context
}
catch (Exception e)
{
// Report Exception
}
}
}
return RedirectToAction("Status");
}
Or you can use IServiceProvider to get and manage a service :
public class MyController
{
private IServiceProvider _services;
public MyController(IServiceProvider services)
{
_services = services;
}
public ActionResult Update()
{
var context = (MyTransientContext)_services.GetService(typeof(MyTransientContext));
Task.Run(() =>
{
using (context)
{
try
{
// Do some long running operation with context
}
catch (Exception e)
{
// Report Exception
}
}
}
return RedirectToAction("Status");
}
}
You mixed the concepts of transient objects that are created by internal DI container asp.net core provides.
You configure the MyTransientContext to be transient in the internal DI system. This practically means that every time a scope is created then a new instance is returned. For asp.net application this scope matches an HTTP request. When the requests ends then all the objects are disposed if applicable.
Now in your code, that is a synchronous action method you spawn a Task with Task.Run. This is an async operation and you don't await for this. Practically during execution this will be started but not wait to finish, the redirect will happen and the request will end. At this point if you try to use the injected instance you will get the exception.
If you would like to solve this you need change to an async action and await on the Task.Run. And most likely you don't need to spawn a new Task. But you need to understand that this is not probably the best way as it will need for the long operation to finish before the redirect takes place.
An alternative to this would be to use a messaging mechanism, and send a message that triggers this operation. And you have another component, like worker service that listens for those messages and process them.

Testing with autowired dependency like session in Validator

I have few custom annotations defined on fields of an object like:
public class Person{
#Accountname
String email;
}
Implementation class of #Accountname:
#Autowired ValidationService service;
#Autowired ClientSession clientSession;
#Override
public boolean isValid(final String email, final ConstraintValidatorContext ctx) {
if(!service.isAccountValid(email, clientSession)){
return false;
}
}
I am trying to write junits for these annotations.
#Test
public void validEmailTest()
{
person.setEmail("abc#xyz.com");
Set<ConstraintViolation<Person>> violations = validatorInstance.getValidator().validateProperty(person, "email");
Assert.assertEquals(1, violations.size());
}
But its throwing this error when I execute the test:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.clientSession': 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:343)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:34)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.getTarget(CglibAopProxy.java:663)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:614)
at org.hibernate.validator.internal.engine.ConstraintTree.validateSingleConstraint(ConstraintTree.java:308)
... 45 more
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:90)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:329)
... 54 more
Any idea on how to write junits if a validator class has a dependency on services like session etc.?
This should be tested separately (units).
The real logic that validates is in your ValidationService, so test it there, in AccountnameValidator test only the logic that is in there, injecting your dependencies:
#Mock ValidationService service;
#Mock ClientSession clientSession;
#InjectMocks AccountnameValidator av = new AccountnameValidator()
//initialize mocks
//example test
when(service.isAccountValid(email, clientSession)).thenReturn(true);
boolean result = av.isValid(email, ctx);
assertTrue(result);
And finally if you want you can validate presence of the annotation in Person class on email field using reflection.

EJB stateless - Private members initialisation

I'm new to EJB and I'm facing my first problem. I'm trying to use an #Schedule method contained in a Stateless EJB. I'd like this method to use a private member variable which would be set at bean creation:
Here's a short example:
#Singleton
#LocalBean
#Startup
public class Starter {
#PostActivate
private void postActivate() {
ScheduleEJB scheduleEjb = new ScheduleEJB("Hello");
}
}
And the schedule bean:
#Stateless
#LocalBean
public class ScheduleEJB {
private String message;
public ScheduleEJB() {
super();
}
public ScheduleEJB(String message) {
super();
this.message= message;
}
#Schedule(second="*/3", minute="*", hour="*", dayOfMonth="*", dayOfWeek="*", month="*", year="*")
private void printMsg() {
System.out.println("MESSAGE : " + message);
}
}
The problem is that my "message" variable is always null when printed in the printMsg() method... What's the best way to achieve this?
Thanks for your help !
You're mixing few things here.
The #PostActivate annotation is to be used on Stateful Session Beans (SFSB), and you use it on the singleton. I guess that you mean the #PostConstruct method which applies to every bean which lifecycle is managed by the container.
You're using a constructor from your EJB. You cannot do:
ScheduleEJB scheduleEjb = new ScheduleEJB("Hello");
as it creates just an instance of this class. It's not an EJB - the container didn't create it, so this class does not have any EJB nature yet.
That's the whole point of dependency injection - you just define what you want and the container is responsible for providing you with an appropriate instance of the resource.
The Stateless Bean (SLSB) is not intented to hold the state. The SFSB is. Even if you would set the message in one SLSB method (i.e. in some ScheduleEJB#setMessage(String) method) than you need to remember that the EJB's are pooled. You don't have any guarantee that the next time you invoke a method on the ScheduleEJB you will get to the same instance.
In your case it would be the easies solution just to add the #Schedule method to your singleton class. Than you can define the variable of your choice in the #PostConstruct method. You can be sure that there is only one Singleton instance per JVM, so your variable will be visible in the Schedule annotated method of the same class.
HTH.

SessionContext.getBusinessObject() in EJB3 & JNDI lookup

In EJB2, one needed to use getEJBBusinessObject() method in a EJB to pass reference to itself when calling another (local/remote) bean.
Does the same apply for EJB3?
e.g.
#Stateless
public class MyBean implements MyBeanLocal {
#Resource private SessionContext sessionContext;
public void myMethod() {
OtherBeanLocal otherBean = ...; // getting reference to other local EJB.
MyBeanLocal myBean = sessionContext.getBusinessObject(MyBeanLocal.class);
b.aMethod(myBean);
}
// Edit: calling myMethodTwo() from inside of myMethodOne()
public void myMethodOne() {
MyBeanLocal myBean = sessionContext.getBusinessObject(MyBeanLocal.class);
myBean.myMethodTwo();
}
public void myMethodTwo() {
...
}
...
}
Also, if I fetch my local bean using getBusinessObject() method, is it the same as if I use common JNDI lookup?
I've tested both approach, and both work, but I'm not sure if bean object is processed the same way by the container.
Edit:
Is fetching the reference to ejb itself, when calling myMethodTwo() from inside myMethodOne() of the same ejb, in EJB3, still needed? Is it allowed to call methods inside the same ejb through this reference?
How will this address transactions, if I decide to use some?
Yes, the same applies to EJB 3. Yes, getBusinessObject is the EJB 3 analog to getEJBObject (or getEJBLocalObject). All of those methods return a proxy for the current bean object. For stateless session beans, this is basically the same as looking up through JNDI, though it's likely to perform better since it avoids JNDI overhead.

Resources