EJB3 communication mechanism - java

I'm new to Java EE and got confused about EJB.
As I understand #remote EJBs are using RMI and JNDI for communication.
Before EJB3.0 beans needed to implement Remote interface through EJBHome interface - that way I understand how RMI was used.
But now I only need to put #remote annotation, which can be substituted by properties in ejb-jar.xml.
So, the question is: how is it possible to use JNDI without Serializible interface and RMI without Remote interface?
Please correct me if some of my assumptions are wrong.

EJB3 still uses RMI underneath except the application container will take care of generating and using RMI stubs and remote interfaces automatically for you and map them to your EJB3 classes.
You are still required to use Serializible in certain cases. See this:
Clustered Session Beans (SLSB & SFSB)
First of all, clustered EJB3
SLSBs or SFSBs do not need to implement Serializable. In fact, it's
recommended that they don't. In the case of clustered SLSBs, no state
replication occurs, so their instance variables do not even need to be
Serializable. With clustered SFSBs though, the same serialization
rules used for SFSB passivation apply to SFSB state replication. In
other words, all non-transient instance variables that are not
references to beans, sessions contexts or user transactions must be
serializable, or null at replication time. For further information on
the SFSB passivation (and by extension replication because in both
cases the SFSB bean context needs to be serialized), please check
section 4.2.1 of the EJB3 core specification.
Clustered Entity Beans
These only need to be marked Serializable if
the clustered entity instances are to be passed by value as a detached
object (e.g., through a remote interface). Otherwise, there's no need
to mark them as Serializable.

EJB uses RMI, but it's not exactly equal to RMI. The container generates classes and interfaces at runtime that conform to the RMI spec, and hide them from you. This is why in a EJB project your remote client usually needs to include in its classpath a bunch of libraries specific to the container.
In this regard, EJB 2.0 was more transparent to the fact that it uses RMI under the hood, and thus, more complicated.

Related

Can I look up an EJB via JNDI and invoke methods using reflection?

