EJB stateless - Private members initialisation - initialization

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.

Related

How to keep a statefull bean clean or reset during a #QuarkusTest?

I test a statefull bean with a #QuarkusTest. It keeps a certain state. Obviously, I would like to have a fresh bean for every test. At the moment, each test might modify he current state, which is the effective for a oncoming test. This is highly undersireable and breaks my tests.
Is there a way to force a new bean clean bean getting injected for every test when running a #QuarkusTest?
Eg. A very basic subscription service, which holds the current subscription to avoid double subscriptions:
#ApplicationScoped
public class SubscriptionService {
#Inject
DeviceClient deviceClient;
private final Set<String> subscribedDevices = new HashSet<>();
public void subscribe(String deviceId, Consumer<RadarFrame> consumer){
if(subscriptions.contains(deviceId)){
return;
}
deviceClient.subscribe(deviceId, consumer);
subscriptions.add(deviceId);
}
public void unsubscribe(String deviceId, Consumer<RadarFrame> consumer){
deviceClient.unsubscribe(deviceId);
subscriptions.remove(deviceId);
}
}
I could manually unsubscribe the device after each test, which is a bad small as I use potention untested implemented logic for setup/teardown. It would be nice if a injected bean could be reinitialized before each test on a #QuarkusTest.
Or did I miss another clean option?
#ApplicationScoped beans will be there for the entire life of the container.
The recommended way to do this is to create a reset() method in the bean to later be called in tests. With JUnit 5 this would be something like:
#AfterEach
void tearDown() {
subscriptionService.reset();
}
You can make that method package friendly to limit it's usage.

How to use ResourceProcessorHandlerMethodReturnValueHandler in a spring-hateos project

When using spring-data-rest there is a post processing of Resource classes returned from Controllers (e.g. RepositoryRestControllers). The proper ResourceProcessor is called in the post processing.
The class responsible for this is ResourceProcessorHandlerMethodReturnValueHandler which is part of spring-hateoas.
I now have a project that only uses spring-hateoas and I wonder how to configure ResourceProcessorHandlerMethodReturnValueHandler in such a scenario. It looks like the auto configuration part of it still resides in spring-data-rest.
Any hints on how to enable ResourceProcessorHandlerMethodReturnValueHandler in a spring-hateoas context?
I've been looking at this recently too, and documentation on how to achieve this is non-existent. If you create a bean of type ResourceProcessorInvokingHandlerAdapter, you seem to lose the the auto-configured RequestMappingHandlerAdapter and all its features. As such, I wanted to avoid using this bean or losing the WebMvcAutoConfiguration, since all I really wanted was the ResourceProcessorHandlerMethodReturnValueHandler.
You can't just add a ResourceProcessorHandlerMethodReturnValueHandler via WebMvcConfigurer.addReturnValueHandlers, because what we need to do is actually override the entire list, as is what happens in ResourceProcessorInvokingHandlerAdapter.afterPropertiesSet:
#Override
public void afterPropertiesSet() {
super.afterPropertiesSet();
// Retrieve actual handlers to use as delegate
HandlerMethodReturnValueHandlerComposite oldHandlers = getReturnValueHandlersComposite();
// Set up ResourceProcessingHandlerMethodResolver to delegate to originally configured ones
List<HandlerMethodReturnValueHandler> newHandlers = new ArrayList<HandlerMethodReturnValueHandler>();
newHandlers.add(new ResourceProcessorHandlerMethodReturnValueHandler(oldHandlers, invoker));
// Configure the new handler to be used
this.setReturnValueHandlers(newHandlers);
}
So, without a better solution available, I added a BeanPostProcessor to handle setting the List of handlers on an existing RequestMappingHandlerAdapter:
#Component
#RequiredArgsConstructor
#ConditionalOnBean(ResourceProcessor.class)
public class ResourceProcessorHandlerMethodReturnValueHandlerConfigurer implements BeanPostProcessor {
private final Collection<ResourceProcessor<?>> resourceProcessors;
#Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
if (bean instanceof RequestMappingHandlerAdapter) {
RequestMappingHandlerAdapter requestMappingHandlerAdapter = (RequestMappingHandlerAdapter) bean;
List<HandlerMethodReturnValueHandler> handlers =
requestMappingHandlerAdapter.getReturnValueHandlers();
HandlerMethodReturnValueHandlerComposite delegate =
handlers instanceof HandlerMethodReturnValueHandlerComposite ?
(HandlerMethodReturnValueHandlerComposite) handlers :
new HandlerMethodReturnValueHandlerComposite().addHandlers(handlers);
requestMappingHandlerAdapter.setReturnValueHandlers(Arrays.asList(
new ResourceProcessorHandlerMethodReturnValueHandler(delegate,
new ResourceProcessorInvoker(resourceProcessors))));
return requestMappingHandlerAdapter;
}
else return bean;
}
}
This has seemed to work so far...

