Starting a EJB dependency in CDI project - ejb

Well, i need use #Schedule (EJB) to put a task in crontab. I know that CDI dont have this (unhappy), just EJB. All my beans are CDI-Managed, so i have some doubts to include EJB inside this project, i hope that you can help me:
1) I'll create a new bean to use #Schedule, but i dont know if this bean should use #Singleton (EJB) or #Named + #RequestScoped (CDI). My ideia is that:
#Singleton
public class RoboFtp implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Inject
private VideoBOImpl videoBO;
#Schedule(...)
public void coletarVideo(){
//do something each 3 seconds
}
}
Note that i have a CDI Bean inside a EJB Bean, this is possible ? This above bean is correct ?
2) How can i add the ejb to my pom.xml ?
3) If i add EJB to my project can have any conflicts ? Because my project is already in production.

To dispel your worries:
1) CDI Bean inside a EJB Bean, this is possible ?
CDI && EJB works pretty well together. In fact CDI will detect EJB beans and turn them into CDI beans as well. So if you create, say #Stateful bean, it will be picked up as CDI bean as well. That means you will be able to perform any CDI-related magic there while still having EJB features.
As for choice of annotation, #Singleton sounds reasonable; or probably #Stateful?. #RequestScoped would only live during request and die afterwards hence killing your periodic task. Choose scope based on nature of your task (one bean vs many/ short lived vs permanent/ ..). Just make sure you make it an EJB bean and CDI will follow.
2) How can i add the ejb to my pom.xml ?
Assuming you have Maven project, add a dependency on EJB api, the implementation will be provided by your Java EE application server.
<dependency>
<groupId>javax.ejb</groupId>
<artifactId>ejb-api</artifactId>
<version>${desiredVersion}</version>
</dependency>
3) If i add EJB to my project can have any conflicts ?
Too general question I am afraid; I do not know your project. But I'll go ahead and say "no". At least as far as CDI and EJB goes, you should be able to deal with it.

Related

#stateful and #sessionScoped - difference and when to use them correctly?

I have read different articles on using #Stateful and #SessionScoped annonations and their differences including this post. From a definition point, #sessionScoped is used when a session is needed/created between client/web tier, while #Stateful is needed in Bussiness Logic layer. But I still do not get a hold of the real differences when it comes to implementing them. Here is a simple example
#Named
#SessionScoped
ShoppingCartUIBean {
#inject
shoppingCart cart;
// more code
}
#Stateful
ShoppingCart {
//business logic of adding/updating/deleting cart items
}
How is the Http session maintained by #SessionScoped bean between a given user and server?
That is, if I have a shopping cart opened in different computers, I should be able to see my shopping cart, which is associated with my user profile. How is this established?
what happens if I switch the two annonations on the above beans? will it have any effect?
(sorry this might sound stupid. I am getting into Java EE world, so I want to get basics correct).
According to this great post on Differences : #SessionScoped vs #Stateful and #ApplicationScoped vs #Singleton, #Stateful beans are hardly used in web applications. Is there a case where #Stateful is absolutely necessary?
ON a related note: is it legal to inject a #stateful bean into #ApplicatonScoped bean? This would mean entire the application has a single #stateful bean and all clients uses the same instance of one stateful bean via proxy. (Just as is demonstrated here, not to inject #Stateful in servlets EJB example for stateless and stateful beans difference).
Thanks.
I will try to answer some of your question with my best.
Ad.1 #SessionScoped is about browser session, so you won't see the same session on different computers(or browsers).
Ad.2 You can't think about those two as the same components only because the same scope. Fundamental think is that EJB and JSF beans rely on different architecture layers. EJB beans should implement business logic while jsf beans should maintain forms and other ui components.
Ad.3 #Stateful beans are very useful in seam framework. Using those beans and extended persistance context is solution for lazy initialization error(probably that's a reason why seam creators use those beans). I prefer Stateless beans according to performance but it hardly depends on use case(whether you want keep state or not).
Ad.4 In general you shouldn't inject "less scope" beans to "more scope" beans. Application scope will exist while session may be destroyed and what this application bean should have in place of destroyed session bean?
Correct me if i'am wrong with any of this answers.

Injecting Entity Bean in to EJB Bean using #EJB