I'm using EJB 3.1. I need to get a references to one of the EJBs in a servlet and I'd rather not put an EJB interface jar on the class path to get the code to compile.
Is it possible to look an EJB via JNDI and find the method I want to invoke using reflection without ever strongly typing the object to an interface?
Yes, if you're looking up a local EJB interface, then you can look up and invoke a local EJB within the same application using reflection.
This should work if you're using a direct lookup or an EJB ref lookup because the Java EE spec requires the application server to make EJB module classes available to WARs within the same application. The EJB spec doesn't require support for local interfaces across applications, so if that's what you're doing, you'll have to check with your application server vendor.
This will not work in general for remote EJB interfaces because a client proxy needs to be created. If you're using RMI-IIOP (EJB 2.x remote or EJB 3 extending java.rmi.Remote), you might be able to cast the EJB lookup result to javax.rmi.CORBA.Stub and use the _servant_preinvoke or _invoke methods the same as a generated stub method would do.
(Ultimately, this is a lot of caveats just to avoid a compile-time dependency. It's probably not worth the fragility, so I would recommend finding a way to solve that and compile normally.)

CDI choosing correct scope for bean

Coming from plain old DI of Spring I can't figure out how to choose scopes properly while writing with CDI.
In Spring all my services have singleton scope by default, which I suppose maps to application scope in CDI (or even #Singleton). I know for e.g. logged in user information I need to use Session scope and for e.g. form params I need request scope.
Say I have a bean that hides external service API calls. It is completely stateless. Should I put it as #Singleton or simply application scoped? Or let it be created on every request (possibly bad option).
Is this correct to inject everything everywhere? In Spring I create my data objects by new. Should I do the same in CDI or simply #Inject them?
Are you only using CDI? or a Java EE 6 container? If you have a stateless class that is used for service calls, then I would recommend using #Stateless, which is from the EJB spec (so you would need a Java EE 6 container) It isn't a singleton, but it doesn't get created on each request either. I believe it is more closely bound to the session, but since it is stateless, instances can be pooled and shared. If you are only dealing with CDI, I believe Singleton matches more directly to Spring's singleton, but I would recommend using ApplicationScoped because it provides a proxy which makes serialization of beans that use it easier.
#Service
#Scope("prototype")
public class CustomerService
{
......
}
Just add #Scope("prototype") annotation to your component.
Is there a reason you would need the bean to remember it's state? If you are using something like a web client, that is a better place to store state in say, session scoped managed beans (assuming jsf), or whatever equivalent for your case. On the back end server side your EJB's would be better kept as #stateless to keep overhead to a minimum and help with the 'keep it simple s..." paradigm. And in case this works, just declare #Stateless on your bean. Unless there is a reason to use a singleton, again it is better to use a stateless bean if you want to go with a Java EE container for your services.
Stateless beans are not really being recreated with every request. That is the purpose of the pool. The app server keeps a ready supply of stateless beans on hand, and if it gets busy, it will make more, and if it quiets down, it will empty some out.

How to achieve clustering, load balancing and fail-over for Session Beans in OGS

JBoss seems to have a pretty easy set of annotations/configurations for clustering and load balancing session beans, but I'm not seeing the same features in the GlassFish 3.x docs.
Let's say I have both MyStatefulBean and MyStatelessBean beans. For both of them, I want the following capabilities:
I want to be able to create a cluster of the bean (to any number or scale) and put them behind a software load balancer that will round robin the beans; and
If 1 of the clustered beans fails for any reason I want it taken out of the pool
Does GlassFish free/(community edition) even support this or would I have to implement this myself?
Tangential to the first question: does clustering/load-balancing even make sense form stateful beans? I don't think it does now that I think of it...but still the question applies to both types of beans until proven otherwise!
First, you need to enable high availability for the application if you want to preserve the session state on failure. If using the admin console, there is a checkbox for this on the deploy app screen. If you are deploying from the command line, then use "asadmin deploy --availabilityenabled=true --target mycluster myapp.ear".
When the bean is looked up, the bean RMI proxy/stub that is generated has a list of all the clustered GlassFish instances that are available. The order of the servers is randomly generated, and the RMI stub will select the server at the top of the list. This is how the load is spread across the cluster. If the remote server fails, the next server in the list is selected. If the remote bean is a stateful session bean, then the session is preserved on failover.
As #pdudits mentions, please read the documentation on the subject for more in-depth coverage.
Hope this helps!
If you plan to invoke the beans via remote calls, this is the chapter in High Availability Guide you're looking for.
Failover of stateful beans makes sense, but load-balancing is also possible. Bear in mind that it has its limits, the greatest one being, that extended persistence context cannot be used.
The pool sizes for a bean is specified in EJB service settings and can be overrided in glassfish-ejb-jar.xml for specific bean
AFAIK this is what EJB Spec says - when a system exception occurs (this includes unchecked exceptions), the bean is destroyed.

JAX-WS - Service Implementation as a POJO

I was doing some reading up on building a soap service using jax-ws as part of java 6. I read that the operations that can be invoked by a client can be defined in the SEI, or Service Endpoint Interface. These operations can be implemented by a SIB, aka "Service Implementation Bean". The part that troubles me, is that this SIB "can either be a POJO or a Stateless Session EJB" according to page 4 of this book. The same definition applies on wikipedia. However, I read that a POJO (according to wikipedia) is "an ordinary Java Object, not a special object, which does not follow any of the major Java object models, conventions, or frameworks such as EJB". Thus follows my question, how can I know that my SIB is a POJO? Additionally, what is the difference between implementing my web service operations via a POJO or a stateless session EJB?
EJB 3.0 introduced annotations that allow any POJO to become a stateless session bean. Therefore the sentence "[a SIB] can either be a POJO or a Stateless Session EJB" applies to stateless session beans pre-EJB 3.0 (such as EJB 2.1). You can now write your SIB as a POJO - that is, without extending any other class or implementing any special interface that you didn't write yourself. You will still need an EJB container, though, such as WebLogic Server, IBM WAS or jBoss if you want to use EJBs.
In my point of view the biggest advantages for a ejb over POJO distrubution capacities of ejb there is plenty features exists for ejbs like CMP.
The other part any class you writed in java is a POJO in another words if your implemantion is a java class then it is a POJO.
POJO term came out for indicating that there is no need for special class type which is a need for java EE world because there is plenty special classes in java EE.
For one of advantages of ejb over POJO you can read this documentation: http://lass.cs.umass.edu/~shenoy/courses/spring11/lectures/Lec24.pdf

Making sense of JPA and EJB3 and WebServices

I'm just getting started with JPA, creating stateless session beans from the JPA entities, then accessing the beans through a web service. While I have a lot of experience developing database backed web services "the old way", I have some questions about what's going on behind the scenes with this new "annotation driven approach".
What I see is, NetBeans sort of directs you to build applications in this manner though their wizards.
Create an Enterprise Application with EJB and Web Application modules.
Create Entity classes. I created mine from an existing database.
Create session beans from the entity class.
Create Web services from the session bean.
It all looks pretty simple, but what's going on behind the scenes? Specifically:
I see that the web service (created with the #WebService annotation) references my stateless session bean (using the #EJB reference).
What happens here? Does it just grab an instance of the EJB from the application server's EJB pool?
Nevermind. I was thinking of an instance where there was more than 1 table - meaning more than 1 type of Entity class and more than 1 type of EJB. I was looking at the web service and just seeing the #EJB reference and didn't understand who it was getting the bean type from that annotation. Just below that however, it the reference to the local bean interface - so that's that.
If there is more than 1 type of EJB deployed to the server, how does it know which one to grab?
The EJB is defined via the #Stateless and #Local annotations. The bean implementation references an EnityManager via the #PersistenceContext annotation.
Where is the jndi lookup to the database done (maybe in the persistence.xml file)?
Do all of the EJBs share a common EntityManager (assuming the EntityManager is thread safe)? If not, I know that the EnityManager utilizes a second level cache to help reduce trips to the database, are these caches somehow kept in sync?
I know this is a lot of questions, but they're all sort of related and there seem to be a lot of complicated concepts for something that's so easy to build through the wizards. I want to make sure I understand what's all going on here.
Thanks in advance!
What happens here? Does it just grab an instance of the EJB from the application server's EJB pool?
A JAX-WS web component endpoint (as opposed to a JAX-WS EJB endpoint) follows the typical servlet threading model, which means that typically there is one instance that is executed concurrently for each client. JAX-WS implementations are free to leverage pools of bean instances to handle a request in a fashion similar to stateless session EJB components. (source: Developing Applications for the JavaTM EE Platform FJ-310).
In all cases, it is fine to inject/look-up stateless beans because the container guarantees that the beans will always be thread safe. In affect, the container automatically serializes clients calls but uses instance pooling to make sure you still get concurrency benefits.
If there is more than 1 EJB deployed to the server, how does it know which one to grab?
Hmm... I didn't get this one. Can you clarify what you mean exactly? Why would there be any ambiguity?
Where is the jndi lookup to the database done (maybe in the persistence.xml file)?
In a Java EE environment, you specify your data source in a <jta-data-source> element in each persistence unit of the persistence.xml file (which can contain several persistence units) and the data source will be obtained by the EntityManager (only when needed, i.e. only if a data access is really needed).
Do all of the EJBs share a common EntityManager?
No. The EntityManager is a non-thread-safe object that should be used once, for a single business process, a single unit of work, and then discarded. In a Java EE environment using EJB 3, the default pattern is "entitymanager-per-request". A request from the client is send to the EJB 3 persistence layer, a new EntityManager is opened, and all database operations are executed in this unit of work. Once the work has been completed (and the response for the client has been prepared), the persistence context is flushed and closed, as well as the entity manager object. (source: Chapter 4. Transactions and Concurrency).

Categories

Resources