Can't use a session ejb in my managed bean cause i get a Null Pointer Exception

First of all I want to say I'm pretty new in programming with ejb and jsf, and I'm trying to complete a project started by a friend of mine.
I'm getting a NullPointerException caused by the invoke of the method utenteSessionBean.CheckUtentebyId(username) of the session bean object called utenteSessionBean, declared inside the managed bean called Neo4jMBean.
I learned that it's not necessary creating and initializing a session bean (as you must do with a normal java object) in managed bean, but it's enough declaring it.
Here is the code of the session bean, which retrieves data from a DB
#Stateless
#LocalBean
public class UtenteSessionBean {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("EnterpriseApplication2-ejbPU");
public boolean CheckUtentebyId(String username){
EntityManager em = emf.createEntityManager();
Query query = em.createNamedQuery("Utente.findByUsername");
query.setParameter("username", username);
List<Utente> Res=query.getResultList();
//completare funzione ctrl+spazio
System.out.println("pre");
System.out.println("pre"+Res.isEmpty());
em.close();
System.out.println("post");
System.out.println("post"+Res.isEmpty());
if(Res.size()>=1)
{
return true;
}
else
{
return false;
}
}
}
Here's the code of the managed bean:
#ManagedBean
#ViewScoped
public class Neo4jMBean {
#EJB
private UtenteSessionBean utenteSessionBean;
static String SERVER_ROOT_URI = "http://localhost:7474/db/data/";
public Neo4jMBean() {
}
public boolean getUser(String username) {
return utenteSessionBean.CheckUtentebyId(username);
}
}
I've searched on StackOverFlow many times a solution for fixing this problem, but I haven't found something that works for me yet.
I fixed it accessing the EJB Components using JNDI.
In few words, if i use an EJB in a managed bean method, i need to add the next lines of code:
InitialContext ic = new InitialContext();
SessionBeanName = (SessionBeanClass) ic.lookup("java:global/NameOfTheApplication/NameOfTheEJBpackage/NameOfTheSessionBean");
It must be surronded by a try-catch statement
Create empty beans.xml file in your WEB-INF folder to enable CDI

Using Spring AOP 3.1.0 to set service instance using method argument

Hi i am new to Annotation and Spring AOP. below is what i am trying to achieve
public interface Service {
public void process(String ServiceName, Bean bean);
}
public class ServiceImpl1 implements Service{
public void process(String ServiceName, Bean bean) {
/// do something here
}
}
public class ServiceImpl2 implements Service{
public void process(String ServiceName, Bean bean) {
/// do something here
}
}
from other class i would be calling something like
...
public void doSomething(String serviceName, Bean bean){
service.process("ServiceImpl1", bean);
}
...
I can achieve the same by using AroundAdvice and Before advice and intercepting my doSomething method and then instantiate the service object after reading the serviceName.
I there is a better approach for this?
I just need a direction and then i will figure this out.
Thanks
Well, I am guessing what you want to do is have a Before advice that takes the passed in service name, creates an object of appropriate class, then calls the appropriate method on that newly created object. It seems like, to me, you are really looking for more of a Factory pattern, but trying to use AOP to accomplish it.
If you took the Factory pattern, you would create a class called ServiceFactory, which takes some parameters and returns the correct Service implementation for those parameters. You calling code would simply use the Factory to get the right Service at runtime.
Another approach, if you want to stick with more of a DI pattern, might be to create a wrapper class that serves as the "conductor". This might have a Map of service names to Service implementation. You could then inject this wrapper into your code, and even inject the Map into the wrapper. Your calling code would call methods on the wrapper, which would locate the correct, singleton implementation and aggrigate the call to it.
I just feel that using AOP for this is asking for trouble.
You can inject the service impl class using the spring #Autowire annotation. Since u have 2 implementation classes, you can use qualifier to specify which impl needs to b injected.

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