I have Stateless Entity Beans(EJB 3.x) and EJB Beans(EJB 2.x) and other classes in my project. I want to inject Entity Bean into EJB Beans. So, far I am able to inject it using JNDI way i.e (BeanName#completename) but I want to inject it using #EJB just like we inject entity beans in another entity beans without any JNDI lookup. Both of these beans are part of different modules but deployed on same server. I am using weblogic with eclipselink.
Entity beans are never injects in EJB beans. You can perform your DB operation on entity beans by using EntityManager. To work with database operation entities must be associated with EntityManager persistence context. so you can not work with your entities until it is not in persistence state.
All the transaction-scoped persistence context are configured by injecting #PersistentContext to EntityManager objects , like this,
#PersistenceContext(name="PersistentUnitName")
private EntityManager entityManager;
Are you using EJB 3 or EJB 2? EclipseLink does not support EJB 2 EntityBean, only EJB 3 Entities.
You cannot inject an Entity bean, it does not make sense, they must be queried from the database through an EntityManager. You can inject an EntityManager using #PersistenceContext.
See,
http://en.wikibooks.org/wiki/Java_Persistence/Runtime#Java_Enterprise_Edition

EJB Visibility from Managed Beans

I have Enterprise Java Bean which is Statefull and it holds current user instance
I want to get this instance from few different baking beans (SessionScoped managed beans) but when Im using:
#EJB
UserSessionBean usb;
(...)
usb.getUser();
I am getting null pointer exceptions in the ManagedBean (seems that every managedbean is getting new instance of UserSessionBean EJB. Why is that? I thought one instance of that bean would be shared among all Beans for that session...
if UserSessionBean is the implementation class or interface?
I think you should use the interface to create an instance of your EJB.
also take a look at #statefull and #singlton annotations.

Is it enough to convert a POJO to an EJB session bean ...?

Is it enough to convert a POJO like Util class to an EJB session bean by putting an annotation (#Stateless or #Stateful) and using injected EntityManager in it?
Yes, #Stateless in enough. Your bean will then become an EJB bean.
The only other requirement is that you can't create such a bean with new. You have to inject it using #EJB in another managed bean (JSF managed bean, Servlet, etc). Or if you aren't yet in any kind of managed bean, you can bootstrap a bean using a JNDI lookup.
Also, EJBs indeed greatly reduce the boilerplate code of starting and committing transactions when working with JPA.
Well It is enough but still few things need to be taken Care,
1) Mark your Entity manager and other new variables to Transient if POJO is used to persist some object.
2) It is better not to do so, as If u need to make it as EJB better to Create Some New Class for it as it is suggested way to not to create complexity.

How to call an EJB method when it deploys itself?

I want to call to a method from an EJB in the same instant in which one deploys itself, without using a servlet.
Thanks.
David.
There seems to be no life-cycle methods defined by the EJB spec for this purpose. Individual vendors may provide extensions to allow this. For example Startup Beans in WebSphere would be a place to put the invocation logic you want.
Using techniques such as a static method seem slightly dangerous in that we don't know whether all dependency injection is complete before that static method fires, and hence whether you can safely use the business methods of the EJB.
Persoanlly, if I needed to be portable I would bite the bullet and use a servlet. It costs very little.
Try doing your initialization within a static block. This will run once when the classloader loads the class.
static { System.out.println("static"); }
The PostConstruct hook is right for that.
Find more info on about PostConstruct here:
in the javadoc
lifecycle of EJBs in the JavaEE 5 tutorial
Let's finish with a quick example:
#Stateless
public class TestEJB implements MyEJBInterface{
#PostConstruct
public void doThatAfterInitialization() {
//put your code here to be executed after creation and initialization of your bean
}
}
Static initializer blocks are technically not illegal in EJB but they are used to execute code before any constructor (which might be a problem) when instantiating a class. They are typically used to initialize static fields which may be illegal in EJB if they are not read only. So, what about using ejbCreate(), setSessionContext() or setEntityContext() methods instead (not even sure this would be appropriate without more details on the problem you are trying to solve)?
The EJB container, for a #Singleton bean, shall create the instance of the bean as soon as the application is deploy if it is annotated #Startup.
That will, of course, fire up static initialization blocks, the constructor, dependency injection setters, #PostConstruct methods etc.
Here is the appropriate referente to the Java EE 6 Tutorial.

Resources