Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can ejb interceptors change the return value of a method before the calling class gets it?

If we have code in the field that has a method that another product calls, and gets a list of objects back. And we need to make changes to the code to make it more flexible in populating the list to return, can we in the interim create an interceptor for the customer, that intercepts the method before it returns the list, and remove items from the list before the product that calls the method gets the list.

e.g.

OurCode.search() returns a list of foundObjects

Other product calls OurCode.search, receives 100 items

Can we create an interceptor that intercepts before OurCode.search returns, and alter the List of foundObjects, removing unnecessary items? This would only be a temporary fix until a future release

like image 505
AntóinÓg Avatar asked Jul 25 '12 23:07

AntóinÓg


People also ask

When to use EJB interceptors?

For example, when you want to log something before of after a Beans method is executed. Or when you want to enforce a specific policy concerning method calls, e.g. authentication, input checking etc. Of course an EJB can have a chain of Interceptors that will intercept the method in a specific order.

What is logginginterceptor in EJB?

The EJB is annotated with @Interceptors where the value is a single interceptor: LoggingInterceptor. We defined the interceptor at the type (or class) level so every single call to any EJB method will be intercepted by the LoggingInterceptor interceptor.

How does an interceptor work in Java?

If you declare an Interceptor for a Bean, every time a method of that Bean is invoked, it will be intercepted with one method of the Interceptor. That means that the execution goes straight to the Interceptor’s method. The intercepting method then, can decide whether to call the intercepted EJB method or simply replace it.

What happens when a client invokes an EJB?

If a client invoked our EJB the following output would be generated to the underlying logging system: We may also extract useful information from the InvocationContext instance that is passed to the interceptor method. In this case we are simply logging the EJB method name that is currently being invoked.


1 Answers

While I don't recommend doing it that way (for sake of understandability, and as in my experience the "temporary fix" will become a permanent one) you can do this with Interceptors.

@AroundInvoke
Object filterSearchResults(InvocationContext ctx) throws Exception {
    Object result = ctx.proceed();
    if ( result != null) {
        List<SearchResult> results = (List<SearchResult>)result;
        // do whatever you want to to with your results here
        return results;
    }
    return result;
}
like image 55
Korgen Avatar answered Sep 20 '22 13:09

Korgen